#!/usr/bin/env python3 """ hyperstitionstud_io.publishing.math_docs Introspective Mathematical Foundations & Quantitative Semiotics Explication Hub (`/math/` Unit M0) & Orthogonal Subpage Cartridge Compiler (`Units M1-M5`, `hs-math-docs`). Reuses the Introspective Cartridge Architecture from `engineering_docs.py` with: - Zero external KaTeX/MathJax CDNs (`100%` native ``/``/`` + DejaVu Sans Mono Unicode glyphs), - Embedded Novice Prerequisite Ladders (`.hs-prereq-ladder`) with curated free public math courses/textbooks, - Time-invariant algebraic conservation-law verification + live empirical constant introspection (`math-manifest.json`), - Single-step, multi-sequential-step, and non-sequential (arbitrary-subset) revertability via `ENABLED_MATH_SUBPAGES`. """ from __future__ import annotations import argparse import json import shutil from pathlib import Path from typing import Any from hyperstitionstud_io import __version__ as CURRENT_VERSION from hyperstitionstud_io.ciphers import ( G3_QUANTIZED_STEPS, REPDIGIT_37_ATTRACTORS, compute_aq, compute_variance, ) from hyperstitionstud_io.config import load_workspace_config from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard from hyperstitionstud_io.ipld import compute_dag_json_cidv1 ALL_MATH_SUBPAGES: tuple[str, ...] = ( "base36-algebra-and-primes", "phonemic-projections-and-g-vectors", "graph-topology-and-eti-scoring", "timeseries-moments-and-confluence-dose", "macro-spreads-and-bayesian-inference", ) ENABLED_MATH_SUBPAGES: tuple[str, ...] = ALL_MATH_SUBPAGES ENABLE_GUILE_SCHEME_LENS: bool = True MATH_GUILE_CARTRIDGES: dict[str, dict[str, str]] = { "M0": { "title": "Polyglot Foil (M0): Applicative-Order Z Combinator, TypeScript Array.reduce & Rust Range.fold", "math_view": "Z = λf. (λx. f (λv. (x x) v)) (λx. f (λv. (x x) v)), ∑_{i=1}^{10} i = 55", "py_view": "# Strict applicative-order fixed-point combinator (z-calculus-scheme)\nZ = lambda f: (lambda x: f(lambda *a: x(x)(*a)))(lambda x: f(lambda *a: x(x)(*a)))", "scm_expr": "((Z (lambda (recur) (lambda (n acc) (if (<= n 0) acc (recur (- n 1) (+ acc n)))))) 10 0)", "ts_expr": "Array.from({length: 10}, (_, i): number => i + 1).reduce((a, b) => a + b, 0)", "rust_expr": "(1..=10_i64).fold(0_i64, |acc, x| acc + x)", "challenge": "Compare how Scheme's anonymous Z-combinator, TypeScript's reduce, and Rust's fold compute ∑_{i=1}^{10} i = 55.", }, "base36-algebra-and-primes": { "title": "Polyglot Foil (M1): Base-36 Semiring Valuation, Mod-9 Root & Prime Factorization", "math_view": "666 = 2 × 3² × 37, 777 = 3 × 7 × 37, dr_9(n) = 1 + ((n - 1) mod 9)", "py_view": "compute_aq('envideea') == 137 # 33rd prime", "scm_expr": "(prime-factors 666)", "ts_expr": "primeFactors(666)", "rust_expr": "prime_factors(666_u64)", "challenge": "Factor 666 or 777 across Guile Scheme, TypeScript, and Rust in the 4-Ring Hardened REPL.", }, "phonemic-projections-and-g-vectors": { "title": "Polyglot Foil (M2): Population Variance Collapse on Cluster 292 (Exact Rational vs. Float)", "math_view": "σ²_0({264, 317, 276}) = 4634/9 ≈ 514.89 → σ²_1({292, 292, 292}) = 0", "py_view": "compute_variance([264, 317, 276]) # 514.89 -> 0.0", "scm_expr": "(variance-pop *cluster-292-gen0*)", "ts_expr": "variancePop([264, 317, 276] as const)", "rust_expr": "variance_pop(&[264.0, 317.0, 276.0])", "challenge": "Notice Guile's exact rational 4634/9 vs. TypeScript and Rust IEEE-754 float 514.8889.", }, "graph-topology-and-eti-scoring": { "title": "Polyglot Foil (M3): Convex ETI Functional (∑ w_k = 1, S1 Apex = 93.08)", "math_view": "ETI = (1/5)CAP + (9/50)COL + (9/50)ARM + (4/25)PRM + (7/50)VEL + (7/50)RES", "py_view": "0.20*cap + 0.18*col + 0.18*arm + 0.16*prm + 0.14*vel + 0.14*res", "scm_expr": "(+ 1/5 9/50 9/50 4/25 7/50 7/50)", "ts_expr": "etiScore({cap: 95, col: 92, arm: 94, prm: 90, vel: 91, res: 96})", "rust_expr": "eti_score(95.0, 92.0, 94.0, 90.0, 91.0, 96.0)", "challenge": "Verify the convex weights and composite ETI score across Guile, TypeScript, and Rust.", }, "timeseries-moments-and-confluence-dose": { "title": "Polyglot Foil (M4): Thomas' Calculus Central Derivative d/dx(x^3) at x=2.0", "math_view": "f'(x) = lim_{h→0} (f(x+h) - f(x-h)) / (2h), D_{i,t} = ∑ I(A_s)", "py_view": "confluence_dose = sum(1 for x in species_hits if x)", "scm_expr": "((derivative (lambda (x) (* x x x)) 1e-5) 2.0)", "ts_expr": "derivative((x: number): number => x ** 3, 1e-5)(2.0)", "rust_expr": "derivative(|x: f64| x * x * x, 1e-5, 2.0)", "challenge": "Compare higher-order derivative closures in Guile Scheme, TypeScript, and Rust.", }, "macro-spreads-and-bayesian-inference": { "title": "Polyglot Foil (M5): 3-State Discrete Bayesian Posterior & Adaptive Simpson Quadrature", "math_view": "P(R_m | E_t) = L_m P_m / ∑_k L_k P_k, ∫_a^b f(x) dx via Simpson Z-subdivision", "py_view": "post = [p * l / z for p, l in zip(priors, likelihoods)]", "scm_expr": "(bayes-update '(1/3 1/3 1/3) '(1/10 3/10 6/10))", "ts_expr": "bayesUpdate([1/3, 1/3, 1/3], [0.1, 0.3, 0.6])", "rust_expr": "bayes_update(&[1.0/3.0; 3], &[0.1, 0.3, 0.6])", "challenge": "Compare Guile's exact rational '(1/10 3/10 3/5) with TypeScript and Rust array posteriors.", }, } def _render_math_guile_cartridge_html(key: str) -> str: from hyperstitionstud_io.publishing.engineering_docs import render_polyglot_cartridge_html return render_polyglot_cartridge_html( MATH_GUILE_CARTRIDGES[key], spec_label="1. Mathematical Identity & Python:", ) MATH_HUB_PREREQ_LADDER: dict[str, Any] = { "unit_id": "M0", "expertise_level": "Level 1-2 (High-School Algebra & Sigma Notation • 3-6 hrs study)", "links": [ {"label": "Internal: Self-Paced Learning Track (/learn/ Modules 1-2)", "url": "/learn/index.html", "external": False}, {"label": "Khan Academy — Algebra & Summation (Σ) Notation", "url": "https://www.khanacademy.org/math/algebra", "external": True}, {"label": "OpenStax Precalculus (Free Peer-Reviewed Textbook, Ch. 1 & 9)", "url": "https://openstax.org/details/books/precalculus-2e", "external": True}, {"label": "Structure and Interpretation of Computer Programs (SICP — Free MIT Text)", "url": "https://sarabander.github.io/sicp/", "external": True}, {"label": "GNU Guile Scheme Official Reference Manual", "url": "https://www.gnu.org/software/guile/manual/", "external": True}, ], } MATH_SUBPAGE_SPECS: dict[str, dict[str, Any]] = { "base36-algebra-and-primes": { "unit_id": "M1", "slug": "base36-algebra-and-primes", "title": "Unit M1: Base-36 Alphanumeric Valuation, Repdigit 37×3k Attractors & Prime Index π(n)", "short_title": "M1: Base-36 & Primes", "pip_class": "plate-lock-gold", "expertise_level": "Level 2: Elementary Number Theory & Base Systems (8-12 hrs study)", "prerequisites": [ "Positional numeral systems and non-decimal radices (Base-10 vs. Base-36)", "Fundamental Theorem of Arithmetic (111 = 3 × 37) and prime-counting function π(n)", "Additive string homomorphisms AQ(u · v) = AQ(u) + AQ(v) over character monoids", ], "public_resources": [ {"label": "Internal: /learn/ Module 1 (Base-36 Valuation Table)", "url": "/learn/index.html", "external": False}, {"label": "Khan Academy — Cryptography & Modular Arithmetic", "url": "https://www.khanacademy.org/computing/computer-science/cryptography", "external": True}, {"label": "MIT 6.042J Mathematics for Computer Science (Ch. 8 Number Theory)", "url": "https://ocw.mit.edu/courses/6-042j-mathematics-for-computer-science-fall-2010/", "external": True}, {"label": "3Blue1Brown — Prime Numbers & Number Theory Visualized", "url": "https://www.3blue1brown.com/topics/number-theory", "external": True}, ], "sections": [ { "heading": "1. The Base-36 Alphanumeric Homomorphism v: {0..9, A..Z} → {0..35}", "body": "For any character c, v(c) = ord(c) - 48 for digits '0'..'9' (0..9), v(c) = ord(lower(c)) - 87 for ASCII letters 'A'..'Z' (10..35), and v(c) = 0 otherwise. Extended over a string w = c_1...c_k, AQ(w) = ∑_{i=1}^k v(c_i). Under concatenation, AQ(w_1 · w_2) = AQ(w_1) + AQ(w_2).", }, { "heading": "2. Repdigit 37 × 3k Attractors & Prime Index π(n)", "body": "Three-digit repdigits R_k = 111 · k = 3 · 37 · k ∈ {111, 222, 333, 444, 555, 666, 777, 888, 999} factor through the prime 37 (12th prime) and 3. For prime coordinates p ∈ P, prime_rank(p) = π(p) = |{q ∈ P : q ≤ p}| (e.g., π(137) = 33 for 'envideea' = 137; π(193) = 44 for 'anthropik' = 'flash krash' = 193).", }, ], }, "phonemic-projections-and-g-vectors": { "unit_id": "M2", "slug": "phonemic-projections-and-g-vectors", "title": "Unit M2: Phonemic Projection Φ: Σ_eng* → Σ_ing* & Genealogical Vectors G1–G6", "short_title": "M2: Phonemic Φ & G1-G6", "pip_class": "plate-lock-emerald", "expertise_level": "Level 2-3: Set Mappings, Equivalence Fibers & Descriptive Statistics (8-12 hrs study)", "prerequisites": [ "Surjective mappings Φ: A → B, equivalence kernels ker(AQ ∘ Φ), and fixed points Φ(w) = w", "Population mean μ = (1/N)∑ x_i and population variance σ²(X) = (1/N)∑(x_i - μ)²", "How non-injective projection onto shared phonemic attractors collapses set variance", ], "public_resources": [ {"label": "OpenStax Introductory Statistics (Ch. 2 Mean & Variance)", "url": "https://openstax.org/details/books/introductory-statistics-2e", "external": True}, {"label": "StatQuest with Josh Starmer — Variance & Standard Deviation", "url": "https://statquest.org/video-index/", "external": True}, {"label": "Book of Proof (Richard Hammack — Free Textbook, Ch. 12 Functions & Fibers)", "url": "https://www.people.vcu.edu/~rhammack/BookOfProof/", "external": True}, ], "sections": [ { "heading": "1. Vector G1 Intergenerational Variance Collapse (Δσ²_G1)", "body": "Given a lexical cluster S = {w_1, ..., w_N}, define Gen 0 variance σ²_0(S) = σ²({AQ(w) : w ∈ S}) and Gen 1 phonemic variance σ²_1(S) = σ²({AQ(Φ(w)) : w ∈ S}). Vector G1 measures Δσ²_G1(S) = σ²_0(S) - σ²_1(S). For S_292 = {'schizoanalysis' (264), 'abstract machine' (317), 'synthetic data' (276)}, Φ maps all three to 292 ('shizohnalizis'=292, 'abstrakt masheen'=292, 'sinthetik dayta'=292), collapsing σ²_0 = 514.89 to σ²_1 = 0.00 (Δσ²_G1 = +514.89).", }, { "heading": "2. Vector G3 Quantized Steps, Vector G4 Isometric Fixed Points (Δ = 0) & Vector G5 Twin Primes", "body": "Define phonemic drift Δ(w) = AQ(Φ(w)) - AQ(w). Vector G4 consists of isometric fixed points where Δ(w) = 0 (21 canonical specimens including 'ASML'=81, 'capital'→'kapatal'=125, 'palantir'→'palanter'=159, 'nineteen'→'nainteen'=137). Vector G3 captures quantized step magnitudes |Δ(w)| ∈ {0, 1, 10, 18, 20, 36, 37, 40, 74}, and Vector G5 captures twin-prime mutations where both AQ(w) ∈ P and AQ(Φ(w)) ∈ P with Δ(w) ≠ 0.", }, ], }, "graph-topology-and-eti-scoring": { "unit_id": "M3", "slug": "graph-topology-and-eti-scoring", "title": "Unit M3: Multi-Relational Property Graph Topology G=(V,E,R), Convex ETI Functional & LENS_REGISTRY", "short_title": "M3: Graph & ETI Math", "pip_class": "plate-lock-gold", "expertise_level": "Level 3: Graph Theory, Convex Linear Combinations & Affine Maps (12-18 hrs study)", "prerequisites": [ "Directed multigraphs G = (V, E), k-partite vertex partitions, and vertex degree deg(v)", "Vectors in R^6, inner products w · s, and convex combinations (∑ w_k = 1, w_k ≥ 0)", "Lexicographic total orderings and invertible affine rescaling maps", ], "public_resources": [ {"label": "3Blue1Brown — Essence of Linear Algebra (Vectors & Dot Products)", "url": "https://www.3blue1brown.com/topics/linear-algebra", "external": True}, {"label": "MIT 6.042J Mathematics for Computer Science (Ch. 9-11 Graph Theory)", "url": "https://ocw.mit.edu/courses/6-042j-mathematics-for-computer-science-fall-2010/", "external": True}, {"label": "Diestel — Graph Theory (Free Electronic Edition, Ch. 1 Basics)", "url": "https://diestel-graph-theory.com/", "external": True}, ], "sections": [ { "heading": "1. Six-Partite Property Graph G = (V, E, R) & Hub Degree Centrality", "body": "The vertex set |V| = 388 is partitioned into 6 disjoint classes (9 Divisions, 22 Volumes, 10 Builds, 92 Operators, 190 Bilingual Specimens, 65 AQCoordinateHubs) linked by |E| = 1,282 typed edges across 10 relations. Hub degree deg(aq:N) peaks at repdigit attractors aq:777 (deg=62), aq:666 (deg=62), and aq:333 (deg=52).", }, { "heading": "2. Convex Ecological Trophic Index (ETI) Functional in [0, 100]", "body": "Each specimen i has a 6-dimensional structural vector s_i = (ARM_i, VEL_i, COL_i, CAP_i, PRM_i, RES_i) ∈ [0, 100]^6. The composite score is the convex inner product ETI_i = 0.20·CAP_i + 0.18·COL_i + 0.18·ARM_i + 0.16·PRM_i + 0.14·VEL_i + 0.14·RES_i where ∑_{k=1}^6 w_k = 1.00, guaranteeing ETI_i ∈ [0, 100]. LENS_REGISTRY applies bijective key/scale projections without mutating s_i.", }, ], }, "timeseries-moments-and-confluence-dose": { "unit_id": "M4", "slug": "timeseries-moments-and-confluence-dose", "title": "Unit M4: Longitudinal Moments (ts_*), Lead-Lag r(τ), Order Statistics (P50, P90) & Confluence Dose D ∈ {0..4}", "short_title": "M4: Time-Series & Dose Math", "pip_class": "plate-lock-emerald", "expertise_level": "Level 3-4: Nonparametric Order Statistics & Time-Series Correlation (15-20 hrs study)", "prerequisites": [ "Basis-point return arithmetic Δbps_{i,t} = round(((P_t - P_{t-1}) / P_{t-1}) × 10^4)", "Nonparametric order statistics (Median P50, 90th percentile P90) vs. outlier-sensitive means", "Pearson linear correlation r(τ) across lags τ ∈ [-5..+5] and indicator sums ∑ I(A_s)", ], "public_resources": [ {"label": "Seeing Theory (Brown University Visual Intro to Probability & Statistics)", "url": "https://seeing-theory.brown.edu/", "external": True}, {"label": "Penn State STAT 510 Applied Time Series Analysis (Cross-Correlation)", "url": "https://online.stat.psu.edu/stat510/", "external": True}, {"label": "NIST/SEMATECH e-Handbook of Statistical Methods (Order Statistics)", "url": "https://www.itl.nist.gov/div898/handbook/", "external": True}, ], "sections": [ { "heading": "1. Four-Species Confluence Dose Indicator Sum D_{i,t} ∈ {0, 1, 2, 3, 4}", "body": "For ticker i on trading session t, D_{i,t} = I(Scope1_{i,t}) + I(Scope2Ring_{i,t}) + I(SharedDossier_{i,t}) + I(WireEntity_{i,t}). Whenever a session is closed or private (data_available = False), D_{i,t} = null rather than 0, preventing missing-data bias.", }, { "heading": "2. Nonparametric Order Statistics (P50, P90) & the Empirical Two-Regime Split", "body": "Because cross-asset returns |Δbps| are heavy-tailed, Median P50 and P90 are the robust estimators: across the 440 real November 2026 bars, Dose 2 (Market Ring × Same-Day Dossier without headline shock, n=34) compresses median displacement by -58% (P50 = 101.0 bps vs. 240.5 bps at Dose 0; P90 = 292 bps vs. 665 bps), whereas Dose 3+ (n=4) triggers a 1.98x volume surge and 377.5 bps next-day continuation.", }, ], }, "macro-spreads-and-bayesian-inference": { "unit_id": "M5", "slug": "macro-spreads-and-bayesian-inference", "title": "Unit M5: Macroeconomic Spread/Velocity Identities, Discrete 3-State Bayes' Rule & Multiple-Testing Bounds", "short_title": "M5: Macro & Bayesian Math", "pip_class": "plate-lock-rose", "expertise_level": "Level 4: Bayesian Inference, Combinatorial Collision Bounds & Macroeconomics (15-25 hrs study)", "prerequisites": [ "Conditional probability P(A | B) and Bayes' Theorem on the 3-state simplex Δ²", "Multiple-hypothesis testing, Birthday Problem collision rates, and degrees of freedom df = n - 2", "Equation of Exchange MV = PQ (V_M2 = GDP / M2), term structure slopes, and real deflation", ], "public_resources": [ {"label": "3Blue1Brown — Bayes' Theorem, The Geometry of Changing Beliefs", "url": "https://www.3blue1brown.com/lessons/bayes-theorem", "external": True}, {"label": "MIT 18.05 Introduction to Probability & Statistics (Bayesian Updating)", "url": "https://ocw.mit.edu/courses/18-05-introduction-to-probability-and-statistics-spring-2022/", "external": True}, {"label": "OpenStax Principles of Macroeconomics (Ch. 14-15 Money & Monetary Policy)", "url": "https://openstax.org/details/books/principles-macroeconomics-3e", "external": True}, ], "sections": [ { "heading": "1. Macroeconomic Spread & Velocity Identities (FRED Native Cadences)", "body": "From real FRED observations: Non-M1 Time-Deposit Spread = M2SL - M1SL = $3,365.9B ($3.37T → 337 [68th Prime]); Liquidity Ratio = M1SL / M2SL = 85.70%; Monetary Velocity V_M2 = GDP / M2SL = 1.405x; Overnight Repo Spread = SOFR - EFFR = +10 bps (EFFR = 388 bps == 388 KG nodes); Term Slope = DGS10 - EFFR = +97 bps ('naintee sevan' = 237); Pipeline Margin = ΔPPI_MoM - ΔCPI_MoM = -54 bps.", }, { "heading": "2. Discrete 3-State Bayesian Updating & 'The Room Filter' Collision Bound", "body": "Given extant priors P_{t-1}(R_m) over R = {R1 Bull, R2 Pinned Isometric, R3 Tail Drawdown} with ∑ P_{t-1}(R_m) = 1, the posterior is P_t(R_m | E_t) = L(E_t | R_m)·P_{t-1}(R_m) / ∑_{k=1}^3 L(E_t | R_k)·P_{t-1}(R_k). Testing 6 numerical encodings against 30 S1-S6 ring coordinates yields an uncoupled single-gate hit rate near Dose 1's observed 16.6% ('Grand Central Station' noise), whereas requiring joint intersection with that exact UTC date's 00:00 GMT dossier coordinates ('The Room Filter', Dose 2/3+) squares the filter selectivity.", }, ], }, } def introspect_math_manifest( enabled_subpages: tuple[str, ...] = ENABLED_MATH_SUBPAGES, workspace_root: str | Path | None = None, ) -> dict[str, Any]: cfg = load_workspace_config(workspace_root=workspace_root) gl_obj = json.loads((cfg.zoology_dir / "taxonomy" / "glossary-registry.json").read_text(encoding="utf-8")) kg_obj = json.loads((cfg.knowledge_graph_dir / "encyclopedia-graph.json").read_text(encoding="utf-8")) ts_obj = json.loads((cfg.core_dir / "site" / "quant" / "quant-timeseries.json").read_text(encoding="utf-8")) mac_obj = json.loads((cfg.core_dir / "site" / "quant" / "real-macro-indicators.json").read_text(encoding="utf-8")) brf_obj = json.loads((cfg.core_dir / "site" / "quant" / "daily-brief-latest.json").read_text(encoding="utf-8")) # Verify algebraic invariants dynamically eti_weights = [0.20, 0.18, 0.18, 0.16, 0.14, 0.14] eti_weight_sum = round(sum(eti_weights), 6) post_probs = brf_obj["agenda_1_executive_summary"]["bayesian_regime_inference"]["posterior_probabilities"] post_sum = round(sum(post_probs.values()), 4) cluster_292_gen0 = [compute_aq("schizoanalysis"), compute_aq("abstract machine"), compute_aq("synthetic data")] cluster_292_gen1 = [compute_aq("shizohnalizis"), compute_aq("abstrakt masheen"), compute_aq("sinthetik dayta")] var_292_gen0 = compute_variance(cluster_292_gen0) var_292_gen1 = compute_variance(cluster_292_gen1) bilingual = gl_obj.get("bilingual_vocabulary_ledger") or [] isometric_fixed_points = [x for x in bilingual if x.get("eng_aq") == x.get("ing_aq")] total_real_bars = sum( sum(1 for b in (inst.get("bars") or []) if b.get("data_available")) for inst in (ts_obj.get("instruments") or []) ) active_subpages = [s for s in ALL_MATH_SUBPAGES if s in enabled_subpages] enabled_routes = ["/math/index.html"] + [f"/math/{s}/index.html" for s in active_subpages] manifest: dict[str, Any] = { "$id": "urn:io:hyperstitionstud:math-manifest", "version": CURRENT_VERSION, "enabled_subpages": active_subpages, "disabled_subpages": [s for s in ALL_MATH_SUBPAGES if s not in active_subpages], "enabled_routes": enabled_routes, "algebraic_invariants": { "eti_weights": eti_weights, "eti_weights_sum": eti_weight_sum, "bayesian_posterior_simplex_sum": post_sum, "cluster_292_gen0_variance": var_292_gen0, "cluster_292_gen1_variance": var_292_gen1, "g4_isometric_fixed_point_count": len(isometric_fixed_points), "g3_quantized_steps": sorted(G3_QUANTIZED_STEPS), "repdigit_37_attractors": sorted(REPDIGIT_37_ATTRACTORS), }, "empirical_counts": { "glossary_entries": sum(len(sec.get("entries") or []) for sec in (gl_obj.get("sections") or [])) + len(gl_obj.get("custom_entries") or []) + len(bilingual), "bilingual_specimens": len(bilingual), "kg_nodes": len(kg_obj.get("nodes") or []), "kg_edges": len(kg_obj.get("edges") or []), "total_real_bars_n": total_real_bars, "fred_macro_series_n": int(mac_obj.get("series_count") or 0), }, "hub_prereq_ladder": MATH_HUB_PREREQ_LADDER, "subpages": {s: MATH_SUBPAGE_SPECS[s] for s in active_subpages}, } manifest["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(manifest)} return manifest def _render_math_nav_html(active_slug: str | None, enabled_subpages: list[str], rel_prefix: str) -> str: links = [ f'Portal Home (/)', f'Math Hub (M0)', ] direct_pages = enabled_subpages[:6] overflow_pages = enabled_subpages[6:] for s in direct_pages: spec = MATH_SUBPAGE_SPECS[s] is_act = (s == active_slug) href = f"{s}/index.html" if active_slug is None else (f"../{s}/index.html" if not is_act else "index.html") style = "border-color:var(--gold);color:var(--gold);" if is_act else "" links.append(f'{spec["short_title"]}') if overflow_pages: opts = [''] for s in overflow_pages: spec = MATH_SUBPAGE_SPECS[s] href = f"{s}/index.html" if active_slug is None else (f"../{s}/index.html" if s != active_slug else "index.html") opts.append(f'') links.append(f'') from hyperstitionstud_io.publishing.engineering_docs import _render_polyglot_selector_html links.append(f'Engineering Hub (/engineering/)') links.append(_render_polyglot_selector_html()) links.append('') links.append( f'' 'DONATE' ) return "\n ".join(links) def _render_math_prereq_html(level_str: str, prereqs: list[str], resources: list[dict[str, Any]], rel_prefix: str) -> str: from hyperstitionstud_io.publishing.engineering_docs import _render_prereq_box_html return _render_prereq_box_html( level_str=level_str, prereqs=prereqs, resources=resources, rel_prefix=rel_prefix, intro_prompt="If any mathematical notation on this page is unfamiliar, occupy your study time with these free foundational resources first:", prereq_heading="Core Mathematical Prerequisites:", ) def _render_math_hub_html(manifest: dict[str, Any], include_guile_lens: bool = True) -> str: from hyperstitionstud_io.publishing.engineering_docs import _render_guile_repl_drawer_html enabled = manifest["enabled_subpages"] inv = manifest["algebraic_invariants"] emp = manifest["empirical_counts"] nav_html = _render_math_nav_html(None, enabled, "") prereq_html = _render_math_prereq_html( MATH_HUB_PREREQ_LADDER["expertise_level"], [ "Variables, functions f(x), and subscript/index notation x_i", "Summation operator ∑_{i=1}^n x_i and absolute value |x|", "Self-Paced Learning Track (/learn/ Modules 1-2)", ], MATH_HUB_PREREQ_LADDER["links"], "", ) guile_hub_html = _render_math_guile_cartridge_html("M0") if include_guile_lens else "" guile_drawer_html = _render_guile_repl_drawer_html("") if include_guile_lens else "" cards_html = "" sigil_map = { "M1": "☿", "M2": "∆ ◈", "M3": "☉", "M4": "♄ ☍", "M5": "⊗ λ", } for s in enabled: sp = MATH_SUBPAGE_SPECS[s] sig = sigil_map.get(sp["unit_id"], "λ") cards_html += ( f'' ) return f""" Mathematical Foundations & Quantitative Semiotics Hub — hyperstitionstud.io/math (v{CURRENT_VERSION})

