Files
encyclopedia-knowledge-graph/docs/PLAN-GUILE-SCHEME-PEDAGOGICAL-TOGGLE-AND-IN-BROWSER-REPL.md
T

119 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Plan: Additive Guile Scheme Mode Toggle (`[ λ GUILE SCHEME LENS ]`) & Offline In-Browser Z-Combinator REPL Across `/engineering/` (`E0–E5`) and `/math/` (`M0–M5`) (`v2.1.0`)
- **Document ID:** `PLAN-GUILE-SCHEME-PEDAGOGICAL-TOGGLE-AND-IN-BROWSER-REPL` (`v2.1.0`)
- **Roadmap Status:** **ACTIVE / READY**
- **Core Pedagogical & Architectural Mandate:**
1. **Zero Eclipse of Existing Curriculum:** The existing `/engineering/` (`E0–E5`) and `/math/` (`M0–M5`) curriculum (Novice Prerequisite Ladders `.hs-prereq-ladder`, formal theorems, Python/SQL/JS implementation tables, and live manifest invariants) remains **100% primary and untouched**. By default (`localStorage["hs:guile-scheme-mode:v1"] == "off"`), pages load in standard mode; toggling **`[ λ GUILE SCHEME LENS: ON ]`** (`Alt+S`) reveals additive **Guile Scheme Teaching Cartridges (`.hs-guile-cartridge`)** alongside each section plus a dockable **In-Browser Guile Scheme & Z-Combinator REPL Drawer (`#hsGuileReplDrawer`)**.
2. **Multi-Modal Guile Scheme Pedagogy (`z-calculus-scheme` Integration):** Uses GNU Guile Scheme and the applicative-order `Z` combinator (`Z = λf. (λx. f (λv. (x x) v)) (λx. f (λv. (x x) v))`) to teach in **6 complementary ways**:
- **(1) Homoiconic Tri-View (`Math Formula <-> Python/JS <-> Guile S-Expression AST`)**,
- **(2) Anonymous Fixed-Point Recursion via `Z` (Thomas' Calculus & Discrete State Fold Lab)**,
- **(3) Interactive Step-by-Step `β-Reduction` & Environment Substitution Tracer**,
- **(4) Exact Rational (`p/q`) vs. IEEE-754 Floating-Point Precision Lab**,
- **(5) Live Equivalence Proof (verifying Scheme output against live `engineering-manifest.json` / `math-manifest.json` invariants)**, and
- **(6) One-Click `"Load in REPL"` Guided Lambda Micro-Challenges**.
3. **Zero Metered LLM Tokens & Zero External CDN Dependencies:** All 12 subpage cartridges, the canonical `guile_prelude.scm` library, and the in-browser Scheme interpreter (`site/assets/hs-guile-scheme-repl.js`) are 100% deterministic local Python/JS/Scheme (`0` LLM tokens, `0` external HTTPS scripts).
- **Target Modules & Assets:**
- `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/publishing/guile_prelude.scm` (Canonical GNU Guile Scheme + `z-calculus-scheme` prelude)
- `/workspace/hyperstitionstudio-core/site/assets/hs-guile-scheme-repl.js` (Offline client-side Guile Scheme S-Expression evaluator, exact rational tower, tail-call trampoline, β-reduction stepper, and dockable REPL UI)
- `/workspace/hyperstitionstudio-core/site/assets/hs-group3-basalt-chamfer.css` (Group 3 Stealth Basalt styling for `#guileSchemeModeToggle`, `.hs-guile-cartridge`, and `#hsGuileReplDrawer`)
- `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/publishing/{engineering_docs.py,math_docs.py}` (Piecewise toggleable `--with-guile-lens` / `--without-guile-lens` cartridge injection across `E0–E5` & `M0–M5`)
- `/workspace/hyperstitionstudio-core/tests/test_core_suite.py`
---
## 1. Non-Eclipsing UI & State Architecture (`Group 3 Stealth Basalt` Compliant)
### 1.1 Header Toggle Pill & Cross-Page State Persistence
- **Control Placement:** In the top navigation / command bar of `/engineering/` (`E0–E5`) and `/math/` (`M0–M5`), adjacent to the cross-links between `/engineering/` and `/math/`, add a `34px`-height Group 3 Stealth Basalt toggle button:
```html
<button id="guileSchemeModeToggle" class="hs-btn-basalt hs-guile-toggle" type="button" aria-pressed="false" title="Toggle additive Guile Scheme & Z-Combinator teaching cartridges and in-browser REPL (Alt+S)">
<span class="hs-guile-lambda-badge">&lambda;</span>
<span class="hs-guile-toggle-label">GUILE SCHEME LENS: <strong id="guileSchemeModeState">OFF</strong></span>
</button>
```
- **Sensory Budget Compliance (`90%` Basalt / `7%` `#38bdf8` Interactive / `3%` `#f59e0b` Beacon):**
- When `OFF`, the toggle button sits quietly in matte basalt (`#0c1324` fill, `#1e293b` hairline border) and `.hs-guile-cartridge` blocks are hidden (`display: none`), ensuring zero visual distraction for readers focused solely on the core curriculum.
- When toggled `ON` (`document.documentElement.setAttribute("data-guile-scheme-mode", "on")` + `localStorage.setItem("hs:guile-scheme-mode:v1", "on")`), the `28px` left-shoulder Signal Pip on each `.hs-guile-cartridge` lights up in `#38bdf8` cyan, expanding the Guile Scheme teaching foil directly beneath each curriculum card without hiding or displacing a single word of the primary explication.
### 1.2 Piecewise & Non-Sequential Revertability
- In `publishing/engineering_docs.py` and `publishing/math_docs.py`, the Guile Scheme layer is governed by an orthogonal feature flag (`ENABLE_GUILE_SCHEME_LENS: bool = True`, CLI flags `--disable-guile-lens` / `--enable-guile-lens`) as well as per-unit overrides (`E0..E5`, `M0..M5`).
- Disabling the Guile lens on any single subpage or globally requires a single deterministic `--sync` command (`0` LLM tokens) and leaves all `E0–E5` and `M0–M5` cartridges intact.
---
## 2. Six Pedagogical Ways Guile Scheme Teaches Across `/math/` (`M0–M5`) and `/engineering/` (`E0–E5`)
| # | Pedagogical Modality | How It Works Inside Each `.hs-guile-cartridge` | Why It Deepens Understanding Without Eclipsing the Main Text |
| :---: | :--- | :--- | :--- |
| **1** | **Homoiconic `S-Expression <-> Math <-> Python` Tri-View** | Side-by-side comparison showing how the mathematical notation ($\sum$, $\prod$, $\nabla$, $\pi_{\text{IPA}}$) and the production Python function map to a pure prefix S-expression `(op arg1 arg2 ...)`. | Eliminates operator-precedence ambiguity and shows novices that formulas, ASTs, and data structures are isomorphic. |
| **2** | **Applicative-Order `Z`-Combinator Fixed-Point Enactment (`z-calculus-scheme`)** | Every iterative or recursive algorithm (limits, derivatives, Simpson quadrature, Base-36 folds, graph degree traversals, Bayesian updates) is written **without named self-reference** using `(Z (lambda (recur) (lambda (...) ...)))`. | Connects discrete software engineering (`E1–E5`) and continuous/discrete applied math (`M1–M5`) to a single atomic primitive from lambda calculus. |
| **3** | **Interactive `β-Reduction` & Substitution Stepper** | Clicking `[ Step β-Reduction ]` advances one evaluation step at a time, showing the environment bindings (`chars`, `acc`, `priors`, `h`) and intermediate return values. | Makes invisible loop state and recursive call frames concretely visible to novices. |
| **4** | **Exact Rational (`p/q`) vs. Floating-Point Contrast** | Evaluates expressions using exact rationals (`7/20 + 1/4 + 1/5 + 1/5 => 1`, `16378/45`) alongside IEEE-754 floats (`363.9555555555556`). | Teaches why exact rational arithmetic prevents rounding drift in convex combinations (`ETI`) and probability simplices, and why inexact floats (`1e-6`) are chosen for deep `Z` convergence loops. |
| **5** | **Live Equivalence Verification Badge** | Automatically runs the cartridge's Scheme program on page load (when Scheme Mode is `ON`) and asserts `Scheme Result === Live Manifest Invariant` (`[ VERIFIED EQUAL ]`). | Proves to the learner that the functional Scheme specification and the production Python engine compute identical results on real repository data. |
| **6** | **Guided `"Load in REPL"` Lambda Micro-Challenges** | Each subpage provides an interactive prompt (e.g., *"Change the prior in `(bayes-update ...)` or compute the 2nd derivative via `((nth-derivative f 2 1e-4) x)`"*) with a one-click `[ Send to REPL ]` button. | Turns passive reading into active experimentation inside the browser. |
---
## 3. Subpage-by-Subpage Guile Scheme Cartridge Curriculum (`M0–M5` & `E0–E5`)
### 3.1 Applied Mathematics & Statistics Subpages (`/math/` — Units `M0–M5`)
- **`M0` (`/math/index.html` — Hub & Prerequisite Bridge):**
- Introduces the applicative-order `Z` combinator (`(define Z (lambda (f) ((lambda (x) (f (lambda args (apply (x x) args)))) (lambda (x) (f (lambda args (apply (x x) args)))))))`), explains why the unguarded Y combinator diverges in strict evaluation while eta-expanded `Z` converges, and adds free novice Scheme resources (*Structure and Interpretation of Computer Programs (SICP)*, *The Little Schemer*, and the GNU Guile Reference Manual) to `.hs-prereq-ladder`.
- **`M1` (`/math/base36-algebra-and-primes/` — Base-36 Semiring & Primes):**
- Enacts `aq-base36` (homomorphic fold over character lists via `Z`), `digital-root-mod9` (fixed-point digit sum until `< 10`), and `prime-factors` (`(prime-factors 666) => (2 3 3 37)`, `(prime-factors 777) => (3 7 37)`).
- **`M2` (`/math/phonemic-projections-and-g-vectors/` — Phonemic Projections & Variance Collapse):**
- Enacts exact rational population & sample `variance` via `Z` on the `292` Synonym Cluster (`(variance-pop '(120 116 144 103 157)) => 8189/25` = `327.56` vs. `(variance-pop '(112 112 112 112 112)) => 0`) and classifies `G1` (`ing_aq` collapse) and `G4` (`eng_aq == ing_aq` fixed point).
- **`M3` (`/math/graph-topology-and-eti-scoring/` — Graph Topology & ETI Scoring):**
- Enacts exact rational `eti-score` (`(+ (* 7/20 s) (* 1/4 p) (* 1/5 c) (* 1/5 m))`) verifying that the rational weights sum to `1` (`20/20`), plus polar radar coordinate projection `(eti->polar eti theta r-min r-max)`.
- **`M4` (`/math/timeseries-moments-and-confluence-dose/` — Time-Series Moments, Confluence Dose & Thomas' Calculus):**
- Enacts `confluence-dose` ($D_{i,t} \in \{0..4\}$ as a `Z`-fold over the 4 species predicates) AND connects discrete bar series to continuous Thomas' Calculus via `limit` and central-difference `derivative` (`(derivative (lambda (t) (* 0.024 t t)) 1e-6)`).
- **`M5` (`/math/macro-spreads-and-bayesian-inference/` — FRED Macro Spreads, Bayesian Inference & Quadrature):**
- Enacts exact rational 3-state `bayes-update` (`P(R_k | E_t)`), `brier-score`, and `adaptive-simpson` numerical quadrature over continuous probability densities via `Z`.
### 3.2 Software Engineering Subpages (`/engineering/` — Units `E0–E5`)
- **`E0` (`/engineering/index.html` — Hub & Homoiconic Introspection):**
- Demonstrates homoiconic S-expression manifest introspection (`(assoc-ref manifest 'version) => "2.1.0"`) and how treating configuration, code, and theorems as uniform S-expression trees eliminates schema drift.
- **`E1` (`/engineering/ciphers-and-phonetics/` — Pure Functional Phonetic Transducers):**
- Enacts the zero-global-state lookup pipeline `(translate-word "hyperstition" cmudict-alist)` with fallback rule composition via `Z`.
- **`E2` (`/engineering/knowledge-graph-and-sqlite/` — Immutable Graph Queries & Isolation Guards):**
- Enacts higher-order `(with-isolation-guard pre-sha256 thunk post-sha256)` and `Z`-combinator multigraph edge filtering `(filter-edges-by-type edges 'G4_ISOMETRIC_INVARIANT)`.
- **`E3` (`/engineering/quant-macro-and-bayesian-brief/` — Zero-Synthetic `#f` Option Semantics):**
- Enacts explicit `#f` (`None`/`null`) handling in Scheme time-series folds: `(filter-valid-bars '((2026-11-27 135.40) (2026-11-28 #f) (2026-11-29 #f) (2026-11-30 138.25)))`, proving how functional filtering naturally forbids synthetic weekend/holiday interpolation.
- **`E4` (`/engineering/mcp-chatbot-rest-and-ipld/` — S-Expression JSON-RPC Dispatcher & Canonical Sorting):**
- Enacts a pure functional MCP tool router `((mcp-router tool-table) '(tools/call "hs_evaluate_aq_and_ingglish" "LEMUR"))` and recursive lexicographic key sorting for IPLD `dag-json` (`0x0129`) via `Z`.
- **`E5` (`/engineering/cicd-vps-tmpfs-and-regression/` — Programmatic SemVer Heuristics & DAG Sort in Scheme):**
- Enacts `evaluate-bump-scope` (the exact 4-tier `noop / patch / minor / major` decision tree from `version_sync.py`) and 6-gate regression conjunction `(all-gates-pass? gates)` via `Z`.
---
## 4. In-Browser Guile Scheme & Z-Combinator Interactive REPL Specification (`site/assets/hs-guile-scheme-repl.js`)
### 4.1 Capabilities of the Client-Side Scheme Engine (`0` External Dependencies)
1. **Complete Core Scheme Special Forms & Tail-Call Trampoline:**
- Supports `define`, `lambda` (both fixed `(lambda (x y) ...)` and variadic `(lambda args ...)` / dotted `(lambda (x . rest) ...)` required by the `Z` combinator!), `let`, `let*`, `if`, `cond`, `and`, `or`, `begin`, `quote` (`'expr`), and `apply`.
- Uses a tail-call optimization (TCO) loop so deep `Z`-combinator recursions (thousands of steps in `riemann-integral`, `adaptive-simpson`, `series-sum`, or `rk4-integrate`) execute in `O(1)` JS stack frames without `RangeError: Maximum call stack size exceeded`.
2. **Exact Rational (`p/q`) + Inexact Float Number Tower:**
- Literal fractions like `7/20`, `1/3`, or exact integer divisions `(/ 16378 45)` preserve exact numerator/denominator GCD-reduced rationals (`363 43/45` / `16378/45`) until combined with an inexact float (`2.0`, `0.5`, `1e-6`) or converted via `(exact->inexact x)` / `(inexact->exact x)`.
3. **Built-In `z-calculus-scheme` & Hyperstition Prelude:**
- Pre-defines `Z`, `limit`, `derivative`, `nth-derivative`, `newton-solve`, `riemann-integral`, `adaptive-simpson`, `series-sum`, `rk4-integrate`, `gradient`, `aq-base36`, `digital-root-mod9`, `prime-factors`, `variance-pop`, `eti-score`, `confluence-dose`, `bayes-update`, `brier-score`, and `evaluate-bump-scope`.
4. **Interactive REPL Drawer UI (`#hsGuileReplDrawer`):**
- Docked at the bottom-right of any `/engineering/*` or `/math/*` page when Guile Scheme Mode is `ON` (collapsible/expandable).
- Features:
- Preset selector dropdown (loads any of the 12 subpage labs or `z-calculus-scheme` Modules 1–5),
- Multi-line S-expression editor with parenthesis matching & `Ctrl+Enter` / `[ Evaluate (λ) ]` execution,
- `[ Step β-Reduction ]` button showing the first 12 evaluation reductions step-by-step,
- Exact Rational vs. Float display toggle, and
- Command history (`Up`/`Down` arrows, persisted in `sessionStorage`).
---
## 5. Test-Suite Appropriateness Analysis & Verification Gates (`tests/test_core_suite.py` & `hs-public-smoke`)
1. **In-Process & Subprocess Verification (`tests/test_core_suite.py`):**
- Verify that `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/publishing/guile_prelude.scm` and `/workspace/hyperstitionstudio-core/site/assets/hs-guile-scheme-repl.js` exist and contain `0` external `https://` script/font URLs.
- Verify that all 6 `/engineering/*` HTML files and all 6 `/math/*` HTML files include `#guileSchemeModeToggle`, `.hs-guile-cartridge`, `#hsGuileReplDrawer`, and `/assets/hs-guile-scheme-repl.js` while retaining 100% of their existing curriculum sections and `.hs-prereq-ladder` blocks.
- Verify piecewise revertability: calling `build_engineering_site(..., include_guile_lens=False)` and `build_math_site(..., include_guile_lens=False)` cleanly omits `.hs-guile-cartridge` while keeping all `E0–E5` and `M0–M5` content intact.
- When `node` is available (already used in `test_core_suite.py`), execute `/workspace/hyperstitionstudio-core/site/assets/hs-guile-scheme-repl.js` headlessly in Node to verify that the in-browser Scheme engine evaluates `Z`-combinator `limit`, `derivative`, `adaptive-simpson`, `aq-base36`, exact rational `eti-score`, `variance-pop` on Cluster `292`, and `bayes-update` to the exact expected analytical values!
2. **Public Surface Regression Gate (`hs-public-smoke` Gate `P6` & `deploy/test-first-deployment.sh`):**
- Add `/assets/hs-guile-scheme-repl.js` to `ROUTES=()` in `deploy/test-first-deployment.sh` and verify `HTTP 200 OK`.