diff --git a/README.md b/README.md index 4de590e..a5b2e5b 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.10.0`) +# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v2.12.0`) -> **Gitea Commit & Release Telemetry (`v2.10.0` • Namespace `urn:io:hyperstitionstud`)** +> **Gitea Commit & Release Telemetry (`v2.12.0` • Namespace `urn:io:hyperstitionstud`)** > - **Repository Role & Public Route:** Shared PEP 420 Python core library (`hyperstitionstud_io.*`), MCP/REST server, `/quant/`, `/learn/`, `/engineering/`, `/math/`, & `/donate/` webroots → [`https://hyperstitionstud.io/`](https://hyperstitionstud.io/) -> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.10.0 release state across 2 tracked module/artifact surface(s) -> - **Touched Files / Surfaces:** `deploy/sync-vps-repos.sh`, `src/hyperstitionstud_io/publishing/readme_sync.py` -> - **Live Verified Ecosystem Metrics (`v2.10.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data +> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.12.0 release state across 68 tracked module/artifact surface(s) +> - **Touched Files / Surfaces:** `deploy/Caddyfile`, `deploy/logrotate.d/hyperstition-sqlite-meta`, `deploy/sync-vps-repos.sh`, `deploy/test-first-deployment.sh`, `package.json`, `packages-js/ciphers-aq/package.json`, `pyproject.toml`, `scripts/build_gallery_manifest.py` (+60 more) +> - **Live Verified Ecosystem Metrics (`v2.12.0`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data Shared Python common library (`hyperstitionstud_io.*`), stateless read-only Model Context Protocol (`/mcp`) & OpenAPI 3.1 REST (`/api/v1/*`) server, SQLite FTS5 metadata catalog (`hs-db-build`), offline `URN:` JSON Schema registry (`urn:io:hyperstitionstud:schema:v1:*`), and Group 3 Stealth Basalt web workbenches (`/`, `/learn/`, `/quant/`, `/engineering/`, `/math/`, `/donate/`) with the 4-Ring Hardened Polyglot REPL (`Guile Scheme`, `TypeScript`, `Rust`) and Subtle Cybernetic Code Rain (`hs-matrix-coderain.js`). @@ -50,7 +50,7 @@ python3 hyperstitionstudio-core/tests/test_core_suite.py --- -## Key Architecture & Capabilities (`v2.10.0`) +## Key Architecture & Capabilities (`v2.12.0`) 1. **17 CLI Entrypoints (`pyproject.toml [project.scripts]`):** - `hs-doctor`, `hs-citations`, `hs-pdf-build`, `hs-kg-build`, `hs-quant-harvest`, `hs-macro-harvest`, `hs-daily-brief`, `hs-ticker-card`, `hs-mcp`, `hs-db-build`, `hs-sync-version`, `hs-readme-sync`, `hs-archive-rotate`, `hs-public-smoke`, `hs-eng-docs`, `hs-math-docs`, and `hs-highlights`. diff --git a/deploy/Caddyfile b/deploy/Caddyfile index a19fc12..c676c5e 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -10,7 +10,8 @@ www.hyperstitionstud.io { } hyperstitionstud.io { - encode zstd gzip + @compressible not path *.gz *.br *.tgz *.xz *.zst *.zip *.woff2 *.png *.mp3 *.pdf + encode @compressible zstd gzip # Zero-PII Route Counter Log (Strategy 3A — remote_ip, client_ip, Cookie, User-Agent, and Referer deleted) log { diff --git a/deploy/logrotate.d/hyperstition-sqlite-meta b/deploy/logrotate.d/hyperstition-sqlite-meta index b3291be..dbcc654 100644 --- a/deploy/logrotate.d/hyperstition-sqlite-meta +++ b/deploy/logrotate.d/hyperstition-sqlite-meta @@ -21,8 +21,7 @@ /var/lib/hyperstitionstud.io/api-telemetry.db { size 100M rotate 12 - compress - delaycompress + nocompress missingok notifempty nocreate diff --git a/deploy/sync-vps-repos.sh b/deploy/sync-vps-repos.sh index bfef551..483bf0f 100755 --- a/deploy/sync-vps-repos.sh +++ b/deploy/sync-vps-repos.sh @@ -49,6 +49,14 @@ DO_CADDY=1 for arg in "$@"; do case "${arg}" in + --repos-root=*) + REPOS_ROOT="${arg#*=}" + export REPOS_ROOT + ;; + --live-repos=*) + LIVE_REPOS="${arg#*=}" + export LIVE_REPOS + ;; --no-pull) DO_PULL=0 ;; @@ -168,7 +176,13 @@ for entry in "${REPOS[@]}"; do fi if [[ -d "${REPOS_ROOT}/${repo}" ]]; then ${LIVE_SUDO} mkdir -p "${LIVE_REPOS}/${repo}" - run_checked "rsync ${repo}" ${LIVE_SUDO} rsync -a --delete --exclude='.git' "${REPOS_ROOT}/${repo}/" "${LIVE_REPOS}/${repo}/" + run_checked "rsync ${repo}" ${LIVE_SUDO} rsync -a --delete \ + --filter='P *.gz' \ + --filter='P *.br' \ + --exclude='.git' \ + --exclude='completed-plans-archive.tar.gz' \ + --exclude='inactive-plans-archive.tar.gz' \ + "${REPOS_ROOT}/${repo}/" "${LIVE_REPOS}/${repo}/" fi done @@ -198,15 +212,46 @@ ${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/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 [[ -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 {} \; +echo "[4/5] Pre-compressing static HTML, JS, JSON, XML, Canvas, MD & CSS assets (< 5 MB) (.br / .gz) incrementally in parallel & enforcing single-layer (1x) compression..." +run_checked "cleanup multi-compressed and orphaned sidecars" ${LIVE_SUDO} bash -c ' + find "$1" -type f \( -name "*.gz.gz" -o -name "*.gz.br" -o -name "*.br.gz" -o -name "*.br.br" -o -name "*.tgz.gz" -o -name "*.tgz.br" \) -delete + while IFS= read -r -d "" sc; do + base="${sc%.*}" + if [[ ! -f "${base}" ]]; then + rm -f "${sc}" + fi + done < <(find "$1" -type f \( -name "*.html.gz" -o -name "*.html.br" -o -name "*.js.gz" -o -name "*.js.br" -o -name "*.json.gz" -o -name "*.json.br" -o -name "*.graphml.gz" -o -name "*.graphml.br" -o -name "*.gexf.gz" -o -name "*.gexf.br" -o -name "*.canvas.gz" -o -name "*.canvas.br" -o -name "*.css.gz" -o -name "*.css.br" -o -name "*.md.gz" -o -name "*.md.br" \) -print0) +' _ "${LIVE_REPOS}" +JOBS="$(nproc 2>&1 || echo 4)" +if [[ ! "${JOBS}" =~ ^[0-9]+$ ]] || [[ "${JOBS}" -lt 1 ]]; then + JOBS=4 fi +run_checked "incremental parallel gzip pre-compression" ${LIVE_SUDO} bash -c ' + live="$1" + jobs="$2" + while IFS= read -r -d "" f; do + if [[ ! -f "${f}.gz" || "${f}" -nt "${f}.gz" ]]; then + printf "%s\0" "${f}" + fi + done < <(find "${live}" -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" \) -print0) \ + | xargs -0 -r -P "${jobs}" -n 16 gzip -9 -k -f +' _ "${LIVE_REPOS}" "${JOBS}" +if [[ -n "$(type -P brotli || true)" ]]; then + run_checked "incremental parallel brotli pre-compression" ${LIVE_SUDO} bash -c ' + live="$1" + jobs="$2" + while IFS= read -r -d "" f; do + if [[ ! -f "${f}.br" || "${f}" -nt "${f}.br" ]]; then + printf "%s\0" "${f}" + fi + done < <(find "${live}" -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" \) -print0) \ + | xargs -0 -r -P "${jobs}" -n 16 brotli -q 11 -k -f + ' _ "${LIVE_REPOS}" "${JOBS}" +fi +run_checked "hs-archive-rotate --enforce-single-compression" "${PYTHON_BIN}" -m hyperstitionstud_io.publishing.archive_rotator \ + --workspace-root "${REPOS_ROOT}" \ + --enforce-single-compression \ + --extra-scan-dir "${LIVE_REPOS}" # Step 5: Idempotent systemd unit, logrotate.d & /etc/caddy/Caddyfile synchronization (enabled by default; skip with --no-caddy) if [[ "${DO_CADDY}" -eq 1 ]]; then diff --git a/deploy/test-first-deployment.sh b/deploy/test-first-deployment.sh index 429345d..e96dec1 100755 --- a/deploy/test-first-deployment.sh +++ b/deploy/test-first-deployment.sh @@ -89,8 +89,10 @@ ROUTES=( "/graph/docs/periodic-harvest-cicd-to-vps-flow-diagram.png" "/graph/docs/VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.pdf" "/graph/docs/OPERATORS-MANUAL-LLM-TOKEN-DEPENDENT-DATA-PIPELINES.pdf" - "/graph/docs/plans/piecewise/PLAN-PIECEWISE-COMPLETE-SOFTWARE-ENGINEERING-EXPLICATION.pdf" - "/graph/docs/plans/piecewise/PLAN-PIECEWISE-COMPLETE-MATHEMATICS-AND-INFO-SCIENCE-EXPLICATION.pdf" + "/graph/docs/archive/archive-manifest.json" + "/graph/docs/plans/inactive/inactive-archive-manifest.json" + "/graph/docs/plans/inactive/PLAN-PIECEWISE-COMPLETE-SOFTWARE-ENGINEERING-EXPLICATION.pdf" + "/graph/docs/plans/inactive/PLAN-PIECEWISE-COMPLETE-MATHEMATICS-AND-INFO-SCIENCE-EXPLICATION.pdf" "/graph/docs/plans/inactive/PLAN-LEXICAL-AND-ETYMOLOGICAL-SIMPLIFICATION.pdf" "/graph/docs/plans/inactive/PLAN-LLM-TOKEN-ECONOMIZER-AND-VARIANCE-ROUTING.pdf" "/graph/docs/plans/inactive/PLAN-LLM-TOKEN-ECONOMIZER-DATA-FIDELITY-AND-DEGRADATION-RISK-EVALUATION.pdf" diff --git a/package.json b/package.json index 7853837..040279e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/workspace-core", - "version": "2.10.0", + "version": "2.12.0", "private": true, "description": "Offline-first ESM & browser global (@hyperstitionstud.io/* / window.HyperstitionStudio.*) packages for Base-36 AQ ciphers and interactive knowledge graph workbenches.", "license": "MIT", diff --git a/packages-js/ciphers-aq/package.json b/packages-js/ciphers-aq/package.json index da2d3fa..21bab4a 100644 --- a/packages-js/ciphers-aq/package.json +++ b/packages-js/ciphers-aq/package.json @@ -1,6 +1,6 @@ { "name": "@hyperstitionstud.io/ciphers-aq", - "version": "2.10.0", + "version": "2.12.0", "type": "module", "main": "index.js", "license": "MIT" diff --git a/pyproject.toml b/pyproject.toml index e77ce4a..cb628a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "hyperstitionstudio-core" -version = "2.10.0" +version = "2.12.0" description = "Shared PEP 420 common library (hyperstitionstud_io.*) for Base-36 AQ ciphers, offline CMUdict Ingglish phonetics, ReportLab/Pillow publishing, SHA-256 glossary isolation guards, local-config citation verification, and multi-format knowledge graphs." readme = "README.md" requires-python = ">=3.10" diff --git a/scripts/build_gallery_manifest.py b/scripts/build_gallery_manifest.py index 85d3796..b45e304 100755 --- a/scripts/build_gallery_manifest.py +++ b/scripts/build_gallery_manifest.py @@ -144,8 +144,8 @@ def main() -> int: }) manifest = { - "version": "2.10.0", - "namespace_urn": "urn:io:hyperstitionstud:gallery:2.10.0", + "version": "2.12.0", + "namespace_urn": "urn:io:hyperstitionstud:gallery:2.12.0", "total_items": len(items), "items": items, } diff --git a/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png b/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png index aecded4..248f617 100644 Binary files a/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png and b/site/assets/closeups/quadrant-1-cybermemetics-calc-graph.png differ diff --git a/site/assets/closeups/quadrant-1-tab-2-graph.png b/site/assets/closeups/quadrant-1-tab-2-graph.png index 14a8e0c..d79cb8d 100644 Binary files a/site/assets/closeups/quadrant-1-tab-2-graph.png and b/site/assets/closeups/quadrant-1-tab-2-graph.png differ diff --git a/site/assets/closeups/quadrant-2-esoteric-finance-quant.png b/site/assets/closeups/quadrant-2-esoteric-finance-quant.png index 0e92e06..fc0d687 100644 Binary files a/site/assets/closeups/quadrant-2-esoteric-finance-quant.png and b/site/assets/closeups/quadrant-2-esoteric-finance-quant.png differ diff --git a/site/assets/closeups/quadrant-2-tab-2-bayesian-fred.png b/site/assets/closeups/quadrant-2-tab-2-bayesian-fred.png index d957cdf..69e38e2 100644 Binary files a/site/assets/closeups/quadrant-2-tab-2-bayesian-fred.png and b/site/assets/closeups/quadrant-2-tab-2-bayesian-fred.png differ diff --git a/site/assets/closeups/quadrant-2-tab-3-leaderboard-card.png b/site/assets/closeups/quadrant-2-tab-3-leaderboard-card.png index 466a10d..8959b8a 100644 Binary files a/site/assets/closeups/quadrant-2-tab-3-leaderboard-card.png and b/site/assets/closeups/quadrant-2-tab-3-leaderboard-card.png differ diff --git a/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png b/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png index 152a5bb..28dbad3 100644 Binary files a/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png and b/site/assets/closeups/quadrant-3-info-science-novice-learn-polyglot.png differ diff --git a/site/assets/closeups/quadrant-3-tab-2-math-guile.png b/site/assets/closeups/quadrant-3-tab-2-math-guile.png index b1b2b70..ce7de22 100644 Binary files a/site/assets/closeups/quadrant-3-tab-2-math-guile.png and b/site/assets/closeups/quadrant-3-tab-2-math-guile.png differ diff --git a/site/assets/closeups/quadrant-3-tab-3-math-ts-rust.png b/site/assets/closeups/quadrant-3-tab-3-math-ts-rust.png index 4ab3a18..731354e 100644 Binary files a/site/assets/closeups/quadrant-3-tab-3-math-ts-rust.png and b/site/assets/closeups/quadrant-3-tab-3-math-ts-rust.png differ diff --git a/site/assets/closeups/quadrant-4-operators-deployment-vps.png b/site/assets/closeups/quadrant-4-operators-deployment-vps.png index a3dc324..378d311 100644 Binary files a/site/assets/closeups/quadrant-4-operators-deployment-vps.png and b/site/assets/closeups/quadrant-4-operators-deployment-vps.png differ diff --git a/site/assets/closeups/quadrant-4-tab-2-mcp-etag.png b/site/assets/closeups/quadrant-4-tab-2-mcp-etag.png index 8b05d81..f5f6a67 100644 Binary files a/site/assets/closeups/quadrant-4-tab-2-mcp-etag.png and b/site/assets/closeups/quadrant-4-tab-2-mcp-etag.png differ diff --git a/site/assets/closeups/quadrant-4-tab-3-ci-gates.png b/site/assets/closeups/quadrant-4-tab-3-ci-gates.png index 6890a8a..0c75f4c 100644 Binary files a/site/assets/closeups/quadrant-4-tab-3-ci-gates.png and b/site/assets/closeups/quadrant-4-tab-3-ci-gates.png differ diff --git a/site/assets/closeups/ui-elements-manifest.json b/site/assets/closeups/ui-elements-manifest.json index 2b862f2..8065bc8 100644 --- a/site/assets/closeups/ui-elements-manifest.json +++ b/site/assets/closeups/ui-elements-manifest.json @@ -1,6 +1,6 @@ { "$id": "urn:io:hyperstitionstud:closeups-ui-manifest", - "ui_elements_fingerprint_sha256": "8f92e3c928a040caab84574cb87213814a0f5b765971c4a01419966ee05d9ee9", + "ui_elements_fingerprint_sha256": "fa44109fa10578953fb173c9e1df91cc4ebf4b33882c2bd5b1a9e317bb5d8cca", "closeup_images": [ "quadrant-1-cybermemetics-calc-graph.png", "quadrant-1-tab-2-graph.png", @@ -69,8 +69,8 @@ ] }, "quant": { - "ui_structure_sha256": "45d9297b103421bada5d84005b5406d5852aa3220ad63c9a2809efa3fdd6541b", - "id_count": 66, + "ui_structure_sha256": "6a8617125aa3a61d26a55c87cb39c0be18aff4fcf79e62e6d4700c49389283e6", + "id_count": 67, "button_count": 21, "option_count": 0, "input_count": 2, @@ -137,6 +137,7 @@ "tutSpeechBtn", "tutStepBadge", "tutSubtitleText", + "tutUiElementIndicator", "vol20d_regimes", "wireEqTape", "wireTapeFilterInput", @@ -604,7 +605,179 @@ "sample_headings": [] } }, + "js_surfaces": { + "quant_app_js": { + "js_ui_sha256": "6d5239bdc10247344a7bb50636f9e3c8d9fc3be0e8d6232a257c735dea5ec0bf", + "dom_ids": [ + "activeDateBadge", + "dailyBriefContainer", + "dateMetricsGrid", + "docReferencesCard", + "exportCsvBtn", + "exportJsonBtn", + "guildFilterPills", + "heatmapPaginationBar", + "heatmapTable", + "hmNextPageBtn", + "hmPrevPageBtn", + "hmToggleAllBtn", + "lagBarsContainer", + "lensProjectionCard", + "lensSelect", + "macroIndicatorsGrid", + "metricModePills", + "navCalc", + "navDonate", + "navGraph", + "navHome", + "navLearn", + "navManual", + "nextDateBtn", + "openTradingViewBtn", + "panel3Title", + "panel3TvBtn", + "passagePreviewBox", + "periodicityAuditFooter", + "popCloseBtn", + "prevDateBtn", + "quantInfoPopover", + "tickerQuickFilter", + "tickerSelect", + "timeWindowPills", + "tsCanvas", + "wireEqTape", + "wireTapeFilterInput", + "wireTapeHeader" + ], + "ui_targets": [], + "ep_codes": [], + "speech_text_count": 0, + "lens_keys": [], + "has_ui_indicator_badge": false, + "has_lens_select_highlight": true + }, + "quant_tutorials_js": { + "js_ui_sha256": "b9174978ea8b9dce2d35f557bcb8b3b4c7f367dc41d0d7c3de8ee7f4dd8f894c", + "dom_ids": [ + "tutCitationPills", + "tutClearSpotlightBtn", + "tutEpisodeTabs", + "tutKeyframeTitle", + "tutNextBtn", + "tutPlayPauseBtn", + "tutPrevBtn", + "tutScrubber", + "tutSpeechBtn", + "tutStepBadge", + "tutSubtitleText", + "tutUiElementIndicator" + ], + "ui_targets": [ + "\"dailyBriefPanel\", \"lensSelect\"", + "\"docReferencesCard\"", + "\"exportCsvBtn\", \"exportJsonBtn\"", + "\"guildFilterPills\", \"tickerQuickFilter\", \"tickerSelect\"", + "\"guildFilterPills\", \"tickerSelect\"", + "\"heatmapTable\", \"dateMetricsGrid\"", + "\"lagBarsContainer\"", + "\"lensSelect\", \"lensProjectionCard\"", + "\"macroIndicatorsPanel\", \"docReferencesCard\"", + "\"metricModePills\", \"tsCanvas\"", + "\"openTradingViewBtn\", \"panel3TvBtn\"", + "\"periodicityAuditFooter\"", + "\"tickerSelect\", \"docReferencesCard\"", + "\"tickerSelect\", \"lagBarsContainer\"", + "\"tickerSelect\", \"metricModePills\", \"tsCanvas\"", + "\"timeWindowPills\", \"activeDateBadge\", \"tsCanvas\"", + "\"tsCanvas\"", + "\"tsCanvas\", \"activeDateBadge\"", + "\"wireTapeFilterInput\", \"wireEqTape\"" + ], + "ep_codes": [ + "Ep 01", + "Ep 02", + "Ep 03", + "Ep 04", + "Ep 05" + ], + "speech_text_count": 25, + "lens_keys": [ + "corporate_board", + "fantasy_sabermetrics", + "fund_manager", + "neutral_math", + "pokedex_scanner" + ], + "has_ui_indicator_badge": true, + "has_lens_select_highlight": true + }, + "learn_app_js": { + "js_ui_sha256": "0df7d15352426f575f0c4ecd65490f8796fd5ebbd9e4f0d26088289130265d03", + "dom_ids": [ + "bmNextBtn", + "bmPrevBtn", + "bookmarkPaginationBar", + "bookmarkedCoordsList", + "btnAddBookmark", + "btnDownloadState", + "btnLoadDemoState", + "btnResetState", + "btnUploadState", + "filterBookmarkInput", + "importModeSelect", + "inputBookmarkCoord", + "inputUploadState", + "m01InputA", + "m01InputB", + "m01Output", + "m02Output", + "m02WordSelect", + "m03ModeSelect", + "m03Output", + "m03TriadSelect", + "m04HeadlineSelect", + "m04Output", + "m05BuildSelect", + "m05Output", + "m06Output", + "m06RegisterSelect", + "progressFill", + "progressText", + "stateCidBadge", + "statePortabilityBar", + "stateStatusMsg" + ], + "ui_targets": [], + "ep_codes": [], + "speech_text_count": 0, + "lens_keys": [], + "has_ui_indicator_badge": false, + "has_lens_select_highlight": false + }, + "polyglot_repl_js": { + "js_ui_sha256": "915cb90a58b96aaa92a6d138e65de8c9aa0e61ebe4ce032ee84e0158b8d27433", + "dom_ids": [ + "guileSchemeModeState", + "guileSchemeModeToggle", + "hsGuilePreferFloat", + "hsGuileReplCloseBtn", + "hsGuileReplDrawer", + "hsGuileReplEvalBtn", + "hsGuileReplInput", + "hsGuileReplOutput", + "hsGuileReplPreset", + "hsGuileReplStepBtn", + "hsPolyglotReplLang" + ], + "ui_targets": [], + "ep_codes": [], + "speech_text_count": 0, + "lens_keys": [], + "has_ui_indicator_badge": false, + "has_lens_select_highlight": false + } + }, "ipld_dag_json_cidv1": { - "/": "baguqeera72nb5g4mc7vivns73awidi4lcvbjc5dnfg7ua7eczuuaexgpmnwa" + "/": "baguqeeraf5ku7guwa7g4hbwsnidffhvynxf43wvipn7qsoxtburh6stp3xea" } } diff --git a/site/donate/index.html b/site/donate/index.html index 8c43f13..89a18e5 100644 --- a/site/donate/index.html +++ b/site/donate/index.html @@ -4,7 +4,7 @@ Signal Patronage & Open-Instrument Notes — hyperstitionstud.io/donate - + - +

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

-

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

+

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

- - - - - + + + + + diff --git a/site/quant/quant-app.js b/site/quant/quant-app.js index 3b19607..6cf70e8 100644 --- a/site/quant/quant-app.js +++ b/site/quant/quant-app.js @@ -1,5 +1,5 @@ // /workspace/hyperstitionstudio-core/site/quant/quant-app.js -// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.10.0) +// Interactive Quantitative Finance & Memetic Gematria Time-Series Workbench (v2.12.0) (function () { "use strict"; diff --git a/site/quant/quant-tutorials.js b/site/quant/quant-tutorials.js index 8beb07a..8ff6a6d 100644 --- a/site/quant/quant-tutorials.js +++ b/site/quant/quant-tutorials.js @@ -1,9 +1,36 @@ // /workspace/hyperstitionstudio-core/site/quant/quant-tutorials.js -// Option B Zero-MP4 Interactive HTML5 Canvas Tutorial Player & Deep-Link Choreographer (v2.10.0) +// Option B Zero-MP4 Interactive HTML5 Canvas Tutorial Player, Spoken Voice Narration & Per-Scene UI Element Indicators (v2.11.0) (function () { "use strict"; - window.HyperstitionStudio = window.HyperstitionStudio || {}; + const rootObj = typeof window !== "undefined" ? window : globalThis; + rootObj.HyperstitionStudio = rootObj.HyperstitionStudio || {}; + + const ALL_HIGHLIGHTABLE_DOM_IDS = [ + "guildFilterPills", + "tickerQuickFilter", + "tickerSelect", + "openTradingViewBtn", + "lensSelect", + "metricModePills", + "timeWindowPills", + "activeDateBadge", + "tsCanvas", + "heatmapTable", + "heatmapPaginationBar", + "panel3TvBtn", + "dateMetricsGrid", + "lensProjectionCard", + "docReferencesCard", + "wireTapeFilterInput", + "wireEqTape", + "lagBarsContainer", + "exportCsvBtn", + "exportJsonBtn", + "periodicityAuditFooter", + "macroIndicatorsPanel", + "dailyBriefPanel" + ]; const EPISODES = [ { @@ -15,7 +42,10 @@ title: "1.1 Strict Periodicity Gate (21:30 UTC Close x 00:00 UTC Wire)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.89, yRatio: 0.22, label: "Strict Periodicity Gate: 19 Real US Equity Sessions in Nov 2026" }, + uiTargets: ["timeWindowPills", "activeDateBadge", "tsCanvas"], + uiElementLabel: "Temporal Window Pills (#timeWindowPills) & Active Date Badge (#activeDateBadge)", subtitle: "Only real periodic timestamp-indexed observations (21:30 UTC US Closing-Bell bars and 00:00 UTC dated news dossiers) enter this workbench. Closed weekend/holiday dates explicitly report 'No data available'.", + speechText: "Scene 1.1. Inspecting the Temporal Window pills and Active Date badge in the top toolbar alongside Panel 1. Only real periodic timestamp-indexed observations, twenty-one thirty UTC US closing-bell bars and midnight UTC dated news dossiers, enter this workbench. Closed weekend and holiday dates explicitly report No data available.", citations: [ { label: "Vol 08A PDF (Room Filter)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/a-to-h-ai-powered-race-to-hidden-chokepoint-screen.pdf#page=2&search=Room%20Filter" }, { label: "Archive Methodology", href: "/archive/00-index-and-methodology.md#:~:text=closing-bell" }, @@ -26,7 +56,10 @@ title: "1.2 Guild S1 — Autoregressive AI Syndicate (Coordinate 292)", state: { guildFilter: "S1", selectedSymbol: "MSFT", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 24 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.83, yRatio: 0.28, label: "S1 AI Guild Filter Active (MSFT 2026-11-25 Close $489.93)" }, + uiTargets: ["guildFilterPills", "tickerSelect"], + uiElementLabel: "Guild Filter Pills (#guildFilterPills -> S1) & Ticker Select (#tickerSelect)", subtitle: "Filtering by Guild S1 isolates the Autoregressive AI Syndicate anchored on Coordinate 292 (shizohnalizis == abstrakt masheen == sinthetik dayta == asset management [Gen 0]).", + speechText: "Scene 1.2. Highlighting the Guild Filter pills and Ticker selector in the toolbar. Filtering by Guild S1 isolates the Autoregressive AI Syndicate anchored on Coordinate 292, where schizoanalysis, abstract machine, and synthetic data all converge in phonemic Ingglish.", citations: [ { label: "Vol 03A PDF (S1 AI)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s1-autoregressive-ai-and-abstract-machine-a-to-z.pdf#page=1&search=292" }, { label: "Dossier 65 (292 Lock)", href: "/zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md#:~:text=292" }, @@ -37,7 +70,10 @@ title: "1.3 Guild S3 — Silicon-Photonic War Machine (137 & 81)", state: { guildFilter: "S3", selectedSymbol: "ASML", selectedLens: "corporate_board", metricMode: "close_usd", selectedDateIdx: 26 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.89, yRatio: 0.30, label: "S3 Isometric Chokepoint: ASML = asml = 81 (Δ = 0)" }, + uiTargets: ["guildFilterPills", "tickerQuickFilter", "tickerSelect"], + uiElementLabel: "Guild Filter (#guildFilterPills -> S3) & Ticker Quick-Filter (#tickerQuickFilter)", subtitle: "Guild S3 maps physical wafer and EUV lithography chokepoints: ASML (81, Δ = 0 isometric), TSMC (95, Δ = 0), and Nvidia (envideea = 137 [33rd Prime]).", + speechText: "Scene 1.3. Highlighting Guild Filter S3 and the Ticker Quick-Filter input in the toolbar. Guild S3 maps physical wafer and extreme ultraviolet lithography chokepoints: ASML at coordinate 81 with zero phonemic drift, TSMC at 95, and Nvidia at 137, the thirty-third prime.", citations: [ { label: "Vol 03C PDF (p.5 ASML/envideea)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=envideea" }, { label: "Dossier 67 (Silicon War Machine)", href: "/zoology/dossiers/67-dossier-technocapital-singularity-silicon-war-machine.md#:~:text=137" }, @@ -48,7 +84,10 @@ title: "1.4 Guild S6 — Apparatus of Capture (Coordinate 125)", state: { guildFilter: "S6", selectedSymbol: "BLK", selectedLens: "corporate_board", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.86, yRatio: 0.26, label: "S6 Capture Ring: kapatal == kapcher == fohldz = 125" }, + uiTargets: ["guildFilterPills", "tickerSelect"], + uiElementLabel: "Guild Filter Pills (#guildFilterPills -> S6) & Ticker Select (#tickerSelect -> BLK)", subtitle: "Guild S6 tracks sovereign and balance-sheet capture around Coordinate 125 (kapatal == kapcher == fohldz = 125) and charter/sloth (136).", + speechText: "Scene 1.4. Highlighting Guild Filter S6 and the Ticker dropdown list selected to BlackRock. Guild S6 tracks sovereign and balance-sheet capture around Coordinate 125, where capital, capture, and folds all evaluate to 125.", citations: [ { label: "Vol 04A PDF (S6 Capture)", href: "/encyclopedia/04-capital-organizational-capture-s6/a-to-f-acquisition-to-fund.pdf#page=1&search=125" }, { label: "Dossier 68 (Capture)", href: "/zoology/dossiers/68-dossier-technocapital-singularity-apparatus-of-capture.md#:~:text=125" }, @@ -59,7 +98,10 @@ title: "1.5 Periodicity Audit Footer & IPLD dag-json CIDv1", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "panel4", xRatio: 0.50, yRatio: 0.85, label: "Cryptographic CIDv1 & Periodicity Audit Footer" }, + uiTargets: ["periodicityAuditFooter"], + uiElementLabel: "Periodicity Audit & CIDv1 Footer (#periodicityAuditFooter)", subtitle: "The bottom footer verifies 21 dated 00:00 UTC dossiers + real exchange closing-bell bars (missing/closed days = null / No data available), and the deterministic IPLD dag-json CIDv1 digest.", + speechText: "Scene 1.5. Inspecting the Periodicity Audit footer at the bottom of Panel 4. This footer verifies the dated midnight UTC dossiers, real exchange closing-bell bars, and the deterministic IPLD dag-json CIDv1 content identifier.", citations: [ { label: "Static Bundle quant-timeseries.json", href: "/quant/quant-timeseries.json" }, { label: "REST API /api/v1/quant/timeseries", href: "/api/v1/quant/timeseries?symbol=NVDA" }, @@ -77,7 +119,10 @@ title: "2.1 Top Pane: Dashed Crimson Identity Line & Real Scope 1 Self-Lock (PLTR)", state: { guildFilter: "ALL", selectedSymbol: "PLTR", selectedLens: "fund_manager", metricMode: "close_usd", selectedDateIdx: 22 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.76, yRatio: 0.25, label: "Real Scope 1 Self-Lock: PLTR Close $159.36 (159 == palanter)" }, + uiTargets: ["metricModePills", "tsCanvas"], + uiElementLabel: "Metric Mode Pills (#metricModePills -> Close Price USD) & Panel 1 Canvas (#tsCanvas)", subtitle: "On 2026-11-23, Palantir (PLTR) closed at $159.36 on the exchange: its rounded integer price (159) lands directly on the dashed crimson threshold marking its own Gen 1 Ingglish name (palanter = 159), firing a real Scope 1 Gold Beacon.", + speechText: "Scene 2.1. Highlighting the Metric Mode pills in the toolbar and the Top Pane of the Panel 1 trajectory canvas. On November 23, 2026, Palantir closed at 159 dollars and 36 cents: its rounded integer price 159 lands directly on the dashed crimson threshold marking its own Ingglish name palanter equals 159, firing a real Scope 1 Gold Beacon.", citations: [ { label: "Vol 03C PDF (S3 War Machine)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=palanter" }, { label: "Dossier 67 (Silicon War Machine)", href: "/zoology/dossiers/67-dossier-technocapital-singularity-silicon-war-machine.md#:~:text=137" }, @@ -88,7 +133,10 @@ title: "2.2 Move (BPS) Mode: TSMC (TSM) +81 bps Ring Migration & Microsoft -125 bps", state: { guildFilter: "ALL", selectedSymbol: "TSM", selectedLens: "fund_manager", metricMode: "change_bps", selectedDateIdx: 17 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.59, yRatio: 0.24, label: "Real Exchange Move: TSM +81 bps on 2026-11-18 (Ring 81 == asml)" }, + uiTargets: ["metricModePills", "tsCanvas"], + uiElementLabel: "Metric Mode Pills (#metricModePills -> Move BPS) & Panel 1 Canvas (#tsCanvas)", subtitle: "Switching Metric Mode to Move (BPS) on 2026-11-18 shows TSMC (TSM) moving +81 bps ($359.70 -> $362.62), landing on the S3 lithography coordinate 81 (asml = 81).", + speechText: "Scene 2.2. Highlighting the Metric Mode pills switched to Move in Basis Points. On November 18, 2026, TSMC moved plus 81 basis points, landing directly on the S3 lithography coordinate 81, matching ASML equals 81.", citations: [ { label: "Vol 03C PDF (ASML = 81)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=ASML" }, { label: "Graph Hub aq:81", href: "/graph/index.html?select=aq:81" } @@ -98,7 +146,10 @@ title: "2.3 Real Repdigit Attractor Lock: Broadcom (AVGO) at $333.40 & NVDA Spoken 333", state: { guildFilter: "ALL", selectedSymbol: "AVGO", selectedLens: "fund_manager", metricMode: "close_usd", selectedDateIdx: 15 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.52, yRatio: 0.20, label: "Real Exchange Repdigit Lock: AVGO $333.40 on 2026-11-16 (333 = 3 x 111)" }, + uiTargets: ["tickerSelect", "metricModePills", "tsCanvas"], + uiElementLabel: "Ticker Select (#tickerSelect -> AVGO) & Panel 1 Top Pane (#tsCanvas)", subtitle: "On 2026-11-16, Broadcom (AVGO) closed at $333.40 (rounded integer 333 = 3 x 111), and on 2026-11-03 Nvidia (NVDA) closed at $206.69 ('too huhndrad siks' = 333), firing real Scope 1 Repdigit Gold Beacons.", + speechText: "Scene 2.3. Inspecting Ticker Select set to Broadcom and the Panel 1 trajectory canvas. On November 16, 2026, Broadcom closed at 333 dollars and 40 cents, rounding to the repdigit attractor 333, while Nvidia closed at 206 dollars and 69 cents whose spoken Ingglish phrase two hundred six also sums to 333.", citations: [ { label: "Vol 03C PDF (S3 Guild)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=333" }, { label: "Graph Hub aq:333", href: "/graph/index.html?select=aq:333" } @@ -108,7 +159,10 @@ title: "2.4 Middle Pane: 00:00 GMT Wire Velocity & Emerald Scope 3 Bars", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 }, spotlight: { target: "canvas", pane: "mid", xRatio: 0.93, yRatio: 0.63, label: "Emerald Bar = Scope 3 News-Wire Co-Presence" }, + uiTargets: ["tsCanvas", "activeDateBadge"], + uiElementLabel: "Panel 1 Middle Pane (#tsCanvas Wire Velocity) & Active Date Badge (#activeDateBadge)", subtitle: "In the middle pane, Violet bars show daily 333/666/777 equation counts; Emerald bars highlight UTC dates where the selected ticker co-occurred in breaking 00:00 GMT news headlines.", + speechText: "Scene 2.4. Inspecting the Middle Pane of the Panel 1 canvas. Violet bars show daily 333, 666, and 777 equation counts, while Emerald bars highlight UTC dates where the selected ticker co-occurred in breaking midnight GMT news headlines.", citations: [ { label: "Dossier 71 (2026-11-29)", href: "/archive/71-dossier-news-2026-11-29.md#:~:text=333" }, { label: "REST Highlight Preview", href: "/api/v1/dossiers/71?highlight=envideea" } @@ -118,7 +172,10 @@ title: "2.5 Bottom Pane: 20-Day Volume Ratio & M1/M2/M3 Thermodynamic Regimes", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 25 }, spotlight: { target: "canvas", pane: "bot", xRatio: 0.83, yRatio: 0.86, label: "Thermodynamic Regime Color Coding (M1 Gold / M2 Crimson / M3 Sky)" }, + uiTargets: ["tsCanvas"], + uiElementLabel: "Panel 1 Bottom Pane (#tsCanvas 20-Day Volume & M1/M2/M3 Regimes)", subtitle: "The bottom pane color-codes 20d relative volume by objective thermodynamic state: Gold (<0.45x) = M1 Stagnation (137), Crimson (>=2.5x or <=-5%) = M2 Flash-Crash Surge (193), Sky-Blue = M3 Leviathan.", + speechText: "Scene 2.5. Inspecting the Bottom Pane of the Panel 1 canvas. Twenty-day relative volume bars are color-coded by thermodynamic regime: Gold for M1 Stagnation, Crimson for M2 Flash-Crash Surge, and Sky-Blue for M3 Leviathan.", citations: [ { label: "Vol 05A PDF (Subclass M1)", href: "/encyclopedia/05-memetic-superclass-and-emergent-m7/m1-vampiric-entropic-and-anti-productive-a-to-m.pdf#page=1&search=M1" }, { label: "Vol 05C PDF (M2-M6)", href: "/encyclopedia/05-memetic-superclass-and-emergent-m7/m2-to-m6-kinetic-leviathan-mimetic-oracle-abyssal-a-to-z.pdf#page=1&search=M2" } @@ -135,7 +192,10 @@ title: "3.1 Panel 2: 24x30 Heatmap & Explicit 'No Data Available' Handling (ANTHR-PVT & Weekends)", state: { guildFilter: "ALL", selectedSymbol: "ANTHR-PVT", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 17 }, spotlight: { target: "panel2", xRatio: 0.50, yRatio: 0.40, label: "Zero Synthetic Data: ANTHR-PVT & Closed Market Days Show 'No data available'" }, + uiTargets: ["heatmapTable", "dateMetricsGrid"], + uiElementLabel: "Panel 2 Spatiotemporal Lock Heatmap (#heatmapTable) & Panel 3 Metrics Grid (#dateMetricsGrid)", subtitle: "This workbench never synthesizes or interpolates missing market data. Because Anthropic (ANTHR-PVT) is a private entity with no public exchange feed (and US stock markets close on weekends and Thanksgiving), those cells explicitly state 'No data available'.", + speechText: "Scene 3.1. Highlighting the Panel 2 Spatiotemporal Lock Heatmap table and the Panel 3 Date Metrics grid. This workbench never synthesizes or interpolates missing market data. Because Anthropic is a private entity with no public exchange feed, and US stock markets close on weekends and holidays, those cells explicitly report No data available.", citations: [ { label: "Vol 06A PDF (Anchor Revision)", href: "/encyclopedia/06-genealogical-vectors-and-quantitative-repricing/a-to-m-attractors-to-multi-build-flex-singularities.pdf#page=1&search=193" }, { label: "Dossier 66 (193 Flash Crash)", href: "/zoology/dossiers/66-dossier-technocapital-singularity-flash-crash-liquidity.md#:~:text=193" }, @@ -146,7 +206,10 @@ title: "3.2 TradingView Superchart Launcher (Shortcut: T)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "panel3", xRatio: 0.85, yRatio: 0.12, label: "Open TradingView Chart ↗ (Zero External Script Embeds)" }, + uiTargets: ["openTradingViewBtn", "panel3TvBtn"], + uiElementLabel: "Open TradingView Chart Buttons (#openTradingViewBtn & #panel3TvBtn)", subtitle: "Every ticker resolves deterministically to EXCHANGE:SYMBOL (e.g. NASDAQ:NVDA, closing at $150.49 on 2026-11-27). Clicking 'TradingView ↗' or pressing 'T' opens the live Superchart in a new window while keeping 0 external scripts embedded.", + speechText: "Scene 3.2. Highlighting the Open TradingView Chart buttons in the toolbar and Panel 3 header. Every ticker resolves deterministically to its exchange and symbol, such as NASDAQ colon NVDA. Clicking TradingView or pressing key T opens the live Superchart in a new window while keeping zero external tracking scripts embedded.", citations: [ { label: "Launch TradingView (NASDAQ:NVDA)", href: "https://www.tradingview.com/chart/?symbol=NASDAQ%3ANVDA" }, { label: "Operator's Manual (PDF)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf#page=1&search=TradingView" } @@ -156,7 +219,10 @@ title: "3.3 Panel 3: Knowledge-Graph-Modeled Documentation & Cited Passages Card", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 }, spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Passage-Encoded PDF (#page & search) + Dossier (#:~:text=) Links" }, + uiTargets: ["docReferencesCard"], + uiElementLabel: "Panel 3 Documentation & Cited Passages Card (#docReferencesCard)", subtitle: "Modeled directly on the Knowledge Graph's inspector drawer, the Documentation Card links every ticker to its exact Encyclopedia PDF page (#page=N&search=...), Dossier passage (#:~:text=...), and Graph node (?select=aq:N).", + speechText: "Scene 3.3. Highlighting the Documentation and Cited Passages card in Panel 3. Modeled directly on the Knowledge Graph inspector drawer, this card links every ticker to its exact Encyclopedia PDF page, Dossier scroll-to-text passage, and Knowledge Graph coordinate node.", citations: [ { label: "Vol 03C PDF (#page=5&search=envideea)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=5&search=envideea" }, { label: "Graph Deep Link (?select=aq:137)", href: "/graph/index.html?select=aq:137" }, @@ -167,7 +233,10 @@ title: "3.4 Panel 3: Verbatim Dated Memetic Equation Tape & Inline Passage Preview", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 28 }, spotlight: { target: "wireTape", xRatio: 0.50, yRatio: 0.50, label: "Dated 333 / 666 / 777 Equations with Scroll-to-Text Deep Links" }, + uiTargets: ["wireTapeFilterInput", "wireEqTape"], + uiElementLabel: "Panel 3 Wire Equation Filter (#wireTapeFilterInput) & Equation Tape (#wireEqTape)", subtitle: "Every equation in the Dated Wire Tape includes a WICG scroll-to-text link (#:~:text=...), a Knowledge Graph coordinate link, and an inline REST passage preview button.", + speechText: "Scene 3.4. Highlighting the Wire Equation filter input and Dated Equation Tape in Panel 3. Every equation in the tape includes a scroll-to-text deep link, a Knowledge Graph coordinate link, and an inline REST passage preview button.", citations: [ { label: "Dossier 71 Scroll-to-Text", href: "/archive/71-dossier-news-2026-11-29.md#:~:text=333" }, { label: "REST Dossier 71 JSON", href: "/api/v1/dossiers/71?highlight=333" } @@ -177,7 +246,10 @@ title: "3.5 Bidirectional Graph & Dossier Cross-Verification", state: { guildFilter: "ALL", selectedSymbol: "COIN", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 27 }, spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Cross-Corpus Coordinate Verification" }, + uiTargets: ["tickerSelect", "docReferencesCard"], + uiElementLabel: "Ticker Select (#tickerSelect -> COIN) & Documentation Card (#docReferencesCard)", subtitle: "Clicking any coordinate pill jumps straight to the Encyclopedia Knowledge Graph with that node centered and isolated in the right-hand drawer.", + speechText: "Scene 3.5. Highlighting Ticker Select set to Coinbase and the Panel 3 Documentation Card. Clicking any coordinate pill jumps straight to the Encyclopedia Knowledge Graph with that node centered and isolated in the right-hand inspector drawer.", citations: [ { label: "Graph Node aq:211", href: "/graph/index.html?select=aq:211" }, { label: "Dossier 68 (S6 Capture)", href: "/zoology/dossiers/68-dossier-technocapital-singularity-apparatus-of-capture.md#:~:text=125" } @@ -194,7 +266,10 @@ title: "4.1 Lens 1: Neutral Mathematical Substrate (neutral_math)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "neutral_math", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Pure Lens-Neutral Keys (struct_* & ts_*)" }, + uiTargets: ["lensSelect", "lensProjectionCard"], + uiElementLabel: "Projection Lens Dropdown List (#lensSelect -> Neutral Math) & Lens Card (#lensProjectionCard)", subtitle: "Under the hood, quant-timeseries.json stores 100% lens-neutral mathematical keys (struct_isometric_armor, ts_duty_cycle_pct, ts_weighted_resonance, ts_excess_over_replacement, ts_optimal_lag_days).", + speechText: "Scene 4.1. Highlighting the Projection Lens dropdown list in the top toolbar and the Lens Projection card in Panel 3. Under the hood, the workbench stores one hundred percent lens-neutral mathematical keys: structural isometric armor, duty cycle percentage, weighted resonance, excess over replacement, and optimal lag days. Use the Projection Lens dropdown list in the toolbar to switch lenses.", citations: [ { label: "Schema quant-timeseries.schema.json", href: "/schemas/v1/quant-timeseries.schema.json" }, { label: "Vol 08A PDF (Stakeholder Registers)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/a-to-h-ai-powered-race-to-hidden-chokepoint-screen.pdf#page=1&search=Register" } @@ -204,7 +279,10 @@ title: "4.2 Lens 2: Out-of-Sample Quantitative Factor Register (fund_manager)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Fund Manager Register: Signal Duty Cycle & Alpha Over Benchmark" }, + uiTargets: ["lensSelect", "lensProjectionCard"], + uiElementLabel: "Projection Lens Dropdown List (#lensSelect -> Fund Manager) & Lens Card (#lensProjectionCard)", subtitle: "Switching to 'Quant Factor (fund_manager)' translates the exact same 6 numbers into institutional factor terminology (Chokepoint Moat, Signal Duty Cycle %, Composite Resonance Load).", + speechText: "Scene 4.2. Highlighting the Projection Lens dropdown list switched to Quant Factor Fund Manager and the Panel 3 Lens Projection card. Selecting Fund Manager in the Projection Lens dropdown translates the exact same six mathematical invariants into institutional factor terminology: Chokepoint Moat, Signal Duty Cycle percentage, and Composite Resonance Load.", citations: [ { label: "Fund Manager Proposal (PDF)", href: "/zoology/proposal-fund-manager-novel-investment-discovery.pdf#page=1&search=Uncaptured" }, { label: "REST Tier List (fund_manager)", href: "/api/v1/zoology/tier-list?register=fund_manager" } @@ -214,7 +292,10 @@ title: "4.3 Lens 3: Corporate Board & Supply-Chain Governance (corporate_board)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "corporate_board", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Corporate Board Register: Supply-Chain Moat & Stress-Test Delta" }, + uiTargets: ["lensSelect", "lensProjectionCard"], + uiElementLabel: "Projection Lens Dropdown List (#lensSelect -> Corporate Board) & Lens Card (#lensProjectionCard)", subtitle: "Switching to 'Corporate Board' frames those identical invariants as Supply-Chain Structural Moat, Cross-Unit Synergy, and Stress-Test Regime Delta.", + speechText: "Scene 4.3. Highlighting the Projection Lens dropdown list switched to Corporate Board and the Panel 3 Lens Projection card. Selecting Corporate Board in the Projection Lens dropdown frames those identical invariants as Supply-Chain Structural Moat, Cross-Unit Synergy, and Stress-Test Regime Delta.", citations: [ { label: "Corporate Board Proposal (PDF)", href: "/zoology/proposal-corporate-board-technocapital-allocation.pdf#page=1&search=Moat" }, { label: "REST Tier List (corporate_board)", href: "/api/v1/zoology/tier-list?register=corporate_board" } @@ -224,7 +305,10 @@ title: "4.4 Lens 4 & 5: TierZoo Ecology (ETI) & Fantasy Sabermetrics (SNAP% / WOPR / WAR)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fantasy_sabermetrics", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Fantasy Sabermetrics: SNAP%, WOPR, WAR (30d) & Matchup Splits" }, + uiTargets: ["lensSelect", "lensProjectionCard"], + uiElementLabel: "Projection Lens Dropdown List (#lensSelect -> Fantasy Sabermetrics) & Lens Card (#lensProjectionCard)", subtitle: "Switching to 'Fantasy Sabermetrics' projects SNAP% (Active Lock Share), WOPR (1.5x Target Share + 0.7x Air-Yards Share), and WAR (30d Wins Above Tier D Replacement).", + speechText: "Scene 4.4. Highlighting the Projection Lens dropdown list switched to Fantasy Sabermetrics and the Panel 3 Lens Projection card. Selecting Fantasy Sabermetrics in the Projection Lens dropdown projects Snap Percentage, Weighted Opportunity Rating, and thirty-day Wins Above Replacement.", citations: [ { label: "ETI Tier List Scorecard (PDF)", href: "/zoology/tier-list-technocapital-assemblage-builds.pdf#page=1&search=ETI" }, { label: "Vol 07A PDF (ETI Ontology)", href: "/encyclopedia/07-ecological-trophic-index-and-tier-list/a-to-z-arm-chokepoint-armor-to-zoological-tie-breaker.pdf#page=1&search=ETI" } @@ -234,7 +318,10 @@ title: "4.5 Lens 6: Gen IV Pokédex Field-Scanner (DEX #137)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "pokedex_scanner", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "lensCard", xRatio: 0.50, yRatio: 0.50, label: "Gen IV Pokédex Scanner: DEX #137, Nature, Ability & EV Yield" }, + uiTargets: ["lensSelect", "lensProjectionCard"], + uiElementLabel: "Projection Lens Dropdown List (#lensSelect -> Pokedex Scanner) & Lens Card (#lensProjectionCard)", subtitle: "Switching to 'Pokédex Scanner' deterministically derives Gen IV attributes (DEX #137, Nature, Passive Ability, EV Yield) from the real time-series moments—and remains 100% removable via ENABLED_LENSES.", + speechText: "Scene 4.5. Highlighting the Projection Lens dropdown list switched to Pokedex Scanner and the Panel 3 Lens Projection card. Selecting Pokedex Scanner deterministically derives Gen 4 attributes including Dex number 137, Nature, Passive Ability, and Effort Value Yield from the real time-series moments.", citations: [ { label: "REST Pokédex Endpoint (/api/v1/zoology/pokedex/NVDA)", href: "/api/v1/zoology/pokedex/NVDA" }, { label: "Vol 08B PDF (Pokédex Semiotics)", href: "/encyclopedia/08-stakeholder-registers-idioms-and-pokedex-semiotics/i-to-z-idiosyncratic-prime-screen-to-united-fidelity.pdf#page=1&search=Pokedex" } @@ -251,7 +338,10 @@ title: "5.1 Panel 4: Lead-Lag Cross-Correlation Curve r(tau) across [-5 .. +5] Days", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "panel4", xRatio: 0.50, yRatio: 0.45, label: "Pearson Cross-Correlation r(tau) & Gold Optimal Causal Lag tau*" }, + uiTargets: ["lagBarsContainer"], + uiElementLabel: "Panel 4 Lead-Lag Cross-Correlation Bar Chart (#lagBarsContainer)", subtitle: "Panel 4 computes the empirical Pearson cross-correlation r(tau) between daily 00:00 GMT news-wire equation velocity M_t and unsigned basis-point displacement |Δbps_{i, t+tau}| across lags tau in [-5, +5] days.", + speechText: "Scene 5.1. Highlighting the Lead-Lag Cross-Correlation bar chart in Panel 4. Panel 4 computes the empirical Pearson cross-correlation r of tau between daily midnight GMT news-wire equation velocity and unsigned basis-point price displacement across lags from minus 5 to plus 5 days.", citations: [ { label: "Operator's Manual (Panel 4 Math)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf#page=2&search=Correlation" }, { label: "Graph Mode 2 Concentric Radar", href: "/graph/index.html?select=aq:137&mode=mode2_radar" } @@ -261,7 +351,10 @@ title: "5.2 Interpreting Optimal Causal Lag tau* (Leader vs. Synchronizer vs. Follower)", state: { guildFilter: "ALL", selectedSymbol: "ASML", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "panel4", xRatio: 0.58, yRatio: 0.45, label: "Gold Bar Marks argmax |r(tau)|" }, + uiTargets: ["tickerSelect", "lagBarsContainer"], + uiElementLabel: "Ticker Select (#tickerSelect -> ASML) & Panel 4 Lead-Lag Bars (#lagBarsContainer)", subtitle: "The Gold bar highlights tau* = argmax |r(tau)|: tau* > 0 indicates a Teleoplexic Wire Leader (midnight wire velocity leads market volatility), tau* = 0 an Instantaneous Synchronizer, and tau* < 0 a Narrative Follower.", + speechText: "Scene 5.2. Highlighting the Gold optimal lag bar in Panel 4. The Gold bar marks tau star, the lag maximizing absolute correlation: positive tau star indicates a Teleoplexic Wire Leader, zero indicates an Instantaneous Synchronizer, and negative tau star indicates a Narrative Follower.", citations: [ { label: "Vol 03C PDF (ASML)", href: "/encyclopedia/03-machinic-phylum-guilds-s1-to-s5/class-s3-silicon-war-machine-and-euv-swarm-a-to-z.pdf#page=1&search=ASML" }, { label: "Graph Node aq:81", href: "/graph/index.html?select=aq:81" } @@ -271,17 +364,23 @@ title: "5.3 Portable .CSV & Lens-Neutral .JSON Slice Exports", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "neutral_math", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "panel4", xRatio: 0.82, yRatio: 0.14, label: "One-Click .CSV & Lens-Neutral .JSON Export" }, + uiTargets: ["exportCsvBtn", "exportJsonBtn"], + uiElementLabel: "Panel 4 Export Buttons (#exportCsvBtn & #exportJsonBtn)", subtitle: "Click 'Export Filtered Series (.CSV)' or 'Export Lens-Neutral Slice (.JSON)' in the Panel 4 header to download any ticker's 30-day periodic bar table and structural/time-series vectors for offline research.", + speechText: "Scene 5.3. Highlighting the Export Filtered Series CSV and Export Lens-Neutral Slice JSON buttons in the Panel 4 header. Click either button to download any ticker's thirty-day periodic bar table and structural vectors for offline research.", citations: [ { label: "Raw Bundle quant-timeseries.json", href: "/quant/quant-timeseries.json" }, { label: "Schema quant-timeseries.schema.json", href: "/schemas/v1/quant-timeseries.schema.json" } ] }, { - title: "5.4 Unified Stateless REST API v1 (/api/v1/*) & OpenAPI 3.1.0", + title: "5.4 Panel 5 FRED Macro Strip & Unified Stateless REST API v1 (/api/v1/*)", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "docCard", xRatio: 0.50, yRatio: 0.50, label: "Programmatic REST API v1 & OpenAPI 3.1.0" }, + uiTargets: ["macroIndicatorsPanel", "docReferencesCard"], + uiElementLabel: "Panel 5 FRED Macroeconomic Telemetry (#macroIndicatorsPanel) & REST API Links (#docReferencesCard)", subtitle: "Every readout on /quant/ is also queryable over HTTP GET/POST via /api/v1/quant/timeseries, /api/v1/quant/instruments/{symbol}, /api/v1/dossiers/{number}?highlight=..., and /api/v1/openapi.json.", + speechText: "Scene 5.4. Highlighting Panel 5 Federal Reserve Macroeconomic Telemetry and the Panel 3 REST API links. Every readout on the workbench is also queryable programmatically over HTTP via the version 1 REST API and OpenAPI 3.1 specification.", citations: [ { label: "OpenAPI 3.1.0 Spec (/api/v1/openapi.json)", href: "/api/v1/openapi.json" }, { label: "REST Status (/api/v1/status)", href: "/api/v1/status" }, @@ -289,10 +388,13 @@ ] }, { - title: "5.5 Complete Tour Summary & Companion Operator's Manual", + title: "5.5 Panel 6 Daily Bayesian Brief & Complete Tour Summary", state: { guildFilter: "ALL", selectedSymbol: "NVDA", selectedLens: "fund_manager", metricMode: "spoken_aq", selectedDateIdx: 26 }, spotlight: { target: "canvas", pane: "top", xRatio: 0.89, yRatio: 0.25, label: "Tour Complete — Explore Any Ticker, Lens, or Deep Citation" }, + uiTargets: ["dailyBriefPanel", "lensSelect"], + uiElementLabel: "Panel 6 Daily Bayesian Regime Update (#dailyBriefPanel) & Projection Lens Dropdown (#lensSelect)", subtitle: "You have completed all 5 episodes of the /quant/ guided walkthrough. Open the Companion Operator's Manual (PDF) or click any heatmap cell, lens, or deep citation link to continue exploring.", + speechText: "Scene 5.5. Highlighting Panel 6, the five-agenda Daily Bayesian Portfolio and Memetic Regime Update, and the Projection Lens dropdown list. You have completed all five episodes of the guided walkthrough. Open the Companion Operator's Manual PDF or click any heatmap cell, projection lens, or deep citation link to continue exploring.", citations: [ { label: "Operator's Manual (PDF)", href: "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf" }, { label: "Interactive Knowledge Graph (/graph/)", href: "/graph/index.html?select=aq:137" }, @@ -348,20 +450,40 @@ let audioCtx = null; function refreshVoices() { - if (typeof window.speechSynthesis === "undefined") return; + if (typeof window === "undefined" || typeof window.speechSynthesis === "undefined") return; try { cachedVoices = window.speechSynthesis.getVoices() || []; } catch (_) { cachedVoices = []; } } - if (typeof window.speechSynthesis !== "undefined") { + if (typeof window !== "undefined" && typeof window.speechSynthesis !== "undefined") { refreshVoices(); if (typeof window.speechSynthesis.onvoiceschanged !== "undefined") { window.speechSynthesis.onvoiceschanged = refreshVoices; } } + function cleanTextForSpeech(rawText, uiElementLabel) { + let base = String(rawText || ""); + if (uiElementLabel && base.indexOf("Inspecting") === -1 && base.indexOf("Highlighting") === -1) { + base = "Inspecting " + uiElementLabel + ". " + base; + } + return base + .replace(/\|Δbps_\{i,\s*t\+tau\}\|/g, "absolute basis point displacement at lag tau") + .replace(/r\(tau\)/g, "r of tau") + .replace(/tau\*/g, "tau star") + .replace(/Δ\s*=\s*0/g, "delta equals zero") + .replace(/==/g, " equals ") + .replace(/#:~:text=/g, "scroll to text ") + .replace(/struct_\*/g, "structural keys") + .replace(/ts_\*/g, "time series keys") + .replace(/24x30/g, "24 by 30") + .replace(/↗/g, "") + .replace(/\s+/g, " ") + .trim(); + } + function playWebAudioTelemetryChime(stepIdx) { try { const Ctx = window.AudioContext || window.webkitAudioContext; @@ -377,12 +499,12 @@ osc.type = i === 0 ? "triangle" : "sine"; osc.frequency.setValueAtTime(freq, now + i * 0.09); gain.gain.setValueAtTime(0.001, now + i * 0.09); - gain.gain.exponentialRampToValueAtTime(0.06, now + i * 0.09 + 0.03); - gain.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.09 + 0.45); + gain.gain.exponentialRampToValueAtTime(0.025, now + i * 0.09 + 0.03); + gain.gain.exponentialRampToValueAtTime(0.0001, now + i * 0.09 + 0.35); osc.connect(gain); gain.connect(audioCtx.destination); osc.start(now + i * 0.09); - osc.stop(now + i * 0.09 + 0.48); + osc.stop(now + i * 0.09 + 0.38); }); } catch (_) {} } @@ -395,52 +517,58 @@ }, delayMs); } - function speakSubtitle(text, onDoneCallback) { + // Strategy 1B & 3A: Synchronous unblocked window.speechSynthesis.speak() + natural-English speechText + function speakSubtitle(kfOrText, onDoneCallback) { if (!speechEnabled) { if (onDoneCallback) scheduleNextStep(7000); return; } - // Always play a subtle harmonic telemetry cue at scene start so audio feedback is immediate even if OS TTS voices are absent - playWebAudioTelemetryChime(curStepIdx); + const rawSpeech = (kfOrText && typeof kfOrText === "object") + ? (kfOrText.speechText || cleanTextForSpeech(kfOrText.subtitle, kfOrText.uiElementLabel)) + : cleanTextForSpeech(String(kfOrText || ""), ""); + playWebAudioTelemetryChime(curStepIdx); refreshVoices(); - if (typeof window.speechSynthesis === "undefined" || cachedVoices.length === 0) { + + if (typeof window.speechSynthesis === "undefined" || typeof SpeechSynthesisUtterance === "undefined") { if (onDoneCallback) scheduleNextStep(7500); return; } try { window.speechSynthesis.cancel(); - window.speechSynthesis.resume(); - setTimeout(function () { - if (!speechEnabled) return; - const u = new SpeechSynthesisUtterance(text); + if (typeof window.speechSynthesis.resume === "function") { + window.speechSynthesis.resume(); + } + const u = new SpeechSynthesisUtterance(rawSpeech); + if (cachedVoices.length > 0) { const preferred = cachedVoices.find(function (v) { return /en(-|_)(US|GB)/i.test(v.lang) && /natural|neural|google|english/i.test(v.name); }) || cachedVoices.find(function (v) { return /^en/i.test(v.lang); }) || cachedVoices[0]; if (preferred) u.voice = preferred; - u.rate = 1.03; - u.pitch = 1.0; - u.volume = 1.0; - let settled = false; - const finish = function () { - if (settled) return; - settled = true; - if (onDoneCallback && isPlaying) { - scheduleNextStep(1800); - } - }; - u.onend = finish; - u.onerror = finish; - window.speechSynthesis.speak(u); - // Safety fallback timer in case browser TTS engine stalls without firing onend - const estMs = Math.max(8500, Math.min(20000, text.split(/\s+/).length * 420)); + } + u.lang = "en-US"; + u.rate = 1.03; + u.pitch = 1.0; + u.volume = 1.0; + let settled = false; + const finish = function () { + if (settled) return; + settled = true; if (onDoneCallback && isPlaying) { - scheduleNextStep(estMs); + scheduleNextStep(1800); } - }, 60); + }; + u.onend = finish; + u.onerror = finish; + // Call speak(u) synchronously without blocking on cachedVoices.length === 0 or setTimeout + window.speechSynthesis.speak(u); + const estMs = Math.max(8500, Math.min(22000, rawSpeech.split(/\s+/).length * 410)); + if (onDoneCallback && isPlaying) { + scheduleNextStep(estMs); + } } catch (_) { if (onDoneCallback) scheduleNextStep(7500); } @@ -451,24 +579,65 @@ return ep.keyframes[curStepIdx] || ep.keyframes[0]; } - function highlightDomTarget(targetId) { - ["heatmapTable", "lensProjectionCard", "docReferencesCard", "wireEqTape", "lagBarsContainer"].forEach(function (id) { + // Strategy 2A: Highlight all 18+ interactive DOM controls (including #lensSelect in Ep 04) + floating pointer badge + function highlightDomTarget(kfOrTargetId) { + ALL_HIGHLIGHTABLE_DOM_IDS.forEach(function (id) { const el = document.getElementById(id); - if (el) el.style.boxShadow = ""; + if (el) { + el.style.boxShadow = ""; + el.classList.remove("tut-ui-highlight"); + } }); - const map = { - panel2: "heatmapTable", - lensCard: "lensProjectionCard", - docCard: "docReferencesCard", - wireTape: "wireEqTape", - panel4: "lagBarsContainer" + const badge = document.getElementById("tutUiElementIndicator"); + if (!kfOrTargetId) { + if (badge) badge.style.display = "none"; + return; + } + + const legacyMap = { + panel2: ["heatmapTable"], + lensCard: ["lensSelect", "lensProjectionCard"], + docCard: ["docReferencesCard"], + wireTape: ["wireTapeFilterInput", "wireEqTape"], + panel4: ["lagBarsContainer"], + panel3: ["openTradingViewBtn", "panel3TvBtn"], + canvas: ["tsCanvas"] }; - const domId = map[targetId]; - if (domId) { + + let targetIds = []; + let badgeText = ""; + if (typeof kfOrTargetId === "object") { + if (Array.isArray(kfOrTargetId.uiTargets) && kfOrTargetId.uiTargets.length > 0) { + targetIds = kfOrTargetId.uiTargets.slice(); + } else if (kfOrTargetId.spotlight && kfOrTargetId.spotlight.target) { + targetIds = legacyMap[kfOrTargetId.spotlight.target] || [kfOrTargetId.spotlight.target]; + } + badgeText = kfOrTargetId.uiElementLabel || ("UI ELEMENT: #" + (targetIds[0] || "tsCanvas")); + } else if (typeof kfOrTargetId === "string") { + targetIds = legacyMap[kfOrTargetId] || [kfOrTargetId]; + badgeText = "UI ELEMENT: #" + targetIds[0]; + } + + let primaryEl = null; + targetIds.forEach(function (domId) { const el = document.getElementById(domId); if (el) { - el.style.boxShadow = "0 0 0 2px #f5c630, 0 0 18px rgba(245, 198, 48, 0.35)"; + el.classList.add("tut-ui-highlight"); + el.style.boxShadow = "0 0 0 2px #f5c630, 0 0 18px rgba(245, 198, 48, 0.45)"; + if (!primaryEl) primaryEl = el; } + }); + + if (badge && primaryEl && typeof primaryEl.getBoundingClientRect === "function") { + const rect = primaryEl.getBoundingClientRect(); + const topPx = Math.max(8, Math.min(window.innerHeight - 36, rect.top - 28)); + const leftPx = Math.max(8, Math.min(window.innerWidth - 320, rect.left)); + badge.textContent = "\u25BC ACTIVE UI ELEMENT: " + badgeText; + badge.style.top = topPx + "px"; + badge.style.left = leftPx + "px"; + badge.style.display = "block"; + } else if (badge) { + badge.style.display = "none"; } } @@ -478,10 +647,10 @@ if (app && typeof app.setStateAndRender === "function") { app.setStateAndRender(kf.state, kf.spotlight); } - highlightDomTarget(kf.spotlight && kf.spotlight.target); + highlightDomTarget(kf); renderTutorialUI(); if (narrateNow || isPlaying) { - speakSubtitle(kf.subtitle, isPlaying); + speakSubtitle(kf, isPlaying); } } @@ -564,14 +733,14 @@ speechBtn.className = speechEnabled ? "btn primary" : "btn"; } if (stepBadge) { - stepBadge.textContent = ep.code + " \u2022 Scene " + (curStepIdx + 1) + "/" + ep.keyframes.length; + stepBadge.textContent = ep.code + " \u2022 Scene " + (curStepIdx + 1) + "/" + ep.keyframes.length + (kf.uiElementLabel ? " \u2022 [" + kf.uiElementLabel + "]" : ""); } if (scrubber) { scrubber.max = String(ep.keyframes.length - 1); scrubber.value = String(curStepIdx); } if (titleEl) { - titleEl.textContent = kf.title; + titleEl.textContent = kf.title + (kf.uiElementLabel ? " \u2014 UI Element: " + kf.uiElementLabel : ""); } if (subEl) { subEl.textContent = kf.subtitle; @@ -614,7 +783,7 @@ if (speechBtn) { speechBtn.onclick = function () { speechEnabled = !speechEnabled; - if (speechEnabled) speakSubtitle(getActiveKeyframe().subtitle, isPlaying); + if (speechEnabled) speakSubtitle(getActiveKeyframe(), isPlaying); else if (typeof window.speechSynthesis !== "undefined") { try { window.speechSynthesis.cancel(); } catch (_) {} } @@ -629,19 +798,33 @@ }; } + window.addEventListener("scroll", function () { + if (isPlaying) highlightDomTarget(getActiveKeyframe()); + }, { passive: true }); + renderTutorialUI(); } - window.HyperstitionStudio.QuantTutorials = { - version: "2.10.0", + const exportedApi = { + version: "2.12.0", episodes: EPISODES, + allHighlightableDomIds: ALL_HIGHLIGHTABLE_DOM_IDS, + cleanTextForSpeech: cleanTextForSpeech, + highlightDomTarget: highlightDomTarget, + speakSubtitle: speakSubtitle, adaptHrefForFileProtocol: adaptHrefForFileProtocol, init: initTutorials }; + rootObj.HyperstitionStudio.QuantTutorials = exportedApi; + if (typeof module !== "undefined" && module.exports) { + module.exports = exportedApi; + } - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", initTutorials); - } else { - initTutorials(); + if (typeof document !== "undefined") { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", initTutorials); + } else { + initTutorials(); + } } })(); diff --git a/src/hyperstitionstud_io/__init__.py b/src/hyperstitionstud_io/__init__.py index 0a6b23b..adffb11 100644 --- a/src/hyperstitionstud_io/__init__.py +++ b/src/hyperstitionstud_io/__init__.py @@ -1,3 +1,3 @@ -"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.10.0).""" -__version__ = "2.10.0" +"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v2.12.0).""" +__version__ = "2.12.0" NAMESPACE_URN = "urn:io:hyperstitionstud" diff --git a/src/hyperstitionstud_io/ci/doctor.py b/src/hyperstitionstud_io/ci/doctor.py index 241d125..98b695a 100644 --- a/src/hyperstitionstud_io/ci/doctor.py +++ b/src/hyperstitionstud_io/ci/doctor.py @@ -64,8 +64,7 @@ def run_diagnostics(workspace_root: str | Path | None = None) -> dict[str, Any]: and "/var/lib/hyperstitionstud.io/api-telemetry.db" in lr_txt and "/tmp/" not in lr_txt and "size 100M" in lr_txt - and "compress" in lr_txt - and "nocompress" not in lr_txt + and "nocompress" in lr_txt and "rotate 0" not in lr_txt and "--truncate-quiescent" in lr_txt and "--compress-archive" in lr_txt diff --git a/src/hyperstitionstud_io/ci/public_regression.py b/src/hyperstitionstud_io/ci/public_regression.py index 5f30bca..285cd50 100644 --- a/src/hyperstitionstud_io/ci/public_regression.py +++ b/src/hyperstitionstud_io/ci/public_regression.py @@ -176,12 +176,14 @@ def write_internal_test_baseline_cache( def _http_fetch(url: str, method: str = "GET", body_bytes: bytes | None = None, timeout: float = 10.0) -> tuple[int, bytes]: + from hyperstitionstud_io.security import safe_urlopen + headers = {"User-Agent": _USER_AGENT} if body_bytes is not None: headers["Content-Type"] = "application/json" req = urllib.request.Request(url, data=body_bytes, headers=headers, method=method) try: - with urllib.request.urlopen(req, timeout=timeout) as resp: + with safe_urlopen(req, timeout=timeout, allow_http_localhost=True) as resp: return int(resp.status), resp.read() except urllib.error.HTTPError as exc: return int(exc.code), exc.read() if exc.fp else b"" diff --git a/src/hyperstitionstud_io/ciphers/__init__.py b/src/hyperstitionstud_io/ciphers/__init__.py index f1eeb31..dbf0b26 100644 --- a/src/hyperstitionstud_io/ciphers/__init__.py +++ b/src/hyperstitionstud_io/ciphers/__init__.py @@ -78,6 +78,23 @@ def compute_aq(text: str, quant_mode: QuantMode = "digit") -> int: return total +def char_value_aq(ch: str) -> int: + c = ch.lower() + if "0" <= c <= "9": + return ord(c) - 48 + if "a" <= c <= "z": + return ord(c) - 87 + return 0 + + +def compute_english_ordinal(text: str) -> int: + return sum((ord(c) - 96) for c in text.lower() if "a" <= c <= "z") + + +def compute_full_reduction(text: str) -> int: + return sum(((ord(c) - 97) % 9) + 1 for c in text.lower() if "a" <= c <= "z") + + def is_prime(n: int) -> bool: if n < 2: return False diff --git a/src/hyperstitionstud_io/config/__init__.py b/src/hyperstitionstud_io/config/__init__.py index 366bccc..06246da 100644 --- a/src/hyperstitionstud_io/config/__init__.py +++ b/src/hyperstitionstud_io/config/__init__.py @@ -7,6 +7,9 @@ hardcoded /workspace assumptions. from __future__ import annotations +import copy +import functools +import json import os import tomllib from dataclasses import dataclass, field @@ -18,6 +21,23 @@ WORKSPACE_ROOT = CORE_REPO_ROOT.parent USER_WORKSPACE_TOML = Path.home() / ".config" / "hyperstitionstud.io" / "workspace.toml" +@functools.lru_cache(maxsize=64) +def _parse_json_by_stat(resolved_path_str: str, st_mtime_ns: int, st_size: int) -> Any: + _ = (st_mtime_ns, st_size) + return json.loads(Path(resolved_path_str).read_text(encoding="utf-8")) + + +def load_json_cached(path: str | Path, *, copy_result: bool = True) -> Any: + """ + Load and parse a UTF-8 JSON file cached by `(resolved_path_str, st_mtime_ns, st_size)`. + Automatically invalidates the instant `st_mtime_ns` or `st_size` changes on disk. + """ + p = Path(path).resolve() + st = p.stat() + parsed = _parse_json_by_stat(str(p), st.st_mtime_ns, st.st_size) + return copy.deepcopy(parsed) if copy_result else parsed + + @dataclass(frozen=True) class WorkspaceConfig: schema_version: str = "1.2.0" diff --git a/src/hyperstitionstud_io/db/sqlite_meta.py b/src/hyperstitionstud_io/db/sqlite_meta.py index 7ec0e9c..c855485 100644 --- a/src/hyperstitionstud_io/db/sqlite_meta.py +++ b/src/hyperstitionstud_io/db/sqlite_meta.py @@ -723,6 +723,8 @@ def _open_readonly_catalog(db_path: Path | str | None = None) -> sqlite3.Connect conn = sqlite3.connect(uri, uri=True) conn.row_factory = sqlite3.Row conn.execute("PRAGMA query_only = ON;") + conn.execute("PRAGMA temp_store = MEMORY;") + conn.execute("PRAGMA cache_size = -8000;") return conn @@ -881,6 +883,44 @@ def query_timeseries_bars( conn.close() +def ensure_single_layer_gzip_file(gz_path: Path | str) -> dict[str, Any]: + """ + Inspect `gz_path` and ensure its decompressed stream is compressed strictly once (`1x`). + If the decompressed payload itself begins with a gzip (`\\x1f\\x8b`) or xz (`\\xfd7zXZ\\x00`) + magic header, iteratively peel outer compression layers in-place until the inner stream + is the raw uncompressed payload (e.g., `"SQLite format 3\\x00"` or POSIX `ustar`). + """ + p = Path(gz_path) + if not p.is_file(): + return {"path": str(p), "peeled_layers": 0, "single_layer_verified": False} + peeled = 0 + while True: + with gzip.open(p, "rb") as f_gz: + head = f_gz.read(6) + if head.startswith(b"\x1f\x8b"): + f_gz.seek(0) + inner_bytes = f_gz.read() + elif head.startswith(b"\xfd7zXZ\x00"): + import lzma + + f_gz.seek(0) + raw_unwrapped = lzma.decompress(f_gz.read()) + tmp_p = p.with_suffix(p.suffix + f".peel.{os.getpid()}") + with open(tmp_p, "wb") as f_raw: + with gzip.GzipFile(filename="", mode="wb", fileobj=f_raw, compresslevel=9, mtime=0) as gz_out: + gz_out.write(raw_unwrapped) + os.replace(tmp_p, p) + peeled += 1 + continue + else: + break + tmp_p = p.with_suffix(p.suffix + f".peel.{os.getpid()}") + tmp_p.write_bytes(inner_bytes) + os.replace(tmp_p, p) + peeled += 1 + return {"path": str(p), "peeled_layers": peeled, "single_layer_verified": True} + + def _rotate_compressed_archives(base_db_path: Path, rotate_keep: int = 12) -> Path: """ Shift existing `.{1..K-1}.gz` archives up by 1 and return `.1.gz`. @@ -893,6 +933,7 @@ def _rotate_compressed_archives(base_db_path: Path, rotate_keep: int = 12) -> Pa src = Path(f"{base_db_path}.{idx}.gz") dst = Path(f"{base_db_path}.{idx + 1}.gz") if src.exists(): + ensure_single_layer_gzip_file(src) src.replace(dst) return Path(f"{base_db_path}.1.gz") @@ -971,6 +1012,7 @@ def truncate_telemetry_db_quiescent( gz_target = _rotate_compressed_archives(t_path, rotate_keep=rotate_keep) with open(snap_tmp, "rb") as f_in, gzip.open(gz_target, "wb", compresslevel=9) as f_out: f_out.write(f_in.read()) + ensure_single_layer_gzip_file(gz_target) compressed_archive_path = str(gz_target) compressed_archive_bytes = gz_target.stat().st_size finally: @@ -1029,6 +1071,27 @@ def _ensure_telemetry_columns(conn: sqlite3.Connection) -> None: conn.execute("ALTER TABLE api_audit_ringbuffer ADD COLUMN traffic_source TEXT NOT NULL DEFAULT 'internal_test';") +_INITIALIZED_TELEMETRY_INODES: set[tuple[str, int, int]] = set() + + +def _ensure_telemetry_schema_initialized(conn: sqlite3.Connection, db_path: Path) -> None: + try: + st = db_path.stat() + inode_key = (str(db_path.resolve()), st.st_dev, st.st_ino) + except OSError: + inode_key = None + if inode_key is not None and inode_key in _INITIALIZED_TELEMETRY_INODES and st.st_size > 0: + return + conn.executescript(TELEMETRY_SCHEMA_SQL) + _ensure_telemetry_columns(conn) + if inode_key is not None: + try: + st_after = db_path.stat() + _INITIALIZED_TELEMETRY_INODES.add((str(db_path.resolve()), st_after.st_dev, st_after.st_ino)) + except OSError: + pass + + def record_api_telemetry( protocol: str, method: str, @@ -1088,8 +1151,7 @@ def record_api_telemetry( conn = sqlite3.connect(str(t_path), timeout=30.0, isolation_level=None) try: conn.execute("PRAGMA busy_timeout = 30000;") - conn.executescript(TELEMETRY_SCHEMA_SQL) - _ensure_telemetry_columns(conn) + _ensure_telemetry_schema_initialized(conn, t_path) conn.execute("BEGIN IMMEDIATE;") try: conn.execute( @@ -1422,8 +1484,10 @@ def run_logrotate_directive( configured_size_str = m_size.group(1) configured_bytes = parse_size_spec_bytes(configured_size_str) - if not re.search(r"^\s*compress\s*$", txt, flags=re.MULTILINE) or re.search(r"^\s*nocompress\s*$", txt, flags=re.MULTILINE): - raise ValueError(f"{c_path} must specify 'compress' (and not 'nocompress') so rotated archives are compressed rather than removed.") + if not re.search(r"^\s*nocompress\s*$", txt, flags=re.MULTILINE) or "--compress-archive" not in txt: + raise ValueError( + f"{c_path} must specify 'nocompress' in the outer logrotate block and '--compress-archive' in prerotate so sqlite_meta.py compresses rotated archives strictly once (1x)." + ) m_rot = re.search(r"^\s*rotate\s+(\d+)\s*$", txt, flags=re.MULTILINE) rotate_count = int(m_rot.group(1)) if m_rot else 0 if rotate_count < 1: diff --git a/src/hyperstitionstud_io/glossary/__init__.py b/src/hyperstitionstud_io/glossary/__init__.py index d59bf32..c057da5 100644 --- a/src/hyperstitionstud_io/glossary/__init__.py +++ b/src/hyperstitionstud_io/glossary/__init__.py @@ -4,13 +4,22 @@ hyperstitionstud_io.glossary — Provenance-Keyed Glossary Registry & Cryptograp from __future__ import annotations +import functools import hashlib from pathlib import Path from typing import Any, Iterable +@functools.lru_cache(maxsize=128) +def _sha256_by_stat(resolved_path_str: str, st_mtime_ns: int, st_size: int) -> str: + _ = (st_mtime_ns, st_size) + return hashlib.sha256(Path(resolved_path_str).read_bytes()).hexdigest() + + def sha256_file(path: str | Path) -> str: - return hashlib.sha256(Path(path).read_bytes()).hexdigest() + p = Path(path).resolve() + st = p.stat() + return _sha256_by_stat(str(p), st.st_mtime_ns, st.st_size) class ReadOnlyIsolationGuard: diff --git a/src/hyperstitionstud_io/mcp/resources.py b/src/hyperstitionstud_io/mcp/resources.py index 9af0246..8d52bb5 100644 --- a/src/hyperstitionstud_io/mcp/resources.py +++ b/src/hyperstitionstud_io/mcp/resources.py @@ -8,7 +8,7 @@ import json import re from typing import Any -from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.config import load_json_cached, load_workspace_config STATIC_RESOURCES: list[dict[str, str]] = [ { @@ -140,7 +140,7 @@ def read_mcp_resource(uri: str) -> dict[str, Any]: } if uri == "urn:io:hyperstitionstud:resource:knowledge-graph-summary": - kg = json.loads((cfg.knowledge_graph_dir / "encyclopedia-graph.json").read_text(encoding="utf-8")) + kg = load_json_cached(cfg.knowledge_graph_dir / "encyclopedia-graph.json", copy_result=False) summary = { "version": kg.get("version"), "namespace_urn": kg.get("namespace_urn"), diff --git a/src/hyperstitionstud_io/mcp/server.py b/src/hyperstitionstud_io/mcp/server.py index 629265c..53f8852 100755 --- a/src/hyperstitionstud_io/mcp/server.py +++ b/src/hyperstitionstud_io/mcp/server.py @@ -39,8 +39,8 @@ from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noq SERVER_INFO = { "name": "hyperstitionstudio-mcp", - "version": "2.10.0", - "namespace_urn": "urn:io:hyperstitionstud:mcp:2.10.0", + "version": "2.12.0", + "namespace_urn": "urn:io:hyperstitionstud:mcp:2.12.0", } diff --git a/src/hyperstitionstud_io/mcp/tools.py b/src/hyperstitionstud_io/mcp/tools.py index 2c1c0a0..2aa1389 100644 --- a/src/hyperstitionstud_io/mcp/tools.py +++ b/src/hyperstitionstud_io/mcp/tools.py @@ -19,10 +19,11 @@ from hyperstitionstud_io.ciphers import ( is_repdigit_37, prime_rank, ) -from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.config import load_json_cached, load_workspace_config from hyperstitionstud_io.ipld import inspect_dag_json_payload from hyperstitionstud_io.phonetics import translate_batch from hyperstitionstud_io.quant.collector import build_financial_quant_harvest +from hyperstitionstud_io.security import safe_tar_members REGISTER_STAT_LABELS = { "academic": { @@ -355,8 +356,8 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: if name == "hs_classify_singularity": terms = [str(t) for t in arguments.get("terms", [])] headline = str(arguments.get("headline_text", "")).lower() - mat = json.loads((cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json").read_text(encoding="utf-8")) - mem = json.loads((cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json").read_text(encoding="utf-8")) + mat = load_json_cached(cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json", copy_result=False) + mem = load_json_cached(cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json", copy_result=False) ing_map = translate_batch(terms) classified = [] @@ -393,7 +394,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: q = str(arguments.get("query", "")).strip().lower() inc_nbr = bool(arguments.get("include_neighbors", True)) kg_path = cfg.knowledge_graph_dir / "encyclopedia-graph.json" - kg = json.loads(kg_path.read_text(encoding="utf-8")) + kg = load_json_cached(kg_path, copy_result=False) matches = [] for n in kg["nodes"]: if ( @@ -429,7 +430,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: q = str(arguments.get("query", "")).strip().lower() g_filt = str(arguments.get("guild_filter", "")).strip().upper() limit = int(arguments.get("limit", 15)) - gl = json.loads((cfg.zoology_dir / "taxonomy" / "glossary-registry.json").read_text(encoding="utf-8")) + gl = load_json_cached(cfg.zoology_dir / "taxonomy" / "glossary-registry.json", copy_result=False) hits = [] for sec in gl.get("sections", []): for ent in sec.get("entries", []): @@ -454,7 +455,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: if name == "hs_inspect_eti_tier_list": b_filt = str(arguments.get("build_filter", "all")).strip().upper() reg = str(arguments.get("register", "academic")).strip().lower() - tl = json.loads((cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json").read_text(encoding="utf-8")) + tl = load_json_cached(cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json", copy_result=False) labels = REGISTER_STAT_LABELS.get(reg, REGISTER_STAT_LABELS["academic"]) rows = [] for r in tl.get("rows", []): @@ -486,7 +487,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: aid = str(arguments.get("anchor_id", "")).strip() new_dig = str(arguments.get("new_digit_str", "")).strip() new_sp_eng = str(arguments.get("new_spoken_eng", "")).strip() - anc_data = json.loads((cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json").read_text(encoding="utf-8")) + anc_data = load_json_cached(cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json", copy_result=False) anchor = next((a for a in anc_data.get("anchors", []) if a["anchor_id"] == aid), None) if anchor is None: return {"error": f"Unknown anchor_id '{aid}'", "available_anchors": [a["anchor_id"] for a in anc_data.get("anchors", [])]} @@ -573,6 +574,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: "engineering-manifest": cfg.core_dir / "site" / "engineering" / "engineering-manifest.json", "math-manifest": cfg.core_dir / "site" / "math" / "math-manifest.json", "archive-manifest": cfg.knowledge_graph_dir / "docs" / "archive" / "archive-manifest.json", + "inactive-archive-manifest": cfg.knowledge_graph_dir / "docs" / "plans" / "inactive" / "inactive-archive-manifest.json", } p = reg_map.get(str(reg_name)) if p is None or not p.is_file(): @@ -604,7 +606,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: lens_q = str(arguments.get("lens", "fund_manager")).strip() ts_json_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json" if ts_json_path.is_file(): - bundle = json.loads(ts_json_path.read_text(encoding="utf-8")) + bundle = load_json_cached(ts_json_path, copy_result=False) else: bundle = build_quant_timeseries_bundle(write_files=False) if sym_q: @@ -662,7 +664,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: slug_f = str(arguments.get("indicator_slug", "")).strip().lower() m_path = cfg.core_dir / "site" / "quant" / "real-macro-indicators.json" if m_path.is_file(): - m_bundle = json.loads(m_path.read_text(encoding="utf-8")) + m_bundle = load_json_cached(m_path, copy_result=False) else: m_bundle = build_macro_indicators_bundle(allow_live_network=False, write_files=False) if slug_f and slug_f in (m_bundle.get("series") or {}): @@ -681,7 +683,7 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: b_path = cfg.core_dir / "site" / "quant" / "daily-brief-latest.json" if bool(arguments.get("refresh")) or not b_path.is_file(): return build_daily_portfolio_brief(allow_live_network=False, write_files=False) - return json.loads(b_path.read_text(encoding="utf-8")) + return load_json_cached(b_path) if name == "hs_inspect_engineering_and_math_docs": from hyperstitionstud_io.publishing.engineering_docs import ( @@ -699,8 +701,8 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: eng_p = cfg.core_dir / "site" / "engineering" / "engineering-manifest.json" math_p = cfg.core_dir / "site" / "math" / "math-manifest.json" - eng_m = json.loads(eng_p.read_text(encoding="utf-8")) if eng_p.is_file() else introspect_engineering_manifest() - math_m = json.loads(math_p.read_text(encoding="utf-8")) if math_p.is_file() else introspect_math_manifest() + eng_m = load_json_cached(eng_p, copy_result=False) if eng_p.is_file() else introspect_engineering_manifest() + math_m = load_json_cached(math_p, copy_result=False) if math_p.is_file() else introspect_math_manifest() out_docs: dict[str, Any] = {"version": eng_m["version"], "domain": dom} if dom in ("all", "engineering"): @@ -832,35 +834,116 @@ def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: archived_out: list[dict[str, Any]] = [] if cat in ("all", "archived_plans"): - for arc_dir in (cfg.knowledge_graph_dir / "docs" / "archive", cfg.zoology_dir / "docs" / "archive"): - tgz_p = arc_dir / "completed-plans-archive.tar.gz" - if not tgz_p.is_file(): - continue - with tarfile.open(tgz_p, "r:gz") as tf: - for m in tf.getmembers(): - if not m.name.endswith(".md"): - continue - stem = Path(m.name).stem - if doc_id and doc_id.lower() not in stem.lower(): - continue - f_obj = tf.extractfile(m) - if f_obj is None: - continue - m_txt = f_obj.read().decode("utf-8", errors="replace") - if sq and sq not in m_txt.lower() and sq not in stem.lower(): - continue - arc_item: dict[str, Any] = { - "id": stem, - "category": "archived_plans", - "bundle": str(tgz_p.name), - "member_name": m.name, - "char_count": len(m_txt), - } - if sq: - arc_item["matched_lines"] = [ln for ln in m_txt.splitlines() if sq in ln.lower()][:10] - if inc_md: - arc_item["markdown"] = m_txt - archived_out.append(arc_item) + from hyperstitionstud_io.publishing.archive_rotator import ( + BUNDLE_FILENAME, + INACTIVE_BUNDLE_FILENAME, + INACTIVE_MANIFEST_FILENAME, + MANIFEST_FILENAME, + read_member_from_git_history, + ) + + arc_sources = [ + ( + cfg.knowledge_graph_dir / "docs" / "archive", + BUNDLE_FILENAME, + MANIFEST_FILENAME, + "archived_completed", + ), + ( + cfg.zoology_dir / "docs" / "archive", + BUNDLE_FILENAME, + MANIFEST_FILENAME, + "archived_completed", + ), + ( + cfg.knowledge_graph_dir / "docs" / "plans" / "inactive", + INACTIVE_BUNDLE_FILENAME, + INACTIVE_MANIFEST_FILENAME, + "archived_inactive", + ), + ] + for arc_dir, b_fname, m_fname, cls_tag in arc_sources: + tgz_p = arc_dir / b_fname + man_p = arc_dir / m_fname + man_obj: dict[str, Any] = {} + if man_p.is_file(): + try: + man_obj = load_json_cached(man_p, copy_result=False) + except Exception: + man_obj = {} + cit_by_name = { + str(it.get("name")): it + for it in (man_obj.get("members") or []) + (man_obj.get("long_term_git_storage_citations") or []) + if it.get("name") + } + + seen_names: set[str] = set() + if tgz_p.is_file(): + with tarfile.open(tgz_p, "r:gz") as tf: + for m in safe_tar_members(tf): + if not m.name.endswith(".md"): + continue + seen_names.add(m.name) + stem = Path(m.name).stem + if doc_id and doc_id.lower() not in stem.lower(): + continue + f_obj = tf.extractfile(m) + if f_obj is None: + continue + m_txt = f_obj.read().decode("utf-8", errors="replace") + if sq and sq not in m_txt.lower() and sq not in stem.lower(): + continue + cit_info = cit_by_name.get(m.name) or {} + arc_item: dict[str, Any] = { + "id": stem, + "category": "archived_plans", + "classification": cit_info.get("classification", cls_tag), + "storage_tier": "active_tar_gz_bundle", + "bundle": str(tgz_p.name), + "member_name": m.name, + "char_count": len(m_txt), + "git_citation_url": cit_info.get("git_citation_url"), + } + if sq: + arc_item["matched_lines"] = [ln for ln in m_txt.splitlines() if sq in ln.lower()][:10] + if inc_md: + arc_item["markdown"] = m_txt + archived_out.append(arc_item) + + # Also search long_term_git_storage_citations via local .git fallback + for lt in man_obj.get("long_term_git_storage_citations") or []: + lt_name = str(lt.get("name") or "") + if not lt_name.endswith(".md") or lt_name in seen_names: + continue + stem = Path(lt_name).stem + if doc_id and doc_id.lower() not in stem.lower(): + continue + raw_b = read_member_from_git_history( + archive_dir=arc_dir, + member_name=lt_name, + citation_meta=lt, + bundle_filename=b_fname, + ) + if raw_b is None: + continue + m_txt = raw_b.decode("utf-8", errors="replace") + if sq and sq not in m_txt.lower() and sq not in stem.lower(): + continue + lt_item: dict[str, Any] = { + "id": stem, + "category": "archived_plans", + "classification": lt.get("classification", cls_tag), + "storage_tier": "git_source_control_long_term", + "bundle": str(tgz_p.name), + "member_name": lt_name, + "char_count": len(m_txt), + "git_citation_url": lt.get("git_citation_url"), + } + if sq: + lt_item["matched_lines"] = [ln for ln in m_txt.splitlines() if sq in ln.lower()][:10] + if inc_md: + lt_item["markdown"] = m_txt + archived_out.append(lt_item) res_doc: dict[str, Any] = { "category_filter": cat, diff --git a/src/hyperstitionstud_io/phonetics/__init__.py b/src/hyperstitionstud_io/phonetics/__init__.py index 62164ec..e3fb3e0 100644 --- a/src/hyperstitionstud_io/phonetics/__init__.py +++ b/src/hyperstitionstud_io/phonetics/__init__.py @@ -11,20 +11,15 @@ import shutil import subprocess from pathlib import Path -from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.config import load_json_cached, load_workspace_config _FALLBACK_PATH = Path(__file__).resolve().parent / "cmudict_fallback.json" -_FALLBACK_CACHE: dict[str, str] | None = None def _load_fallback() -> dict[str, str]: - global _FALLBACK_CACHE - if _FALLBACK_CACHE is None: - if _FALLBACK_PATH.is_file(): - _FALLBACK_CACHE = json.loads(_FALLBACK_PATH.read_text(encoding="utf-8")) - else: - _FALLBACK_CACHE = {} - return _FALLBACK_CACHE + if _FALLBACK_PATH.is_file(): + return load_json_cached(_FALLBACK_PATH, copy_result=False) + return {} def translate_batch(terms: list[str], workdir: str | Path | None = None) -> dict[str, str]: diff --git a/src/hyperstitionstud_io/publishing/archive_rotator.py b/src/hyperstitionstud_io/publishing/archive_rotator.py index 35ca517..07be252 100644 --- a/src/hyperstitionstud_io/publishing/archive_rotator.py +++ b/src/hyperstitionstud_io/publishing/archive_rotator.py @@ -1,41 +1,67 @@ #!/usr/bin/env python3 """ hyperstitionstud_io.publishing.archive_rotator -Deterministic Cold-Storage Archive Rotator (`hs-archive-rotate`) for Completed Software Plans in `docs/archive/`. +Deterministic Cold-Storage Archive Rotator (`hs-archive-rotate`) for Completed (`docs/archive/`) +and Marked Inactive (`docs/plans/inactive/`) Software Plans. + Enforces: 1. Gematria-Pipeline Immunity Gate (`assert_not_gematria_pipeline_source()` — 0 gematria/dossier/lexicon/graph/quant/calc sources ever rotated), 2. Pre- vs. Post-Rotation Gematria Richness Parity Gate (`verify_gematria_pipeline_richness_invariant()`), - 3. Companion-Markdown Requirement (`require_companion_md=True` — standalone `.pdf`s with `has_md=False` are never rotated or unlinked). + 3. Companion-Markdown Requirement (`require_companion_md=True` — standalone `.pdf`s in `docs/archive/` with `has_md=False` are never rotated or unlinked), + 4. Single-Layer (`1x`) Compression Enforcement & `.md`-Only Bundle Policy (`PLAN-SINGLE-LAYER-COMPRESSION-ENFORCEMENT-AND-MULTI-COMPRESSED-FILE-REMEDIATION`), + 5. Bounded Server-Side Bundle Size Cap (`DEFAULT_MAX_ARCHIVE_BUNDLE_BYTES = 262_144` / `256 KB` via `--max-bundle-kb`) with FIFO rotation into Long-Term Source-Control (`git.libre.audio`) Hyperlink Citations (`PLAN-SERVER-SIDE-COMPRESSED-PLAN-SIZE-CAP-AND-GIT-CITATION-ROTATION`), + 6. Selective Cold-Archival of Inactive Plans Marked for Archival (`--archive-inactive`, `--extract-inactive`, `PLAN-INACTIVE-PLANS-COLD-ARCHIVE-AND-COMPRESSION`), + 7. Shared `_pack_verify_and_write_archive_manifest()` Core, Per-Repo Git Citation Memoization & `PEP 706` `safe_tar_members()` (`Strategies 3A, 4A, 7A`). """ from __future__ import annotations import argparse +import functools import gzip import hashlib import io import json import os +import re import shutil +import subprocess import tarfile import tempfile from pathlib import Path from typing import Any from hyperstitionstud_io import __version__ as CURRENT_VERSION -from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.config import load_json_cached, load_workspace_config +from hyperstitionstud_io.db.sqlite_meta import ensure_single_layer_gzip_file, parse_size_spec_bytes from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard, sha256_file +from hyperstitionstud_io.ipld import compute_dag_json_cidv1 +from hyperstitionstud_io.security import safe_tar_members BUNDLE_FILENAME = "completed-plans-archive.tar.gz" MANIFEST_FILENAME = "archive-manifest.json" +INACTIVE_BUNDLE_FILENAME = "inactive-plans-archive.tar.gz" +INACTIVE_MANIFEST_FILENAME = "inactive-archive-manifest.json" + +DEFAULT_MAX_ARCHIVE_BUNDLE_BYTES = 256 * 1024 # 262,144 bytes (256 KB) + + +def _norm_ws_path(p: Path | str, workspace_root: str | Path | None = None) -> str: + cfg = load_workspace_config(workspace_root=workspace_root) + ws_res = str(cfg.workspace_root.resolve()) + s = str(Path(p).resolve()) + if s.startswith(ws_res): + return "/workspace" + s[len(ws_res):] + return str(p) + def assert_not_gematria_pipeline_source(target_path: str | Path, workspace_root: str | Path | None = None) -> Path: """ Hard programmatic block guaranteeing that NO file supplying any gematria, phonemic, knowledge-graph, zoological, quantitative, macroeconomic, or calculator pipeline can ever be rotated or compressed. - Only files strictly inside `/docs/archive/` are eligible. + Only files strictly inside `/docs/archive/` or `encyclopedia-knowledge-graph/docs/plans/inactive/` are eligible. """ cfg = load_workspace_config(workspace_root=workspace_root) p = Path(target_path).resolve() @@ -69,6 +95,7 @@ def assert_not_gematria_pipeline_source(target_path: str | Path, workspace_root: allowed_dirs = ( (cfg.knowledge_graph_dir / "docs" / "archive").resolve(), (cfg.zoology_dir / "docs" / "archive").resolve(), + (cfg.knowledge_graph_dir / "docs" / "plans" / "inactive").resolve(), ) if p not in allowed_dirs and p.parent not in allowed_dirs: raise ValueError( @@ -83,15 +110,19 @@ def snapshot_gematria_pipeline_richness(workspace_root: str | Path | None = None dossiers = sorted(cfg.archive_dir.rglob("*.md")) dated_news = sorted(cfg.archive_dir.rglob("*-dossier-news-*.md")) gl_path = cfg.zoology_dir / "taxonomy" / "glossary-registry.json" - gl_obj = json.loads(gl_path.read_text(encoding="utf-8")) + gl_obj = load_json_cached(gl_path, copy_result=False) bilingual_cnt = len(gl_obj.get("bilingual_vocabulary_ledger") or []) - sec_entries_cnt = sum(len(sec.get("entries") or []) for sec in (gl_obj.get("sections") or [])) + len(gl_obj.get("custom_entries") or []) + bilingual_cnt + sec_entries_cnt = ( + sum(len(sec.get("entries") or []) for sec in (gl_obj.get("sections") or [])) + + len(gl_obj.get("custom_entries") or []) + + bilingual_cnt + ) kg_path = cfg.knowledge_graph_dir / "encyclopedia-graph.json" - kg_obj = json.loads(kg_path.read_text(encoding="utf-8")) + kg_obj = load_json_cached(kg_path, copy_result=False) ts_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json" - ts_obj = json.loads(ts_path.read_text(encoding="utf-8")) + ts_obj = load_json_cached(ts_path, copy_result=False) mac_path = cfg.core_dir / "site" / "quant" / "real-macro-indicators.json" - mac_obj = json.loads(mac_path.read_text(encoding="utf-8")) + mac_obj = load_json_cached(mac_path, copy_result=False) calc_db_txt = cfg.paths["gematria_js_dir"] / "db.txt" fb_path = cfg.core_dir / "src" / "hyperstitionstud_io" / "phonetics" / "cmudict_fallback.json" @@ -111,7 +142,7 @@ def snapshot_gematria_pipeline_richness(workspace_root: str | Path | None = None ), "fred_macro_series_count": int(mac_obj.get("series_count") or 0), "calc_db_txt_bytes": calc_db_txt.stat().st_size if calc_db_txt.is_file() else 0, - "cmudict_fallback_entries": len(json.loads(fb_path.read_text(encoding="utf-8"))), + "cmudict_fallback_entries": len(load_json_cached(fb_path, copy_result=False)), } @@ -136,143 +167,876 @@ def verify_gematria_pipeline_richness_invariant( return True +def _find_git_repo_root(path: Path) -> Path | None: + cur = path.resolve() + if cur.is_file(): + cur = cur.parent + for cand in (cur, *cur.parents): + if (cand / ".git").exists(): + return cand + return None + + +@functools.lru_cache(maxsize=16) +def _get_repo_git_citation_cache(repo_root_str: str) -> dict[str, Any]: + """ + Strategy 7A: Query `git remote`, `git rev-parse HEAD`, `git show-ref --tags`, and + `git log --name-status` ONCE per repository rather than spawning 2-4 `git` subprocesses + per archived plan member. + """ + repo_root = Path(repo_root_str) + repo_name = repo_root.name + origin_https = f"https://git.libre.audio/seasharp/{repo_name}" + try: + rem = subprocess.check_output( + ["git", "-C", repo_root_str, "remote", "get-url", "origin"], + text=True, + stderr=subprocess.DEVNULL, + ).strip() + m_rem = re.search(r"git\.libre\.audio(?::\d+)?[:/]([^/]+/[^/.]+?)(?:\.git)?$", rem) + if m_rem: + origin_https = f"https://git.libre.audio/{m_rem.group(1)}" + except Exception: + pass + + head_sha = "0" * 40 + try: + head_sha = subprocess.check_output( + ["git", "-C", repo_root_str, "rev-parse", "HEAD"], + text=True, + stderr=subprocess.DEVNULL, + ).strip() + except Exception: + pass + + tags_by_sha: dict[str, str] = {} + try: + tag_lines = subprocess.check_output( + ["git", "-C", repo_root_str, "show-ref", "--tags", "-d"], + text=True, + stderr=subprocess.DEVNULL, + ).splitlines() + for ln in tag_lines: + parts = ln.split() + if len(parts) == 2: + sha_s, ref_s = parts + t_name = ref_s.removeprefix("refs/tags/").removesuffix("^{}") + tags_by_sha[sha_s] = t_name + except Exception: + pass + + # Map relative file paths to their latest non-deletion commit SHA in a single git log call + latest_non_delete_sha: dict[str, str] = {} + all_shas_by_path: dict[str, list[str]] = {} + try: + log_out = subprocess.check_output( + ["git", "-C", repo_root_str, "log", "--format=COMMIT:%H", "--name-status", "--", "docs/"], + text=True, + stderr=subprocess.DEVNULL, + ).splitlines() + cur_sha = "" + for ln in log_out: + if ln.startswith("COMMIT:"): + cur_sha = ln.split(":", 1)[1].strip() + elif cur_sha and "\t" in ln: + st_parts = ln.split("\t") + status_ch = st_parts[0].strip()[:1] + rel_p = st_parts[-1].strip() + if status_ch != "D": + all_shas_by_path.setdefault(rel_p, []).append(cur_sha) + if rel_p not in latest_non_delete_sha: + latest_non_delete_sha[rel_p] = cur_sha + except Exception: + pass + + return { + "origin_https": origin_https, + "head_sha": head_sha, + "tags_by_sha": tags_by_sha, + "latest_non_delete_sha": latest_non_delete_sha, + "all_shas_by_path": all_shas_by_path, + } + + +def resolve_git_citation_metadata( + archive_dir: Path, + member_name: str, + bundle_filename: str = BUNDLE_FILENAME, + existing_meta: dict[str, Any] | None = None, +) -> dict[str, Any]: + """ + Resolve canonical `https://git.libre.audio/seasharp//src/commit//...` citation metadata + for a plan `.md` member inside `archive_dir` using the per-repo memoized Git history index. + """ + repo_root = _find_git_repo_root(archive_dir) + if repo_root is None: + return { + "git_commit_sha": (existing_meta or {}).get("git_commit_sha", "0" * 40), + "git_release_tag": (existing_meta or {}).get("git_release_tag", f"v{CURRENT_VERSION}"), + "git_citation_url": (existing_meta or {}).get( + "git_citation_url", + f"https://git.libre.audio/seasharp/encyclopedia-knowledge-graph/src/branch/main/{member_name}", + ), + "git_source_path": (existing_meta or {}).get("git_source_path", member_name), + } + + idx = _get_repo_git_citation_cache(str(repo_root.resolve())) + origin_https = idx["origin_https"] + rel_arc = archive_dir.resolve().relative_to(repo_root.resolve()).as_posix() + rel_member = f"{rel_arc}/{member_name}" + rel_bundle = f"{rel_arc}/{bundle_filename}" + + commit_sha = idx["latest_non_delete_sha"].get(rel_member, "") + git_source_path = rel_member + + if not commit_sha: + if existing_meta and existing_meta.get("git_commit_sha") and len(str(existing_meta["git_commit_sha"])) >= 7: + commit_sha = str(existing_meta["git_commit_sha"]) + git_source_path = str(existing_meta.get("git_source_path") or f"{rel_bundle}#{member_name}") + else: + commit_sha = idx["latest_non_delete_sha"].get(rel_bundle, "") or idx["head_sha"] + git_source_path = f"{rel_bundle}#{member_name}" + + release_tag = idx["tags_by_sha"].get(commit_sha, f"v{CURRENT_VERSION}") + citation_url = f"{origin_https}/src/commit/{commit_sha}/{git_source_path}" + + return { + "git_commit_sha": commit_sha, + "git_release_tag": release_tag, + "git_citation_url": citation_url, + "git_source_path": git_source_path, + } + + +def read_member_from_git_history( + archive_dir: Path, + member_name: str, + citation_meta: dict[str, Any] | None = None, + bundle_filename: str = BUNDLE_FILENAME, +) -> bytes | None: + """ + Recover a plan `.md` member's exact bytes from local `.git` history (either from a direct + file commit `:` or from a committed `:` tarball snapshot). + """ + repo_root = _find_git_repo_root(archive_dir) + if repo_root is None: + return None + idx = _get_repo_git_citation_cache(str(repo_root.resolve())) + rel_arc = archive_dir.resolve().relative_to(repo_root.resolve()).as_posix() + rel_member = f"{rel_arc}/{member_name}" + rel_bundle = f"{rel_arc}/{bundle_filename}" + + candidates: list[tuple[str, str]] = [] + if citation_meta: + c_sha = str(citation_meta.get("git_commit_sha") or "").strip() + c_src = str(citation_meta.get("git_source_path") or "").strip() + if c_sha and c_src: + candidates.append((c_sha, c_src)) + + for s in idx["all_shas_by_path"].get(rel_member, []): + candidates.append((s, rel_member)) + for s in idx["all_shas_by_path"].get(rel_bundle, []): + candidates.append((s, f"{rel_bundle}#{member_name}")) + + seen: set[tuple[str, str]] = set() + for sha, src_spec in candidates: + if not sha or (sha, src_spec) in seen: + continue + seen.add((sha, src_spec)) + if "#" in src_spec: + b_path, m_name = src_spec.split("#", 1) + proc = subprocess.run( + ["git", "-C", str(repo_root), "show", f"{sha}:{b_path}"], + capture_output=True, + check=False, + ) + if proc.returncode == 0 and proc.stdout: + try: + with tarfile.open(fileobj=io.BytesIO(proc.stdout), mode="r:gz") as tf: + for m_info in safe_tar_members(tf): + if m_info.name == m_name: + ex = tf.extractfile(m_info) + if ex is not None: + return ex.read() + except Exception: + continue + else: + proc = subprocess.run( + ["git", "-C", str(repo_root), "show", f"{sha}:{src_spec}"], + capture_output=True, + check=False, + ) + if proc.returncode == 0 and proc.stdout: + return proc.stdout + return None + + +def assert_persisted_in_git_history( + archive_dir: Path, + member_name: str, + expected_sha256: str, + citation_meta: dict[str, Any] | None = None, + bundle_filename: str = BUNDLE_FILENAME, +) -> bool: + recovered = read_member_from_git_history( + archive_dir=archive_dir, + member_name=member_name, + citation_meta=citation_meta, + bundle_filename=bundle_filename, + ) + if recovered is None: + return False + return hashlib.sha256(recovered).hexdigest() == expected_sha256 + + +def _pack_deterministic_tar_gz(staged_files: list[Path], out_bundle_path: Path) -> tuple[list[dict[str, Any]], int]: + tmp_bundle = out_bundle_path.parent / f".{out_bundle_path.name}.tmp.{os.getpid()}" + raw_tar_buf = io.BytesIO() + members_meta: list[dict[str, Any]] = [] + total_uncompressed = 0 + + with tarfile.open(fileobj=raw_tar_buf, mode="w") as tf_out: + for sf in sorted(staged_files, key=lambda p: p.name): + data = sf.read_bytes() + sha = hashlib.sha256(data).hexdigest() + ti = tarfile.TarInfo(name=sf.name) + ti.size = len(data) + ti.mtime = 0 + ti.mode = 0o644 + ti.uid = 0 + ti.gid = 0 + ti.uname = "root" + ti.gname = "root" + tf_out.addfile(ti, io.BytesIO(data)) + total_uncompressed += len(data) + members_meta.append( + { + "name": sf.name, + "size_bytes": len(data), + "sha256": sha, + } + ) + + with open(tmp_bundle, "wb") as f_raw: + with gzip.GzipFile(filename="", mode="wb", fileobj=f_raw, compresslevel=9, mtime=0) as gz_out: + gz_out.write(raw_tar_buf.getvalue()) + os.replace(tmp_bundle, out_bundle_path) + ensure_single_layer_gzip_file(out_bundle_path) + return members_meta, total_uncompressed + + +def _pack_verify_and_write_archive_manifest( + *, + arc_p: Path, + bundle_p: Path, + manifest_p: Path, + bundle_filename: str, + archive_classification: str, + staged_files: list[Path], + existing_member_meta_by_name: dict[str, dict[str, Any]], + companion_pdf_meta_by_stem: dict[str, dict[str, Any]], + long_term_by_name: dict[str, dict[str, Any]], + eff_max_bytes: int, + evict_count_to_git: int = 0, + extra_manifest_fields: dict[str, Any] | None = None, + restore_cmd_prefix: str = "hs-archive-rotate --extract", +) -> tuple[str, str, list[dict[str, Any]], list[dict[str, Any]], int]: + """ + Strategy 7A: Shared packaging, FIFO Git-citation eviction, active member enrichment, + read-back SHA-256 verification, and `manifest_dag_json_cid` writer used by both + `rotate_docs_archive_directory()` and `rotate_inactive_plans_marked_for_archival()`. + """ + members_meta, total_uncompressed = _pack_deterministic_tar_gz(staged_files, bundle_p) + + readme_order: list[str] = [] + rm_p = arc_p / "README.md" + if rm_p.is_file(): + for m_rm in re.finditer(r"`([A-Za-z0-9_-]+)\.\{?md", rm_p.read_text(encoding="utf-8")): + cand_md = f"{m_rm.group(1)}.md" + if cand_md not in readme_order: + readme_order.append(cand_md) + + def _fifo_sort_key(p: Path) -> tuple[int, str]: + if p.name in readme_order: + return (readme_order.index(p.name), p.name) + return (len(readme_order) + 100, p.name) + + fifo_candidates = sorted(staged_files, key=_fifo_sort_key) + evicted_this_run = 0 + cls_label = "archived_inactive" if "inactive" in archive_classification else "archived_completed" + + for cand_p in list(fifo_candidates): + need_evict = (bundle_p.stat().st_size > eff_max_bytes) or (evicted_this_run < evict_count_to_git) + if not need_evict or len(staged_files) <= 1: + break + cand_bytes = cand_p.read_bytes() + cand_sha = hashlib.sha256(cand_bytes).hexdigest() + cit_meta = resolve_git_citation_metadata( + archive_dir=arc_p, + member_name=cand_p.name, + bundle_filename=bundle_filename, + existing_meta=existing_member_meta_by_name.get(cand_p.name), + ) + if not assert_persisted_in_git_history( + archive_dir=arc_p, + member_name=cand_p.name, + expected_sha256=cand_sha, + citation_meta=cit_meta, + bundle_filename=bundle_filename, + ): + continue + + stem = cand_p.stem + comp_pdf = companion_pdf_meta_by_stem.get(stem, {}) + long_term_by_name[cand_p.name] = { + "name": cand_p.name, + "plan_id": stem, + "classification": cls_label, + "storage_tier": "git_source_control_long_term", + "size_bytes": len(cand_bytes), + "sha256": cand_sha, + "companion_pdf_sha256": comp_pdf.get("companion_pdf_sha256"), + "companion_pdf_size_bytes": comp_pdf.get("companion_pdf_size_bytes"), + **cit_meta, + "local_git_restore_cmd": f"{restore_cmd_prefix} {cand_p.name}", + } + cand_p.unlink() + staged_files = [p for p in staged_files if p.name != cand_p.name] + evicted_this_run += 1 + members_meta, total_uncompressed = _pack_deterministic_tar_gz(staged_files, bundle_p) + + enriched_members: list[dict[str, Any]] = [] + for m_info in members_meta: + m_name = m_info["name"] + stem = Path(m_name).stem + comp_pdf = companion_pdf_meta_by_stem.get(stem, {}) + cit_meta = resolve_git_citation_metadata( + archive_dir=arc_p, + member_name=m_name, + bundle_filename=bundle_filename, + existing_meta=existing_member_meta_by_name.get(m_name), + ) + enriched_members.append( + { + "name": m_name, + "plan_id": stem, + "classification": cls_label, + "storage_tier": "active_tar_gz_bundle", + "size_bytes": m_info["size_bytes"], + "sha256": m_info["sha256"], + "companion_pdf_sha256": comp_pdf.get("companion_pdf_sha256"), + "companion_pdf_size_bytes": comp_pdf.get("companion_pdf_size_bytes"), + **cit_meta, + } + ) + + with tarfile.open(bundle_p, "r:gz") as tf_verify: + safe_by_name = {m.name: m for m in safe_tar_members(tf_verify)} + for m_info in enriched_members: + assert m_info["name"] in safe_by_name, f"Missing {m_info['name']} in {bundle_p}" + assert not m_info["name"].endswith(".pdf"), f"Redundant .pdf found in {bundle_p}: {m_info['name']}" + ex = tf_verify.extractfile(safe_by_name[m_info["name"]]) + assert ex is not None + actual_sha = hashlib.sha256(ex.read()).hexdigest() + assert actual_sha == m_info["sha256"], f"SHA-256 mismatch for {m_info['name']}" + + bundle_sha = sha256_file(bundle_p) + sorted_long_term = [long_term_by_name[k] for k in sorted(long_term_by_name.keys())] + manifest_core: dict[str, Any] = { + "version": CURRENT_VERSION, + "archive_classification": archive_classification, + "bundle_filename": bundle_filename, + "bundle_policy": "md_only_single_layer_bounded_with_git_citation_rotation", + "max_bundle_bytes": eff_max_bytes, + "bundle_size_bytes": bundle_p.stat().st_size, + "bundle_sha256": bundle_sha, + **(extra_manifest_fields or {}), + "member_count": len(enriched_members), + "active_bundle_member_count": len(enriched_members), + "long_term_git_rotated_count": len(sorted_long_term), + "total_uncompressed_bytes": total_uncompressed, + "members": enriched_members, + "long_term_git_storage_citations": sorted_long_term, + } + manifest_cid = compute_dag_json_cidv1(manifest_core) + manifest_obj = { + **manifest_core, + "manifest_dag_json_cid": manifest_cid, + } + manifest_p.write_text(json.dumps(manifest_obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + return manifest_cid, bundle_sha, enriched_members, sorted_long_term, total_uncompressed + + +def _load_existing_manifest_maps(manifest_p: Path) -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: + existing_manifest: dict[str, Any] = {} + if manifest_p.is_file(): + try: + existing_manifest = load_json_cached(manifest_p) + except Exception: + existing_manifest = {} + + existing_member_meta_by_name: dict[str, dict[str, Any]] = {} + companion_pdf_meta_by_stem: dict[str, dict[str, Any]] = {} + long_term_by_name: dict[str, dict[str, Any]] = {} + + for m in existing_manifest.get("members") or []: + m_name = str(m.get("name") or "") + if m_name.endswith(".pdf"): + companion_pdf_meta_by_stem[Path(m_name).stem] = { + "companion_pdf_sha256": m.get("sha256"), + "companion_pdf_size_bytes": m.get("size_bytes"), + } + elif m_name.endswith(".md"): + existing_member_meta_by_name[m_name] = dict(m) + if m.get("companion_pdf_sha256"): + companion_pdf_meta_by_stem[Path(m_name).stem] = { + "companion_pdf_sha256": m.get("companion_pdf_sha256"), + "companion_pdf_size_bytes": m.get("companion_pdf_size_bytes"), + } + + for lt in existing_manifest.get("long_term_git_storage_citations") or []: + lt_name = str(lt.get("name") or "") + if lt_name.endswith(".md"): + long_term_by_name[lt_name] = dict(lt) + if lt.get("companion_pdf_sha256"): + companion_pdf_meta_by_stem[Path(lt_name).stem] = { + "companion_pdf_sha256": lt.get("companion_pdf_sha256"), + "companion_pdf_size_bytes": lt.get("companion_pdf_size_bytes"), + } + return existing_member_meta_by_name, companion_pdf_meta_by_stem, long_term_by_name + + def rotate_docs_archive_directory( archive_dir: str | Path, require_companion_md: bool = True, check_allowed_dir: bool = True, + max_bundle_bytes: int | str | None = None, + evict_count_to_git: int = 0, + bundle_filename: str = BUNDLE_FILENAME, + manifest_filename: str = MANIFEST_FILENAME, + archive_classification: str = "archived_completed_plans", ) -> dict[str, Any]: - """ - Rotate completed `.md` (excluding `README.md`) and `.pdf` pairs inside `archive_dir` - into a deterministic `completed-plans-archive.tar.gz` and `archive-manifest.json`. - When `require_companion_md=True` (default), standalone `.pdf` files that lack a matching - `.md` file on disk (`has_md=False`) are preserved untouched on disk. - """ arc_p = assert_not_gematria_pipeline_source(archive_dir) if check_allowed_dir else Path(archive_dir).resolve() arc_p.mkdir(parents=True, exist_ok=True) - bundle_p = arc_p / BUNDLE_FILENAME - manifest_p = arc_p / MANIFEST_FILENAME + bundle_p = arc_p / bundle_filename + manifest_p = arc_p / manifest_filename + + env_kb = os.environ.get("HYPERSTITION_MAX_PLAN_ARCHIVE_KB") + default_cap = int(float(env_kb) * 1024) if env_kb else DEFAULT_MAX_ARCHIVE_BUNDLE_BYTES + eff_max_bytes = parse_size_spec_bytes(max_bundle_bytes, default_bytes=default_cap) + + existing_member_meta_by_name, companion_pdf_meta_by_stem, long_term_by_name = _load_existing_manifest_maps(manifest_p) with tempfile.TemporaryDirectory() as tmp_s: stage_dir = Path(tmp_s) / "stage" stage_dir.mkdir(parents=True, exist_ok=True) - # 1. If an existing bundle is present, unpack its members into stage_dir first so rotation is additive + removed_legacy_pdf_members = 0 if bundle_p.is_file(): with tarfile.open(bundle_p, "r:gz") as tf_in: - for member in tf_in.getmembers(): - if member.isfile() and "/" not in member.name and not member.name.startswith("."): - f_obj = tf_in.extractfile(member) - if f_obj is not None: - (stage_dir / member.name).write_bytes(f_obj.read()) + for member in safe_tar_members(tf_in): + if "/" in member.name or member.name.startswith("."): + continue + f_obj = tf_in.extractfile(member) + if f_obj is None: + continue + raw_b = f_obj.read() + if member.name.endswith(".pdf"): + stem = Path(member.name).stem + companion_pdf_meta_by_stem[stem] = { + "companion_pdf_sha256": hashlib.sha256(raw_b).hexdigest(), + "companion_pdf_size_bytes": len(raw_b), + } + removed_legacy_pdf_members += 1 + elif member.name.endswith(".md") and member.name not in long_term_by_name: + (stage_dir / member.name).write_bytes(raw_b) - # 2. Identify eligible loose .md and .pdf files in arc_p loose_to_remove: list[Path] = [] preserved_standalone_pdfs: list[str] = [] for item in sorted(arc_p.iterdir()): - if not item.is_file() or item.name in ("README.md", BUNDLE_FILENAME, MANIFEST_FILENAME): + if not item.is_file() or item.name in ( + "README.md", + bundle_filename, + manifest_filename, + BUNDLE_FILENAME, + MANIFEST_FILENAME, + INACTIVE_BUNDLE_FILENAME, + INACTIVE_MANIFEST_FILENAME, + ): continue if check_allowed_dir: assert_not_gematria_pipeline_source(item) if item.suffix == ".pdf": - has_md = item.with_suffix(".md").is_file() or (stage_dir / item.with_suffix(".md").name).is_file() + has_md = ( + item.with_suffix(".md").is_file() + or (stage_dir / item.with_suffix(".md").name).is_file() + or (item.with_suffix(".md").name in long_term_by_name) + ) if require_companion_md and not has_md: preserved_standalone_pdfs.append(item.name) continue - shutil.copy2(item, stage_dir / item.name) + pdf_b = item.read_bytes() + companion_pdf_meta_by_stem[item.stem] = { + "companion_pdf_sha256": hashlib.sha256(pdf_b).hexdigest(), + "companion_pdf_size_bytes": len(pdf_b), + } loose_to_remove.append(item) elif item.suffix == ".md": shutil.copy2(item, stage_dir / item.name) + long_term_by_name.pop(item.name, None) loose_to_remove.append(item) - staged_files = sorted(p for p in stage_dir.iterdir() if p.is_file()) - if not staged_files: + staged_files = sorted(p for p in stage_dir.iterdir() if p.is_file() and p.suffix == ".md") + if not staged_files and not long_term_by_name: return { - "archive_dir": str(arc_p), - "bundle_path": str(bundle_p), + "archive_dir": _norm_ws_path(arc_p), + "bundle_path": _norm_ws_path(bundle_p), "member_count": 0, "rotated_loose_files": 0, "preserved_standalone_pdfs": preserved_standalone_pdfs, } - # 3. Write deterministic gzip-compressed tar archive (mtime=0, sorted members) - tmp_bundle = arc_p / f".{BUNDLE_FILENAME}.tmp.{os.getpid()}" - raw_tar_buf = io.BytesIO() - members_meta: list[dict[str, Any]] = [] - total_uncompressed = 0 + manifest_cid, bundle_sha, enriched_members, sorted_long_term, total_uncompressed = _pack_verify_and_write_archive_manifest( + arc_p=arc_p, + bundle_p=bundle_p, + manifest_p=manifest_p, + bundle_filename=bundle_filename, + archive_classification=archive_classification, + staged_files=staged_files, + existing_member_meta_by_name=existing_member_meta_by_name, + companion_pdf_meta_by_stem=companion_pdf_meta_by_stem, + long_term_by_name=long_term_by_name, + eff_max_bytes=eff_max_bytes, + evict_count_to_git=evict_count_to_git, + extra_manifest_fields={ + "require_companion_md": require_companion_md, + "preserved_standalone_pdfs": preserved_standalone_pdfs, + }, + restore_cmd_prefix="hs-archive-rotate --extract", + ) - with tarfile.open(fileobj=raw_tar_buf, mode="w") as tf_out: - for sf in staged_files: - data = sf.read_bytes() - sha = hashlib.sha256(data).hexdigest() - ti = tarfile.TarInfo(name=sf.name) - ti.size = len(data) - ti.mtime = 0 - ti.mode = 0o644 - ti.uid = 0 - ti.gid = 0 - ti.uname = "root" - ti.gname = "root" - tf_out.addfile(ti, io.BytesIO(data)) - total_uncompressed += len(data) - members_meta.append({ - "name": sf.name, - "size_bytes": len(data), - "sha256": sha, - }) - - with open(tmp_bundle, "wb") as f_raw: - with gzip.GzipFile(filename="", mode="wb", fileobj=f_raw, compresslevel=9, mtime=0) as gz_out: - gz_out.write(raw_tar_buf.getvalue()) - os.replace(tmp_bundle, bundle_p) - - # 4. Verify read-back integrity of every member in bundle_p before unlinking loose files - with tarfile.open(bundle_p, "r:gz") as tf_verify: - names_in_tar = set(tf_verify.getnames()) - for m_info in members_meta: - assert m_info["name"] in names_in_tar, f"Missing {m_info['name']} in {bundle_p}" - ex = tf_verify.extractfile(m_info["name"]) - assert ex is not None - actual_sha = hashlib.sha256(ex.read()).hexdigest() - assert actual_sha == m_info["sha256"], f"SHA-256 mismatch for {m_info['name']}" - - bundle_sha = sha256_file(bundle_p) - manifest_obj = { - "version": CURRENT_VERSION, - "bundle_filename": BUNDLE_FILENAME, - "bundle_size_bytes": bundle_p.stat().st_size, - "bundle_sha256": bundle_sha, - "require_companion_md": require_companion_md, - "member_count": len(members_meta), - "total_uncompressed_bytes": total_uncompressed, - "preserved_standalone_pdfs": preserved_standalone_pdfs, - "members": members_meta, - } - manifest_p.write_text(json.dumps(manifest_obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - - # 5. Unlink rotated loose files only after verification succeeded for lp in loose_to_remove: lp.unlink() return { - "archive_dir": str(arc_p), - "bundle_path": str(bundle_p), - "manifest_path": str(manifest_p), + "archive_dir": _norm_ws_path(arc_p), + "bundle_path": _norm_ws_path(bundle_p), + "manifest_path": _norm_ws_path(manifest_p), + "manifest_dag_json_cid": manifest_cid, + "max_bundle_bytes": eff_max_bytes, "bundle_size_bytes": bundle_p.stat().st_size, "bundle_sha256": bundle_sha, - "member_count": len(members_meta), + "member_count": len(enriched_members), + "active_bundle_member_count": len(enriched_members), + "long_term_git_rotated_count": len(sorted_long_term), + "removed_legacy_pdf_members": removed_legacy_pdf_members, "total_uncompressed_bytes": total_uncompressed, "rotated_loose_files": len(loose_to_remove), "preserved_standalone_pdfs": preserved_standalone_pdfs, } -def rotate_all_docs_archives(workspace_root: str | Path | None = None) -> dict[str, Any]: +def _is_inactive_plan_marked_for_archival(md_path: Path, explicit_plan_ids: set[str]) -> bool: + stem = md_path.stem + if stem in explicit_plan_ids or md_path.name in explicit_plan_ids: + return True + try: + head_txt = md_path.read_text(encoding="utf-8")[:1600] + except Exception: + return False + return bool( + re.search( + r"\*\*(?:Roadmap\s+)?Status:\*\*\s*(?:`|\*\*)?ARCHIVED(?:\s+INACTIVE)?\b", + head_txt, + flags=re.IGNORECASE, + ) + ) + + +def rotate_inactive_plans_marked_for_archival( + workspace_root: str | Path | None = None, + plan_ids: list[str] | tuple[str, ...] | None = None, + max_bundle_bytes: int | str | None = None, + _skip_outer_guard: bool = False, +) -> dict[str, Any]: + cfg = load_workspace_config(workspace_root=workspace_root) + inactive_dir = assert_not_gematria_pipeline_source( + cfg.knowledge_graph_dir / "docs" / "plans" / "inactive", + workspace_root=workspace_root, + ) + inactive_dir.mkdir(parents=True, exist_ok=True) + bundle_p = inactive_dir / INACTIVE_BUNDLE_FILENAME + manifest_p = inactive_dir / INACTIVE_MANIFEST_FILENAME + + env_kb = os.environ.get("HYPERSTITION_MAX_PLAN_ARCHIVE_KB") + default_cap = int(float(env_kb) * 1024) if env_kb else DEFAULT_MAX_ARCHIVE_BUNDLE_BYTES + eff_max_bytes = parse_size_spec_bytes(max_bundle_bytes, default_bytes=default_cap) + explicit_ids = {str(x).strip().removesuffix(".md").removesuffix(".pdf") for x in (plan_ids or []) if str(x).strip()} + + def _run_core() -> dict[str, Any]: + existing_meta_by_name, companion_pdf_meta_by_stem, long_term_by_name = _load_existing_manifest_maps(manifest_p) + with tempfile.TemporaryDirectory() as tmp_s: + stage_dir = Path(tmp_s) / "stage" + stage_dir.mkdir(parents=True, exist_ok=True) + + if bundle_p.is_file(): + with tarfile.open(bundle_p, "r:gz") as tf_in: + for member in safe_tar_members(tf_in): + if member.name.endswith(".md") and "/" not in member.name and member.name not in long_term_by_name: + f_obj = tf_in.extractfile(member) + if f_obj is not None: + (stage_dir / member.name).write_bytes(f_obj.read()) + + loose_to_remove: list[Path] = [] + retained_inactive_plans: list[str] = [] + + for md_item in sorted(inactive_dir.glob("*.md")): + if md_item.name == "README.md": + continue + assert_not_gematria_pipeline_source(md_item, workspace_root=workspace_root) + if _is_inactive_plan_marked_for_archival(md_item, explicit_ids): + shutil.copy2(md_item, stage_dir / md_item.name) + long_term_by_name.pop(md_item.name, None) + loose_to_remove.append(md_item) + pdf_companion = md_item.with_suffix(".pdf") + if pdf_companion.is_file(): + assert_not_gematria_pipeline_source(pdf_companion, workspace_root=workspace_root) + pdf_b = pdf_companion.read_bytes() + companion_pdf_meta_by_stem[md_item.stem] = { + "companion_pdf_sha256": hashlib.sha256(pdf_b).hexdigest(), + "companion_pdf_size_bytes": len(pdf_b), + } + loose_to_remove.append(pdf_companion) + else: + retained_inactive_plans.append(md_item.stem) + + staged_files = sorted(p for p in stage_dir.iterdir() if p.is_file() and p.suffix == ".md") + if not staged_files and not long_term_by_name: + return { + "ok": True, + "inactive_dir": _norm_ws_path(inactive_dir, workspace_root=workspace_root), + "bundle_path": _norm_ws_path(bundle_p, workspace_root=workspace_root), + "member_count": 0, + "rotated_loose_files": 0, + "retained_inactive_plans": retained_inactive_plans, + } + + manifest_cid, bundle_sha, enriched_members, sorted_long_term, total_uncompressed = _pack_verify_and_write_archive_manifest( + arc_p=inactive_dir, + bundle_p=bundle_p, + manifest_p=manifest_p, + bundle_filename=INACTIVE_BUNDLE_FILENAME, + archive_classification="archived_inactive_plans", + staged_files=staged_files, + existing_member_meta_by_name=existing_meta_by_name, + companion_pdf_meta_by_stem=companion_pdf_meta_by_stem, + long_term_by_name=long_term_by_name, + eff_max_bytes=eff_max_bytes, + extra_manifest_fields={"retained_inactive_plans": retained_inactive_plans}, + restore_cmd_prefix="hs-archive-rotate --extract-inactive", + ) + + for lp in loose_to_remove: + lp.unlink() + + return { + "ok": True, + "version": CURRENT_VERSION, + "inactive_dir": _norm_ws_path(inactive_dir, workspace_root=workspace_root), + "bundle_path": _norm_ws_path(bundle_p, workspace_root=workspace_root), + "manifest_path": _norm_ws_path(manifest_p, workspace_root=workspace_root), + "manifest_dag_json_cid": manifest_cid, + "bundle_size_bytes": bundle_p.stat().st_size, + "bundle_sha256": bundle_sha, + "member_count": len(enriched_members), + "long_term_git_rotated_count": len(sorted_long_term), + "total_uncompressed_bytes": total_uncompressed, + "rotated_loose_files": len(loose_to_remove), + "retained_inactive_plans": retained_inactive_plans, + } + + if _skip_outer_guard: + return _run_core() + + with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: + pre_snap = snapshot_gematria_pipeline_richness(workspace_root=workspace_root) + res = _run_core() + post_snap = snapshot_gematria_pipeline_richness(workspace_root=workspace_root) + verify_gematria_pipeline_richness_invariant(pre_snap, post_snap) + res["isolation_receipt"] = guard.audit_receipt() + return res + + +def extract_archive_member( + archive_dir: str | Path, + member_name: str, + out_dir: str | Path, + bundle_filename: str = BUNDLE_FILENAME, + manifest_filename: str = MANIFEST_FILENAME, +) -> Path: + arc_p = Path(archive_dir).resolve() + bundle_p = arc_p / bundle_filename + manifest_p = arc_p / manifest_filename + out_p = Path(out_dir).resolve() + out_p.mkdir(parents=True, exist_ok=True) + + norm_name = member_name if member_name.endswith((".md", ".pdf")) else f"{member_name}.md" + + if bundle_p.is_file(): + with tarfile.open(bundle_p, "r:gz") as tf: + safe_map = {m.name: m for m in safe_tar_members(tf)} + for cand in (member_name, norm_name): + if cand in safe_map: + f_obj = tf.extractfile(safe_map[cand]) + if f_obj is not None: + dst = out_p / Path(cand).name + dst.write_bytes(f_obj.read()) + return dst + + cit_meta: dict[str, Any] | None = None + if manifest_p.is_file(): + try: + man_obj = load_json_cached(manifest_p, copy_result=False) + for item in (man_obj.get("long_term_git_storage_citations") or []) + (man_obj.get("members") or []): + if item.get("name") in (member_name, norm_name) or item.get("plan_id") == member_name: + cit_meta = item + norm_name = str(item.get("name") or norm_name) + break + except Exception: + pass + + recovered = read_member_from_git_history( + archive_dir=arc_p, + member_name=norm_name, + citation_meta=cit_meta, + bundle_filename=bundle_filename, + ) + if recovered is not None: + dst = out_p / Path(norm_name).name + dst.write_bytes(recovered) + return dst + + raise ValueError(f"Member {member_name!r} not found in {bundle_p} or local Git history") + + +def extract_inactive_plan_member( + plan_id_or_name: str, + out_dir: str | Path | None = None, + workspace_root: str | Path | None = None, +) -> Path: + cfg = load_workspace_config(workspace_root=workspace_root) + inactive_dir = cfg.knowledge_graph_dir / "docs" / "plans" / "inactive" + target_out = Path(out_dir).resolve() if out_dir else inactive_dir.resolve() + return extract_archive_member( + archive_dir=inactive_dir, + member_name=plan_id_or_name, + out_dir=target_out, + bundle_filename=INACTIVE_BUNDLE_FILENAME, + manifest_filename=INACTIVE_MANIFEST_FILENAME, + ) + + +def audit_and_fix_multi_compressed_files( + workspace_root: str | Path | None = None, + extra_dirs: list[str | Path] | None = None, + fix: bool = True, +) -> dict[str, Any]: + cfg = load_workspace_config(workspace_root=workspace_root) + scan_roots: list[Path] = [ + cfg.core_dir, + cfg.archive_dir.parent, + cfg.zoology_dir, + cfg.knowledge_graph_dir, + cfg.paths["gematria_js_dir"], + cfg.paths.get("ci_repo_dir", cfg.workspace_root / "hyperdope-ci-build"), + ] + for ed in extra_dirs or []: + ep = Path(ed) + if ep.is_dir(): + scan_roots.append(ep) + + double_ext_re = re.compile(r"\.(?:gz|br|tgz|xz|zst|zip|woff2)\.(?:gz|br)$", flags=re.IGNORECASE) + nested_comp_ext_re = re.compile(r"\.(?:gz|tgz|xz|br|zip|zst|pdf)$", flags=re.IGNORECASE) + + peeled_gzip_files: list[str] = [] + removed_double_sidecars: list[str] = [] + nested_archive_violations: list[dict[str, Any]] = [] + scanned_gz_count = 0 + scanned_tar_count = 0 + + for rdir in scan_roots: + if not rdir.is_dir(): + continue + for root_s, dirs, files in os.walk(rdir): + dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "__pycache__", ".cache")] + for fn in sorted(files): + fp = Path(root_s) / fn + if fp.is_symlink() or not fp.is_file(): + continue + if double_ext_re.search(fn): + if fix: + base_p = fp.with_suffix("") + if base_p.is_file(): + fp.unlink() + else: + fp.rename(base_p) + removed_double_sidecars.append(_norm_ws_path(fp, workspace_root=workspace_root)) + continue + else: + removed_double_sidecars.append(_norm_ws_path(fp, workspace_root=workspace_root)) + + if fn.endswith((".gz", ".tgz")): + scanned_gz_count += 1 + try: + with gzip.open(fp, "rb") as f_gz: + head = f_gz.read(6) + except Exception: + continue + if head.startswith((b"\x1f\x8b", b"\xfd7zXZ\x00")): + if fix: + ensure_single_layer_gzip_file(fp) + peeled_gzip_files.append(_norm_ws_path(fp, workspace_root=workspace_root)) + + if fn.endswith((".tar.gz", ".tgz", ".tar.xz")): + scanned_tar_count += 1 + try: + with tarfile.open(fp, "r:*") as tf: + bad_members = [ + m.name + for m in safe_tar_members(tf) + if nested_comp_ext_re.search(m.name) + ] + except Exception: + bad_members = [] + if bad_members: + nested_archive_violations.append( + { + "archive": _norm_ws_path(fp, workspace_root=workspace_root), + "nested_compressed_members": bad_members, + } + ) + + return { + "ok": len(nested_archive_violations) == 0 and (fix or (not peeled_gzip_files and not removed_double_sidecars)), + "scanned_gz_count": scanned_gz_count, + "scanned_tar_count": scanned_tar_count, + "peeled_gzip_files": peeled_gzip_files, + "removed_double_sidecars": removed_double_sidecars, + "nested_archive_violations": nested_archive_violations, + } + + +def rotate_all_docs_archives( + workspace_root: str | Path | None = None, + max_bundle_bytes: int | str | None = None, + evict_count_to_git: int = 0, + include_marked_inactive: bool = True, +) -> dict[str, Any]: cfg = load_workspace_config(workspace_root=workspace_root) with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: pre_snap = snapshot_gematria_pipeline_richness(workspace_root=workspace_root) - # Relocate deferred Episodes 06-09 podcast plan from zoology/docs/archive/ to zoology/docs/ if still in archive/ zoo_arc = cfg.zoology_dir / "docs" / "archive" zoo_docs = cfg.zoology_dir / "docs" for ext in (".md", ".pdf"): @@ -281,41 +1045,66 @@ def rotate_all_docs_archives(workspace_root: str | Path | None = None) -> dict[s if pod_src.is_file() and not pod_dst.is_file(): shutil.move(str(pod_src), str(pod_dst)) - kg_res = rotate_docs_archive_directory(cfg.knowledge_graph_dir / "docs" / "archive", require_companion_md=True) - zoo_res = rotate_docs_archive_directory(zoo_arc, require_companion_md=True) + kg_res = rotate_docs_archive_directory( + cfg.knowledge_graph_dir / "docs" / "archive", + require_companion_md=True, + max_bundle_bytes=max_bundle_bytes, + evict_count_to_git=evict_count_to_git, + ) + zoo_res = rotate_docs_archive_directory( + zoo_arc, + require_companion_md=True, + max_bundle_bytes=max_bundle_bytes, + evict_count_to_git=0, + ) + + inactive_res: dict[str, Any] | None = None + if include_marked_inactive: + inactive_res = rotate_inactive_plans_marked_for_archival( + workspace_root=workspace_root, + max_bundle_bytes=max_bundle_bytes, + _skip_outer_guard=True, + ) + + comp_audit = audit_and_fix_multi_compressed_files(workspace_root=workspace_root, fix=True) post_snap = snapshot_gematria_pipeline_richness(workspace_root=workspace_root) verify_gematria_pipeline_richness_invariant(pre_snap, post_snap) + if inactive_res is not None: + inactive_res["isolation_receipt"] = guard.audit_receipt() + + rot_cnt = ( + int(kg_res.get("rotated_loose_files", 0)) + + int(zoo_res.get("rotated_loose_files", 0)) + + int((inactive_res or {}).get("rotated_loose_files", 0)) + ) return { "ok": True, "version": CURRENT_VERSION, - "rotated_loose_files": int(kg_res.get("rotated_loose_files", 0)) + int(zoo_res.get("rotated_loose_files", 0)), + "rotated_loose_files": rot_cnt, "gematria_richness_invariant_verified": True, "gematria_richness_snapshot": post_snap, "archives_rotated": [kg_res, zoo_res], + "inactive_archive_rotated": inactive_res, + "single_compression_audit": comp_audit, "isolation_receipt": guard.audit_receipt(), } -def extract_archive_member(archive_dir: str | Path, member_name: str, out_dir: str | Path) -> Path: - arc_p = Path(archive_dir).resolve() - bundle_p = arc_p / BUNDLE_FILENAME - out_p = Path(out_dir).resolve() - out_p.mkdir(parents=True, exist_ok=True) - with tarfile.open(bundle_p, "r:gz") as tf: - f_obj = tf.extractfile(member_name) - if f_obj is None: - raise ValueError(f"Member {member_name!r} not found in {bundle_p}") - dst = out_p / Path(member_name).name - dst.write_bytes(f_obj.read()) - return dst - - def main(argv: list[str] | None = None) -> int: - ap = argparse.ArgumentParser(prog="hs-archive-rotate", description="Rotate completed software plans in docs/archive/ into deterministic .tar.gz bundles.") - ap.add_argument("--list", action="store_true", help="List archived members from archive-manifest.json.") - ap.add_argument("--extract", default=None, help="Extract a specific archived filename to --out-dir.") + ap = argparse.ArgumentParser( + prog="hs-archive-rotate", + description="Rotate completed software plans in docs/archive/ and marked inactive plans in docs/plans/inactive/ into bounded .md-only 1x-compressed .tar.gz bundles.", + ) + ap.add_argument("--list", action="store_true", help="List archived members from archive-manifest.json and inactive-archive-manifest.json.") + ap.add_argument("--extract", default=None, help="Extract a specific archived filename from completed-plans-archive.tar.gz (or Git fallback) to --out-dir.") + ap.add_argument("--archive-inactive", nargs="*", default=None, help="Rotate inactive plans marked for archival (or explicit PLAN_IDs) into docs/plans/inactive/inactive-plans-archive.tar.gz.") + ap.add_argument("--extract-inactive", default=None, help="Extract an archived inactive plan from inactive-plans-archive.tar.gz to --out-dir (or docs/plans/inactive/).") + ap.add_argument("--max-bundle-kb", type=float, default=None, help="Upper size cap in KB for compressed plan tar.gz bundles (default: 256 KB).") + ap.add_argument("--evict-to-git-count", type=int, default=0, help="Explicitly evict N oldest members to long_term_git_storage_citations after verifying Git history.") + ap.add_argument("--enforce-single-compression", action="store_true", help="Audit and fix multi-compressed files across all repositories.") + ap.add_argument("--extra-scan-dir", action="append", default=[], help="Additional directory (e.g. LIVE_REPOS) to audit for single-layer compression.") ap.add_argument("--archive-dir", default=None, help="Optional specific docs/archive directory.") ap.add_argument("--out-dir", default="/tmp/hyperstition-extracted-archive") ap.add_argument("--workspace-root", default=None, help="Optional workspace root directory.") @@ -323,12 +1112,27 @@ def main(argv: list[str] | None = None) -> int: args = ap.parse_args(argv) cfg = load_workspace_config(workspace_root=args.workspace_root) + max_b: int | None = int(args.max_bundle_kb * 1024) if args.max_bundle_kb is not None else None + + if args.enforce_single_compression: + audit_res = audit_and_fix_multi_compressed_files( + workspace_root=args.workspace_root, + extra_dirs=args.extra_scan_dir, + fix=not args.dry_run, + ) + print(json.dumps(audit_res, indent=2)) + return 0 if audit_res["ok"] else 1 + if args.list or args.dry_run: out: dict[str, Any] = {"rotated_loose_files": 0} - for d in (cfg.knowledge_graph_dir / "docs" / "archive", cfg.zoology_dir / "docs" / "archive"): - mp = d / MANIFEST_FILENAME + for d, mf in ( + (cfg.knowledge_graph_dir / "docs" / "archive", MANIFEST_FILENAME), + (cfg.zoology_dir / "docs" / "archive", MANIFEST_FILENAME), + (cfg.knowledge_graph_dir / "docs" / "plans" / "inactive", INACTIVE_MANIFEST_FILENAME), + ): + mp = d / mf if mp.is_file(): - out[str(d)] = json.loads(mp.read_text(encoding="utf-8")) + out[_norm_ws_path(d, workspace_root=args.workspace_root)] = load_json_cached(mp) print(json.dumps(out, indent=2)) return 0 @@ -338,7 +1142,26 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps({"extracted": str(dst), "size_bytes": dst.stat().st_size}, indent=2)) return 0 - res = rotate_all_docs_archives(workspace_root=args.workspace_root) + if args.extract_inactive: + out_target = args.out_dir if args.out_dir != "/tmp/hyperstition-extracted-archive" else None + dst = extract_inactive_plan_member(args.extract_inactive, out_dir=out_target, workspace_root=args.workspace_root) + print(json.dumps({"extracted": str(dst), "size_bytes": dst.stat().st_size}, indent=2)) + return 0 + + if args.archive_inactive is not None: + inact_res = rotate_inactive_plans_marked_for_archival( + workspace_root=args.workspace_root, + plan_ids=args.archive_inactive, + max_bundle_bytes=max_b, + ) + print(json.dumps(inact_res, indent=2)) + return 0 + + res = rotate_all_docs_archives( + workspace_root=args.workspace_root, + max_bundle_bytes=max_b, + evict_count_to_git=args.evict_to_git_count, + ) print(json.dumps(res, indent=2)) return 0 diff --git a/src/hyperstitionstud_io/publishing/closeups_sync.py b/src/hyperstitionstud_io/publishing/closeups_sync.py index 57df4d6..9ac5a2f 100644 --- a/src/hyperstitionstud_io/publishing/closeups_sync.py +++ b/src/hyperstitionstud_io/publishing/closeups_sync.py @@ -20,29 +20,34 @@ import re from pathlib import Path from typing import Any -from PIL import Image, ImageDraw, ImageFont +from PIL import Image, ImageDraw from hyperstitionstud_io import __version__ as CURRENT_VERSION -from hyperstitionstud_io.config import load_workspace_config +from hyperstitionstud_io.config import load_json_cached, load_workspace_config from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard from hyperstitionstud_io.ipld import compute_dag_json_cidv1 +from hyperstitionstud_io.publishing.fonts import ( + GROUP3_PALETTE, + draw_group3_chamfered_plate, + load_pillow_font, +) -FONT_SANS = "/usr/share/fonts/google-noto/NotoSans-Regular.ttf" -FONT_BOLD = "/usr/share/fonts/google-noto/NotoSans-Bold.ttf" -FONT_MONO = "/usr/share/fonts/dejavu-sans-mono-fonts/DejaVuSansMono.ttf" -FONT_MONO_B = "/usr/share/fonts/dejavu-sans-mono-fonts/DejaVuSansMono-Bold.ttf" +FONT_SANS = "DejaVuSans.ttf" +FONT_BOLD = "DejaVuSans-Bold.ttf" +FONT_MONO = "DejaVuSansMono.ttf" +FONT_MONO_B = "DejaVuSansMono-Bold.ttf" -VOID = (7, 9, 13) -PLATE = (12, 16, 23) -WELL = (18, 24, 34) -BORDER = (30, 41, 59) -TEXT = (241, 245, 249) -MUTED = (148, 163, 184) -CYAN = (56, 189, 248) +VOID = GROUP3_PALETTE["BG_VOID"] +PLATE = GROUP3_PALETTE["BG_ODD"] +WELL = GROUP3_PALETTE["BG_EVEN"] +BORDER = GROUP3_PALETTE["BORDER_MUTED"] +TEXT = GROUP3_PALETTE["TXT_PRI"] +MUTED = GROUP3_PALETTE["TXT_SEC"] +CYAN = GROUP3_PALETTE["CYAN"] GOLD = (245, 198, 48) -EMERALD = (52, 211, 153) -ROSE = (251, 113, 133) -VIOLET = (167, 139, 250) +EMERALD = GROUP3_PALETTE["EMERALD"] +ROSE = GROUP3_PALETTE["ROSE"] +VIOLET = GROUP3_PALETTE["VIOLET"] ALL_CLOSEUP_FILENAMES: tuple[str, ...] = ( "quadrant-1-cybermemetics-calc-graph.png", @@ -60,10 +65,35 @@ ALL_CLOSEUP_FILENAMES: tuple[str, ...] = ( def _fnt(path: str, size: int) -> Any: - try: - return ImageFont.truetype(path, size) - except Exception: - return ImageFont.load_default() + return load_pillow_font(path, size) + + +def _extract_js_ui_signature(js_text: str) -> dict[str, Any]: + """ + Strategy 4A (Plan #51): Introspect companion `.js` files (`quant-app.js`, `quant-tutorials.js`, + `learn-app.js`, `hs-guile-scheme-repl.js`) for dynamic DOM IDs, episode/scene definitions, + highlightable UI targets, and control labels. + """ + clean = re.sub(r"\bv\d+\.\d+\.\d+\b", "vX.Y.Z", js_text) + dom_ids = sorted(set(re.findall(r'getElementById\(\s*["\']([^"\']+)["\']\s*\)', clean))) + ui_targets = sorted(set(re.findall(r'uiTargets:\s*\[([^\]]+)\]', clean))) + ep_codes = re.findall(r'code:\s*["\'](Ep\s*\d+)["\']', clean) + speech_texts = re.findall(r'speechText:\s*["\']([^"\']+)["\']', clean) + lens_keys = sorted(set(re.findall(r'selectedLens:\s*["\']([^"\']+)["\']', clean))) + payload = { + "dom_ids": dom_ids, + "ui_targets": ui_targets, + "ep_codes": ep_codes, + "speech_text_count": len(speech_texts), + "lens_keys": lens_keys, + "has_ui_indicator_badge": "tutUiElementIndicator" in clean, + "has_lens_select_highlight": '"lensSelect"' in clean, + } + digest = hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest() + return { + "js_ui_sha256": digest, + **payload, + } def _extract_dom_signature(html_text: str) -> dict[str, Any]: @@ -127,22 +157,33 @@ def introspect_live_ui_elements(workspace_root: str | Path | None = None) -> dic if p.is_file(): surface_sigs[k] = _extract_dom_signature(p.read_text(encoding="utf-8")) + js_surfaces: dict[str, Path] = { + "quant_app_js": core / "site" / "quant" / "quant-app.js", + "quant_tutorials_js": core / "site" / "quant" / "quant-tutorials.js", + "learn_app_js": core / "site" / "learn" / "learn-app.js", + "polyglot_repl_js": core / "site" / "assets" / "hs-guile-scheme-repl.js", + } + js_sigs: dict[str, Any] = {} + for jk, jp in js_surfaces.items(): + if jp.is_file(): + js_sigs[jk] = _extract_js_ui_signature(jp.read_text(encoding="utf-8")) + # Live data counts from registries ts_p = core / "site" / "quant" / "quant-timeseries.json" - ts_obj = json.loads(ts_p.read_text(encoding="utf-8")) if ts_p.is_file() else {} + ts_obj = load_json_cached(ts_p, copy_result=False) if ts_p.is_file() else {} total_bars = sum( sum(1 for b in (inst.get("bars") or []) if b.get("data_available")) for inst in (ts_obj.get("instruments") or []) ) brf_p = core / "site" / "quant" / "daily-brief-latest.json" - brf_obj = json.loads(brf_p.read_text(encoding="utf-8")) if brf_p.is_file() else {} + brf_obj = load_json_cached(brf_p, copy_result=False) if brf_p.is_file() else {} post_probs = ( ((brf_obj.get("agenda_1_executive_summary") or {}).get("bayesian_regime_inference") or {}).get("posterior_probabilities") or {"R1_BULL_EXPANSION": 0.24, "R2_PINNED_ISOMETRIC": 0.61, "R3_TAIL_DRAWDOWN_RISK_OFF": 0.15} ) eng_p = core / "site" / "engineering" / "engineering-manifest.json" - eng_obj = json.loads(eng_p.read_text(encoding="utf-8")) if eng_p.is_file() else {} + eng_obj = load_json_cached(eng_p, copy_result=False) if eng_p.is_file() else {} eng_counts = eng_obj.get("introspected_counts") or { "repositories": 6, "cli_entrypoints": 17, @@ -161,12 +202,13 @@ def introspect_live_ui_elements(workspace_root: str | Path | None = None) -> dic db_entries_count = sum(1 for _ in db_txt_p.open(encoding="utf-8")) if db_txt_p.is_file() else 231615 ci_rep_p = ci_dir / "ci-audit-report.json" - ci_obj = json.loads(ci_rep_p.read_text(encoding="utf-8")) if ci_rep_p.is_file() else {} + ci_obj = load_json_cached(ci_rep_p, copy_result=False) if ci_rep_p.is_file() else {} combined_hash = hashlib.sha256( json.dumps( { "surfaces": {k: v["ui_structure_sha256"] for k, v in sorted(surface_sigs.items())}, + "js_surfaces": {k: v["js_ui_sha256"] for k, v in sorted(js_sigs.items())}, "total_bars": total_bars, "db_entries_count": db_entries_count, "mcp_tools": eng_counts.get("mcp_tools", 20), @@ -188,6 +230,7 @@ def introspect_live_ui_elements(workspace_root: str | Path | None = None) -> dic "ci_keep_rate_pct": ci_obj.get("keep_rate_pct", 100.0), }, "surfaces": surface_sigs, + "js_surfaces": js_sigs, } manifest["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(manifest)} return manifest @@ -211,11 +254,8 @@ def _draw_chamfer_box( chamfer: int = 8, pip: tuple[int, int, int] | None = None, ) -> None: - x0, y0, x1, y1 = box - pts = [(x0, y0), (x1 - chamfer, y0), (x1, y0 + chamfer), (x1, y1), (x0, y1)] - d.polygon(pts, fill=fill, outline=outline) - if pip: - d.rectangle([x0, y0, x0 + 3, y1], fill=pip) + _ = chamfer + draw_group3_chamfered_plate(d, box, fill=fill, attention_color=outline, pip_color=pip) def render_all_quadrant_closeups( @@ -277,10 +317,15 @@ def render_all_quadrant_closeups( eng_c = metrics["engineering_counts"] surfaces = live_manifest["surfaces"] - # Detect live controls on /graph/, /quant/, /learn/, /engineering/ + # Detect live controls on /graph/, /quant/, /learn/, /engineering/ (HTML + JS) + quant_ids = set(surfaces.get("quant", {}).get("ids") or []) + quant_tut_js = (live_manifest.get("js_surfaces") or {}).get("quant_tutorials_js") or {} graph_has_min_deg = "minDegreeFilter" in (surfaces.get("graph", {}).get("ids") or []) - quant_has_window = "timeWindowPills" in (surfaces.get("quant", {}).get("ids") or []) - quant_has_quick_filter = "tickerQuickFilter" in (surfaces.get("quant", {}).get("ids") or []) + quant_has_window = "timeWindowPills" in quant_ids + quant_has_quick_filter = "tickerQuickFilter" in quant_ids + quant_has_speech_btn = "tutSpeechBtn" in quant_ids + quant_has_lens_select = "lensSelect" in quant_ids + quant_has_ui_indicator = bool(quant_tut_js.get("has_ui_indicator_badge") or ("tutUiElementIndicator" in quant_ids)) learn_has_seal_ribbon = "grimoireSealRibbon" in (surfaces.get("learn", {}).get("ids") or []) learn_has_sigil_svg = "grimoireSigilSvg" in (surfaces.get("learn", {}).get("ids") or []) eng_has_cli_filter = "engCliFilterInput" in (surfaces.get("engineering_hub", {}).get("ids") or []) @@ -369,14 +414,15 @@ def render_all_quadrant_closeups( d.text((466, ly + 3), lv[:26], font=f_mono_xs, fill=TEXT) im.save(out_dir / "quadrant-1-tab-2-graph.png", "PNG") - # 3. Quadrant 02 Tab 1: Panel 1 Trajectory & Dose + # 3. Quadrant 02 Tab 1: Panel 1 Trajectory & Dose (dynamically reflects #tutSpeechBtn, #timeWindowPills, #tickerQuickFilter) im, d = _new_canvas() _draw_chamfer_box(d, (10, 10, 670, 250), PLATE, BORDER, chamfer=10, pip=GOLD) d.text((24, 18), "PANEL 1: Synchronized 2-Pane Trajectory & Dose D ∈ {0..4}", font=f_hdr, fill=GOLD) - win_badge = "[30D|90D|ALL] • " if quant_has_window else "" - flt_badge = "QuickFilter • " if quant_has_quick_filter else "" - d.rectangle([416, 16, 656, 36], fill=WELL, outline=GOLD) - d.text((424, 19), f"{win_badge}{flt_badge}NVDA (S3)", font=f_mono_xs, fill=GOLD) + win_badge = "[30D|90D|ALL]•" if quant_has_window else "" + flt_badge = "Filter•" if quant_has_quick_filter else "" + vox_badge = "🔊Voice:ON•" if quant_has_speech_btn else "" + d.rectangle([388, 16, 656, 36], fill=WELL, outline=GOLD) + d.text((394, 19), f"{vox_badge}{win_badge}{flt_badge}NVDA", font=f_mono_xs, fill=GOLD) d.rectangle([24, 42, 656, 168], fill=WELL, outline=BORDER) d.line([(36, 114), (644, 114)], fill=(180, 50, 70), width=1) d.text((42, 96), "Entity Threshold: envideea = 137", font=f_mono_xs, fill=ROSE) @@ -439,10 +485,14 @@ def render_all_quadrant_closeups( d.text((568, fy + 5), fn[:11], font=f_mono_xs, fill=EMERALD) im.save(out_dir / "quadrant-2-tab-2-bayesian-fred.png", "PNG") - # 5. Quadrant 02 Tab 3: Panel 2 6-Lens Leaderboard & TCG Card + # 5. Quadrant 02 Tab 3: Panel 2 6-Lens Leaderboard & TCG Card (dynamically reflects #lensSelect & UI indicator badge) im, d = _new_canvas() _draw_chamfer_box(d, (10, 10, 670, 250), PLATE, BORDER, chamfer=10, pip=GOLD) - d.text((24, 18), "PANEL 2 & 3: 6-Lens Assemblage Leaderboard & One-Shot TCG Stats Card", font=f_hdr, fill=GOLD) + hdr_q2_t3 = "PANEL 2 & 3: #lensSelect 6-Lens Leaderboard & TCG Card" if quant_has_lens_select else "PANEL 2 & 3: 6-Lens Assemblage Leaderboard & One-Shot TCG Stats Card" + d.text((24, 18), hdr_q2_t3, font=f_hdr, fill=GOLD) + if quant_has_ui_indicator: + d.rectangle([476, 15, 656, 35], fill=WELL, outline=GOLD) + d.text((482, 18), "▼ UI: #lensSelect", font=f_mono_xs, fill=GOLD) _draw_chamfer_box(d, (24, 42, 416, 240), WELL, GOLD, chamfer=8, pip=GOLD) lenses = ["[Fund Mgr]", "[TierZoo]", "[Board]", "[Sabermetric]"] for li, ltxt in enumerate(lenses): @@ -694,7 +744,7 @@ def render_all_quadrant_closeups( "ui_elements_fingerprint_sha256": live_manifest["ui_elements_fingerprint_sha256"], "cidv1": live_manifest["ipld_dag_json_cidv1"]["/"], "closeup_count": len(ALL_CLOSEUP_FILENAMES), - "isolation_receipt": guard.verification_receipt(), + "isolation_receipt": guard.audit_receipt(), } diff --git a/src/hyperstitionstud_io/publishing/engineering_docs.py b/src/hyperstitionstud_io/publishing/engineering_docs.py index 772d459..f4c4af8 100644 --- a/src/hyperstitionstud_io/publishing/engineering_docs.py +++ b/src/hyperstitionstud_io/publishing/engineering_docs.py @@ -112,17 +112,19 @@ def _render_polyglot_selector_html() -> str: ) -def _render_guile_cartridge_html(key: str) -> str: +def render_polyglot_cartridge_html( + cartridge: dict[str, str], + spec_label: str = "1. Formal Specification & Python:", +) -> str: import html - c = ENGINEERING_GUILE_CARTRIDGES[key] - esc_scm = html.escape(c["scm_expr"], quote=True) - esc_ts = html.escape(c["ts_expr"], quote=True) - esc_rs = html.escape(c["rust_expr"], quote=True) - esc_math = html.escape(c["math_view"], quote=True) - esc_py = html.escape(c["py_view"], quote=True) - esc_title = html.escape(c["title"], quote=True) - esc_chal = html.escape(c["challenge"], quote=True) + esc_scm = html.escape(cartridge["scm_expr"], quote=True) + esc_ts = html.escape(cartridge["ts_expr"], quote=True) + esc_rs = html.escape(cartridge["rust_expr"], quote=True) + esc_math = html.escape(cartridge["math_view"], quote=True) + esc_py = html.escape(cartridge["py_view"], quote=True) + esc_title = html.escape(cartridge["title"], quote=True) + esc_chal = html.escape(cartridge["challenge"], quote=True) return ( '
' '
' @@ -136,7 +138,7 @@ def _render_guile_cartridge_html(key: str) -> str: '
' '' '
' - f'
1. Formal Specification & Python:{esc_math}
{esc_py}
' + f'
{spec_label}{esc_math}
{esc_py}
' f'
λ Guile Scheme (Z-Combinator):
{esc_scm}
=> [Select Lens to evaluate]
' f'
TS TypeScript (Strict AST):
{esc_ts}
=> [Select Lens to evaluate]
' f'
Rs Rust (Option/Iterator AST):
{esc_rs}
=> [Select Lens to evaluate]
' @@ -146,6 +148,13 @@ def _render_guile_cartridge_html(key: str) -> str: ) +def _render_guile_cartridge_html(key: str) -> str: + return render_polyglot_cartridge_html( + ENGINEERING_GUILE_CARTRIDGES[key], + spec_label="1. Formal Specification & Python:", + ) + + def _render_guile_repl_drawer_html(rel_prefix: str) -> str: return f"""