HYPERSTITION STUDIO // MATHEMATICAL FOUNDATIONS & QUANTITATIVE SEMIOTICS HUB (UNIT M0)

Zero-CDN Native Unicode Math • Commutative Empirical Introspection • Piecewise & Non-Sequentially Revertible • urn:io:hyperstitionstud:math:v{CURRENT_VERSION}

{prereq_html} {guile_hub_html}
ETI Convex Sum (∑w_k)
{inv["eti_weights_sum"]:.2f}
Bayesian Simplex (∑P_m)
{inv["bayesian_posterior_simplex_sum"]:.4f}
292 G1 Collapse (σ²_0 → σ²_1)
{inv["cluster_292_gen0_variance"]} → {inv["cluster_292_gen1_variance"]}
G4 Fixed Points (Δ=0)
{inv["g4_isometric_fixed_point_count"]}
Real Bars / FRED Series
{emp["total_real_bars_n"]} / {emp["fred_macro_series_n"]}
{cards_html}
hyperstitionstud.io/math v{CURRENT_VERSION} • CIDv1: {manifest["ipld_dag_json_cidv1"]["/"][:36]}... • • Made with ♥ by Lemurs.
{guile_drawer_html} """ def _render_math_subpage_html(slug: str, manifest: dict[str, Any], include_guile_lens: bool = True) -> str: from hyperstitionstud_io.publishing.engineering_docs import _render_guile_repl_drawer_html enabled = manifest["enabled_subpages"] spec = MATH_SUBPAGE_SPECS[slug] nav_html = _render_math_nav_html(slug, enabled, "../") prereq_html = _render_math_prereq_html(spec["expertise_level"], spec["prerequisites"], spec["public_resources"], "../") guile_sub_html = _render_math_guile_cartridge_html(slug) if include_guile_lens else "" guile_drawer_html = _render_guile_repl_drawer_html("../") if include_guile_lens else "" idx = enabled.index(slug) prev_link = f'← Prev: {MATH_SUBPAGE_SPECS[enabled[idx - 1]]["short_title"]}' if idx > 0 else '← Back to Math Hub (M0)' next_link = f'Next: {MATH_SUBPAGE_SPECS[enabled[idx + 1]]["short_title"]} →' if idx + 1 < len(enabled) else 'Return to Math Hub (M0) ↑' secs_html = "" for sec in spec["sections"]: secs_html += ( '
' f'

{sec["heading"]}

' f'

{sec["body"]}

' '
' ) return f""" {spec["title"]} — hyperstitionstud.io/math (v{CURRENT_VERSION})

