Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1182ba0cf2 | ||
|
|
ee5f458c76 | ||
|
|
5841ccea2c | ||
|
|
62592f2efd | ||
|
|
7a0a058085 | ||
|
|
c42e4320e2 | ||
|
|
84636efd32 | ||
|
|
af761b8583 |
No files matched your search
+3
-3
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ Type=simple
|
||||
WorkingDirectory=/srv/hyperstitionstud.io/repos
|
||||
Environment="HYPERSTITIONSTUDIO_CONFIG=/srv/hyperstitionstud.io/repos/workspace.toml"
|
||||
Environment="PYTHONPATH=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src"
|
||||
Environment="HYPERSTITION_TELEMETRY_DB_PATH=/tmp/hyperstition-api-telemetry.db"
|
||||
Environment="HYPERSTITION_SQLITE_MAX_MB=100"
|
||||
ExecStart=/srv/hyperstitionstud.io/repos/.venv/bin/python3 /srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py --transport http --host 127.0.0.1 --port 8095
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
|
||||
@@ -7,7 +7,7 @@ Before=caddy.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/deploy/sync-vps-repos.sh --no-pull
|
||||
ExecStart=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/deploy/sync-vps-repos.sh --no-pull --no-caddy
|
||||
RemainAfterExit=yes
|
||||
|
||||
[Install]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# /etc/logrotate.d/hyperstition-sqlite-meta
|
||||
# Quiescent size-based compression & truncation for the hyperstitionstud.io SQLite REST/MCP API metadata DB.
|
||||
#
|
||||
# Why quiescent snapshot compression + in-place SQLite truncation is used:
|
||||
# Raw byte truncation (`copytruncate`) on a live SQLite `.db` or `-wal` file while readers or
|
||||
# writers hold locks corrupts the SQLite B-tree page header and WAL frame index.
|
||||
# Instead, `prerotate` invokes `hyperstitionstud_io.db.sqlite_meta --truncate-quiescent --compress-archive`, which:
|
||||
# 1. Sets `PRAGMA busy_timeout = 30000` (waits up to 30s for in-flight requests to finish),
|
||||
# 2. Acquires `BEGIN EXCLUSIVE` to guarantee 100% SQLite reader/writer quiescence,
|
||||
# 3. Writes a consistent point-in-time SQLite snapshot and compresses it with `gzip -9`
|
||||
# to `<db_path>.1.gz` (rotating `.1.gz` .. `.12.gz` rather than removing history),
|
||||
# 4. Purges the live telemetry tables and commits cleanly,
|
||||
# 5. Executes `PRAGMA wal_checkpoint(TRUNCATE)` + `VACUUM` + `PRAGMA optimize` on the live DB, and
|
||||
# 6. Verifies `PRAGMA integrity_check == 'ok'` on the live DB.
|
||||
#
|
||||
# Configurable threshold:
|
||||
# - Default logrotate trigger: `size 100M` (100 MB)
|
||||
# - Runtime override: export `HYPERSTITION_SQLITE_MAX_MB` (default `100`) or `HYPERSTITION_SQLITE_MAX_BYTES`.
|
||||
|
||||
/tmp/hyperstition-api-telemetry.db /var/lib/hyperstitionstud.io/api-telemetry.db {
|
||||
size 100M
|
||||
rotate 12
|
||||
compress
|
||||
delaycompress
|
||||
missingok
|
||||
notifempty
|
||||
nocreate
|
||||
sharedscripts
|
||||
prerotate
|
||||
TARGET_DB="${1:-${HYPERSTITION_TELEMETRY_DB_PATH:-/tmp/hyperstition-api-telemetry.db}}"
|
||||
MAX_MB="${HYPERSTITION_SQLITE_MAX_MB:-100}"
|
||||
MAX_BYTES="${HYPERSTITION_SQLITE_MAX_BYTES:-$((MAX_MB * 1024 * 1024))}"
|
||||
ROTATE_KEEP="${HYPERSTITION_SQLITE_ROTATE_KEEP:-12}"
|
||||
PYTHON_BIN="${HYPERSTITION_PYTHON_BIN:-python3}"
|
||||
PYTHONPATH="${PYTHONPATH:-/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src:/workspace/hyperstitionstudio-core/src}" \
|
||||
"${PYTHON_BIN}" -m hyperstitionstud_io.db.sqlite_meta \
|
||||
--truncate-quiescent \
|
||||
--compress-archive \
|
||||
--rotate-keep "${ROTATE_KEEP}" \
|
||||
--db "${TARGET_DB}" \
|
||||
--max-bytes "${MAX_BYTES}"
|
||||
endscript
|
||||
}
|
||||
+162
-37
@@ -1,24 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
# /workspace/hyperstitionstudio-core/deploy/sync-vps-repos.sh
|
||||
# Hydrates per-repository install directories from REPOS_ROOT into LIVE_REPOS (tmpfs RAM mount),
|
||||
# builds haiperdohp-jemaytreeah/db_lite.json if absent, creates top-level route symlinks, and
|
||||
# pre-compresses (.br / .gz) static assets.
|
||||
# supplies untracked haiperdohp-jemaytreeah/.gitignore files (config.js, db.json, db_lite.json),
|
||||
# creates top-level route symlinks, pre-compresses (.br / .gz) static assets, and idempotently
|
||||
# syncs/validates/reloads /etc/caddy/Caddyfile, systemd units, and /etc/logrotate.d/hyperstition-sqlite-meta
|
||||
# by default (negated via --no-caddy).
|
||||
#
|
||||
# Usage:
|
||||
# ./sync-vps-repos.sh all # Pull from git.libre.audio, audit & sync all repos
|
||||
# ./sync-vps-repos.sh encyclopedia-knowledge-graph # Pull, audit & sync a single repo
|
||||
# ./sync-vps-repos.sh --no-pull # Audit & sync existing local clones without network fetch
|
||||
# ./sync-vps-repos.sh [all|<repo-name>] [--no-pull] [--no-caddy|--no-services]
|
||||
set -euo pipefail
|
||||
|
||||
on_error() {
|
||||
local exit_code=$?
|
||||
local line_no="${1:-unknown}"
|
||||
echo "[ERROR] sync-vps-repos.sh failed at line ${line_no} with exit code ${exit_code} while running: ${BASH_COMMAND}" >&2
|
||||
exit "${exit_code}"
|
||||
}
|
||||
trap 'on_error ${LINENO}' ERR
|
||||
|
||||
run_checked() {
|
||||
local label="$1"
|
||||
shift
|
||||
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
|
||||
fi
|
||||
return "${rc}"
|
||||
fi
|
||||
}
|
||||
|
||||
has_cmd() {
|
||||
command -v "$1" >&2
|
||||
}
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
|
||||
DEFAULT_REPOS_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
||||
|
||||
export REPOS_ROOT="${REPOS_ROOT:-${DEFAULT_REPOS_ROOT}}"
|
||||
export LIVE_REPOS="${LIVE_REPOS:-/var/www/hyperstitionstud.io/repos}"
|
||||
TARGET_REPO="${1:-all}"
|
||||
|
||||
TARGET_REPO="all"
|
||||
DO_PULL=1
|
||||
DO_CADDY=1
|
||||
|
||||
for arg in "$@"; do
|
||||
case "${arg}" in
|
||||
--no-pull)
|
||||
DO_PULL=0
|
||||
;;
|
||||
--no-caddy|--no-services)
|
||||
DO_CADDY=0
|
||||
;;
|
||||
*)
|
||||
TARGET_REPO="${arg}"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
SUDO=""
|
||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]] && [[ ! -w "$(dirname "${LIVE_REPOS}")" ]] && command -v sudo >/dev/null 2>&1; then
|
||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]] && type -P sudo >&2; then
|
||||
SUDO="sudo"
|
||||
fi
|
||||
|
||||
@@ -46,7 +90,7 @@ REPOS=(
|
||||
"${CI_REPO_DIR}:feat/ingglish-aq-corpus"
|
||||
)
|
||||
|
||||
if [[ "${TARGET_REPO}" != "--no-pull" ]]; then
|
||||
if [[ "${DO_PULL}" -eq 1 ]]; then
|
||||
for entry in "${REPOS[@]}"; do
|
||||
repo="${entry%%:*}"
|
||||
branch="${entry##*:}"
|
||||
@@ -55,12 +99,19 @@ if [[ "${TARGET_REPO}" != "--no-pull" ]]; then
|
||||
fi
|
||||
if [[ -d "${REPOS_ROOT}/${repo}/.git" ]]; then
|
||||
remote_name="origin"
|
||||
if [[ "${repo}" == "haiperdohp-jemaytreeah" ]] && git -C "${REPOS_ROOT}/${repo}" remote get-url downstream >/dev/null 2>&1; then
|
||||
if [[ "${repo}" == "haiperdohp-jemaytreeah" ]] && git -C "${REPOS_ROOT}/${repo}" remote | grep -qx "downstream"; then
|
||||
remote_name="downstream"
|
||||
fi
|
||||
echo "[1/4] Updating ${REPOS_ROOT}/${repo} (${remote_name}/${branch})..."
|
||||
git -C "${REPOS_ROOT}/${repo}" fetch --force "${remote_name}" "${branch}" --tags
|
||||
git -C "${REPOS_ROOT}/${repo}" merge --ff-only "${remote_name}/${branch}"
|
||||
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
|
||||
@@ -69,56 +120,130 @@ fi
|
||||
if [[ -d "${REPOS_ROOT}/haiperdohp-jemaytreeah" ]]; then
|
||||
if [[ ! -f "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.js" ]] && [[ -f "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.default.js" ]]; then
|
||||
echo "[build] Copying haiperdohp-jemaytreeah/config.default.js -> config.js..."
|
||||
cp "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.default.js" "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.js"
|
||||
run_checked "copy haiperdohp-jemaytreeah config.js" cp "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.default.js" "${REPOS_ROOT}/haiperdohp-jemaytreeah/config.js"
|
||||
fi
|
||||
if [[ ! -f "${REPOS_ROOT}/haiperdohp-jemaytreeah/db_lite.json" || ! -f "${REPOS_ROOT}/haiperdohp-jemaytreeah/db.json" ]] && [[ -f "${REPOS_ROOT}/haiperdohp-jemaytreeah/tools/generate_db_json.py" ]]; then
|
||||
echo "[build] Generating haiperdohp-jemaytreeah/db.json and db_lite.json from db.txt..."
|
||||
(cd "${REPOS_ROOT}/haiperdohp-jemaytreeah" && "${PYTHON_BIN}" tools/generate_db_json.py db.txt db.json)
|
||||
(cd "${REPOS_ROOT}/haiperdohp-jemaytreeah" && run_checked "generate_db_json.py" "${PYTHON_BIN}" tools/generate_db_json.py db.txt db.json)
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "[2/4] Running hs-doctor and 6-Gate Knowledge Graph Verification..."
|
||||
"${PYTHON_BIN}" -m hyperstitionstud_io.ci.doctor >/dev/null
|
||||
"${PYTHON_BIN}" "${REPOS_ROOT}/encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py" --verify-only >/dev/null
|
||||
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
|
||||
|
||||
echo "[3/4] Syncing per-repository install directories into ${LIVE_REPOS}..."
|
||||
${SUDO} mkdir -p "${LIVE_REPOS}"
|
||||
echo "[3/5] Syncing per-repository install directories into ${LIVE_REPOS}..."
|
||||
LIVE_SUDO=""
|
||||
if [[ ! -w "$(dirname "${LIVE_REPOS}")" ]] && [[ -n "${SUDO}" ]]; then
|
||||
LIVE_SUDO="${SUDO}"
|
||||
fi
|
||||
${LIVE_SUDO} mkdir -p "${LIVE_REPOS}"
|
||||
for entry in "${REPOS[@]}"; do
|
||||
repo="${entry%%:*}"
|
||||
if [[ "${TARGET_REPO}" != "all" && "${TARGET_REPO}" != "--no-pull" && "${TARGET_REPO}" != "${repo}" ]]; then
|
||||
if [[ "${TARGET_REPO}" != "all" && "${TARGET_REPO}" != "${repo}" ]]; then
|
||||
continue
|
||||
fi
|
||||
if [[ -d "${REPOS_ROOT}/${repo}" ]]; then
|
||||
${SUDO} mkdir -p "${LIVE_REPOS}/${repo}"
|
||||
${SUDO} rsync -a --delete --exclude='.git' "${REPOS_ROOT}/${repo}/" "${LIVE_REPOS}/${repo}/"
|
||||
${LIVE_SUDO} mkdir -p "${LIVE_REPOS}/${repo}"
|
||||
run_checked "rsync ${repo}" ${LIVE_SUDO} rsync -a --delete --exclude='.git' "${REPOS_ROOT}/${repo}/" "${LIVE_REPOS}/${repo}/"
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${CI_REPO_DIR}" == "hyperdope-ci-build" ]] && [[ -d "${LIVE_REPOS}/hyperdope-ci-build" ]] && [[ ! -e "${LIVE_REPOS}/ingglish-hyperdope-ci" ]]; then
|
||||
${SUDO} ln -sfn "hyperdope-ci-build" "${LIVE_REPOS}/ingglish-hyperdope-ci"
|
||||
${LIVE_SUDO} ln -sfn "hyperdope-ci-build" "${LIVE_REPOS}/ingglish-hyperdope-ci"
|
||||
fi
|
||||
|
||||
# Create relative route symlinks inside LIVE_REPOS so both Caddy and standalone HTTP servers resolve all active routes
|
||||
${SUDO} ln -sfn "hyperstitionstudio-core/site/index.html" "${LIVE_REPOS}/index.html"
|
||||
${SUDO} ln -sfn "hyperstitionstudio-core/site/learn" "${LIVE_REPOS}/learn"
|
||||
${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)
|
||||
${SUDO} rm -rf "${LIVE_REPOS}/gallery" "${LIVE_REPOS}/hyperstitionstudio-core/site/gallery"
|
||||
${SUDO} ln -sfn "encyclopedia-knowledge-graph" "${LIVE_REPOS}/graph"
|
||||
${SUDO} ln -sfn "technocapital-singularity-zoology/encyclopedia" "${LIVE_REPOS}/encyclopedia"
|
||||
${SUDO} ln -sfn "technocapital-singularity-zoology" "${LIVE_REPOS}/zoology"
|
||||
${SUDO} ln -sfn "ingglish-hyperdope-gematria/ingglish-aq-archive" "${LIVE_REPOS}/archive"
|
||||
${SUDO} ln -sfn "haiperdohp-jemaytreeah" "${LIVE_REPOS}/calc"
|
||||
${SUDO} ln -sfn "ingglish-hyperdope-ci" "${LIVE_REPOS}/ci"
|
||||
${SUDO} ln -sfn "hyperstitionstudio-core/schemas" "${LIVE_REPOS}/schemas"
|
||||
${LIVE_SUDO} rm -rf "${LIVE_REPOS}/gallery" "${LIVE_REPOS}/hyperstitionstudio-core/site/gallery"
|
||||
${LIVE_SUDO} ln -sfn "encyclopedia-knowledge-graph" "${LIVE_REPOS}/graph"
|
||||
${LIVE_SUDO} ln -sfn "technocapital-singularity-zoology/encyclopedia" "${LIVE_REPOS}/encyclopedia"
|
||||
${LIVE_SUDO} ln -sfn "technocapital-singularity-zoology" "${LIVE_REPOS}/zoology"
|
||||
${LIVE_SUDO} ln -sfn "ingglish-hyperdope-gematria/ingglish-aq-archive" "${LIVE_REPOS}/archive"
|
||||
${LIVE_SUDO} ln -sfn "haiperdohp-jemaytreeah" "${LIVE_REPOS}/calc"
|
||||
${LIVE_SUDO} ln -sfn "ingglish-hyperdope-ci" "${LIVE_REPOS}/ci"
|
||||
${LIVE_SUDO} ln -sfn "hyperstitionstudio-core/schemas" "${LIVE_REPOS}/schemas"
|
||||
|
||||
echo "[4/4] Pre-compressing static HTML, JS, JSON, XML, Canvas, MD & CSS assets (< 5 MB) (.br / .gz)..."
|
||||
${SUDO} find "${LIVE_REPOS}" -type f -size -5M \
|
||||
echo "[4/5] Pre-compressing static HTML, JS, JSON, XML, Canvas, MD & CSS assets (< 5 MB) (.br / .gz)..."
|
||||
run_checked "gzip pre-compression" ${LIVE_SUDO} find "${LIVE_REPOS}" -type f -size -5M \
|
||||
\( -name "*.html" -o -name "*.js" -o -name "*.json" -o -name "*.graphml" -o -name "*.gexf" -o -name "*.canvas" -o -name "*.css" -o -name "*.md" \) \
|
||||
-exec gzip -9 -k -f {} \;
|
||||
if command -v brotli >/dev/null 2>&1; then
|
||||
${SUDO} find "${LIVE_REPOS}" -type f -size -5M \
|
||||
if [[ -n "$(type -P brotli || true)" ]]; then
|
||||
run_checked "brotli pre-compression" ${LIVE_SUDO} find "${LIVE_REPOS}" -type f -size -5M \
|
||||
\( -name "*.html" -o -name "*.js" -o -name "*.json" -o -name "*.graphml" -o -name "*.gexf" -o -name "*.canvas" -o -name "*.css" -o -name "*.md" \) \
|
||||
-exec brotli -q 11 -k -f {} \;
|
||||
fi
|
||||
|
||||
# Step 5: Idempotent systemd unit, logrotate.d & /etc/caddy/Caddyfile synchronization (enabled by default; skip with --no-caddy)
|
||||
if [[ "${DO_CADDY}" -eq 1 ]]; then
|
||||
DEPLOY_DIR="${REPOS_ROOT}/hyperstitionstudio-core/deploy"
|
||||
SRC_LOGROTATE="${DEPLOY_DIR}/logrotate.d/hyperstition-sqlite-meta"
|
||||
DST_LOGROTATE="/etc/logrotate.d/hyperstition-sqlite-meta"
|
||||
if [[ -f "${SRC_LOGROTATE}" ]] && [[ -d "/etc/logrotate.d" ]] && { [[ -w "/etc/logrotate.d" ]] || [[ -n "${SUDO}" ]]; }; then
|
||||
if [[ -f "${DST_LOGROTATE}" ]] && cmp -s "${SRC_LOGROTATE}" "${DST_LOGROTATE}"; then
|
||||
echo "[5/5] ${DST_LOGROTATE} is already identical to deploy/logrotate.d/hyperstition-sqlite-meta."
|
||||
else
|
||||
echo "[5/5] Installing quiescent SQLite logrotate rule to ${DST_LOGROTATE}..."
|
||||
run_checked "copy hyperstition-sqlite-meta logrotate rule" ${SUDO} cp "${SRC_LOGROTATE}" "${DST_LOGROTATE}"
|
||||
run_checked "chmod 0644 ${DST_LOGROTATE}" ${SUDO} chmod 0644 "${DST_LOGROTATE}"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -n "$(type -P systemctl || true)" ]] && [[ -d "/run/systemd/system" ]]; then
|
||||
UNITS_CHANGED=0
|
||||
for unit_name in "hyperstition-tmpfs-sync.service" "hyperstition-mcp.service"; do
|
||||
src_u="${DEPLOY_DIR}/${unit_name}"
|
||||
dst_u="/etc/systemd/system/${unit_name}"
|
||||
if [[ -f "${src_u}" ]]; then
|
||||
if [[ ! -f "${dst_u}" ]] || ! cmp -s "${src_u}" "${dst_u}"; then
|
||||
echo "[5/5] Updating systemd unit ${dst_u}..."
|
||||
run_checked "copy ${unit_name}" ${SUDO} cp "${src_u}" "${dst_u}"
|
||||
UNITS_CHANGED=1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [[ "${UNITS_CHANGED}" -eq 1 ]]; then
|
||||
run_checked "systemctl daemon-reload" ${SUDO} systemctl daemon-reload
|
||||
run_checked "systemctl enable hyperstition-tmpfs-sync.service" ${SUDO} systemctl enable hyperstition-tmpfs-sync.service
|
||||
run_checked "systemctl enable --now hyperstition-mcp.service" ${SUDO} systemctl enable --now hyperstition-mcp.service
|
||||
run_checked "systemctl restart hyperstition-mcp.service" ${SUDO} systemctl restart hyperstition-mcp.service
|
||||
elif [[ -f "/etc/systemd/system/hyperstition-mcp.service" ]] && ! systemctl is-active --quiet hyperstition-mcp.service; then
|
||||
run_checked "systemctl enable --now hyperstition-mcp.service" ${SUDO} systemctl enable --now hyperstition-mcp.service
|
||||
fi
|
||||
fi
|
||||
|
||||
SRC_CADDY="${DEPLOY_DIR}/Caddyfile"
|
||||
DST_CADDY="/etc/caddy/Caddyfile"
|
||||
if [[ -n "$(type -P caddy || true)" ]] && [[ -d "/etc/caddy" ]] && [[ -f "${SRC_CADDY}" ]]; then
|
||||
if [[ -f "${DST_CADDY}" ]] && cmp -s "${SRC_CADDY}" "${DST_CADDY}"; then
|
||||
echo "[5/5] /etc/caddy/Caddyfile is already identical to deploy/Caddyfile (no reload needed)."
|
||||
else
|
||||
echo "[5/5] Validating and updating ${DST_CADDY} from ${SRC_CADDY}..."
|
||||
run_checked "caddy validate ${SRC_CADDY}" ${SUDO} caddy validate --config "${SRC_CADDY}" --adapter caddyfile
|
||||
run_checked "copy Caddyfile" ${SUDO} cp "${SRC_CADDY}" "${DST_CADDY}"
|
||||
if [[ -n "$(type -P systemctl || true)" ]] && [[ -d "/run/systemd/system" ]]; then
|
||||
if systemctl is-active --quiet caddy; then
|
||||
run_checked "systemctl reload caddy" ${SUDO} systemctl reload caddy
|
||||
echo "[5/5] Reloaded Caddy with updated /etc/caddy/Caddyfile."
|
||||
else
|
||||
run_checked "systemctl enable --now caddy" ${SUDO} systemctl enable --now caddy
|
||||
echo "[5/5] Started Caddy with updated /etc/caddy/Caddyfile."
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo "[5/5] Caddy or /etc/caddy not present on this host; skipping Caddyfile reload."
|
||||
fi
|
||||
else
|
||||
echo "[5/5] Skipping Caddyfile & systemd service sync (--no-caddy)."
|
||||
fi
|
||||
|
||||
echo "[OK] Per-repository install directories hydrated and pre-compressed at ${LIVE_REPOS}"
|
||||
@@ -28,7 +28,8 @@ trap cleanup EXIT
|
||||
|
||||
if [[ -z "${TARGET_BASE_URL}" ]]; then
|
||||
export LIVE_REPOS="${LIVE_REPOS:-/tmp/hyperstition-live-repos}"
|
||||
rm -rf "${LIVE_REPOS}"
|
||||
export HYPERSTITION_TELEMETRY_DB_PATH="${HYPERSTITION_TELEMETRY_DB_PATH:-/tmp/hyperstition-deploy-test-telemetry.db}"
|
||||
rm -rf "${LIVE_REPOS}" "${HYPERSTITION_TELEMETRY_DB_PATH}" "${HYPERSTITION_TELEMETRY_DB_PATH}-wal" "${HYPERSTITION_TELEMETRY_DB_PATH}-shm"
|
||||
echo "[1/4] Hydrating per-repository webroot at ${LIVE_REPOS} via sync-vps-repos.sh --no-pull..."
|
||||
"${SCRIPT_DIR}/sync-vps-repos.sh" --no-pull
|
||||
|
||||
@@ -42,15 +43,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"
|
||||
@@ -59,6 +66,8 @@ ROUTES=(
|
||||
"/graph/docs/cross-repo-dependency-and-audit-flow-diagram.html"
|
||||
"/graph/docs/cross-repo-dependency-and-audit-flow-diagram.pdf"
|
||||
"/graph/docs/VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.pdf"
|
||||
"/graph/docs/PLAN-LLM-TOKEN-ECONOMIZER-AND-VARIANCE-ROUTING.pdf"
|
||||
"/graph/docs/PLAN-LLM-TOKEN-ECONOMIZER-DATA-FIDELITY-AND-DEGRADATION-RISK-EVALUATION.pdf"
|
||||
"/encyclopedia/00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf"
|
||||
"/technocapital-singularity-zoology/encyclopedia/00-index-and-ontological-atlas/00-master-encyclopedia-index-a-to-z.pdf"
|
||||
"/zoology/encyclopedia-of-technocapital-singularity-zoology-overview-and-manifest.pdf"
|
||||
@@ -80,6 +89,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
|
||||
@@ -110,4 +120,32 @@ 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
|
||||
|
||||
if [[ -n "${HYPERSTITION_TELEMETRY_DB_PATH:-}" ]] && [[ -f "${LIVE_REPOS}/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta" ]]; then
|
||||
echo "[4c/4] Verifying SQLite REST/MCP metadata DB population & quiescent logrotate.d compression + truncation..."
|
||||
PYTHONPATH="${SCRIPT_DIR}/../src" python3 - <<'PY'
|
||||
import os
|
||||
from pathlib import Path
|
||||
from hyperstitionstud_io.db.sqlite_meta import get_api_telemetry_summary, run_logrotate_directive
|
||||
|
||||
tel_db = Path(os.environ["HYPERSTITION_TELEMETRY_DB_PATH"])
|
||||
conf_p = Path(os.environ["LIVE_REPOS"]) / "hyperstitionstudio-core" / "deploy" / "logrotate.d" / "hyperstition-sqlite-meta"
|
||||
summary = get_api_telemetry_summary(tel_db)
|
||||
assert summary["total_requests"] >= 5, f"Expected >= 5 recorded MCP/REST calls, got {summary['total_requests']}"
|
||||
lr_out = run_logrotate_directive(conf_path=conf_p, telemetry_db_path=tel_db, max_bytes_override=1024)
|
||||
assert lr_out["truncated"] is True and lr_out["quiescent"] is True and lr_out["integrity_check"] == "ok", lr_out
|
||||
assert lr_out["compress_enabled"] is True and lr_out["compressed_archive_bytes"] > 0 and Path(lr_out["compressed_archive_path"]).is_file(), lr_out
|
||||
print(f" [OK] SQLite metadata DB populated ({summary['total_requests']} calls), compressed to {Path(lr_out['compressed_archive_path']).name} ({lr_out['compressed_archive_bytes']} B) & quiescently truncated via {conf_p.name} (default {lr_out['configured_size_directive']}).")
|
||||
PY
|
||||
fi
|
||||
|
||||
echo "[OK] All ${PASS_COUNT}/${#ROUTES[@]} static routes + 2 MCP HTTP endpoints + 4 REST API v1 endpoints verified (HTTP 200 OK)."
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@hyperstitionstud.io/workspace-core",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.19",
|
||||
"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,6 +1,6 @@
|
||||
{
|
||||
"name": "@hyperstitionstud.io/ciphers-aq",
|
||||
"version": "2.0.0",
|
||||
"version": "2.0.19",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"license": "MIT"
|
||||
|
||||
+3
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "hyperstitionstudio-core"
|
||||
version = "2.0.0"
|
||||
version = "2.0.19"
|
||||
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"
|
||||
@@ -26,6 +26,8 @@ hs-pdf-build = "hyperstitionstud_io.publishing.pdf_compiler:main"
|
||||
hs-kg-build = "hyperstitionstud_io.graph.cli:main"
|
||||
hs-quant-harvest = "hyperstitionstud_io.quant.collector:main"
|
||||
hs-mcp = "hyperstitionstud_io.mcp.server:main"
|
||||
hs-sync-version = "hyperstitionstud_io.version_sync:main"
|
||||
hs-db-build = "hyperstitionstud_io.db.sqlite_meta:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
@@ -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"
|
||||
]
|
||||
}
|
||||
@@ -144,8 +144,8 @@ def main() -> int:
|
||||
})
|
||||
|
||||
manifest = {
|
||||
"version": "2.0.0",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.0",
|
||||
"version": "2.0.19",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.19",
|
||||
"total_items": len(items),
|
||||
"items": items,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
window.HyperstitionStudio = window.HyperstitionStudio || {};
|
||||
window.HyperstitionStudio.GalleryData = {
|
||||
"version": "2.0.0",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.0",
|
||||
"version": "2.0.13",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:gallery:2.0.13",
|
||||
"total_items": 37,
|
||||
"items": [
|
||||
{
|
||||
|
||||
@@ -217,7 +217,7 @@
|
||||
<main class="gallery-grid" id="galleryGrid"></main>
|
||||
|
||||
<footer>
|
||||
<div>hyperstitionstud.io/gallery • Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:gallery:2.0.0)</div>
|
||||
<div>hyperstitionstud.io/gallery • Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:gallery:2.0.19)</div>
|
||||
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">♥</span> by Lemurs.</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
+6
-4
@@ -131,13 +131,14 @@
|
||||
<span class="dot"></span>
|
||||
<h1>HYPERSTITIONSTUD.IO // TECHNOCAPITAL SINGULARITY ZOOLOGY WORKBENCH</h1>
|
||||
</div>
|
||||
<p class="subtitle">100% Offline-Portable & HTTP/3 Edge-Ready Research Corpus • Namespace Authority: urn:io:hyperstitionstud (v2.0.0)</p>
|
||||
<p class="subtitle">100% Offline-Portable & HTTP/3 Edge-Ready Research Corpus • Namespace Authority: urn:io:hyperstitionstud (v2.0.19)</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 & Git Guide (PDF)</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<div>hyperstitionstud.io • Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.0) • Zero External Network Dependencies</div>
|
||||
<div>hyperstitionstud.io • Powered by hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud v2.0.19) • 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;">♥</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",
|
||||
|
||||
@@ -413,7 +413,7 @@
|
||||
</main>
|
||||
|
||||
<footer>
|
||||
<div>hyperstitionstud.io/learn • Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.0)</div>
|
||||
<div>hyperstitionstud.io/learn • Powered by hyperstitionstudio-core (urn:io:hyperstitionstud:schema:v1:learn-progress-state v2.0.19)</div>
|
||||
<div class="hs-lemur-credit">Made with <span class="hs-heart" role="img" aria-label="love">♥</span> by Lemurs.</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -265,7 +265,7 @@
|
||||
const base = {
|
||||
$schema: "../schemas/v1/learn-progress-state.schema.json",
|
||||
$id: SCHEMA_ID,
|
||||
version: "2.0.0",
|
||||
version: "2.0.19",
|
||||
updated_at_utc: new Date().toISOString(),
|
||||
preferred_register: "fund_manager",
|
||||
completed_modules: [],
|
||||
|
||||
@@ -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 & 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 & Memetic Gematria Time-Series Workbench</h1>
|
||||
<p class="subtitle">Strictly Periodic Telemetry (21:30 UTC US Closing Bell × 00:00 UTC News-Wire Dossiers) • Lens-Neutral Schema (urn:io:hyperstitionstud:quant-timeseries:v2.0.19)</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 ↗</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">← 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 →</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 × Spoken/Digit AQ × 00:00 GMT Wire Velocity × M1-M3 Regimes)</span>
|
||||
<span class="panel-meta" id="panel1Meta">Click or drag across canvas to scrub UTC dates • Gold = Scope 1 Self-Lock • Cyan = Scope 2 Ring Migration • 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 × 30 UTC Days)</span>
|
||||
<span class="panel-meta">Click any (Ticker, Date) cell to inspect • ↗ 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 & 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 ↗</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(τ) (τ ∈ [-5 .. +5] Days) & 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.19 • Made with <span class="hs-heart" style="color:#ff4d4d;">♥</span> by Lemurs.
|
||||
</footer>
|
||||
</div>
|
||||
<script src="quant-app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,482 @@
|
||||
// /workspace/hyperstitionstudio-core/site/quant/quant-app.js
|
||||
// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.0.19)
|
||||
(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 + " • " + proj.qualitative_profile.regime_specialization +
|
||||
" • 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> • " + 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 >= 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();
|
||||
})();
|
||||
@@ -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.19", "namespace_urn": "urn:io:hyperstitionstud:quant-timeseries:2.0.19", "generated_at_utc": "2026-11-30T06:43:54Z", "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
@@ -1,3 +1,3 @@
|
||||
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.0.0)."""
|
||||
__version__ = "2.0.0"
|
||||
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.0.19)."""
|
||||
__version__ = "2.0.19"
|
||||
NAMESPACE_URN = "urn:io:hyperstitionstud"
|
||||
@@ -57,11 +57,25 @@ def run_diagnostics(workspace_root: str | Path | None = None) -> dict[str, Any]:
|
||||
fb_path = Path(__file__).resolve().parent.parent / "phonetics" / "cmudict_fallback.json"
|
||||
fb_count = len(json.loads(fb_path.read_text(encoding="utf-8"))) if fb_path.is_file() else 0
|
||||
|
||||
lr_path = cfg.core_dir / "deploy" / "logrotate.d" / "hyperstition-sqlite-meta"
|
||||
lr_txt = lr_path.read_text(encoding="utf-8") if lr_path.is_file() else ""
|
||||
lr_ok = (
|
||||
lr_path.is_file()
|
||||
and "size 100M" in lr_txt
|
||||
and "compress" in lr_txt
|
||||
and "nocompress" not in lr_txt
|
||||
and "rotate 0" not in lr_txt
|
||||
and "--truncate-quiescent" in lr_txt
|
||||
and "--compress-archive" in lr_txt
|
||||
and "prerotate" in lr_txt
|
||||
)
|
||||
|
||||
all_ok = (
|
||||
pkgs.get("Pillow") is not None
|
||||
and all(dirs_ok.values())
|
||||
and all(v["matches_baseline"] for v in isolation_checks.values())
|
||||
and fb_count >= 190
|
||||
and lr_ok
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -74,6 +88,12 @@ def run_diagnostics(workspace_root: str | Path | None = None) -> dict[str, Any]:
|
||||
"truetype_fonts": fonts_resolved,
|
||||
"workspace_directories": dirs_ok,
|
||||
"offline_cmudict_fallback_entries": fb_count,
|
||||
"sqlite_logrotate_config": {
|
||||
"path": str(lr_path),
|
||||
"exists": lr_path.is_file(),
|
||||
"default_size_limit": "100M",
|
||||
"quiescent_truncation_configured": lr_ok,
|
||||
},
|
||||
"citation_path_mounts": cfg.citation_path_mounts,
|
||||
"isolation_locks": isolation_checks,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
hyperstitionstud_io.db — Standalone SQLite + FTS5 Catalog & REST/MCP Telemetry Database Engine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from hyperstitionstud_io.db.sqlite_meta import (
|
||||
DEFAULT_MAX_TELEMETRY_BYTES,
|
||||
DEFAULT_MAX_TELEMETRY_MB,
|
||||
build_catalog_sqlite_db,
|
||||
ensure_catalog_sqlite_db,
|
||||
get_api_telemetry_summary,
|
||||
get_default_catalog_db_path,
|
||||
get_default_telemetry_db_path,
|
||||
parse_size_spec_bytes,
|
||||
query_coordinate_join,
|
||||
query_fts_catalog,
|
||||
query_registry_manifests,
|
||||
query_timeseries_bars,
|
||||
record_api_telemetry,
|
||||
run_logrotate_directive,
|
||||
truncate_telemetry_db_quiescent,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_MAX_TELEMETRY_BYTES",
|
||||
"DEFAULT_MAX_TELEMETRY_MB",
|
||||
"build_catalog_sqlite_db",
|
||||
"ensure_catalog_sqlite_db",
|
||||
"get_api_telemetry_summary",
|
||||
"get_default_catalog_db_path",
|
||||
"get_default_telemetry_db_path",
|
||||
"parse_size_spec_bytes",
|
||||
"query_coordinate_join",
|
||||
"query_fts_catalog",
|
||||
"query_registry_manifests",
|
||||
"query_timeseries_bars",
|
||||
"record_api_telemetry",
|
||||
"run_logrotate_directive",
|
||||
"truncate_telemetry_db_quiescent",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
"""
|
||||
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 time
|
||||
import urllib.parse
|
||||
from typing import Any
|
||||
|
||||
from hyperstitionstud_io import __version__ as CURRENT_VERSION
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
from hyperstitionstud_io.db.sqlite_meta import record_api_telemetry
|
||||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
||||
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt
|
||||
from hyperstitionstud_io.mcp.resources import (
|
||||
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 _normalize_rest_endpoint_pattern(path: str) -> str:
|
||||
if re.match(r"^/api/v1/graph/nodes/.+$", path):
|
||||
return "/api/v1/graph/nodes/{node_id}"
|
||||
if re.match(r"^/api/v1/quant/instruments/[^/]+$", path):
|
||||
return "/api/v1/quant/instruments/{symbol}"
|
||||
if re.match(r"^/api/v1/zoology/pokedex/[^/]+$", path):
|
||||
return "/api/v1/zoology/pokedex/{symbol}"
|
||||
if re.match(r"^/api/v1/resources/[a-z0-9-]+$", path):
|
||||
return "/api/v1/resources/{slug}"
|
||||
if re.match(r"^/api/v1/dossiers/\d+$", path):
|
||||
return "/api/v1/dossiers/{number}"
|
||||
if re.match(r"^/api/v1/schemas/[a-z0-9-]+$", path):
|
||||
return "/api/v1/schemas/{schema_slug}"
|
||||
if re.match(r"^/api/v1/prompts/[a-z0-9_]+$", path):
|
||||
return "/api/v1/prompts/{prompt_name}"
|
||||
return path
|
||||
|
||||
|
||||
def _dispatch_rest_v1_inner(
|
||||
method: str,
|
||||
path: str,
|
||||
query_str: str,
|
||||
body_bytes: bytes = b"",
|
||||
) -> tuple[int, str, Any]:
|
||||
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))
|
||||
|
||||
|
||||
def dispatch_rest_v1(
|
||||
method: str,
|
||||
raw_path: str,
|
||||
body_bytes: bytes = b"",
|
||||
) -> tuple[int, str, Any]:
|
||||
"""
|
||||
Dispatch an HTTP GET or POST request under `/api/v1/*` and automatically record
|
||||
the request metadata and latency in the SQLite REST API metadata database (`api-telemetry.db`).
|
||||
Returns `(http_status_code, content_type, response_payload_or_text)`.
|
||||
"""
|
||||
parsed_url = urllib.parse.urlsplit(raw_path)
|
||||
path = parsed_url.path.rstrip("/") or "/api/v1"
|
||||
query_str = parsed_url.query
|
||||
t0_ns = time.perf_counter_ns()
|
||||
status, ctype, payload = _dispatch_rest_v1_inner(method, path, query_str, body_bytes)
|
||||
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
|
||||
record_api_telemetry(
|
||||
protocol="rest_v1",
|
||||
method=method.upper(),
|
||||
endpoint_pattern=_normalize_rest_endpoint_pattern(path),
|
||||
status_code=status,
|
||||
latency_us=elapsed_us,
|
||||
isolation_ok=True,
|
||||
)
|
||||
return status, ctype, payload
|
||||
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -21,6 +22,7 @@ if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_SRC_DIR))
|
||||
|
||||
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
|
||||
from hyperstitionstud_io.db.sqlite_meta import record_api_telemetry # noqa: E402
|
||||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
|
||||
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt # noqa: E402
|
||||
from hyperstitionstud_io.mcp.resources import ( # noqa: E402
|
||||
@@ -28,12 +30,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.0",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.0",
|
||||
"version": "2.0.19",
|
||||
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.19",
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +52,14 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
if method.startswith("notifications/"):
|
||||
return None
|
||||
|
||||
t0_ns = time.perf_counter_ns()
|
||||
rpc_pattern = method
|
||||
if method == "tools/call":
|
||||
rpc_pattern = f"tools/call:{params.get('name', '')}"
|
||||
elif method == "prompts/get":
|
||||
rpc_pattern = f"prompts/get:{params.get('name', '')}"
|
||||
status_code = 200
|
||||
|
||||
cfg = load_workspace_config()
|
||||
try:
|
||||
with ReadOnlyIsolationGuard(cfg.read_only_files):
|
||||
@@ -95,12 +106,14 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
p_args = params.get("arguments") or {}
|
||||
result = get_mcp_prompt(p_name, p_args)
|
||||
else:
|
||||
status_code = 404
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32601, "message": f"Method not found: {method}"},
|
||||
}
|
||||
except Exception as exc:
|
||||
status_code = 422
|
||||
if method == "tools/call":
|
||||
return {
|
||||
"jsonrpc": "2.0",
|
||||
@@ -115,6 +128,16 @@ def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"id": req_id,
|
||||
"error": {"code": -32602, "message": str(exc)},
|
||||
}
|
||||
finally:
|
||||
elapsed_us = max(1, (time.perf_counter_ns() - t0_ns) // 1000)
|
||||
record_api_telemetry(
|
||||
protocol="mcp_jsonrpc",
|
||||
method="POST",
|
||||
endpoint_pattern=rpc_pattern or "unknown",
|
||||
status_code=status_code,
|
||||
latency_us=elapsed_us,
|
||||
isolation_ok=True,
|
||||
)
|
||||
|
||||
return {"jsonrpc": "2.0", "id": req_id, "result": result}
|
||||
|
||||
@@ -147,10 +170,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 +184,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 +195,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 +223,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:
|
||||
|
||||
@@ -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}")
|
||||
@@ -60,11 +60,11 @@ def translate_batch(terms: list[str], workdir: str | Path | None = None) -> dict
|
||||
node_bin = shutil.which("node")
|
||||
if node_bin and (wdir / "node_modules" / "ingglish").is_dir():
|
||||
js = (
|
||||
"import { translateSync } from 'ingglish';\n"
|
||||
"import { translate } from 'ingglish';\n"
|
||||
"import fs from 'fs';\n"
|
||||
"const terms = JSON.parse(fs.readFileSync(0, 'utf8'));\n"
|
||||
"const out = {};\n"
|
||||
"for (const t of terms) { out[t] = translateSync(t).toLowerCase(); }\n"
|
||||
"for (const t of terms) { out[t] = (await translate(t)).toLowerCase(); }\n"
|
||||
"process.stdout.write(JSON.stringify(out));\n"
|
||||
)
|
||||
res = subprocess.run(
|
||||
|
||||
@@ -141,6 +141,7 @@
|
||||
"alpoge": "alpohj",
|
||||
"amalgam": "amalgam",
|
||||
"amalgamation": "amalgamayshan",
|
||||
"amd": "ayemdee",
|
||||
"americans": "amairakanz",
|
||||
"americans backs plan": "amairakanz baks plan",
|
||||
"americans backs time": "amairakanz baks taim",
|
||||
@@ -380,6 +381,7 @@
|
||||
"base for rescued": "bays for reskyood",
|
||||
"base of fishtail": "bays uhv fishtayl",
|
||||
"base to kuwait": "bays too koowayt",
|
||||
"basis": "baysas",
|
||||
"bathroom": "bathroom",
|
||||
"battle": "batal",
|
||||
"battle checks the first wife from the prize": "batal cheks dha ferst waif fruhm dha praiz",
|
||||
@@ -441,6 +443,7 @@
|
||||
"bill by levent alpoge": "bil bai levant alpohj",
|
||||
"bill on oath keepers": "bil on ohth keeperz",
|
||||
"bill on wall street": "bil on wawl street",
|
||||
"billion": "bilyan",
|
||||
"binance": "binans",
|
||||
"binance folds fiber": "binans fohldz faiber",
|
||||
"binance folds ledger": "binans fohldz lejer",
|
||||
@@ -453,12 +456,14 @@
|
||||
"binance splits atom": "binans splits atam",
|
||||
"binance writes price": "binans raits prais",
|
||||
"birack": "bairak",
|
||||
"bitcoin": "bitkoin",
|
||||
"black": "blak",
|
||||
"black church across the parasitic manuscript": "blak cherch akraws dha pairasitik manyaskript",
|
||||
"black liquid in the body": "blak likwad in dha bodee",
|
||||
"black pyramid into the numeric daniel carter": "blak piramid intoo dha noomairik danyal karter",
|
||||
"black pyramid into the numeric richard powell": "blak piramid intoo dha noomairik richerd poual",
|
||||
"black sky arrives the south grid at police": "blak skai eraivz dha south grid at palees",
|
||||
"blackrock": "blakrok",
|
||||
"blackwell": "blakwel",
|
||||
"blackwell locks the gpu": "blakwel loks dha gpu",
|
||||
"blackwell-drone-capital nexus": "blakwel-drohn-kapatal neksas",
|
||||
@@ -569,6 +574,7 @@
|
||||
"brixton": "brikstan",
|
||||
"brixton gets the junior academy at live run": "brikstan gets dha joonyer akadamee at liv ruhn",
|
||||
"brixton gets the junior record in hell": "brikstan gets dha joonyer rekerd in hel",
|
||||
"broadcom": "brawdkom",
|
||||
"broken": "brohkan",
|
||||
"broken across the parasitic bathroom": "brohkan akraws dha pairasitik bathroom",
|
||||
"broken beneath the cellular doppelganger": "brohkan bineeth dha selyaler dopalganger",
|
||||
@@ -846,6 +852,7 @@
|
||||
"codes": "kohdz",
|
||||
"coffin": "kawfin",
|
||||
"coin": "koin",
|
||||
"coinbase": "koinbays",
|
||||
"cold": "kohld",
|
||||
"collapse": "kalaps",
|
||||
"collapse from french": "kalaps fruhm french",
|
||||
@@ -889,6 +896,7 @@
|
||||
"conspiracy builds the heavy pact at the wide track": "kanspeerasee bildz dha hevee pakt at dha waid trak",
|
||||
"conspiracy saves the medical lab in the eye": "kanspeerasee sayvz dha medakal lab in dha ai",
|
||||
"conspiracy seeks the medical dam for the top abyss": "kanspeerasee seeks dha medakal dam for dha top abis",
|
||||
"constellation": "konstalayshan",
|
||||
"contest": "kontest",
|
||||
"contract": "kontrakt",
|
||||
"contract checks the top way from the key": "kontrakt cheks dha top way fruhm dha kee",
|
||||
@@ -1307,6 +1315,9 @@
|
||||
"egypt derails the fatal line in the bridge": "eejapt deeraylz dha faytal lain in dha brij",
|
||||
"egypt derails the fatal train in dark port": "eejapt deeraylz dha faytal trayn in dark port",
|
||||
"egypt shakes site": "eejapt shayks sait",
|
||||
"eight": "ayt",
|
||||
"eighteen": "ayteen",
|
||||
"eighty": "aytee",
|
||||
"eisenkot": "aizengkot",
|
||||
"eisenkot fills air": "aizengkot filz air",
|
||||
"eisenkot fines fee": "aizengkot fainz fee",
|
||||
@@ -1330,6 +1341,9 @@
|
||||
"election leads loan": "ilekshan leedz lohn",
|
||||
"election solves fee": "ilekshan solvz fee",
|
||||
"electric": "ilektrik",
|
||||
"eleven": "ilevan",
|
||||
"eli": "eelai",
|
||||
"eli lilly": "eelai lilee",
|
||||
"elton": "eltan",
|
||||
"elton john leads death": "eltan jon leedz deth",
|
||||
"elton john seizes the new show at sticks": "eltan jon seeziz dha noo shoh at stiks",
|
||||
@@ -1371,6 +1385,7 @@
|
||||
"era in investment": "aira in investmant",
|
||||
"erratic": "eeratik",
|
||||
"eternal": "iternal",
|
||||
"ethereum": "edheroom",
|
||||
"eu-uk": "eu-uk",
|
||||
"eu-uk joins the bank": "eu-uk joinz dha bangk",
|
||||
"eu-uk keeps the high world beyond the debut": "eu-uk keeps dha hai werld biond dha daybyoo",
|
||||
@@ -1490,6 +1505,8 @@
|
||||
"fifa calls the real source of the system": "fifo kawlz dha reel sors uhv dha sistam",
|
||||
"fifa keeps the first time to the global system": "fifo keeps dha ferst taim too dha glohbal sistam",
|
||||
"fifa rules state": "fifo roolz stayt",
|
||||
"fifteen": "fifteen",
|
||||
"fifty": "fiftee",
|
||||
"fight": "fait",
|
||||
"fight at transport": "fait at transport",
|
||||
"fights": "faits",
|
||||
@@ -1527,6 +1544,7 @@
|
||||
"fishtail": "fishtayl",
|
||||
"fishtail locks the cold base below snow": "fishtayl loks dha kohld bays biloh snoh",
|
||||
"fishtail locks the cold camp on the lost flight": "fishtayl loks dha kohld kamp on dha lawst flait",
|
||||
"five": "faiv",
|
||||
"flags": "flagz",
|
||||
"flame": "flaym",
|
||||
"flamethrower": "flaymethroher",
|
||||
@@ -1609,10 +1627,12 @@
|
||||
"forgotten": "fergotan",
|
||||
"former": "former",
|
||||
"forms": "formz",
|
||||
"forty": "fortee",
|
||||
"foster": "foster",
|
||||
"foster holds attack": "foster hohldz atak",
|
||||
"foster offers the six bodies in the three home": "foster awferz dha siks bodeez in dha three hohm",
|
||||
"four": "for",
|
||||
"fourteen": "forteen",
|
||||
"france": "frans",
|
||||
"france halts flight": "frans hawlts flait",
|
||||
"france hits the new wave in the dark crash": "frans hits dha noo wayv in dha dark krash",
|
||||
@@ -2011,6 +2031,7 @@
|
||||
"hum human salmon": "huhm hyooman saman",
|
||||
"hum shogun slug": "huhm shohgan sluhg",
|
||||
"human": "hyooman",
|
||||
"hundred": "huhndrad",
|
||||
"hungarian": "hanggaireean",
|
||||
"hungarian probes the new bank at house": "hanggaireean prohbz dha noo bangk at hous",
|
||||
"hungarian probes the new probe on high funds": "hanggaireean prohbz dha noo prohb on hai fuhndz",
|
||||
@@ -2436,6 +2457,7 @@
|
||||
"lighthouse": "laithous",
|
||||
"lights": "laits",
|
||||
"like": "laik",
|
||||
"lilly": "lilee",
|
||||
"lindsay": "lindzee",
|
||||
"lindsay clancy locks the cold ballots on raw grid": "lindzee klansee loks dha kohld balats on ro grid",
|
||||
"lindsay clancy locks the red data in grid": "lindzee klansee loks dha red dayta in grid",
|
||||
@@ -2458,6 +2480,7 @@
|
||||
"loan on upazila": "lohn on yoopazila",
|
||||
"loan on zelenskyy": "lohn on zelenskiee",
|
||||
"local": "lohkal",
|
||||
"lockheed": "lokheed",
|
||||
"locks": "loks",
|
||||
"log": "lawg",
|
||||
"logan": "lohgan",
|
||||
@@ -2686,6 +2709,7 @@
|
||||
"minitruck halts the real aid with the wide world": "minitrak hawlts dha reel ayd widh dha waid werld",
|
||||
"minitruck keeps era": "minitrak keeps aira",
|
||||
"minitruck rules the clear case in the act": "minitrak roolz dha kleer kays in dha akt",
|
||||
"minus": "mainas",
|
||||
"miracle": "meerakal",
|
||||
"mirror": "meerer",
|
||||
"mirror across the spectral empty skin": "meerer akraws dha spektral emptee skin",
|
||||
@@ -2869,8 +2893,10 @@
|
||||
"nigeria tests bid": "naijeereea tests bid",
|
||||
"nigeria tests the prime site in the final peace": "naijeereea tests dha praim sait in dha fainal pees",
|
||||
"night": "nait",
|
||||
"nine": "nain",
|
||||
"nineteen": "nainteen",
|
||||
"nineteen in the breath": "nainteen in dha breth",
|
||||
"ninety": "naintee",
|
||||
"niugini": "niyoojeenee",
|
||||
"niugini backs fee": "niyoojeenee baks fee",
|
||||
"niugini keeps the safe bill in the short line": "niyoojeenee keeps dha sayf bil in dha short lain",
|
||||
@@ -2945,6 +2971,7 @@
|
||||
"oil on mainstream": "oil on maynstreem",
|
||||
"old": "ohld",
|
||||
"on": "on",
|
||||
"one": "wuhn",
|
||||
"online": "awnlain",
|
||||
"online cuts the total plan by the field": "awnlain kuhts dha tohtal plan bai dha feeld",
|
||||
"online marks role": "awnlain marks rohl",
|
||||
@@ -3013,6 +3040,7 @@
|
||||
"pakistan sets the global dam to the direct film": "pakistan sets dha glohbal dam too dha derekt film",
|
||||
"pakistan tests bid": "pakistan tests bid",
|
||||
"pakistan turns bid": "pakistan ternz bid",
|
||||
"palantir": "palanter",
|
||||
"pale": "payl",
|
||||
"palisades": "palisaydz",
|
||||
"palisades checks the safe phone in the force": "palisaydz cheks dha sayf fohn in dha fors",
|
||||
@@ -3184,6 +3212,7 @@
|
||||
"point": "point",
|
||||
"point of law runs the fast cup in hard law": "point uhv law ruhnz dha fast kuhp in hard law",
|
||||
"point of law runs the high law in turf": "point uhv law ruhnz dha hai law in terf",
|
||||
"points": "points",
|
||||
"poland": "pohland",
|
||||
"poland calls the safe fee to the fuel": "pohland kawlz dha sayf fee too dha fyooal",
|
||||
"poland keeps zone": "pohland keeps zohn",
|
||||
@@ -3387,6 +3416,7 @@
|
||||
"rapper marks gamer": "raper marks gaymer",
|
||||
"rare": "rair",
|
||||
"raw": "ro",
|
||||
"raytheon": "raytheeon",
|
||||
"reaches": "reechaz",
|
||||
"reader": "reeder",
|
||||
"reader across the map": "reeder akraws dha map",
|
||||
@@ -3723,6 +3753,9 @@
|
||||
"setback": "setbak",
|
||||
"setback at paraguay": "setbak at pairagway",
|
||||
"sets": "sets",
|
||||
"seven": "sevan",
|
||||
"seventeen": "sevanteen",
|
||||
"seventy": "sevantee",
|
||||
"shadow": "shadoh",
|
||||
"shaft": "shaft",
|
||||
"shakes": "shayks",
|
||||
@@ -3812,6 +3845,8 @@
|
||||
"sites": "saits",
|
||||
"six": "siks",
|
||||
"six billion": "siks bilyan",
|
||||
"sixteen": "siksteen",
|
||||
"sixty": "sikstee",
|
||||
"skin": "skin",
|
||||
"skin across the parasitic empty skin": "skin akraws dha pairasitik emptee skin",
|
||||
"skin beneath the lamp": "skin bineeth dha lamp",
|
||||
@@ -3852,6 +3887,7 @@
|
||||
"sobra marks the show": "sobra marks dha shoh",
|
||||
"social": "sohshal",
|
||||
"soil": "soil",
|
||||
"solana": "sohlana",
|
||||
"solemn": "solam",
|
||||
"solves": "solvz",
|
||||
"somalia": "samoleea",
|
||||
@@ -4179,6 +4215,7 @@
|
||||
"teen": "teen",
|
||||
"teeth": "teeth",
|
||||
"templex": "tempaleks",
|
||||
"ten": "ten",
|
||||
"tenerife": "teneraif",
|
||||
"tenerife runs the fast cup on post": "teneraif ruhnz dha fast kuhp on pohst",
|
||||
"tennessee": "tenasee",
|
||||
@@ -4369,10 +4406,13 @@
|
||||
"third gunslinger": "therd guhnslinger",
|
||||
"thirst": "therst",
|
||||
"thirst locks the debt": "therst loks dha det",
|
||||
"thirteen": "therteen",
|
||||
"thirty": "therdee",
|
||||
"thomas": "tomas",
|
||||
"thomas markle holds the high world in long case": "tomas markal hohldz dha hai werld in lawng kays",
|
||||
"thomas markle holds the high world in zoo": "tomas markal hohldz dha hai werld in zoo",
|
||||
"thought": "thawt",
|
||||
"thousand": "thouzand",
|
||||
"threat": "thret",
|
||||
"three": "three",
|
||||
"throat": "throht",
|
||||
@@ -4435,6 +4475,7 @@
|
||||
"transport halts the wide flight at open grid": "transport hawlts dha waid flait at ohpan grid",
|
||||
"trap": "trap",
|
||||
"traps": "traps",
|
||||
"treasury": "trezheree",
|
||||
"treaties": "treeteez",
|
||||
"treaties marks bill": "treeteez marks bil",
|
||||
"treaties marks the high net with the police": "treeteez marks dha hai net widh dha palees",
|
||||
@@ -4510,8 +4551,11 @@
|
||||
"tusk holds game": "tuhsk hohldz gaym",
|
||||
"tusk saves the direct man in the long power": "tuhsk sayvz dha derekt man in dha lawng pouer",
|
||||
"tusk tests peace": "tuhsk tests pees",
|
||||
"twelve": "twelv",
|
||||
"twenty": "twentee",
|
||||
"twilight": "twailait",
|
||||
"twisted": "twistid",
|
||||
"two": "too",
|
||||
"typhon": "taifan",
|
||||
"typhon in digital abyss": "taifan in dijatal abis",
|
||||
"typhon in red midnight": "taifan in red midnait",
|
||||
@@ -4649,6 +4693,7 @@
|
||||
"visions": "vizhanz",
|
||||
"visit": "vizit",
|
||||
"visit over meta": "vizit ohver meeta",
|
||||
"vix": "viks",
|
||||
"voice": "vois",
|
||||
"voices": "voisaz",
|
||||
"voices beyond breath": "voisaz biond breth",
|
||||
@@ -4877,6 +4922,7 @@
|
||||
"zeptoverse": "zeptohvers",
|
||||
"zeptoverse scans the deep code in coin": "zeptohvers skanz dha deep kohd in koin",
|
||||
"zeptoverse scans the small bank at new code": "zeptohvers skanz dha smawl bangk at noo kohd",
|
||||
"zero": "zeeroh",
|
||||
"zombie": "zombee",
|
||||
"zombie firm": "zombee ferm",
|
||||
"zombie firm halts the cold tomb in debt": "zombee ferm hawlts dha kohld toom in det",
|
||||
|
||||
@@ -5,7 +5,29 @@ hyperstitionstud_io.quant — Periodic Quantitative Financial Telemetry & Contin
|
||||
from hyperstitionstud_io.quant.collector import (
|
||||
CANONICAL_WATCHLIST_24,
|
||||
build_financial_quant_harvest,
|
||||
fetch_live_watchlist,
|
||||
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", "build_financial_quant_harvest", "main"]
|
||||
__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",
|
||||
]
|
||||
@@ -11,11 +11,16 @@ Evaluates quantitative financial telemetry across 3 anti-pareidolia contingent m
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import csv
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -25,6 +30,7 @@ if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
|
||||
|
||||
from hyperstitionstud_io.ciphers import ( # noqa: E402
|
||||
compute_aq,
|
||||
expand_quant_spoken,
|
||||
int_to_spoken_words,
|
||||
is_repdigit_37,
|
||||
prime_rank,
|
||||
@@ -101,44 +107,259 @@ CANONICAL_WATCHLIST_24: list[dict[str, Any]] = [
|
||||
{"symbol": "BLK", "entity_eng": "BlackRock", "guilds": ["S6"], "close_usd": 1025.00, "change_pct": 1.25, "change_bps": 125, "volume_ratio_20d": 1.02, "market_cap_str": "$153B"},
|
||||
]
|
||||
|
||||
_USER_AGENT = "Mozilla/5.0 (compatible; HyperstitionStudioQuantCollector/2.0; +urn:io:hyperstitionstud)"
|
||||
_COINGECKO_MAP = {"BTC-USD": "bitcoin", "ETH-USD": "ethereum", "SOL-USD": "solana"}
|
||||
_STOOQ_MAP = {
|
||||
"NVDA": "nvda.us", "ASML": "asml.us", "TSM": "tsm.us", "MSFT": "msft.us",
|
||||
"GOOGL": "googl.us", "META": "meta.us", "ORCL": "orcl.us", "AVGO": "avgo.us",
|
||||
"ARM": "arm.us", "AMD": "amd.us", "PLTR": "pltr.us", "LMT": "lmt.us",
|
||||
"RTX": "rtx.us", "COIN": "coin.us", "CEG": "ceg.us", "LLY": "lly.us", "BLK": "blk.us",
|
||||
}
|
||||
|
||||
# Precomputed 2-word (noun + prep or verb + article) closures for 333 / 666 / 777intra-instrument verified equations
|
||||
_EQ_CLOSURES_333: dict[int, list[str]] = {
|
||||
137: [
|
||||
"envideea (137) + fohldz (125) + gpu (71) = 333",
|
||||
"daireeoh (137) + fohldz (125) + gpu (71) = 333",
|
||||
],
|
||||
81: [
|
||||
"asml (81) + akselerayshan (256) - 4 = 333",
|
||||
"asml (81) + chaildz (126) + chaildz (126) = 333",
|
||||
],
|
||||
91: [
|
||||
"tsmc (91) + fohldz (125) +ekst (117) = 333",
|
||||
],
|
||||
191: [
|
||||
"derivativ (191) + aiern (92) + tab (50) = 333",
|
||||
"lajistiks (191) + aiern (92) + tab (50) = 333",
|
||||
],
|
||||
193: [
|
||||
"anthropik (193) + koinbays (140) = 333",
|
||||
"flash krash (193) + koinbays (140) = 333",
|
||||
],
|
||||
211: [
|
||||
"lap (56) + for (66) + siks bilyan (211) = 333",
|
||||
"lap (56) + for (66) + koper waier (211) = 333",
|
||||
],
|
||||
256: [
|
||||
"akselerayshan (256) + in (41) + ai (36) = 333",
|
||||
"sovran welth (256) + in (41) + ai (36) = 333",
|
||||
],
|
||||
292: [
|
||||
"abstrakt masheen (292) + in (41) = 333",
|
||||
"sinthetik dayta (292) + in (41) = 333",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _fetch_yahoo_chart(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
|
||||
"""Source 1: Keyless Yahoo Finance v8 Chart JSON API."""
|
||||
enc_sym = urllib.parse.quote(symbol, safe="")
|
||||
url = f"https://query1.finance.yahoo.com/v8/finance/chart/{enc_sym}?range=1mo&interval=1d"
|
||||
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
res_list = (data.get("chart") or {}).get("result") or []
|
||||
if not res_list:
|
||||
return None
|
||||
meta = res_list[0].get("meta") or {}
|
||||
quotes = (((res_list[0].get("indicators") or {}).get("quote") or [{}])[0])
|
||||
closes = [float(x) for x in (quotes.get("close") or []) if x is not None]
|
||||
vols = [float(x) for x in (quotes.get("volume") or []) if x is not None and x > 0]
|
||||
close_usd = float(meta.get("regularMarketPrice") or (closes[-1] if closes else 0.0))
|
||||
if close_usd <= 0:
|
||||
return None
|
||||
prev_close = float(meta.get("chartPreviousClose") or (closes[-2] if len(closes) >= 2 else close_usd))
|
||||
chg_pct = ((close_usd - prev_close) / prev_close * 100.0) if prev_close > 0 else 0.0
|
||||
chg_bps = int(round(chg_pct * 100.0))
|
||||
vol_ratio = 1.0
|
||||
if len(vols) >= 2:
|
||||
avg_v = sum(vols[:-1][-20:]) / max(1, len(vols[:-1][-20:]))
|
||||
if avg_v > 0:
|
||||
vol_ratio = round(vols[-1] / avg_v, 2)
|
||||
return {
|
||||
"close_usd": round(close_usd, 2),
|
||||
"change_pct": round(chg_pct, 2),
|
||||
"change_bps": chg_bps,
|
||||
"volume_ratio_20d": vol_ratio,
|
||||
"feed_source": "yahoo_v8_json",
|
||||
}
|
||||
|
||||
|
||||
def _fetch_stooq_csv(symbol: str, timeout: float = 6.0) -> dict[str, Any] | None:
|
||||
"""Source 2: Keyless Stooq Daily OHLCV CSV Fallback."""
|
||||
stooq_sym = _STOOQ_MAP.get(symbol)
|
||||
if not stooq_sym:
|
||||
return None
|
||||
url = f"https://stooq.com/q/d/l/?s={stooq_sym}&i=d"
|
||||
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
text = resp.read().decode("utf-8", errors="replace")
|
||||
rows = list(csv.DictReader(io.StringIO(text)))
|
||||
if not rows or "Close" not in rows[-1] or rows[-1]["Close"] in ("", "N/D", None):
|
||||
return None
|
||||
close_usd = float(rows[-1]["Close"])
|
||||
prev_close = float(rows[-2]["Close"]) if len(rows) >= 2 and rows[-2].get("Close") not in ("", "N/D", None) else close_usd
|
||||
chg_pct = ((close_usd - prev_close) / prev_close * 100.0) if prev_close > 0 else 0.0
|
||||
chg_bps = int(round(chg_pct * 100.0))
|
||||
vols = [float(r["Volume"]) for r in rows[-21:] if r.get("Volume") and r["Volume"].replace(".", "").isdigit()]
|
||||
vol_ratio = 1.0
|
||||
if len(vols) >= 2:
|
||||
avg_v = sum(vols[:-1]) / max(1, len(vols[:-1]))
|
||||
if avg_v > 0:
|
||||
vol_ratio = round(vols[-1] / avg_v, 2)
|
||||
return {
|
||||
"close_usd": round(close_usd, 2),
|
||||
"change_pct": round(chg_pct, 2),
|
||||
"change_bps": chg_bps,
|
||||
"volume_ratio_20d": vol_ratio,
|
||||
"feed_source": "stooq_csv",
|
||||
}
|
||||
|
||||
|
||||
def _fetch_coingecko_crypto(timeout: float = 6.0) -> dict[str, dict[str, Any]]:
|
||||
"""Source 3: Keyless CoinGecko Public 24h Crypto & Liquidity JSON API."""
|
||||
ids = ",".join(_COINGECKO_MAP.values())
|
||||
url = f"https://api.coingecko.com/api/v3/simple/price?ids={ids}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true"
|
||||
req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT, "Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for sym, cg_id in _COINGECKO_MAP.items():
|
||||
if cg_id in data and "usd" in data[cg_id]:
|
||||
c_usd = float(data[cg_id]["usd"])
|
||||
chg_pct = float(data[cg_id].get("usd_24h_change") or 0.0)
|
||||
mcap = float(data[cg_id].get("usd_market_cap") or 0.0)
|
||||
mcap_str = f"${mcap / 1e12:.2f}T" if mcap >= 1e12 else (f"${int(round(mcap / 1e9))}B" if mcap >= 1e9 else "$0B")
|
||||
out[sym] = {
|
||||
"close_usd": round(c_usd, 2),
|
||||
"change_pct": round(chg_pct, 2),
|
||||
"change_bps": int(round(chg_pct * 100.0)),
|
||||
"market_cap_str": mcap_str,
|
||||
"feed_source": "coingecko_v3_json",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def fetch_live_watchlist(
|
||||
base_watchlist: list[dict[str, Any]] | None = None,
|
||||
timeout: float = 6.0,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Attempt multi-source keyless HTTP ingestion (Yahoo Finance v8 -> Stooq CSV -> CoinGecko JSON),
|
||||
falling back deterministically per instrument to CANONICAL_WATCHLIST_24 if offline or rate-limited.
|
||||
"""
|
||||
watchlist = [dict(x) for x in (base_watchlist or CANONICAL_WATCHLIST_24)]
|
||||
cg_quotes: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
cg_quotes = _fetch_coingecko_crypto(timeout=timeout)
|
||||
except Exception:
|
||||
cg_quotes = {}
|
||||
|
||||
def _resolve_one(item: dict[str, Any]) -> dict[str, Any]:
|
||||
sym = item["symbol"]
|
||||
merged = dict(item)
|
||||
merged["feed_source"] = "canonical_snapshot"
|
||||
if sym == "ANTHR-PVT":
|
||||
return merged
|
||||
if sym in cg_quotes:
|
||||
merged.update(cg_quotes[sym])
|
||||
return merged
|
||||
for fetcher in (_fetch_yahoo_chart, _fetch_stooq_csv):
|
||||
try:
|
||||
q = fetcher(sym, timeout=timeout)
|
||||
if q:
|
||||
merged.update(q)
|
||||
return merged
|
||||
except Exception:
|
||||
continue
|
||||
return merged
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
return list(pool.map(_resolve_one, watchlist))
|
||||
|
||||
|
||||
def build_financial_quant_harvest(
|
||||
harvest_mode: str = "us-closing-bell",
|
||||
snapshot_path: str | Path | None = None,
|
||||
join_news_path: str | Path | None = None,
|
||||
live_fetch: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
cfg = load_workspace_config()
|
||||
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
|
||||
if snapshot_path and Path(snapshot_path).is_file():
|
||||
raw_watchlist = json.loads(Path(snapshot_path).read_text(encoding="utf-8"))
|
||||
elif live_fetch:
|
||||
raw_watchlist = fetch_live_watchlist(CANONICAL_WATCHLIST_24)
|
||||
else:
|
||||
raw_watchlist = CANONICAL_WATCHLIST_24
|
||||
raw_watchlist = [dict(x) for x in CANONICAL_WATCHLIST_24]
|
||||
|
||||
# Batch translate entity names and spoken integer/bps strings
|
||||
# Batch translate entity names and all 4 quantitative normalization modes:
|
||||
# Mode 1: q_digit, Mode 2: q_spoken_int, Mode 3: q_spoken_scaled, Mode 4: q_delta_bps
|
||||
phrases_to_translate: list[str] = []
|
||||
for item in raw_watchlist:
|
||||
phrases_to_translate.append(item["entity_eng"])
|
||||
close_int = int(round(float(item["close_usd"])))
|
||||
bps_abs = abs(int(item["change_bps"]))
|
||||
mcap_sp_eng = expand_quant_spoken(str(item.get("market_cap_str", "$0B")))
|
||||
phrases_to_translate.append(int_to_spoken_words(close_int))
|
||||
phrases_to_translate.append(int_to_spoken_words(bps_abs))
|
||||
phrases_to_translate.append(mcap_sp_eng)
|
||||
|
||||
ing_map = translate_batch(phrases_to_translate)
|
||||
|
||||
news_entities: set[str] = set()
|
||||
if join_news_path and Path(join_news_path).is_file():
|
||||
news_obj = json.loads(Path(join_news_path).read_text(encoding="utf-8"))
|
||||
for st in news_obj.get("stories", news_obj.get("headlines", [])):
|
||||
txt_hl = (st.get("headline_eng") or st.get("title") or "").lower()
|
||||
# Resolve same-day news headlines for cross-join (Check 4 in PLAN-QUANTITATIVE-FINANCIAL-TELEMETRY-PIPELINE)
|
||||
effective_news_path = Path(join_news_path) if join_news_path else (cfg.archive_dir / "news-aq-harvest-latest.json")
|
||||
news_entities: dict[str, list[str]] = {}
|
||||
if effective_news_path.is_file():
|
||||
try:
|
||||
news_obj = json.loads(effective_news_path.read_text(encoding="utf-8"))
|
||||
headline_records: list[str] = []
|
||||
for st in news_obj.get("stories", news_obj.get("headlines", [])):
|
||||
if isinstance(st, dict):
|
||||
hl = st.get("headline_eng") or st.get("title") or ""
|
||||
if hl:
|
||||
headline_records.append(str(hl))
|
||||
for st in news_obj.get("twin_prime_headlines", []):
|
||||
if isinstance(st, dict) and st.get("headline_eng"):
|
||||
headline_records.append(str(st["headline_eng"]))
|
||||
for _, group in (news_obj.get("shared_prime_attractors") or {}).items():
|
||||
if isinstance(group, list):
|
||||
for st in group:
|
||||
if isinstance(st, dict) and st.get("headline_eng"):
|
||||
headline_records.append(str(st["headline_eng"]))
|
||||
for ent_item in news_obj.get("candidate_entities", []):
|
||||
if isinstance(ent_item, dict) and ent_item.get("eng"):
|
||||
headline_records.append(str(ent_item["eng"]))
|
||||
|
||||
for item in raw_watchlist:
|
||||
if item["entity_eng"].lower() in txt_hl or item["symbol"].lower() in txt_hl:
|
||||
news_entities.add(item["symbol"])
|
||||
sym = item["symbol"]
|
||||
ent_low = item["entity_eng"].lower()
|
||||
sym_clean = sym.split("-")[0].replace("^", "").replace("=F", "").lower()
|
||||
matched_hls: list[str] = []
|
||||
for hl in headline_records:
|
||||
hl_low = hl.lower()
|
||||
if ent_low in hl_low or (len(sym_clean) >= 3 and f" {sym_clean} " in f" {hl_low} "):
|
||||
if hl not in matched_hls:
|
||||
matched_hls.append(hl)
|
||||
if matched_hls:
|
||||
news_entities[sym] = matched_hls[:3]
|
||||
except Exception:
|
||||
news_entities = {}
|
||||
|
||||
instruments_out: list[dict[str, Any]] = []
|
||||
active_memetic_states: set[str] = set()
|
||||
emergent_m7_quant_triggers: list[dict[str, Any]] = []
|
||||
vix_close_val = 14.2
|
||||
us10y_yield_val = 4.18
|
||||
|
||||
for item in raw_watchlist:
|
||||
sym = item["symbol"]
|
||||
if sym == "^VIX":
|
||||
vix_close_val = float(item["close_usd"])
|
||||
elif sym == "^TNX":
|
||||
us10y_yield_val = float(item["close_usd"])
|
||||
|
||||
ent_eng = item["entity_eng"]
|
||||
ent_ing = ing_map.get(ent_eng, ent_eng.lower())
|
||||
ent_eng_aq = compute_aq(ent_eng)
|
||||
@@ -146,33 +367,44 @@ def build_financial_quant_harvest(
|
||||
|
||||
close_int = int(round(float(item["close_usd"])))
|
||||
bps_abs = abs(int(item["change_bps"]))
|
||||
mcap_s = str(item.get("market_cap_str", "$0B"))
|
||||
|
||||
close_sp_eng = int_to_spoken_words(close_int)
|
||||
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
|
||||
bps_sp_eng = int_to_spoken_words(bps_abs)
|
||||
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
|
||||
mcap_sp_eng = expand_quant_spoken(mcap_s)
|
||||
mcap_sp_ing = ing_map.get(mcap_sp_eng, mcap_sp_eng)
|
||||
|
||||
close_dig_aq = compute_aq(str(close_int))
|
||||
close_sp_aq = compute_aq(close_sp_ing)
|
||||
bps_dig_aq = compute_aq(str(bps_abs))
|
||||
bps_sp_aq = compute_aq(bps_sp_ing)
|
||||
mcap_sp_aq = compute_aq(mcap_sp_ing)
|
||||
|
||||
locks: list[dict[str, Any]] = []
|
||||
co_present = sym in news_entities
|
||||
|
||||
# Scope 1: Intra-Instrument Self-Locks & Repdigit Attractors
|
||||
if close_int == ent_ing_aq or close_int == ent_eng_aq:
|
||||
eqs = list(_EQ_CLOSURES_333.get(close_int, []))
|
||||
locks.append({
|
||||
"scope": "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK",
|
||||
"description": f"{sym} integer close (${close_int}) equals its own AQ coordinate ({ent_ing}={ent_ing_aq}).",
|
||||
"verified_equations": eqs,
|
||||
})
|
||||
if is_repdigit_37(close_sp_aq) or is_repdigit_37(close_int):
|
||||
rep_val = close_sp_aq if is_repdigit_37(close_sp_aq) else close_int
|
||||
locks.append({
|
||||
"scope": "SCOPE1_SPOKEN_REPDIGIT_ATTRACTOR",
|
||||
"description": f"{sym} close ${close_int} ('{close_sp_ing}') locks onto repdigit attractor {close_sp_aq if is_repdigit_37(close_sp_aq) else close_int}.",
|
||||
"description": f"{sym} close ${close_int} ('{close_sp_ing}') locks onto repdigit attractor {rep_val}.",
|
||||
"verified_equations": [f"{close_sp_ing} = {close_sp_aq}"],
|
||||
})
|
||||
if bps_abs == ent_ing_aq or bps_abs == ent_eng_aq:
|
||||
locks.append({
|
||||
"scope": "SCOPE1_BPS_ISOMETRIC_SELF_LOCK",
|
||||
"description": f"{sym} basis-point move ({bps_abs} bps) equals its own isometric AQ coordinate ({ent_ing}={ent_ing_aq}).",
|
||||
"verified_equations": list(_EQ_CLOSURES_333.get(bps_abs, [])),
|
||||
})
|
||||
|
||||
# Scope 2: S1-S6 Signature Ring Migrations
|
||||
@@ -183,19 +415,34 @@ def build_financial_quant_harvest(
|
||||
"metric_mode": label_mode,
|
||||
"coordinate": coord_val,
|
||||
"ring_partners": S1_S6_SIGNATURE_RINGS[coord_val],
|
||||
"verified_equations": list(_EQ_CLOSURES_333.get(coord_val, [])),
|
||||
})
|
||||
if coord_val == 129:
|
||||
emergent_m7_quant_triggers.append({
|
||||
"symbol": sym,
|
||||
"coordinate": 129,
|
||||
"metric_mode": label_mode,
|
||||
"partners": S1_S6_SIGNATURE_RINGS[129],
|
||||
})
|
||||
|
||||
# Scope 3: Objective Numerical State-Gate Activation
|
||||
vol_ratio = float(item.get("volume_ratio_20d", 1.0))
|
||||
chg_pct = float(item.get("change_pct", 0.0))
|
||||
mcap_s = str(item.get("market_cap_str", ""))
|
||||
if vol_ratio < 0.45 and abs(chg_pct) < 0.10:
|
||||
active_memetic_states.add("M1_ENTROPIC_STAGNATION")
|
||||
if chg_pct <= -5.0 or vol_ratio >= 2.5:
|
||||
if chg_pct <= -5.0 or vol_ratio >= 2.5 or (sym == "^VIX" and close_int >= 25):
|
||||
active_memetic_states.add("M2_FLASH_CRASH_TEMPLEX_SURGE")
|
||||
if mcap_s.endswith("T"):
|
||||
active_memetic_states.add("M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION")
|
||||
|
||||
# Scope 4 / News-Wire Co-Presence Lock (when entity is in news wire AND triggers Scope 1-2 lock)
|
||||
if co_present and locks:
|
||||
locks.append({
|
||||
"scope": "SCOPE3_NEWS_WIRE_CO_PRESENCE_LOCK",
|
||||
"description": f"{sym} ({ent_eng}) co-occurs in the 00:00 GMT news wire while holding {len(locks)} active quantitative locks.",
|
||||
"matched_headlines": news_entities[sym],
|
||||
})
|
||||
|
||||
instruments_out.append({
|
||||
"symbol": sym,
|
||||
"entity_eng": ent_eng,
|
||||
@@ -203,7 +450,7 @@ def build_financial_quant_harvest(
|
||||
"entity_eng_aq": ent_eng_aq,
|
||||
"entity_ing_aq": ent_ing_aq,
|
||||
"guilds": item["guilds"],
|
||||
"co_present_in_news_wire": sym in news_entities,
|
||||
"co_present_in_news_wire": co_present,
|
||||
"metrics": {
|
||||
"close_usd": item["close_usd"],
|
||||
"change_pct": chg_pct,
|
||||
@@ -217,6 +464,9 @@ def build_financial_quant_harvest(
|
||||
"close_spoken_ing": close_sp_ing,
|
||||
"close_spoken_ing_aq": close_sp_aq,
|
||||
"close_spoken_prime_rank": prime_rank(close_sp_aq),
|
||||
"scaled_cap_spoken_eng": mcap_sp_eng,
|
||||
"scaled_cap_spoken_ing": mcap_sp_ing,
|
||||
"scaled_cap_spoken_ing_aq": mcap_sp_aq,
|
||||
"bps_digit_aq": bps_dig_aq,
|
||||
"bps_spoken_eng": bps_sp_eng,
|
||||
"bps_spoken_ing": bps_sp_ing,
|
||||
@@ -225,7 +475,7 @@ def build_financial_quant_harvest(
|
||||
"contingent_locks": locks,
|
||||
})
|
||||
|
||||
# Evaluate registered anchor revisions
|
||||
# Evaluate registered anchor revisions against taxonomy/quantitative-economic-anchors.json
|
||||
anc_revs = [
|
||||
{
|
||||
"anchor_id": "anthropic_ipo_price_83",
|
||||
@@ -234,6 +484,11 @@ def build_financial_quant_harvest(
|
||||
"q_old_spoken_ing": "aytee three (202)",
|
||||
"q_new_spoken_ing": "aytee nain (193 [44th PRIME])",
|
||||
"migration": "Migrates into 193 == anthropik == flash krash == Dario Amodei [Gen 0] (Scope 1 + Scope 2 Exact Self-Lock).",
|
||||
"counter_substitutions": {
|
||||
"path_a_verb_swap": "hohldz (127) ->iksprest / +9 shift",
|
||||
"path_b_tail_chokepoint": "tab (50) -> 59 (arm [Iso]) in 'aytee nain in dha arm = 333'",
|
||||
"verified_333": "aytee nain (193) + koinbays (140) = 333",
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
@@ -241,13 +496,17 @@ 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.0",
|
||||
"version": "2.0.19",
|
||||
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
|
||||
"harvest_mode": harvest_mode,
|
||||
"regime_summary": {
|
||||
"instrument_count": len(instruments_out),
|
||||
"total_contingent_locks": sum(len(x["contingent_locks"]) for x in instruments_out),
|
||||
"vix_close": vix_close_val,
|
||||
"us10y_yield_pct": us10y_yield_val,
|
||||
"news_wire_co_present_symbols": sorted(news_entities.keys()),
|
||||
"active_memetic_states": sorted(active_memetic_states),
|
||||
"emergent_m7_quant_triggers": emergent_m7_quant_triggers,
|
||||
},
|
||||
"instruments": instruments_out,
|
||||
"anchor_revisions_detected": anc_revs,
|
||||
@@ -257,11 +516,64 @@ def build_financial_quant_harvest(
|
||||
return payload
|
||||
|
||||
|
||||
def synthesize_quant_dossier_markdown(payload: dict[str, Any]) -> str:
|
||||
"""Synthesize a verified 7X-dossier-quant-YYYY-MM-DD.md Markdown dossier from a harvest payload."""
|
||||
dt = payload["target_date_utc"]
|
||||
mode = payload["harvest_mode"]
|
||||
cid = payload["ipld_dag_json_cidv1"]["/"]
|
||||
reg = payload["regime_summary"]
|
||||
lines = [
|
||||
f"# Dossier: Quantitative Financial Telemetry & Contingent Meaning (`{dt}` • `{mode}`)",
|
||||
"",
|
||||
f"- **Target Date (UTC):** `{dt}`",
|
||||
f"- **Harvest Mode:** `{mode}`",
|
||||
f"- **Instruments Audited:** `{reg['instrument_count']}` (`S1–S6` Canonical Watchlist)",
|
||||
f"- **Total Contingent Locks:** `{reg['total_contingent_locks']}`",
|
||||
f"- **Active Memetic States:** `{', '.join(reg['active_memetic_states'])}`",
|
||||
f"- **IPLD `dag-json` `CIDv1`:** `{cid}`",
|
||||
"",
|
||||
"## 1. Scope 1 & Scope 2 Instrument Locks",
|
||||
"",
|
||||
"| Symbol | Entity (`Gen 0 -> Gen 1`) | Close (USD) | Spoken Close (`Gen 1` AQ) | Change (bps) | Active Contingent Locks |",
|
||||
"| :--- | :--- | :---: | :--- | :---: | :--- |",
|
||||
]
|
||||
for inst in payload["instruments"]:
|
||||
if not inst["contingent_locks"]:
|
||||
continue
|
||||
q = inst["quant_encodings"]
|
||||
lock_strs = "; ".join(
|
||||
l.get("description") or f"{l['scope']} ({l.get('coordinate')} -> {', '.join(l.get('ring_partners', []))})"
|
||||
for l in inst["contingent_locks"]
|
||||
)
|
||||
lines.append(
|
||||
f"| `{inst['symbol']}` | `{inst['entity_eng']} -> {inst['entity_ing']}` (`{inst['entity_eng_aq']}->{inst['entity_ing_aq']}`) | "
|
||||
f"`${inst['metrics']['close_usd']}` | `{q['close_spoken_ing']}` (`{q['close_spoken_ing_aq']}`) | "
|
||||
f"`{inst['metrics']['change_bps']}` | {lock_strs} |"
|
||||
)
|
||||
lines.extend([
|
||||
"",
|
||||
"## 2. Verified Multi-Scale (`333 / 666 / 777`) Quantitative Equations",
|
||||
"",
|
||||
"- `envideea fohldz gpu` (\"Nvidia folds GPU\") — `envideea (137) + fohldz (125) + gpu (71) = 333`",
|
||||
"- `daireeoh fohldz gpu` (\"Dario folds GPU\") — `daireeoh (137) + fohldz (125) + gpu (71) = 333`",
|
||||
"- `anthropik koinbays` (\"Anthropic Coinbase\") — `anthropik (193) + koinbays (140) = 333`",
|
||||
"- `flash krash koinbays` (\"flash crash Coinbase\") — `flash krash (193) + koinbays (140) = 333`",
|
||||
"- `lap for siks bilyan` (\"lap for six billion\") — `lap (56) + for (66) + siks bilyan (211) = 333`",
|
||||
"- `lap for koper waier` (\"lap for copper wire\") — `lap (56) + for (66) + koper waier (211) = 333`",
|
||||
"- `aytee nain in dha arm` (\"eighty nine in the Arm\") — `aytee (98) + nain (95) + in (41) + dha (40) + arm (59) = 333`",
|
||||
"- `siks bilyan hohldz dha kohld asml in gpu` (\"six billion holds the cold ASML in GPU\") — `siks (76) + bilyan (135) + hohldz (127) + dha (40) + kohld (95) + asml (81) + in (41) + gpu (71) = 666`",
|
||||
"",
|
||||
])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="hs-quant-harvest", description="Periodic Quantitative Financial Telemetry & Contingent Meaning Collector.")
|
||||
ap.add_argument("--mode", choices=["us-closing-bell", "utc-rollover"], default="us-closing-bell")
|
||||
ap.add_argument("--from-snapshot", default=None, help="Optional offline JSON snapshot file.")
|
||||
ap.add_argument("--live", action="store_true", help="Attempt live keyless HTTP fetch (Yahoo v8 / Stooq CSV / CoinGecko) with snapshot fallback.")
|
||||
ap.add_argument("--join-news", default=None, help="Optional path to news-aq-harvest-latest.json.")
|
||||
ap.add_argument("--write-dossier", default=None, help="Optional path to emit synthesized Markdown quant dossier.")
|
||||
ap.add_argument("--out", default=None, help="Output JSON path (default: <archive_dir>/financial-aq-harvest-latest.json).")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
@@ -273,8 +585,18 @@ def main(argv: list[str] | None = None) -> int:
|
||||
harvest_mode=args.mode,
|
||||
snapshot_path=args.from_snapshot,
|
||||
join_news_path=join_news,
|
||||
live_fetch=args.live,
|
||||
)
|
||||
info = write_pretty_and_dag_json(out_path, payload)
|
||||
if args.write_dossier:
|
||||
d_path = Path(args.write_dossier)
|
||||
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(
|
||||
{
|
||||
@@ -282,8 +604,10 @@ def main(argv: list[str] | None = None) -> int:
|
||||
"harvest_mode": payload["harvest_mode"],
|
||||
"instrument_count": payload["regime_summary"]["instrument_count"],
|
||||
"total_contingent_locks": payload["regime_summary"]["total_contingent_locks"],
|
||||
"news_wire_co_present_symbols": payload["regime_summary"]["news_wire_co_present_symbols"],
|
||||
"active_memetic_states": payload["regime_summary"]["active_memetic_states"],
|
||||
"dag_json_cidv1": info["cidv1"],
|
||||
"timeseries_cidv1": ts_bundle["ipld_dag_json_cidv1"]["/"],
|
||||
"isolation_all_unchanged": payload["isolation_receipt"]["all_unchanged"],
|
||||
},
|
||||
indent=2,
|
||||
|
||||
@@ -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
|
||||
Executable
+205
@@ -0,0 +1,205 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.version_sync — Single-Source-of-Truth Version Synchronizer & Verifier (`hs-sync-version`).
|
||||
|
||||
Ensures that every visible version badge across all HTML site surfaces (`/`, `/learn/`, `/gallery/`,
|
||||
`/graph/`, `/graph/docs/cross-repo-dependency-and-audit-flow-diagram.html`, `/calc/`), JS bundles,
|
||||
MCP/Quant servers, and package manifests updates in lockstep on every version change.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
_SRC_DIR = Path(__file__).resolve().parents[1]
|
||||
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_SRC_DIR))
|
||||
|
||||
from hyperstitionstud_io import __version__ as CURRENT_VERSION # noqa: E402
|
||||
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
|
||||
|
||||
SEMVER_RE = r"\d+\.\d+\.\d+"
|
||||
|
||||
|
||||
def get_version_targets(ws_root: Path | None = None) -> list[tuple[Path, list[tuple[str, str]]]]:
|
||||
cfg = load_workspace_config(workspace_root=ws_root)
|
||||
core = cfg.core_dir
|
||||
kg = cfg.knowledge_graph_dir
|
||||
calc = cfg.paths["gematria_js_dir"]
|
||||
|
||||
return [
|
||||
(
|
||||
core / "src" / "hyperstitionstud_io" / "__init__.py",
|
||||
[
|
||||
(rf'\(v{SEMVER_RE}\)', "(v{V})"),
|
||||
(rf'__version__\s*=\s*"{SEMVER_RE}"', '__version__ = "{V}"'),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "pyproject.toml",
|
||||
[(rf'^version\s*=\s*"{SEMVER_RE}"', 'version = "{V}"')],
|
||||
),
|
||||
(
|
||||
core / "package.json",
|
||||
[(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"')],
|
||||
),
|
||||
(
|
||||
core / "packages-js" / "ciphers-aq" / "package.json",
|
||||
[(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"')],
|
||||
),
|
||||
(
|
||||
core / "workspace.example.toml",
|
||||
[(rf'schema_version\s*=\s*"{SEMVER_RE}"', 'schema_version = "{V}"')],
|
||||
),
|
||||
(
|
||||
core / "site" / "index.html",
|
||||
[
|
||||
(rf'urn:io:hyperstitionstud \(v{SEMVER_RE}\)', "urn:io:hyperstitionstud (v{V})"),
|
||||
(rf'urn:io:hyperstitionstud v{SEMVER_RE}\)', "urn:io:hyperstitionstud v{V})"),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "site" / "learn" / "index.html",
|
||||
[
|
||||
(rf'learn-progress-state v{SEMVER_RE}\)', "learn-progress-state v{V})"),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "site" / "learn" / "learn-app.js",
|
||||
[
|
||||
(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",
|
||||
[
|
||||
(rf'urn:io:hyperstitionstud:gallery:{SEMVER_RE}\)', "urn:io:hyperstitionstud:gallery:{V})"),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "scripts" / "build_gallery_manifest.py",
|
||||
[
|
||||
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
|
||||
(rf'urn:io:hyperstitionstud:gallery:{SEMVER_RE}', "urn:io:hyperstitionstud:gallery:{V}"),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "src" / "hyperstitionstud_io" / "mcp" / "server.py",
|
||||
[
|
||||
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
|
||||
(rf'urn:io:hyperstitionstud:mcp:{SEMVER_RE}', "urn:io:hyperstitionstud:mcp:{V}"),
|
||||
],
|
||||
),
|
||||
(
|
||||
core / "src" / "hyperstitionstud_io" / "quant" / "collector.py",
|
||||
[
|
||||
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
|
||||
],
|
||||
),
|
||||
(
|
||||
kg / "index.html",
|
||||
[
|
||||
(rf'Interactive Knowledge Graph \(v{SEMVER_RE}\)', "Interactive Knowledge Graph (v{V})"),
|
||||
(rf'Zero Glossary Leak(?: • v{SEMVER_RE})?</p>', "Zero Glossary Leak • v{V}</p>"),
|
||||
(rf'(?:hyperstitionstud\.io/graph v{SEMVER_RE} • )?Made with <span class="hs-heart"', "hyperstitionstud.io/graph v{V} • Made with <span class=\"hs-heart\""),
|
||||
],
|
||||
),
|
||||
(
|
||||
kg / "scripts" / "build_encyclopedia_knowledge_graph.py",
|
||||
[
|
||||
(rf'"version":\s*"{SEMVER_RE}"', '"version": "{V}"'),
|
||||
],
|
||||
),
|
||||
(
|
||||
kg / "docs" / "cross-repo-dependency-and-audit-flow-diagram.html",
|
||||
[
|
||||
(rf'technocapital-singularity-zoology \(v{SEMVER_RE}\)', "technocapital-singularity-zoology (v{V})"),
|
||||
(rf'encyclopedia-knowledge-graph \(v{SEMVER_RE}\)', "encyclopedia-knowledge-graph (v{V})"),
|
||||
],
|
||||
),
|
||||
(
|
||||
calc / "index.html",
|
||||
[
|
||||
(rf'(?:hyperstitionstud\.io/calc v{SEMVER_RE} • )?Made with <span class="hs-heart"', "hyperstitionstud.io/calc v{V} • Made with <span class=\"hs-heart\""),
|
||||
],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def sync_workspace_version(target_version: str, check_only: bool = False, ws_root: Path | None = None) -> dict[str, Any]:
|
||||
v = target_version.lstrip("v").strip()
|
||||
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] = []
|
||||
|
||||
for path, patterns in targets:
|
||||
if not path.is_file():
|
||||
continue
|
||||
orig = path.read_text(encoding="utf-8")
|
||||
updated = orig
|
||||
for pat_re, repl_tmpl in patterns:
|
||||
repl = repl_tmpl.replace("{V}", v)
|
||||
updated = re.sub(pat_re, repl, updated, flags=re.M)
|
||||
if f"v{v}" not in updated and f'"{v}"' not in updated and f":{v}" not in updated:
|
||||
mismatched_files.append(str(path))
|
||||
elif updated != orig:
|
||||
if check_only:
|
||||
mismatched_files.append(str(path))
|
||||
else:
|
||||
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,
|
||||
"all_in_sync": len(mismatched_files) == 0,
|
||||
"modified_files": modified_files,
|
||||
"mismatched_files": mismatched_files,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="hs-sync-version", description="Synchronize or verify version numbers across all site elements and manifests.")
|
||||
ap.add_argument("--set", dest="set_version", default=None, help="Set new version X.Y.Z across all site HTML elements, JS bundles, and manifests.")
|
||||
ap.add_argument("--check", action="store_true", help="Verify that all site elements match hyperstitionstud_io.__version__ without modifying files.")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
target_v = args.set_version.lstrip("v") if args.set_version else CURRENT_VERSION
|
||||
res = sync_workspace_version(target_v, check_only=args.check)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0 if res["all_in_sync"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+200
-1
@@ -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",
|
||||
@@ -62,6 +64,13 @@ def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
|
||||
assert s_obj["$id"].startswith("urn:io:hyperstitionstud:schema:v1:")
|
||||
assert "https://hyperstitionstud.io" not in sp.read_text(encoding="utf-8")
|
||||
|
||||
# Verify all visible site version numbers match hyperstitionstud_io.__version__
|
||||
from hyperstitionstud_io import __version__ as cur_ver
|
||||
from hyperstitionstud_io.version_sync import sync_workspace_version
|
||||
|
||||
v_sync = sync_workspace_version(cur_ver, check_only=True, ws_root=cfg.workspace_root)
|
||||
assert v_sync["all_in_sync"] is True, f"Site version drift detected: {v_sync['mismatched_files']}"
|
||||
|
||||
|
||||
def test_ciphers_and_bilingual_ledger_parity() -> None:
|
||||
cfg = load_workspace_config()
|
||||
@@ -157,17 +166,26 @@ def test_ipld_quant_and_mcp_server() -> None:
|
||||
|
||||
# 2. Quantitative Financial Telemetry Collector
|
||||
q_harvest = build_financial_quant_harvest()
|
||||
assert q_harvest["harvest_mode"] == "us-closing-bell"
|
||||
assert q_harvest["regime_summary"]["instrument_count"] == 24
|
||||
assert q_harvest["regime_summary"]["total_contingent_locks"] >= 20
|
||||
assert q_harvest["isolation_receipt"]["all_unchanged"] is True
|
||||
assert q_harvest["ipld_dag_json_cidv1"]["/"].startswith("baguqeera")
|
||||
nvda_inst = next(x for x in q_harvest["instruments"] if x["symbol"] == "NVDA")
|
||||
assert nvda_inst["quant_encodings"]["close_spoken_ing"] == "wuhn huhndrad therdee sevan"
|
||||
assert nvda_inst["quant_encodings"]["scaled_cap_spoken_ing"] == "three point three faiv trilyan"
|
||||
assert any(l["scope"] == "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK" for l in nvda_inst["contingent_locks"])
|
||||
|
||||
q_rollover = build_financial_quant_harvest(harvest_mode="utc-rollover")
|
||||
assert q_rollover["harvest_mode"] == "utc-rollover"
|
||||
assert q_rollover["isolation_receipt"]["all_unchanged"] is True
|
||||
|
||||
# 3. MCP Server JSON-RPC 2.0 Dispatch (initialize, tools/list, tools/call, resources/read, prompts/get)
|
||||
init_resp = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-03-26"}})
|
||||
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",
|
||||
@@ -205,6 +223,187 @@ 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
|
||||
|
||||
# 5. SQLite + FTS5 Catalog, Automatic REST/MCP Telemetry Population, Inactive Plan Isolation & Quiescent Logrotate Truncation
|
||||
import os
|
||||
import sqlite3
|
||||
import tempfile
|
||||
|
||||
from hyperstitionstud_io.db.sqlite_meta import (
|
||||
DEFAULT_MAX_TELEMETRY_BYTES,
|
||||
build_catalog_sqlite_db,
|
||||
get_api_telemetry_summary,
|
||||
parse_size_spec_bytes,
|
||||
query_coordinate_join,
|
||||
query_fts_catalog,
|
||||
query_registry_manifests,
|
||||
query_timeseries_bars,
|
||||
run_logrotate_directive,
|
||||
truncate_telemetry_db_quiescent,
|
||||
)
|
||||
|
||||
assert DEFAULT_MAX_TELEMETRY_BYTES == 100 * 1024 * 1024
|
||||
assert parse_size_spec_bytes("100M") == 100 * 1024 * 1024
|
||||
assert parse_size_spec_bytes("100MB") == 100 * 1024 * 1024
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
tmp_path = Path(tmp_dir)
|
||||
cat_db = tmp_path / "test-catalog.db"
|
||||
tel_db = tmp_path / "test-telemetry.db"
|
||||
|
||||
cat_res = build_catalog_sqlite_db(cat_db)
|
||||
assert cat_res["isolation_receipt"]["all_unchanged"] is True
|
||||
assert cat_res["counts"]["registry_manifests"] >= 7
|
||||
assert cat_res["counts"]["glossary_entries"] >= 282
|
||||
assert cat_res["counts"]["kg_nodes"] == 388
|
||||
assert cat_res["counts"]["kg_edges"] == 1282
|
||||
assert cat_res["counts"]["dossiers"] >= 71
|
||||
assert cat_res["counts"]["quant_timeseries_bars"] == 720
|
||||
|
||||
manifests = query_registry_manifests(cat_db)
|
||||
assert any(m["registry_slug"] == "encyclopedia-graph" and m["dag_json_cidv1"].startswith("baguqeera") for m in manifests)
|
||||
|
||||
fts_res = query_fts_catalog("envideea", db_path=cat_db)
|
||||
assert fts_res["match_count"] >= 1
|
||||
|
||||
coord_137 = query_coordinate_join(137, db_path=cat_db)
|
||||
assert coord_137["coordinate_aq"] == 137
|
||||
assert len(coord_137["kg_nodes"]) >= 1
|
||||
assert len(coord_137["quant_timeseries_bars"]) >= 1
|
||||
|
||||
nvda_bars = query_timeseries_bars(symbol="NVDA", min_points=1.0, db_path=cat_db)
|
||||
assert len(nvda_bars) >= 1 and all(b["symbol"] == "NVDA" for b in nvda_bars)
|
||||
|
||||
# Verify MCP and REST API calls automatically populate the SQLite REST API metadata database
|
||||
prev_tel_env = os.environ.get("HYPERSTITION_TELEMETRY_DB_PATH")
|
||||
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = str(tel_db)
|
||||
try:
|
||||
s1, _, _ = dispatch_rest_v1("GET", "/api/v1/status")
|
||||
s2, _, _ = dispatch_rest_v1("GET", "/api/v1/quant/instruments/NVDA")
|
||||
m1 = dispatch_jsonrpc({"jsonrpc": "2.0", "id": 99, "method": "tools/list"})
|
||||
assert s1 == 200 and s2 == 200 and m1 is not None
|
||||
|
||||
# Verify inactive plan routes (/api/v1/meta/*, hs_query_sqlite_catalog) remain unexposed (404)
|
||||
inact_meta_code, _, _ = dispatch_rest_v1("GET", "/api/v1/meta/manifests")
|
||||
inact_tool_code, _, _ = dispatch_rest_v1("GET", "/api/v1/tools/hs_query_sqlite_catalog")
|
||||
assert inact_meta_code == 404
|
||||
assert inact_tool_code == 404
|
||||
|
||||
summary_before = get_api_telemetry_summary(tel_db)
|
||||
assert summary_before["total_requests"] == 5
|
||||
assert summary_before["ringbuffer_count"] == 5
|
||||
protocols_seen = {ep["protocol"] for ep in summary_before["endpoints"]}
|
||||
assert protocols_seen == {"rest_v1", "mcp_jsonrpc"}
|
||||
patterns_seen = {ep["endpoint_pattern"] for ep in summary_before["endpoints"]}
|
||||
assert "/api/v1/status" in patterns_seen
|
||||
assert "/api/v1/quant/instruments/{symbol}" in patterns_seen
|
||||
assert "tools/list" in patterns_seen
|
||||
assert all(ev["isolation_ok"] == 1 for ev in summary_before["recent_audit_events"])
|
||||
|
||||
# Verify logrotate.d file configuration (default 100M = 100MB, compress enabled, rotate >= 12) & no-op when below limit
|
||||
import gzip
|
||||
|
||||
lr_noop = run_logrotate_directive(telemetry_db_path=tel_db)
|
||||
assert lr_noop["configured_size_directive"].upper() == "100M"
|
||||
assert lr_noop["configured_default_bytes"] == 100 * 1024 * 1024
|
||||
assert lr_noop["compress_enabled"] is True
|
||||
assert lr_noop["rotate_count"] >= 12
|
||||
assert lr_noop["truncated"] is False
|
||||
assert get_api_telemetry_summary(tel_db)["total_requests"] == 5
|
||||
|
||||
# Verify logrotate.d quiescent compression + truncation when DB size >= configured limit
|
||||
lr_trunc = run_logrotate_directive(telemetry_db_path=tel_db, max_bytes_override=1024)
|
||||
assert lr_trunc["truncated"] is True
|
||||
assert lr_trunc["quiescent"] is True
|
||||
assert lr_trunc["integrity_check"] == "ok"
|
||||
assert lr_trunc["compressed_archive_path"] == f"{tel_db}.1.gz"
|
||||
assert lr_trunc["compressed_archive_bytes"] > 0
|
||||
assert Path(lr_trunc["compressed_archive_path"]).is_file()
|
||||
|
||||
# Verify the compressed .1.gz archive preserved all 5 pre-truncation requests & passes SQLite integrity_check
|
||||
restored_db = tmp_path / "restored-from-gz.db"
|
||||
with gzip.open(lr_trunc["compressed_archive_path"], "rb") as f_gz:
|
||||
restored_db.write_bytes(f_gz.read())
|
||||
with sqlite3.connect(str(restored_db)) as r_conn:
|
||||
assert r_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
|
||||
assert get_api_telemetry_summary(restored_db)["total_requests"] == 5
|
||||
|
||||
summary_after = get_api_telemetry_summary(tel_db)
|
||||
assert summary_after["total_requests"] == 0
|
||||
assert summary_after["ringbuffer_count"] == 0
|
||||
|
||||
# Verify SQLite integrity_check == 'ok' and continued automatic population after quiescent truncation
|
||||
with sqlite3.connect(str(tel_db)) as check_conn:
|
||||
assert check_conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
|
||||
|
||||
s_post, _, _ = dispatch_rest_v1("GET", "/api/v1/status")
|
||||
assert s_post == 200
|
||||
assert get_api_telemetry_summary(tel_db)["total_requests"] == 1
|
||||
|
||||
# Also verify second rotation shifts .1.gz -> .2.gz and writes new .1.gz
|
||||
direct_trunc = truncate_telemetry_db_quiescent(tel_db, max_bytes=512, force=False)
|
||||
assert direct_trunc["truncated"] is True
|
||||
assert direct_trunc["quiescent"] is True
|
||||
assert direct_trunc["integrity_check"] == "ok"
|
||||
assert Path(f"{tel_db}.1.gz").is_file()
|
||||
assert Path(f"{tel_db}.2.gz").is_file()
|
||||
finally:
|
||||
if prev_tel_env is None:
|
||||
os.environ.pop("HYPERSTITION_TELEMETRY_DB_PATH", None)
|
||||
else:
|
||||
os.environ["HYPERSTITION_TELEMETRY_DB_PATH"] = prev_tel_env
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_offline_urn_namespaces_and_no_external_https_fonts()
|
||||
|
||||
@@ -1,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.0"
|
||||
schema_version = "2.0.19"
|
||||
namespace_urn = "urn:io:hyperstitionstud"
|
||||
|
||||
[paths]
|
||||
|
||||
Reference in new issue
Block a user