{spec["title"]}

Cartridge {spec["unit_id"]} • Non-Sequentially Revertible via hs-math-docs --disable {slug} • v{CURRENT_VERSION}

{prereq_html} {guile_sub_html} {secs_html}
{prev_link} {next_link}
hyperstitionstud.io/math/{slug} v{CURRENT_VERSION} • • Made with ♥ by Lemurs.
{guile_drawer_html} """ def build_math_site( out_dir: str | Path | None = None, enabled_subpages: tuple[str, ...] | list[str] = ENABLED_MATH_SUBPAGES, disable_all: bool = False, include_guile_lens: bool = ENABLE_GUILE_SCHEME_LENS, workspace_root: str | Path | None = None, ) -> dict[str, Any]: cfg = load_workspace_config(workspace_root=workspace_root) target_dir = Path(out_dir).resolve() if out_dir else (cfg.core_dir / "site" / "math").resolve() with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: if disable_all: if target_dir.is_dir(): shutil.rmtree(target_dir) return {"ok": True, "disabled_all": True, "enabled_routes": []} target_dir.mkdir(parents=True, exist_ok=True) active_tuple = tuple(s for s in ALL_MATH_SUBPAGES if s in enabled_subpages) manifest = introspect_math_manifest(enabled_subpages=active_tuple, workspace_root=workspace_root) (target_dir / "math-manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") (target_dir / "math-manifest-data.js").write_text( "window.HYPERSTITION_MATH_MANIFEST = " + json.dumps(manifest, ensure_ascii=False) + ";\n", encoding="utf-8", ) (target_dir / "math-app.js").write_text("(function(){ 'use strict'; })();\n", encoding="utf-8") (target_dir / "index.html").write_text(_render_math_hub_html(manifest, include_guile_lens=include_guile_lens), encoding="utf-8") for s in ALL_MATH_SUBPAGES: sub_d = target_dir / s if s in active_tuple: sub_d.mkdir(parents=True, exist_ok=True) (sub_d / "index.html").write_text(_render_math_subpage_html(s, manifest, include_guile_lens=include_guile_lens), encoding="utf-8") elif sub_d.is_dir(): shutil.rmtree(sub_d) return { "ok": True, "version": CURRENT_VERSION, "output_dir": str(target_dir), "guile_scheme_lens_enabled": include_guile_lens, "enabled_subpages": list(active_tuple), "enabled_routes": manifest["enabled_routes"], "cidv1": manifest["ipld_dag_json_cidv1"]["/"], "isolation_receipt": guard.audit_receipt(), } def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="hs-math-docs", description="Build or toggle the /math/ Hub & modular subpages (M0-M5).") ap.add_argument("--sync", action="store_true") ap.add_argument("--disable", default="", help="Comma-separated subpage slugs or unit IDs (e.g. M3) to disable.") ap.add_argument("--only", default="", help="Comma-separated subpage slugs or unit IDs (e.g. M1,M4) to enable exclusively.") ap.add_argument("--disable-all", action="store_true") ap.add_argument("--disable-guile-lens", action="store_true", help="Omit additive Guile Scheme cartridges without touching M0-M5 content.") ap.add_argument("--out-dir", default=None) args = ap.parse_args(argv) unit_map = {spec["unit_id"].upper(): slug for slug, spec in MATH_SUBPAGE_SPECS.items()} enabled = list(ALL_MATH_SUBPAGES) if args.only: req = {unit_map.get(x.strip().upper(), x.strip()) for x in args.only.split(",") if x.strip()} enabled = [s for s in ALL_MATH_SUBPAGES if s in req] if args.disable: dis = {unit_map.get(x.strip().upper(), x.strip()) for x in args.disable.split(",") if x.strip()} enabled = [s for s in enabled if s not in dis] res = build_math_site( out_dir=args.out_dir, enabled_subpages=tuple(enabled), disable_all=args.disable_all, include_guile_lens=not args.disable_guile_lens, ) print(json.dumps(res, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())