feat(zoology): integrate hyperstitionstud_io.* offline phonetics fallback, full 11-function local-config sources.py shim, and v1.2.0 common library

This commit is contained in:
Hermes Agent committed 2026-11-29 21:06:48 +00:00
1 parent 83c9069f23
commit 1f2c4f4a7e
7 files changed
+332 -606

No files matched your search

+121 -130
View File
@@ -1,71 +1,118 @@
# Architecture & Migration Plan: Shared Common Library Across All `/workspace` Projects Under the `hyperstitionstud.io` Namespace (`v1.0.0`)
# Architecture & Implementation Plan: Shared Common Library Under the `hyperstitionstud.io` Namespace (`v1.2.0` — 100% Offline `URN:` Namespace & Dual `file://` + `http://` Portability Edition)
- **Document ID:** `PLAN-COMMON-LIBRARY-HYPERSTITIONSTUDIO` (`v1.0.0`)
- **Canonical Domain & Authority:** `hyperstitionstud.io`
- **Python PEP 420 Reverse-DNS Namespace:** `io.hyperstitionstud.*` (installed from `/workspace/hyperstitionstudio-core`)
- **JavaScript / ESM Scope Namespace:** `@hyperstitionstud.io/*` (`window.HyperstitionStudio.*` in offline browser bundles)
- **Schema, XML & URN Authority:** `https://hyperstitionstud.io/schemas/v1/*`, `https://hyperstitionstud.io/ns/*`, and `urn:io:hyperstitionstud:*`
- **Glossary & Encyclopedia Isolation Invariant:** Verified (`0` changes to `taxonomy/glossary-registry.json` or `encyclopedia/encyclopedia-manifest.json`).
- **Document ID:** `PLAN-COMMON-LIBRARY-HYPERSTITIONSTUDIO` (`v1.2.0`)
- **Offline Namespace Authority (Zero `https://` Network Calls):**
- **Python PEP 420 Namespace:** `hyperstitionstud_io.*`
- **JavaScript / Browser Global Namespace:** `@hyperstitionstud.io/*` & `window.HyperstitionStudio.*`
- **URN Schema, XML & Entity Authority (RFC 8141):** `urn:io:hyperstitionstud:schema:v1:*`, `urn:io:hyperstitionstud:ns:kg:1.0`, and `urn:io:hyperstitionstud:<domain>:<type>:<id>`
- **Local Relative Schema Paths:** `./schemas/v1/<name>.schema.json`
- **Dual Deployment Target:**
1. **Scenario A (`file://` Direct Offline In-Browser Application):** Zero HTTP server, zero `fetch()` CORS errors, zero external CDN/font/schema requests.
2. **Scenario B (`http://` Static Web Server Hosting):** Works identically under `python3 -m http.server`, Nginx, Caddy, or LAN self-hosting whether served from the `/workspace` parent directory or as a standalone web root.
- **Artifact & Citation URL Resolution Rule:** **100% Local-Configuration Driven** (`[citations.path_mounts]` in local `workspace.toml`, falling back to verified local paths).
- **Version-Control Operations in Scope:** **0%** (All file integrity and isolation checks use pure Python `hashlib.sha256` and atomic `.tmp -> os.replace()` writes).
---
## 1. Executive Summary & Architectural Problem Statement
## 1. Review of `https://hyperstitionstud.io` URLs: Why They Are Replaced by Offline `urn:io:hyperstitionstud:*` & Relative Paths in `v1.2.0`
Across the peer repositories in `/workspace` (`ingglish-hyperdope-gematria`, `technocapital-singularity-zoology`, `encyclopedia-knowledge-graph`, `hyperdope-ci-build`, `hyperdope-gematria`, `memes`, and `thomas-calculus-tutor`), several foundational subsystems are currently either **duplicated in-file** or **coupled via cross-repository hardcoded script paths**:
In `v1.0.0–v1.1.0`, the domain `hyperstitionstud.io` was formatted as `https://hyperstitionstud.io/...` in two places: JSON Schema `$id`/`$schema` fields and GraphML/GEXF `xmlns:hs` declarations. Reviewing those against a **100% offline, portable in-browser and static-HTTP deployment requirement** exposes three concrete failure modes:
1. **Cross-Repo Subprocess Handoffs for PDF & Tier-List Rendering:**
Both `technocapital-singularity-zoology` and `encyclopedia-knowledge-graph` invoke `/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/build_wire_report_pdf.py` and `generate_aq_tier_list.py` via hardcoded sibling paths.
2. **Cross-Repo Node.js `ingglish` (`CMUdict`) Resolution:**
`technocapital-singularity-zoology/scripts/classify_technocapital_singularity.py` spawns `node --input-type=module` with `--workdir /workspace/ingglish-hyperdope-gematria` to resolve `node_modules/ingglish`.
3. **Duplicated Base-36 `AQ` & Prime Arithmetic:**
`compute_aq()`, prime-sieve/rank lookup (`is_prime`, `prime_rank`), repdigit detection (`37 * k`), and `G1–G6` drift/variance-collapse equations are re-implemented separately in `classify_technocapital_singularity.py`, `build_encyclopedia_knowledge_graph.py`, `ci_provision_ingglish.py`, and `generate_aq_tier_list.py`.
4. **Ad-Hoc JSON Schema & Provenance Identifiers:**
The 8 JSON registries in `technocapital-singularity-zoology` and the exported graph files in `encyclopedia-knowledge-graph` lack a unified `$schema` URI and XML/URN namespace authority.
### Solution Overview
Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering, cryptographic isolation guards, and CI validation into a single, zero-duplication sibling repository:
- **Repository Path:** `/workspace/hyperstitionstudio-core`
- **Python Namespace Package (PEP 420):** `io.hyperstitionstud.*`
- **JS/Browser Namespace:** `@hyperstitionstud.io/*`
- **XML/JSON/URN Namespace:** `https://hyperstitionstud.io/...` & `urn:io:hyperstitionstud:...`
---
## 2. Canonical `hyperstitionstud.io` Namespace Hierarchy
| Layer / Ecosystem | Canonical Namespace Pattern | Concrete Examples |
| Former `https://` Usage (`v1.1.0`) | Why It Hurts 100% Offline & Portable Deployment | `v1.2.0` Portable Replacement (Zero Network Calls) |
| :--- | :--- | :--- |
| **Python 3.10+ (PEP 420 Namespace Package)** | `io.hyperstitionstud.<module>` | `io.hyperstitionstud.ciphers`<br/>`io.hyperstitionstud.phonetics`<br/>`io.hyperstitionstud.publishing`<br/>`io.hyperstitionstud.glossary`<br/>`io.hyperstitionstud.graph`<br/>`io.hyperstitionstud.ci`<br/>`io.hyperstitionstud.audio` |
| **Node.js / ESM Packages** | `@hyperstitionstud.io/<pkg>` | `@hyperstitionstud.io/phonetics-g2p`<br/>`"@hyperstitionstud.io/ciphers-aq"`<br/>`"@hyperstitionstud.io/graph-workbench"` |
| **Offline Browser Global (`file://`)** | `window.HyperstitionStudio.<Module>` | `window.HyperstitionStudio.EncyclopediaGraphData`<br/>`window.HyperstitionStudio.GraphWorkbench`<br/>`window.HyperstitionStudio.Ciphers` |
| **JSON Schema `$schema` & `$id` URIs** | `https://hyperstitionstud.io/schemas/v1/<name>.schema.json` | `https://hyperstitionstud.io/schemas/v1/glossary-registry.schema.json`<br/>`https://hyperstitionstud.io/schemas/v1/encyclopedia-manifest.schema.json`<br/>`https://hyperstitionstud.io/schemas/v1/encyclopedia-graph.schema.json` |
| **GraphML / GEXF XML Namespace** | `xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"` | `<graphml xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0">`<br/>`<data key="hs:g1_variance_collapsed">249.36</data>` |
| **Entity & Node URN Identifiers** | `urn:io:hyperstitionstud:<domain>:<type>:<id>` | `urn:io:hyperstitionstud:zoology:build:S1`<br/>`urn:io:hyperstitionstud:aq:hub:125`<br/>`urn:io:hyperstitionstud:lexicon:spec:blackwell` |
| **CLI Entry Points (`pyproject.toml`)** | `hs-<tool>` | `hs-pdf-build`, `hs-tier-list`, `hs-ci-provision`, `hs-kg-build`, `hs-isolation-check` |
| **`$schema: "https://hyperstitionstud.io/schemas/v1/*.schema.json"`** | IDEs (VS Code, JetBrains), browser JSON inspectors, and schema validators attempt to **HTTP-fetch `https://` `$schema` URLs**. Offline or on an air-gapped LAN, this triggers DNS timeouts or validation warnings. | **Dual Offline Identity:**<br/>• `"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"` (RFC 8141 URN — never fetched over DNS)<br/>• `"$schema": "./schemas/v1/encyclopedia-graph.schema.json"` (relative local file path that resolves both on `file://` and on any `http://` server) |
| **`xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"`** | Conflates a nominal XML namespace with a live `https://` endpoint; some XML/GEXF tools probe `https://` namespace URIs for XSD files. | **`xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0"`**<br/>Explicitly location-independent URN namespace; Gephi, Cytoscape, yEd, and `xml.etree.ElementTree` parse it 100% offline. |
| **External Web Fonts / CDNs (`https://fonts.googleapis.com/...`)** | Stalls browser rendering on `file://` or offline LAN `http://` while waiting for external DNS/TLS handshakes to fail. | **Zero External `<link>` or `<script>` URLs:**<br/>All HTML workbenches and SVG diagrams use pure inline/local CSS and local font stacks (`'DejaVu Sans Mono', 'JetBrains Mono', ui-monospace, monospace`). |
**Rule in `v1.2.0`:** Zero `https://hyperstitionstud.io` URLs appear anywhere in code, schemas, XML exports, HTML files, or citation ledgers. Every `hyperstitionstud.io` namespace identifier uses **reverse-DNS module/URN syntax (`hyperstitionstud_io.*` / `urn:io:hyperstitionstud:*`)** or **relative local paths (`./...`)**.
---
## 3. Repository Layout of `/workspace/hyperstitionstudio-core`
## 2. Canonical `hyperstitionstud.io` Offline Namespace Table (`v1.2.0`)
| Layer / Ecosystem | Offline-First Namespace Pattern | Concrete Examples |
| :--- | :--- | :--- |
| **Python 3.10+ (PEP 420)** | `hyperstitionstud_io.<module>` | `hyperstitionstud_io.{config,ciphers,phonetics,publishing,glossary,graph,ci,audio}` |
| **JavaScript / ESM Modules** | `@hyperstitionstud.io/<pkg>` | `@hyperstitionstud.io/{ciphers-aq,phonetics-g2p,graph-workbench}` |
| **In-Browser Offline Global (`file://` & `http://`)** | `window.HyperstitionStudio.<Module>` | `window.HyperstitionStudio.EncyclopediaGraphData`<br/>`window.HyperstitionStudio.Config`<br/>`window.HyperstitionStudio.GraphWorkbench` |
| **JSON Schema `$id` (Nominal Identity)** | `urn:io:hyperstitionstud:schema:v1:<name>` | `"$id": "urn:io:hyperstitionstud:schema:v1:glossary-registry"`<br/>`"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"` |
| **JSON Schema `$schema` (Local Resolution)** | `./schemas/v1/<name>.schema.json` | `"$schema": "./schemas/v1/encyclopedia-graph.schema.json"` |
| **GraphML / GEXF XML Namespace** | `xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0"` | `<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0">` |
| **Graph Node & Entity URNs** | `urn:io:hyperstitionstud:<domain>:<type>:<id>` | `urn:io:hyperstitionstud:zoology:build:S1`<br/>`urn:io:hyperstitionstud:aq:hub:125` |
---
## 3. Engineering for Both Deployment Scenarios (`Scenario A: file://` & `Scenario B: http://`)
To make the interactive application (`index.html`) 100% portable across both **direct offline browser opens (`file://`)** and **any static HTTP server (`http://`)**, `hyperstitionstud_io.graph` and the operator documentation must explicitly address five browser-level behaviors:
### 3.1 How Data Loading Works in Both Scenarios (`graph-data.js` Synchronous Script vs. `fetch()`)
- **Why `fetch("./encyclopedia-graph.json")` Fails on `file://`:**
Every modern browser (Firefox, Chromium, Brave, Safari) blocks `fetch()` and `XMLHttpRequest` when the page origin is `file://` (`Cross-Origin Request Blocked: CORS request not http`).
- **Portable Dual-Mode Design:**
`build_encyclopedia_knowledge_graph.py` emits **both**:
1. `encyclopedia-graph.json` (for Python, `jq`, or HTTP API consumers), and
2. `graph-data.js` (`window.HyperstitionStudio = window.HyperstitionStudio || {}; window.HyperstitionStudio.EncyclopediaGraphData = {...};`), loaded via `<script src="./graph-data.js"></script>`.
- Because `<script src="./graph-data.js">` is permitted on **both** `file://` and `http://` origins without CORS restrictions, the exact same `index.html` boots instantaneously in both deployment modes with zero network configuration.
### 3.2 How Encyclopedia PDF Links Work in Both Scenarios (`encyclopediaBasePath` Auto-Resolution)
When a user clicks `"Open Encyclopedia Volume PDF"` inside the right-hand Inspector Drawer of `index.html`, the target path depends on how the folder is deployed:
| Deployment Scenario | How the User Opens `index.html` | How `encyclopedia/<div_id>/<slug>.pdf` Resolves |
| :--- | :--- | :--- |
| **Scenario A: Direct Offline `file://` Open** | Opens `file:///.../workspace/encyclopedia-knowledge-graph/index.html` directly in a browser | Relative link `../technocapital-singularity-zoology/encyclopedia/<div_id>/<slug>.pdf` (or `./encyclopedia/<div_id>/<slug>.pdf` if bundled) opens directly in the browser's built-in PDF viewer. |
| **Scenario B1: Static HTTP Server at `/workspace` Root** | Runs `python3 -m http.server 8090 --directory /workspace` and opens `http://127.0.0.1:8090/encyclopedia-knowledge-graph/index.html` | Relative link `../technocapital-singularity-zoology/encyclopedia/<div_id>/<slug>.pdf` resolves to `http://127.0.0.1:8090/technocapital-singularity-zoology/encyclopedia/...`. |
| **Scenario B2: Static HTTP Server Inside `/workspace/encyclopedia-knowledge-graph` Only** | Runs `python3 -m http.server 8090 --directory /workspace/encyclopedia-knowledge-graph` (or drops the folder onto Nginx/Caddy) and opens `http://127.0.0.1:8090/index.html` | **Notice the `../` Boundary:** An HTTP server cannot serve files *above* its `--directory` root (`../` clamps to `/` and 404s unless `encyclopedia/` is reachable inside the root).<br/>**Solution in `hyperstitionstud_io.graph`:** Provide `--bundle-encyclopedia` (copies or symlinks `./encyclopedia/` into the output directory and sets `encyclopediaBasePath = "./encyclopedia"` in `graph-data.js`), OR run `hs-kg serve` which mounts both directories automatically on `http://127.0.0.1:8090`. |
### 3.3 Side-by-Side Documentation Pattern for End Users (Zsh / Jellyfin Style)
Every operator manual and `README.md` produced by `hyperstitionstud_io.publishing` will document **both** deployment modes side by side so the user never has to guess why a path behaves differently under `file://` vs. `http://`:
```text
DEPLOYMENT MODE A — 100% OFFLINE IN-BROWSER APPLICATION (ZERO SERVER, file://)
1. Open index.html directly in any modern browser:
xdg-open /workspace/encyclopedia-knowledge-graph/index.html
or paste into the address bar:
file:///home/m00t/hermes/workspace/encyclopedia-knowledge-graph/index.html
2. All 388 nodes, 1,282 edges, 4 layout modes, search filters, PNG canvas export,
and ../technocapital-singularity-zoology/encyclopedia/*.pdf links work offline.
DEPLOYMENT MODE B — STATIC HTTP SERVER HOSTING (LOCALHOST OR LAN, http://)
Option B1 (Serve parent /workspace so sibling ../technocapital-singularity-zoology/encyclopedia/*.pdf resolves):
python3 -m http.server 8090 --bind 127.0.0.1 --directory /workspace
Open: http://127.0.0.1:8090/encyclopedia-knowledge-graph/index.html
Option B2 (Serve /workspace/encyclopedia-knowledge-graph as a single self-contained web root):
python3 /workspace/encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py --bundle-encyclopedia
python3 -m http.server 8090 --bind 127.0.0.1 --directory /workspace/encyclopedia-knowledge-graph
Open: http://127.0.0.1:8090/index.html
```
---
## 4. Repository Layout of `/workspace/hyperstitionstudio-core` (`v1.2.0`)
```text
/workspace/hyperstitionstudio-core/
├── pyproject.toml # Editable install: pip install -e /workspace/hyperstitionstudio-core
├── package.json # Workspace root for @hyperstitionstud.io/* JS/ESM packages
├── pyproject.toml # Editable install: pip install --no-deps -e /workspace/hyperstitionstudio-core
├── package.json # Local workspace root for @hyperstitionstud.io/* ESM packages (0 network deps)
├── requirements.txt # Pillow>=10.0, reportlab>=4.0, pypdf>=4.0, pdfplumber>=0.10
├── README.md
├── workspace.example.toml # Template for /workspace/workspace.toml
├── schemas/
│ └── v1/ # Canonical JSON Schemas (https://hyperstitionstud.io/schemas/v1/*)
│ └── v1/ # Offline JSON Schemas ($id = urn:io:hyperstitionstud:schema:v1:*)
│ ├── glossary-registry.schema.json
│ ├── encyclopedia-manifest.schema.json
│ ├── singularity-zoology-matrix.schema.json
│ ├── memetic-superclass-registry.schema.json
│ ├── assemblage-builds-tier-list.schema.json
│ ├── quantitative-economic-anchors.schema.json
│ ├── citations-ledger.schema.json
│ ├── citations-ledger.schema.json # Separates canonical `local_path` from local-config `url`
│ └── encyclopedia-graph.schema.json
├── src/
│ └── io/
│ └── hyperstitionstud/ # PEP 420 Namespace Root (no __init__.py at io/, explicit at leaf packages)
│ └── hyperstitionstud/ # PEP 420 Namespace Root
│ ├── config/
│ │ ├── __init__.py
│ │ └── settings.py # Loads workspace.toml, resolves [paths] & [citations.path_mounts]
│ ├── ciphers/
│ │ ├── __init__.py
│ │ ├── base36_aq.py # compute_aq(), digit/spoken/dual quant modes, zero-d-filter guard
@@ -73,36 +120,37 @@ Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering,
│ │ └── vectors_g1_g6.py # G1 variance collapse, G2 cross-gen twins, G3 steps, G4 iso, G5 twin-prime
│ ├── phonetics/
│ │ ├── __init__.py
│ │ ├── ingglish_bridge.py # Self-contained Node G2P bridge + pure-Python CMUdict fallback cache
│ │ └── cmudict_fallback.json # Offline deterministic fallback so zero --workdir coupling is needed
│ │ ├── ingglish_bridge.py # Self-contained G2P translator + pure-Python CMUdict fallback
│ │ └── cmudict_fallback.json # Offline deterministic fallback (removes --workdir coupling)
│ ├── publishing/
│ │ ├── __init__.py
│ │ ├── fonts.py # DejaVu Sans / Mono TrueType resolver & ReportLab family registration
│ │ ├── pdf_compiler.py # Unified build_wire_report_pdf (atomic .tmp.pdf + pypdf verification)
│ │ ├── tier_list_renderer.py # Unified S+..F & ETI 0-100 .pdf/.png card renderer (Pillow + ReportLab)
│ │ ├── fonts.py # Local DejaVu Sans / Mono TrueType resolver (zero remote font fetches)
│ │ ├── pdf_compiler.py # Unified Markdown->PDF compiler (atomic .tmp.pdf + pypdf verification)
│ │ ├── tier_list_renderer.py # Unified S+..F & ETI 0-100 .pdf/.png renderer (Pillow + ReportLab)
│ │ ├── encyclopedia_pdf.py # Multi-division, alphabetized volume PDF compiler
│ │ └── pokedex_compositor.py # Gen IV INFO Pokedex & meme-card compositor with box collision audit
│ ├── glossary/
│ │ ├── __init__.py
│ │ ├── registry.py # GlossaryRegistry CRUD, provenance-keyed filtering (source_type)
│ │ └── isolation_guard.py # Pre/post SHA-256 context manager (`with ReadOnlyIsolationGuard(...):`)
│ │ ├── registry.py # GlossaryRegistry CRUD, source_type provenance filter
│ │ └── isolation_guard.py # Pure-Python hashlib.sha256 ReadOnlyIsolationGuard context manager
│ ├── graph/
│ │ ├── __init__.py
│ │ ├── builder.py # Multi-partite property graph builder & seen_edges deduplicator
│ │ ├── layouts.py # Mode 1 Trophic, Mode 2 Concentric ETI Radar, Mode 3 Funnel, Mode 4 Grid
│ │ ├── exporters.py # JSON, GraphML (xmlns:hs), GEXF 1.3, Obsidian JSON Canvas 1.0
│ │ └── atlas_png.py # 1600x1060 high-res static board renderer with pill-masked arrows
│ │ ├── exporters.py # JSON, GraphML (urn:io:hyperstitionstud:ns:kg:1.0), GEXF 1.3, Canvas 1.0
│ │ ├── atlas_png.py # 1600x1060 high-res static board renderer with pill-masked arrows
│ │ └── bundler.py # Supports --bundle-encyclopedia for single-folder static HTTP deployment
│ ├── ci/
│ │ ├── __init__.py
│ │ ├── gates_hyperdope.py # 4-Gate CI validator (normalize_caps, classify_candidates, db.json)
│ │ └── citation_sources.py # 3-tier provenance verifier (git remote URL -> local full-path fallback)
│ │ ├── citation_sources.py # Pure local-config path_mounts resolver + local_path quote verifier
│ │ └── doctor.py # `hs-doctor`: single-command offline readiness, font, schema & SHA-256 check
│ └── audio/
│ ├── __init__.py
│ └── multi_voice_tts.py # 5-voice edge-tts synthesizer, ffmpeg concat, mutagen duration audit
├── packages-js/
│ ├── ciphers-aq/ # @hyperstitionstud.io/ciphers-aq (shared with hyperdope-gematria)
│ └── graph-workbench/ # @hyperstitionstud.io/graph-workbench (shared with index.html)
│ └── multi_voice_tts.py # 5-voice TTS lecture synthesizer, ffmpeg concat, mutagen duration audit
└── tests/
├── test_offline_portability_no_https.py # Asserts zero outbound https:// schema/font/CDN links in HTML/XML/JSON
├── test_config_and_citation_mounts.py
├── test_ciphers_and_vectors.py
├── test_phonetics_offline.py
├── test_publishing_pdf_and_png.py
@@ -112,79 +160,22 @@ Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering,
---
## 4. Detailed Module Specifications & How Each Eliminates Cross-Repo Coupling
## 5. Four-Phase Implementation Roadmap (`v1.2.0`)
### 4.1 `io.hyperstitionstud.ciphers` — Unified Base-36 `AQ`, Prime & `G1–G6` Vector Engine
- **Replaces duplicated code in:**
- `technocapital-singularity-zoology/scripts/classify_technocapital_singularity.py`
- `encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py`
- `ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/ci_provision_ingglish.py`
- `ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/generate_aq_tier_list.py`
- **Capabilities:**
- `compute_aq(text: str, quant_mode: Literal["off", "spoken", "digit", "dual"] = "off") -> int`
- `prime_rank(n: int) -> int | None` (1-indexed prime rank, e.g., `193 -> 44`, `137 -> 33`, `71 -> 20`)
- `evaluate_bidirectional_lock(eng: str, ing: str) -> BidirectionalLock` (computes all 18 fields of the `G1–G6` schema: `eng_aq`, `ing_aq`, `delta`, `isometric`, `twin_prime_mutation`, `g3_quantized_step`, etc.)
- `assert_zero_d_filter(text: str)` (enforces the strict boundary that Zoology and Knowledge Graph artifacts contain `0` references to the 10-letter `d` decagram).
### Phase 1: Scaffold `/workspace/hyperstitionstudio-core`, `workspace.toml` & Offline `URN:` JSON Schemas
1. Create `/workspace/hyperstitionstudio-core` with `pyproject.toml`, `src/io/hyperstitionstud/config/settings.py`, and `/workspace/workspace.toml`.
2. Author the 8 JSON Schema files under `schemas/v1/*.schema.json` using `"$id": "urn:io:hyperstitionstud:schema:v1:<name>"` (zero `https://` schema URLs).
3. Add `test_offline_portability_no_https.py` to verify that no HTML workbench, SVG diagram, XML export, or JSON schema contains external `https://` font, script, or namespace links.
### 4.2 `io.hyperstitionstud.phonetics` — Self-Contained `Ingglish` (`CMUdict`) Translator
- **Eliminates `--workdir /workspace/ingglish-hyperdope-gematria` coupling:**
- Currently, `classify_technocapital_singularity.py` requires `/workspace/ingglish-hyperdope-gematria/node_modules/ingglish` on disk to translate new English tokens into `Gen 1` Ingglish.
- `io.hyperstitionstud.phonetics.translate_batch(terms)` embeds both:
1. A bundled deterministic `cmudict_fallback.json` + pure-Python ARPAbet-to-Ingglish grapheme mapper for `100%` offline zero-Node operation, and
2. An optional Node `@hyperstitionstud.io/phonetics-g2p` bridge when Node.js is available.
- Result: `technocapital-singularity-zoology` can run `--scan-harvest`, `--revise-anchor`, and `--terms` on any machine even if `ingglish-hyperdope-gematria` is not cloned alongside it.
### Phase 2: Implement `ciphers`, `phonetics` (Offline `CMUdict`), `glossary` & `ci.citation_sources`
1. Extract `hyperstitionstud_io.ciphers` (`compute_aq`, `prime_rank`, `G1–G6` vectors, `assert_zero_d_filter`).
2. Extract `hyperstitionstud_io.phonetics` with bundled `cmudict_fallback.json` for 100% offline `Gen 0 -> Gen 1` translation.
3. Implement `hyperstitionstud_io.glossary.ReadOnlyIsolationGuard` (`hashlib.sha256`) and `hyperstitionstud_io.ci.citation_sources` (pure `[citations.path_mounts]` resolution).
### 4.3 `io.hyperstitionstud.publishing` — Unified ReportLab PDF & Pillow Visual Renderer
- **Eliminates hardcoded cross-repo script calls (`build_wire_report_pdf.py` & `generate_aq_tier_list.py`):**
- `compile_markdown_to_pdf(md_path, pdf_path, title, namespace_footer="hyperstitionstud.io")`:
- Performs atomic writes via `.tmp.pdf` -> `os.replace()`.
- Automatically escapes inline code spans before bold/italic regexes so ReportLab's XML parser never fails on `<` or `>`.
- Automatically verifies page count and extracted character count via `pypdf` and `pdfplumber`.
- `render_tier_list_artifacts(rows, tier_defs, out_md, out_pdf, out_png)`:
- Directly importable by both `ingglish-hyperdope-gematria` (`Option #4` `S+..F` evaluations) and `technocapital-singularity-zoology` (`ETI 0–100` Zoological Assemblage Builds) without spawning cross-repo subprocesses.
### Phase 3: Implement `publishing` & `graph` Modules (With Dual `file://` + `http://` Support)
1. Extract ReportLab/Pillow rendering into `hyperstitionstud_io.publishing` and `hyperstitionstud_io.graph`.
2. Add `--bundle-encyclopedia` support in `hyperstitionstud_io.graph.bundler` so `index.html` resolves PDF links both when opened via `file://` / `/workspace` HTTP root (`../technocapital-singularity-zoology/encyclopedia/...`) and when served as a standalone single-folder HTTP root (`./encyclopedia/...`).
### 4.4 `io.hyperstitionstud.glossary` — Provenance-Keyed Glossary & Cryptographic Isolation Guard
- **Provides reusable glossary infrastructure for all `/workspace` projects:**
- `ReadOnlyIsolationGuard(paths: list[Path])`:
```python
from io.hyperstitionstud.glossary import ReadOnlyIsolationGuard
with ReadOnlyIsolationGuard([glossary_path, encyclopedia_manifest_path]) as guard:
graph = build_graph(upstream_repo)
# Automatically asserts pre_sha256 == post_sha256 on exit and emits guard.audit_receipt()
```
- `ProvenanceFilter`: Filters entries by explicit `source_type` (`"archive_dossier"`, `"news_wire_harvest"`, `"podcast_series"`, `"knowledge_graph_meta"`) rather than fragile substring matching, guaranteeing that excluding in-house media or graph terms never strips extrinsic news-wire or dossier vocabulary.
---
## 5. Project-by-Project Dependency & Migration Matrix
| Workspace Project | Components Replaced by `io.hyperstitionstud.*` | Post-Migration Modularity Status |
| :--- | :--- | :--- |
| **`/workspace/technocapital-singularity-zoology`** | Replaces `--workdir` Node `ingglish` subprocess, subprocess calls to `generate_aq_tier_list.py` and `build_wire_report_pdf.py`, and in-file `compute_aq`/`prime_rank` with `io.hyperstitionstud.{ciphers,phonetics,publishing,glossary,ci,audio}`. | **100% Standalone** (zero runtime or build-time dependency on `ingglish-hyperdope-gematria`). |
| **`/workspace/encyclopedia-knowledge-graph`** | Replaces in-file `compute_aq`, XML/Canvas serializers, SHA-256 check boilerplate, and `build_wire_report_pdf.py` calls with `io.hyperstitionstud.{graph,glossary,publishing}` + `xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"` and `urn:io:hyperstitionstud:*` node URNs. | **100% Standalone Compiler & Workbench** (consumes upstream JSONs validated against `https://hyperstitionstud.io/schemas/v1/*`). |
| **`/workspace/ingglish-hyperdope-gematria`** | Delegates `build_wire_report_pdf.py`, `generate_aq_tier_list.py`, and `ci_provision_ingglish.py` core logic to `io.hyperstitionstud.{publishing,ci,ciphers}` while keeping thin CLI wrappers at existing script paths for backwards compatibility. | **100% Backwards-Compatible** (zero broken CLI paths; zero duplicated rendering code). |
| **`/workspace/hyperdope-ci-build`** | Uses `io.hyperstitionstud.ci.gates_hyperdope` during provisioning while keeping `feat/ingglish-aq-corpus` free of third-party files so upstream PR diffs remain 100% clean. | **100% PR-Clean** (zero extraneous files added to upstream PR branch). |
| **`/workspace/hyperdope-gematria`** | Consumes `@hyperstitionstud.io/ciphers-aq` in `calc/ciphers.js` on branch `feat/ingglish-priority-toggle`. | **Shared JS Cipher Parity** with Python `io.hyperstitionstud.ciphers`. |
| **`/workspace/memes`** | Uses `io.hyperstitionstud.publishing.pokedex_compositor` for Gen IV INFO Pokedex cards and meme templates. | **Unified Card & Font Rendering** with automatic box-collision verification. |
---
## 6. Phased Implementation & Rollout Roadmap (`Phases 1–4`, Non-Breaking)
### Phase 1: Scaffold `/workspace/hyperstitionstudio-core` & Publish `v1` JSON Schemas
1. Initialize `/workspace/hyperstitionstudio-core` (`git init -b main`) with `pyproject.toml` (`name = "hyperstitionstudio-core"`, `version = "1.0.0"`) and `src/io/hyperstitionstud/`.
2. Author the 8 canonical JSON Schema files under `schemas/v1/*.schema.json` with `$id: "https://hyperstitionstud.io/schemas/v1/<name>.schema.json"`.
3. Install in editable mode across the workspace environment (`pip install --no-deps -e /workspace/hyperstitionstudio-core`).
### Phase 2: Extract `ciphers`, `phonetics`, `glossary`, and `ci` Modules + Unit Test Suite
1. Implement `io.hyperstitionstud.ciphers`, `io.hyperstitionstud.phonetics` (with offline `cmudict_fallback.json`), `io.hyperstitionstud.glossary.isolation_guard`, and `io.hyperstitionstud.ci`.
2. Run `pytest /workspace/hyperstitionstudio-core/tests/` to verify 100% numerical parity on all `282` glossary entries, `190` bilingual specimens, and `189` cross-scale `333/666/777` equations.
### Phase 3: Extract `publishing` (`pdf_compiler`, `tier_list_renderer`, `pokedex_compositor`) & `graph`
1. Move the core ReportLab and Pillow rendering engines into `io.hyperstitionstud.publishing` and `io.hyperstitionstud.graph`.
2. Replace the bodies of `/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/build_wire_report_pdf.py` and `generate_aq_tier_list.py` with thin, backwards-compatible CLI shims that import from `io.hyperstitionstud.publishing`.
### Phase 4: Cut Over `technocapital-singularity-zoology` & `encyclopedia-knowledge-graph` and Run 3-Stage Audit
1. Update `classify_technocapital_singularity.py` and `build_encyclopedia_knowledge_graph.py` to import from `io.hyperstitionstud.*`.
2. Execute the full 3-Stage `BUILD -> TEST -> STAGE_COMMIT` pipeline (`ci_provision_ingglish.py --tier 2`, `sources.py verify --evidence`, and `build_encyclopedia_knowledge_graph.py --verify-only`), verifying `all_gates_passed == true` and `0` SHA-256 mutations on `glossary-registry.json` and `encyclopedia-manifest.json`.
### Phase 4: Cut Over Consumer Projects & Verify Offline + HTTP Portability
1. Update `classify_technocapital_singularity.py` and `build_encyclopedia_knowledge_graph.py` to import from `hyperstitionstud_io.*`.
2. Run `hs-doctor`, `pytest`, and `build_encyclopedia_knowledge_graph.py --verify-only`, confirming `all_gates_passed == true`, `0` external `https://` dependencies in HTML/XML/JSON, and `0` SHA-256 mutations on `glossary-registry.json` and `encyclopedia-manifest.json`.
Binary file not shown.
+121 -130
View File
@@ -1,71 +1,118 @@
# Architecture & Migration Plan: Shared Common Library Across All `/workspace` Projects Under the `hyperstitionstud.io` Namespace (`v1.0.0`)
# Architecture & Implementation Plan: Shared Common Library Under the `hyperstitionstud.io` Namespace (`v1.2.0` — 100% Offline `URN:` Namespace & Dual `file://` + `http://` Portability Edition)
- **Document ID:** `PLAN-COMMON-LIBRARY-HYPERSTITIONSTUDIO` (`v1.0.0`)
- **Canonical Domain & Authority:** `hyperstitionstud.io`
- **Python PEP 420 Reverse-DNS Namespace:** `io.hyperstitionstud.*` (installed from `/workspace/hyperstitionstudio-core`)
- **JavaScript / ESM Scope Namespace:** `@hyperstitionstud.io/*` (`window.HyperstitionStudio.*` in offline browser bundles)
- **Schema, XML & URN Authority:** `https://hyperstitionstud.io/schemas/v1/*`, `https://hyperstitionstud.io/ns/*`, and `urn:io:hyperstitionstud:*`
- **Glossary & Encyclopedia Isolation Invariant:** Verified (`0` changes to `taxonomy/glossary-registry.json` or `encyclopedia/encyclopedia-manifest.json`).
- **Document ID:** `PLAN-COMMON-LIBRARY-HYPERSTITIONSTUDIO` (`v1.2.0`)
- **Offline Namespace Authority (Zero `https://` Network Calls):**
- **Python PEP 420 Namespace:** `hyperstitionstud_io.*`
- **JavaScript / Browser Global Namespace:** `@hyperstitionstud.io/*` & `window.HyperstitionStudio.*`
- **URN Schema, XML & Entity Authority (RFC 8141):** `urn:io:hyperstitionstud:schema:v1:*`, `urn:io:hyperstitionstud:ns:kg:1.0`, and `urn:io:hyperstitionstud:<domain>:<type>:<id>`
- **Local Relative Schema Paths:** `./schemas/v1/<name>.schema.json`
- **Dual Deployment Target:**
1. **Scenario A (`file://` Direct Offline In-Browser Application):** Zero HTTP server, zero `fetch()` CORS errors, zero external CDN/font/schema requests.
2. **Scenario B (`http://` Static Web Server Hosting):** Works identically under `python3 -m http.server`, Nginx, Caddy, or LAN self-hosting whether served from the `/workspace` parent directory or as a standalone web root.
- **Artifact & Citation URL Resolution Rule:** **100% Local-Configuration Driven** (`[citations.path_mounts]` in local `workspace.toml`, falling back to verified local paths).
- **Version-Control Operations in Scope:** **0%** (All file integrity and isolation checks use pure Python `hashlib.sha256` and atomic `.tmp -> os.replace()` writes).
---
## 1. Executive Summary & Architectural Problem Statement
## 1. Review of `https://hyperstitionstud.io` URLs: Why They Are Replaced by Offline `urn:io:hyperstitionstud:*` & Relative Paths in `v1.2.0`
Across the peer repositories in `/workspace` (`ingglish-hyperdope-gematria`, `technocapital-singularity-zoology`, `encyclopedia-knowledge-graph`, `hyperdope-ci-build`, `hyperdope-gematria`, `memes`, and `thomas-calculus-tutor`), several foundational subsystems are currently either **duplicated in-file** or **coupled via cross-repository hardcoded script paths**:
In `v1.0.0–v1.1.0`, the domain `hyperstitionstud.io` was formatted as `https://hyperstitionstud.io/...` in two places: JSON Schema `$id`/`$schema` fields and GraphML/GEXF `xmlns:hs` declarations. Reviewing those against a **100% offline, portable in-browser and static-HTTP deployment requirement** exposes three concrete failure modes:
1. **Cross-Repo Subprocess Handoffs for PDF & Tier-List Rendering:**
Both `technocapital-singularity-zoology` and `encyclopedia-knowledge-graph` invoke `/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/build_wire_report_pdf.py` and `generate_aq_tier_list.py` via hardcoded sibling paths.
2. **Cross-Repo Node.js `ingglish` (`CMUdict`) Resolution:**
`technocapital-singularity-zoology/scripts/classify_technocapital_singularity.py` spawns `node --input-type=module` with `--workdir /workspace/ingglish-hyperdope-gematria` to resolve `node_modules/ingglish`.
3. **Duplicated Base-36 `AQ` & Prime Arithmetic:**
`compute_aq()`, prime-sieve/rank lookup (`is_prime`, `prime_rank`), repdigit detection (`37 * k`), and `G1–G6` drift/variance-collapse equations are re-implemented separately in `classify_technocapital_singularity.py`, `build_encyclopedia_knowledge_graph.py`, `ci_provision_ingglish.py`, and `generate_aq_tier_list.py`.
4. **Ad-Hoc JSON Schema & Provenance Identifiers:**
The 8 JSON registries in `technocapital-singularity-zoology` and the exported graph files in `encyclopedia-knowledge-graph` lack a unified `$schema` URI and XML/URN namespace authority.
### Solution Overview
Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering, cryptographic isolation guards, and CI validation into a single, zero-duplication sibling repository:
- **Repository Path:** `/workspace/hyperstitionstudio-core`
- **Python Namespace Package (PEP 420):** `io.hyperstitionstud.*`
- **JS/Browser Namespace:** `@hyperstitionstud.io/*`
- **XML/JSON/URN Namespace:** `https://hyperstitionstud.io/...` & `urn:io:hyperstitionstud:...`
---
## 2. Canonical `hyperstitionstud.io` Namespace Hierarchy
| Layer / Ecosystem | Canonical Namespace Pattern | Concrete Examples |
| Former `https://` Usage (`v1.1.0`) | Why It Hurts 100% Offline & Portable Deployment | `v1.2.0` Portable Replacement (Zero Network Calls) |
| :--- | :--- | :--- |
| **Python 3.10+ (PEP 420 Namespace Package)** | `io.hyperstitionstud.<module>` | `io.hyperstitionstud.ciphers`<br/>`io.hyperstitionstud.phonetics`<br/>`io.hyperstitionstud.publishing`<br/>`io.hyperstitionstud.glossary`<br/>`io.hyperstitionstud.graph`<br/>`io.hyperstitionstud.ci`<br/>`io.hyperstitionstud.audio` |
| **Node.js / ESM Packages** | `@hyperstitionstud.io/<pkg>` | `@hyperstitionstud.io/phonetics-g2p`<br/>`"@hyperstitionstud.io/ciphers-aq"`<br/>`"@hyperstitionstud.io/graph-workbench"` |
| **Offline Browser Global (`file://`)** | `window.HyperstitionStudio.<Module>` | `window.HyperstitionStudio.EncyclopediaGraphData`<br/>`window.HyperstitionStudio.GraphWorkbench`<br/>`window.HyperstitionStudio.Ciphers` |
| **JSON Schema `$schema` & `$id` URIs** | `https://hyperstitionstud.io/schemas/v1/<name>.schema.json` | `https://hyperstitionstud.io/schemas/v1/glossary-registry.schema.json`<br/>`https://hyperstitionstud.io/schemas/v1/encyclopedia-manifest.schema.json`<br/>`https://hyperstitionstud.io/schemas/v1/encyclopedia-graph.schema.json` |
| **GraphML / GEXF XML Namespace** | `xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"` | `<graphml xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0">`<br/>`<data key="hs:g1_variance_collapsed">249.36</data>` |
| **Entity & Node URN Identifiers** | `urn:io:hyperstitionstud:<domain>:<type>:<id>` | `urn:io:hyperstitionstud:zoology:build:S1`<br/>`urn:io:hyperstitionstud:aq:hub:125`<br/>`urn:io:hyperstitionstud:lexicon:spec:blackwell` |
| **CLI Entry Points (`pyproject.toml`)** | `hs-<tool>` | `hs-pdf-build`, `hs-tier-list`, `hs-ci-provision`, `hs-kg-build`, `hs-isolation-check` |
| **`$schema: "https://hyperstitionstud.io/schemas/v1/*.schema.json"`** | IDEs (VS Code, JetBrains), browser JSON inspectors, and schema validators attempt to **HTTP-fetch `https://` `$schema` URLs**. Offline or on an air-gapped LAN, this triggers DNS timeouts or validation warnings. | **Dual Offline Identity:**<br/>• `"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"` (RFC 8141 URN — never fetched over DNS)<br/>• `"$schema": "./schemas/v1/encyclopedia-graph.schema.json"` (relative local file path that resolves both on `file://` and on any `http://` server) |
| **`xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"`** | Conflates a nominal XML namespace with a live `https://` endpoint; some XML/GEXF tools probe `https://` namespace URIs for XSD files. | **`xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0"`**<br/>Explicitly location-independent URN namespace; Gephi, Cytoscape, yEd, and `xml.etree.ElementTree` parse it 100% offline. |
| **External Web Fonts / CDNs (`https://fonts.googleapis.com/...`)** | Stalls browser rendering on `file://` or offline LAN `http://` while waiting for external DNS/TLS handshakes to fail. | **Zero External `<link>` or `<script>` URLs:**<br/>All HTML workbenches and SVG diagrams use pure inline/local CSS and local font stacks (`'DejaVu Sans Mono', 'JetBrains Mono', ui-monospace, monospace`). |
**Rule in `v1.2.0`:** Zero `https://hyperstitionstud.io` URLs appear anywhere in code, schemas, XML exports, HTML files, or citation ledgers. Every `hyperstitionstud.io` namespace identifier uses **reverse-DNS module/URN syntax (`hyperstitionstud_io.*` / `urn:io:hyperstitionstud:*`)** or **relative local paths (`./...`)**.
---
## 3. Repository Layout of `/workspace/hyperstitionstudio-core`
## 2. Canonical `hyperstitionstud.io` Offline Namespace Table (`v1.2.0`)
| Layer / Ecosystem | Offline-First Namespace Pattern | Concrete Examples |
| :--- | :--- | :--- |
| **Python 3.10+ (PEP 420)** | `hyperstitionstud_io.<module>` | `hyperstitionstud_io.{config,ciphers,phonetics,publishing,glossary,graph,ci,audio}` |
| **JavaScript / ESM Modules** | `@hyperstitionstud.io/<pkg>` | `@hyperstitionstud.io/{ciphers-aq,phonetics-g2p,graph-workbench}` |
| **In-Browser Offline Global (`file://` & `http://`)** | `window.HyperstitionStudio.<Module>` | `window.HyperstitionStudio.EncyclopediaGraphData`<br/>`window.HyperstitionStudio.Config`<br/>`window.HyperstitionStudio.GraphWorkbench` |
| **JSON Schema `$id` (Nominal Identity)** | `urn:io:hyperstitionstud:schema:v1:<name>` | `"$id": "urn:io:hyperstitionstud:schema:v1:glossary-registry"`<br/>`"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"` |
| **JSON Schema `$schema` (Local Resolution)** | `./schemas/v1/<name>.schema.json` | `"$schema": "./schemas/v1/encyclopedia-graph.schema.json"` |
| **GraphML / GEXF XML Namespace** | `xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0"` | `<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0">` |
| **Graph Node & Entity URNs** | `urn:io:hyperstitionstud:<domain>:<type>:<id>` | `urn:io:hyperstitionstud:zoology:build:S1`<br/>`urn:io:hyperstitionstud:aq:hub:125` |
---
## 3. Engineering for Both Deployment Scenarios (`Scenario A: file://` & `Scenario B: http://`)
To make the interactive application (`index.html`) 100% portable across both **direct offline browser opens (`file://`)** and **any static HTTP server (`http://`)**, `hyperstitionstud_io.graph` and the operator documentation must explicitly address five browser-level behaviors:
### 3.1 How Data Loading Works in Both Scenarios (`graph-data.js` Synchronous Script vs. `fetch()`)
- **Why `fetch("./encyclopedia-graph.json")` Fails on `file://`:**
Every modern browser (Firefox, Chromium, Brave, Safari) blocks `fetch()` and `XMLHttpRequest` when the page origin is `file://` (`Cross-Origin Request Blocked: CORS request not http`).
- **Portable Dual-Mode Design:**
`build_encyclopedia_knowledge_graph.py` emits **both**:
1. `encyclopedia-graph.json` (for Python, `jq`, or HTTP API consumers), and
2. `graph-data.js` (`window.HyperstitionStudio = window.HyperstitionStudio || {}; window.HyperstitionStudio.EncyclopediaGraphData = {...};`), loaded via `<script src="./graph-data.js"></script>`.
- Because `<script src="./graph-data.js">` is permitted on **both** `file://` and `http://` origins without CORS restrictions, the exact same `index.html` boots instantaneously in both deployment modes with zero network configuration.
### 3.2 How Encyclopedia PDF Links Work in Both Scenarios (`encyclopediaBasePath` Auto-Resolution)
When a user clicks `"Open Encyclopedia Volume PDF"` inside the right-hand Inspector Drawer of `index.html`, the target path depends on how the folder is deployed:
| Deployment Scenario | How the User Opens `index.html` | How `encyclopedia/<div_id>/<slug>.pdf` Resolves |
| :--- | :--- | :--- |
| **Scenario A: Direct Offline `file://` Open** | Opens `file:///.../workspace/encyclopedia-knowledge-graph/index.html` directly in a browser | Relative link `../technocapital-singularity-zoology/encyclopedia/<div_id>/<slug>.pdf` (or `./encyclopedia/<div_id>/<slug>.pdf` if bundled) opens directly in the browser's built-in PDF viewer. |
| **Scenario B1: Static HTTP Server at `/workspace` Root** | Runs `python3 -m http.server 8090 --directory /workspace` and opens `http://127.0.0.1:8090/encyclopedia-knowledge-graph/index.html` | Relative link `../technocapital-singularity-zoology/encyclopedia/<div_id>/<slug>.pdf` resolves to `http://127.0.0.1:8090/technocapital-singularity-zoology/encyclopedia/...`. |
| **Scenario B2: Static HTTP Server Inside `/workspace/encyclopedia-knowledge-graph` Only** | Runs `python3 -m http.server 8090 --directory /workspace/encyclopedia-knowledge-graph` (or drops the folder onto Nginx/Caddy) and opens `http://127.0.0.1:8090/index.html` | **Notice the `../` Boundary:** An HTTP server cannot serve files *above* its `--directory` root (`../` clamps to `/` and 404s unless `encyclopedia/` is reachable inside the root).<br/>**Solution in `hyperstitionstud_io.graph`:** Provide `--bundle-encyclopedia` (copies or symlinks `./encyclopedia/` into the output directory and sets `encyclopediaBasePath = "./encyclopedia"` in `graph-data.js`), OR run `hs-kg serve` which mounts both directories automatically on `http://127.0.0.1:8090`. |
### 3.3 Side-by-Side Documentation Pattern for End Users (Zsh / Jellyfin Style)
Every operator manual and `README.md` produced by `hyperstitionstud_io.publishing` will document **both** deployment modes side by side so the user never has to guess why a path behaves differently under `file://` vs. `http://`:
```text
DEPLOYMENT MODE A — 100% OFFLINE IN-BROWSER APPLICATION (ZERO SERVER, file://)
1. Open index.html directly in any modern browser:
xdg-open /workspace/encyclopedia-knowledge-graph/index.html
or paste into the address bar:
file:///home/m00t/hermes/workspace/encyclopedia-knowledge-graph/index.html
2. All 388 nodes, 1,282 edges, 4 layout modes, search filters, PNG canvas export,
and ../technocapital-singularity-zoology/encyclopedia/*.pdf links work offline.
DEPLOYMENT MODE B — STATIC HTTP SERVER HOSTING (LOCALHOST OR LAN, http://)
Option B1 (Serve parent /workspace so sibling ../technocapital-singularity-zoology/encyclopedia/*.pdf resolves):
python3 -m http.server 8090 --bind 127.0.0.1 --directory /workspace
Open: http://127.0.0.1:8090/encyclopedia-knowledge-graph/index.html
Option B2 (Serve /workspace/encyclopedia-knowledge-graph as a single self-contained web root):
python3 /workspace/encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py --bundle-encyclopedia
python3 -m http.server 8090 --bind 127.0.0.1 --directory /workspace/encyclopedia-knowledge-graph
Open: http://127.0.0.1:8090/index.html
```
---
## 4. Repository Layout of `/workspace/hyperstitionstudio-core` (`v1.2.0`)
```text
/workspace/hyperstitionstudio-core/
├── pyproject.toml # Editable install: pip install -e /workspace/hyperstitionstudio-core
├── package.json # Workspace root for @hyperstitionstud.io/* JS/ESM packages
├── pyproject.toml # Editable install: pip install --no-deps -e /workspace/hyperstitionstudio-core
├── package.json # Local workspace root for @hyperstitionstud.io/* ESM packages (0 network deps)
├── requirements.txt # Pillow>=10.0, reportlab>=4.0, pypdf>=4.0, pdfplumber>=0.10
├── README.md
├── workspace.example.toml # Template for /workspace/workspace.toml
├── schemas/
│ └── v1/ # Canonical JSON Schemas (https://hyperstitionstud.io/schemas/v1/*)
│ └── v1/ # Offline JSON Schemas ($id = urn:io:hyperstitionstud:schema:v1:*)
│ ├── glossary-registry.schema.json
│ ├── encyclopedia-manifest.schema.json
│ ├── singularity-zoology-matrix.schema.json
│ ├── memetic-superclass-registry.schema.json
│ ├── assemblage-builds-tier-list.schema.json
│ ├── quantitative-economic-anchors.schema.json
│ ├── citations-ledger.schema.json
│ ├── citations-ledger.schema.json # Separates canonical `local_path` from local-config `url`
│ └── encyclopedia-graph.schema.json
├── src/
│ └── io/
│ └── hyperstitionstud/ # PEP 420 Namespace Root (no __init__.py at io/, explicit at leaf packages)
│ └── hyperstitionstud/ # PEP 420 Namespace Root
│ ├── config/
│ │ ├── __init__.py
│ │ └── settings.py # Loads workspace.toml, resolves [paths] & [citations.path_mounts]
│ ├── ciphers/
│ │ ├── __init__.py
│ │ ├── base36_aq.py # compute_aq(), digit/spoken/dual quant modes, zero-d-filter guard
@@ -73,36 +120,37 @@ Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering,
│ │ └── vectors_g1_g6.py # G1 variance collapse, G2 cross-gen twins, G3 steps, G4 iso, G5 twin-prime
│ ├── phonetics/
│ │ ├── __init__.py
│ │ ├── ingglish_bridge.py # Self-contained Node G2P bridge + pure-Python CMUdict fallback cache
│ │ └── cmudict_fallback.json # Offline deterministic fallback so zero --workdir coupling is needed
│ │ ├── ingglish_bridge.py # Self-contained G2P translator + pure-Python CMUdict fallback
│ │ └── cmudict_fallback.json # Offline deterministic fallback (removes --workdir coupling)
│ ├── publishing/
│ │ ├── __init__.py
│ │ ├── fonts.py # DejaVu Sans / Mono TrueType resolver & ReportLab family registration
│ │ ├── pdf_compiler.py # Unified build_wire_report_pdf (atomic .tmp.pdf + pypdf verification)
│ │ ├── tier_list_renderer.py # Unified S+..F & ETI 0-100 .pdf/.png card renderer (Pillow + ReportLab)
│ │ ├── fonts.py # Local DejaVu Sans / Mono TrueType resolver (zero remote font fetches)
│ │ ├── pdf_compiler.py # Unified Markdown->PDF compiler (atomic .tmp.pdf + pypdf verification)
│ │ ├── tier_list_renderer.py # Unified S+..F & ETI 0-100 .pdf/.png renderer (Pillow + ReportLab)
│ │ ├── encyclopedia_pdf.py # Multi-division, alphabetized volume PDF compiler
│ │ └── pokedex_compositor.py # Gen IV INFO Pokedex & meme-card compositor with box collision audit
│ ├── glossary/
│ │ ├── __init__.py
│ │ ├── registry.py # GlossaryRegistry CRUD, provenance-keyed filtering (source_type)
│ │ └── isolation_guard.py # Pre/post SHA-256 context manager (`with ReadOnlyIsolationGuard(...):`)
│ │ ├── registry.py # GlossaryRegistry CRUD, source_type provenance filter
│ │ └── isolation_guard.py # Pure-Python hashlib.sha256 ReadOnlyIsolationGuard context manager
│ ├── graph/
│ │ ├── __init__.py
│ │ ├── builder.py # Multi-partite property graph builder & seen_edges deduplicator
│ │ ├── layouts.py # Mode 1 Trophic, Mode 2 Concentric ETI Radar, Mode 3 Funnel, Mode 4 Grid
│ │ ├── exporters.py # JSON, GraphML (xmlns:hs), GEXF 1.3, Obsidian JSON Canvas 1.0
│ │ └── atlas_png.py # 1600x1060 high-res static board renderer with pill-masked arrows
│ │ ├── exporters.py # JSON, GraphML (urn:io:hyperstitionstud:ns:kg:1.0), GEXF 1.3, Canvas 1.0
│ │ ├── atlas_png.py # 1600x1060 high-res static board renderer with pill-masked arrows
│ │ └── bundler.py # Supports --bundle-encyclopedia for single-folder static HTTP deployment
│ ├── ci/
│ │ ├── __init__.py
│ │ ├── gates_hyperdope.py # 4-Gate CI validator (normalize_caps, classify_candidates, db.json)
│ │ └── citation_sources.py # 3-tier provenance verifier (git remote URL -> local full-path fallback)
│ │ ├── citation_sources.py # Pure local-config path_mounts resolver + local_path quote verifier
│ │ └── doctor.py # `hs-doctor`: single-command offline readiness, font, schema & SHA-256 check
│ └── audio/
│ ├── __init__.py
│ └── multi_voice_tts.py # 5-voice edge-tts synthesizer, ffmpeg concat, mutagen duration audit
├── packages-js/
│ ├── ciphers-aq/ # @hyperstitionstud.io/ciphers-aq (shared with hyperdope-gematria)
│ └── graph-workbench/ # @hyperstitionstud.io/graph-workbench (shared with index.html)
│ └── multi_voice_tts.py # 5-voice TTS lecture synthesizer, ffmpeg concat, mutagen duration audit
└── tests/
├── test_offline_portability_no_https.py # Asserts zero outbound https:// schema/font/CDN links in HTML/XML/JSON
├── test_config_and_citation_mounts.py
├── test_ciphers_and_vectors.py
├── test_phonetics_offline.py
├── test_publishing_pdf_and_png.py
@@ -112,79 +160,22 @@ Extract all shared computation, phonetic translation, PDF/PNG/Canvas rendering,
---
## 4. Detailed Module Specifications & How Each Eliminates Cross-Repo Coupling
## 5. Four-Phase Implementation Roadmap (`v1.2.0`)
### 4.1 `io.hyperstitionstud.ciphers` — Unified Base-36 `AQ`, Prime & `G1–G6` Vector Engine
- **Replaces duplicated code in:**
- `technocapital-singularity-zoology/scripts/classify_technocapital_singularity.py`
- `encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py`
- `ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/ci_provision_ingglish.py`
- `ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/generate_aq_tier_list.py`
- **Capabilities:**
- `compute_aq(text: str, quant_mode: Literal["off", "spoken", "digit", "dual"] = "off") -> int`
- `prime_rank(n: int) -> int | None` (1-indexed prime rank, e.g., `193 -> 44`, `137 -> 33`, `71 -> 20`)
- `evaluate_bidirectional_lock(eng: str, ing: str) -> BidirectionalLock` (computes all 18 fields of the `G1–G6` schema: `eng_aq`, `ing_aq`, `delta`, `isometric`, `twin_prime_mutation`, `g3_quantized_step`, etc.)
- `assert_zero_d_filter(text: str)` (enforces the strict boundary that Zoology and Knowledge Graph artifacts contain `0` references to the 10-letter `d` decagram).
### Phase 1: Scaffold `/workspace/hyperstitionstudio-core`, `workspace.toml` & Offline `URN:` JSON Schemas
1. Create `/workspace/hyperstitionstudio-core` with `pyproject.toml`, `src/io/hyperstitionstud/config/settings.py`, and `/workspace/workspace.toml`.
2. Author the 8 JSON Schema files under `schemas/v1/*.schema.json` using `"$id": "urn:io:hyperstitionstud:schema:v1:<name>"` (zero `https://` schema URLs).
3. Add `test_offline_portability_no_https.py` to verify that no HTML workbench, SVG diagram, XML export, or JSON schema contains external `https://` font, script, or namespace links.
### 4.2 `io.hyperstitionstud.phonetics` — Self-Contained `Ingglish` (`CMUdict`) Translator
- **Eliminates `--workdir /workspace/ingglish-hyperdope-gematria` coupling:**
- Currently, `classify_technocapital_singularity.py` requires `/workspace/ingglish-hyperdope-gematria/node_modules/ingglish` on disk to translate new English tokens into `Gen 1` Ingglish.
- `io.hyperstitionstud.phonetics.translate_batch(terms)` embeds both:
1. A bundled deterministic `cmudict_fallback.json` + pure-Python ARPAbet-to-Ingglish grapheme mapper for `100%` offline zero-Node operation, and
2. An optional Node `@hyperstitionstud.io/phonetics-g2p` bridge when Node.js is available.
- Result: `technocapital-singularity-zoology` can run `--scan-harvest`, `--revise-anchor`, and `--terms` on any machine even if `ingglish-hyperdope-gematria` is not cloned alongside it.
### Phase 2: Implement `ciphers`, `phonetics` (Offline `CMUdict`), `glossary` & `ci.citation_sources`
1. Extract `hyperstitionstud_io.ciphers` (`compute_aq`, `prime_rank`, `G1–G6` vectors, `assert_zero_d_filter`).
2. Extract `hyperstitionstud_io.phonetics` with bundled `cmudict_fallback.json` for 100% offline `Gen 0 -> Gen 1` translation.
3. Implement `hyperstitionstud_io.glossary.ReadOnlyIsolationGuard` (`hashlib.sha256`) and `hyperstitionstud_io.ci.citation_sources` (pure `[citations.path_mounts]` resolution).
### 4.3 `io.hyperstitionstud.publishing` — Unified ReportLab PDF & Pillow Visual Renderer
- **Eliminates hardcoded cross-repo script calls (`build_wire_report_pdf.py` & `generate_aq_tier_list.py`):**
- `compile_markdown_to_pdf(md_path, pdf_path, title, namespace_footer="hyperstitionstud.io")`:
- Performs atomic writes via `.tmp.pdf` -> `os.replace()`.
- Automatically escapes inline code spans before bold/italic regexes so ReportLab's XML parser never fails on `<` or `>`.
- Automatically verifies page count and extracted character count via `pypdf` and `pdfplumber`.
- `render_tier_list_artifacts(rows, tier_defs, out_md, out_pdf, out_png)`:
- Directly importable by both `ingglish-hyperdope-gematria` (`Option #4` `S+..F` evaluations) and `technocapital-singularity-zoology` (`ETI 0–100` Zoological Assemblage Builds) without spawning cross-repo subprocesses.
### Phase 3: Implement `publishing` & `graph` Modules (With Dual `file://` + `http://` Support)
1. Extract ReportLab/Pillow rendering into `hyperstitionstud_io.publishing` and `hyperstitionstud_io.graph`.
2. Add `--bundle-encyclopedia` support in `hyperstitionstud_io.graph.bundler` so `index.html` resolves PDF links both when opened via `file://` / `/workspace` HTTP root (`../technocapital-singularity-zoology/encyclopedia/...`) and when served as a standalone single-folder HTTP root (`./encyclopedia/...`).
### 4.4 `io.hyperstitionstud.glossary` — Provenance-Keyed Glossary & Cryptographic Isolation Guard
- **Provides reusable glossary infrastructure for all `/workspace` projects:**
- `ReadOnlyIsolationGuard(paths: list[Path])`:
```python
from io.hyperstitionstud.glossary import ReadOnlyIsolationGuard
with ReadOnlyIsolationGuard([glossary_path, encyclopedia_manifest_path]) as guard:
graph = build_graph(upstream_repo)
# Automatically asserts pre_sha256 == post_sha256 on exit and emits guard.audit_receipt()
```
- `ProvenanceFilter`: Filters entries by explicit `source_type` (`"archive_dossier"`, `"news_wire_harvest"`, `"podcast_series"`, `"knowledge_graph_meta"`) rather than fragile substring matching, guaranteeing that excluding in-house media or graph terms never strips extrinsic news-wire or dossier vocabulary.
---
## 5. Project-by-Project Dependency & Migration Matrix
| Workspace Project | Components Replaced by `io.hyperstitionstud.*` | Post-Migration Modularity Status |
| :--- | :--- | :--- |
| **`/workspace/technocapital-singularity-zoology`** | Replaces `--workdir` Node `ingglish` subprocess, subprocess calls to `generate_aq_tier_list.py` and `build_wire_report_pdf.py`, and in-file `compute_aq`/`prime_rank` with `io.hyperstitionstud.{ciphers,phonetics,publishing,glossary,ci,audio}`. | **100% Standalone** (zero runtime or build-time dependency on `ingglish-hyperdope-gematria`). |
| **`/workspace/encyclopedia-knowledge-graph`** | Replaces in-file `compute_aq`, XML/Canvas serializers, SHA-256 check boilerplate, and `build_wire_report_pdf.py` calls with `io.hyperstitionstud.{graph,glossary,publishing}` + `xmlns:hs="https://hyperstitionstud.io/ns/kg/1.0"` and `urn:io:hyperstitionstud:*` node URNs. | **100% Standalone Compiler & Workbench** (consumes upstream JSONs validated against `https://hyperstitionstud.io/schemas/v1/*`). |
| **`/workspace/ingglish-hyperdope-gematria`** | Delegates `build_wire_report_pdf.py`, `generate_aq_tier_list.py`, and `ci_provision_ingglish.py` core logic to `io.hyperstitionstud.{publishing,ci,ciphers}` while keeping thin CLI wrappers at existing script paths for backwards compatibility. | **100% Backwards-Compatible** (zero broken CLI paths; zero duplicated rendering code). |
| **`/workspace/hyperdope-ci-build`** | Uses `io.hyperstitionstud.ci.gates_hyperdope` during provisioning while keeping `feat/ingglish-aq-corpus` free of third-party files so upstream PR diffs remain 100% clean. | **100% PR-Clean** (zero extraneous files added to upstream PR branch). |
| **`/workspace/hyperdope-gematria`** | Consumes `@hyperstitionstud.io/ciphers-aq` in `calc/ciphers.js` on branch `feat/ingglish-priority-toggle`. | **Shared JS Cipher Parity** with Python `io.hyperstitionstud.ciphers`. |
| **`/workspace/memes`** | Uses `io.hyperstitionstud.publishing.pokedex_compositor` for Gen IV INFO Pokedex cards and meme templates. | **Unified Card & Font Rendering** with automatic box-collision verification. |
---
## 6. Phased Implementation & Rollout Roadmap (`Phases 1–4`, Non-Breaking)
### Phase 1: Scaffold `/workspace/hyperstitionstudio-core` & Publish `v1` JSON Schemas
1. Initialize `/workspace/hyperstitionstudio-core` (`git init -b main`) with `pyproject.toml` (`name = "hyperstitionstudio-core"`, `version = "1.0.0"`) and `src/io/hyperstitionstud/`.
2. Author the 8 canonical JSON Schema files under `schemas/v1/*.schema.json` with `$id: "https://hyperstitionstud.io/schemas/v1/<name>.schema.json"`.
3. Install in editable mode across the workspace environment (`pip install --no-deps -e /workspace/hyperstitionstudio-core`).
### Phase 2: Extract `ciphers`, `phonetics`, `glossary`, and `ci` Modules + Unit Test Suite
1. Implement `io.hyperstitionstud.ciphers`, `io.hyperstitionstud.phonetics` (with offline `cmudict_fallback.json`), `io.hyperstitionstud.glossary.isolation_guard`, and `io.hyperstitionstud.ci`.
2. Run `pytest /workspace/hyperstitionstudio-core/tests/` to verify 100% numerical parity on all `282` glossary entries, `190` bilingual specimens, and `189` cross-scale `333/666/777` equations.
### Phase 3: Extract `publishing` (`pdf_compiler`, `tier_list_renderer`, `pokedex_compositor`) & `graph`
1. Move the core ReportLab and Pillow rendering engines into `io.hyperstitionstud.publishing` and `io.hyperstitionstud.graph`.
2. Replace the bodies of `/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/build_wire_report_pdf.py` and `generate_aq_tier_list.py` with thin, backwards-compatible CLI shims that import from `io.hyperstitionstud.publishing`.
### Phase 4: Cut Over `technocapital-singularity-zoology` & `encyclopedia-knowledge-graph` and Run 3-Stage Audit
1. Update `classify_technocapital_singularity.py` and `build_encyclopedia_knowledge_graph.py` to import from `io.hyperstitionstud.*`.
2. Execute the full 3-Stage `BUILD -> TEST -> STAGE_COMMIT` pipeline (`ci_provision_ingglish.py --tier 2`, `sources.py verify --evidence`, and `build_encyclopedia_knowledge_graph.py --verify-only`), verifying `all_gates_passed == true` and `0` SHA-256 mutations on `glossary-registry.json` and `encyclopedia-manifest.json`.
### Phase 4: Cut Over Consumer Projects & Verify Offline + HTTP Portability
1. Update `classify_technocapital_singularity.py` and `build_encyclopedia_knowledge_graph.py` to import from `hyperstitionstud_io.*`.
2. Run `hs-doctor`, `pytest`, and `build_encyclopedia_knowledge_graph.py --verify-only`, confirming `all_gates_passed == true`, `0` external `https://` dependencies in HTML/XML/JSON, and `0` SHA-256 mutations on `glossary-registry.json` and `encyclopedia-manifest.json`.
Binary file not shown.
@@ -4,7 +4,6 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cross-Repository Dependency Graph &amp; Auditable Build-&gt;Test-&gt;Stage_Commit Pipeline</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
@@ -12,7 +11,7 @@
box-sizing: border-box;
}
body {
font-family: 'JetBrains Mono', monospace;
font-family: 'DejaVu Sans Mono', 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
background: #020617;
min-height: 100vh;
padding: 2rem;
+30 -9
View File
@@ -30,11 +30,25 @@ import argparse
import json
import math
import subprocess
import sys
from pathlib import Path
from typing import Any
_CORE_SRC = Path("/workspace/hyperstitionstudio-core/src")
if _CORE_SRC.is_dir() and str(_CORE_SRC) not in sys.path:
sys.path.insert(0, str(_CORE_SRC))
try:
from hyperstitionstud_io.ciphers import compute_aq as _hs_compute_aq
from hyperstitionstud_io.phonetics import translate_batch as _hs_translate_batch
except ImportError:
_hs_compute_aq = None
_hs_translate_batch = None
def compute_aq(text: str) -> int:
if _hs_compute_aq is not None:
return _hs_compute_aq(text, quant_mode="digit")
total = 0
for ch in text.lower():
if "0" <= ch <= "9":
@@ -163,6 +177,8 @@ PREP_POOL = [
def batch_translate(terms: list[str], workdir: str = "/workspace/ingglish-hyperdope-gematria") -> dict[str, str]:
if not terms:
return {}
if _hs_translate_batch is not None and not (Path(workdir) / "node_modules" / "ingglish").is_dir():
return _hs_translate_batch(terms, workdir=workdir)
node_script = """
import { translate } from 'ingglish';
import fs from 'fs';
@@ -174,15 +190,20 @@ for (const t of items) {
}
process.stdout.write(JSON.stringify(out));
"""
proc = subprocess.run(
["node", "--input-type=module", "-e", node_script],
input=json.dumps(terms),
text=True,
cwd=workdir,
capture_output=True,
check=True,
)
return json.loads(proc.stdout)
try:
proc = subprocess.run(
["node", "--input-type=module", "-e", node_script],
input=json.dumps(terms),
text=True,
cwd=workdir,
capture_output=True,
check=True,
)
return json.loads(proc.stdout)
except Exception:
if _hs_translate_batch is not None:
return _hs_translate_batch(terms, workdir=workdir)
raise
def classify_term(eng: str, ing: str, eng_aq: int, ing_aq: int) -> list[str]:
+59 -335
View File
@@ -1,347 +1,71 @@
#!/usr/bin/env python3
"""Citation ledger for grounded answers and documents (with local full-path fallback support)."""
"""
Citation ledger for grounded answers and documents.
Delegates to `hyperstitionstud_io.ci.citation_sources` in `/workspace/hyperstitionstudio-core`,
preserving the full 11-function Python API and all 7 CLI subcommands (`reset`, `add`, `ingest`,
`quote`, `list`, `render`, `verify`) with pure local-configuration URL resolution (`workspace.toml`).
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Iterable
SCHEMA_VERSION = 1
_CORE_SRC = Path("/workspace/hyperstitionstudio-core/src")
if _CORE_SRC.is_dir() and str(_CORE_SRC) not in sys.path:
sys.path.insert(0, str(_CORE_SRC))
_CITE_RE = re.compile(r"\[(\d{1,4})\](?![(:])")
_SOURCES_HEADER_RE = re.compile(r"^\s*(?:#{1,6}\s*)?(?:\*\*)?sources:?(?:\*\*)?\s*$", re.IGNORECASE)
_SOURCE_LINE_RE = re.compile(r"^\s*\[(\d{1,4})\]\s*[-–:]?\s*(\S+)")
_URL_IN_TEXT_RE = re.compile(r"(?:https?://|/)[^\s\"'<>)\]}]+")
_FENCE_RE = re.compile(r"^\s*(?:```|~~~)")
_UNVERIFIED_RE = re.compile(r"\[unverified\]", re.IGNORECASE)
_MD_LINK_RE = re.compile(r"\[([^\]]*)\]\((?:[^()\s]|\([^()]*\))*\)")
_MD_NOISE_RE = re.compile(r"[*_`~]|\\(?=[^\w\s])")
def resolve_repo_url_or_path(local_full_path: str, prefer_local_if_no_remote: bool = True) -> str:
"""
Resolve a local file path to its hosted Git repository HTTPS URL when the owning
repository has a configured git remote, or fall back to the local filesystem full path
when no git remote URL is available.
"""
p = Path(local_full_path).resolve()
cur = p if p.is_dir() else p.parent
repo_root = None
while cur != cur.parent:
if (cur / ".git").exists():
repo_root = cur
break
cur = cur.parent
if repo_root is None:
return str(p)
res = subprocess.run(
["git", "-C", str(repo_root), "remote", "get-url", "origin"],
capture_output=True,
text=True,
)
remote = res.stdout.strip() if res.returncode == 0 else ""
if not remote:
return str(p)
br = subprocess.run(
["git", "-C", str(repo_root), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
)
branch = br.stdout.strip() if br.returncode == 0 and br.stdout.strip() else "main"
rel = p.relative_to(repo_root).as_posix()
if remote.startswith("ssh://git@git.libre.audio:2222/"):
slug = remote.split("ssh://git@git.libre.audio:2222/", 1)[1]
if slug.endswith(".git"):
slug = slug[:-4]
return f"https://git.libre.audio/{slug}/src/branch/{branch}/{rel}"
if "github.com/" in remote:
slug = remote.split("github.com/", 1)[1]
if slug.endswith(".git"):
slug = slug[:-4]
return f"https://github.com/{slug}/blob/{branch}/{rel}"
return str(p)
def normalize_url(url: str) -> str:
u = (url or "").strip()
if "#" in u and u.startswith(("http://", "https://")):
u = u.split("#", 1)[0]
stripped = u.rstrip("/")
return stripped or u
def load_ledger(path: Path) -> dict[str, Any]:
if not path.exists():
return {"version": SCHEMA_VERSION, "sources": []}
return json.loads(path.read_text(encoding="utf-8"))
def save_ledger(path: Path, data: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + f".tmp{os.getpid()}")
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
os.replace(tmp, path)
def add_sources(
path: Path,
urls: Iterable[str],
title: str | None = None,
accessed: str | None = None,
) -> list[dict[str, Any]]:
urls = [u for u in (str(u).strip() for u in urls) if u]
if not urls:
return []
data = load_ledger(path)
sources = data["sources"]
index = {s["url"]: s for s in sources}
out: list[dict[str, Any]] = []
changed = False
for raw in urls:
key = normalize_url(raw)
existing = index.get(key)
if existing is not None:
if title and not existing.get("title"):
existing["title"] = title
changed = True
out.append(existing)
continue
entry = {
"id": len(sources) + 1,
"url": key,
"title": (title or "").strip(),
"accessed": accessed or time.strftime("%Y-%m-%d"),
}
sources.append(entry)
index[key] = entry
out.append(entry)
changed = True
if changed:
save_ledger(path, data)
return out
def _normalize_ws(text: str) -> str:
return " ".join((text or "").split())
def _match_key(text: str) -> str:
collapsed = _MD_LINK_RE.sub(r"\1", text or "")
return _normalize_ws(_MD_NOISE_RE.sub("", collapsed)).casefold()
def quote_in_evidence(quote: str, evidence: str) -> bool:
q = _match_key(quote)
return bool(q) and q in _match_key(evidence)
def attach_quote(path: Path, source_id: int, quote: str, evidence: str) -> dict[str, Any]:
quote = (quote or "").strip()
if len(_normalize_ws(quote).split()) < 3:
raise SystemExit("error: quote too short — use at least 3 words of verbatim text")
if not quote_in_evidence(quote, evidence):
raise SystemExit(f"error: quote not found verbatim in the evidence text: {quote[:80]}")
data = load_ledger(path)
entry = next((s for s in data["sources"] if s["id"] == source_id), None)
if entry is None:
raise SystemExit(f"error: no source [{source_id}] in the ledger")
quotes = entry.setdefault("quotes", [])
norm = _match_key(quote)
if not any(_match_key(q.get("text", "")) == norm for q in quotes):
quotes.append({"text": quote, "added": time.strftime("%Y-%m-%d")})
save_ledger(path, data)
return entry
def render_sources(
sources: list[dict[str, Any]],
style: str = "markdown",
only: set[int] | None = None,
) -> str:
picked = [s for s in sources if only is None or s["id"] in only]
picked.sort(key=lambda s: s["id"])
if not picked:
return ""
lines: list[str] = ["## Sources", ""]
for s in picked:
title = s.get("title")
suffix = f" — {title}" if title else ""
lines.append(f"[{s['id']}] `{s['url']}`{suffix}")
if style == "evidence":
for q in s.get("quotes", []):
lines.append(f' - Verbatim Lock: `"{q.get("text", "")}"`')
return "\n".join(lines)
def _split_draft(text: str) -> tuple[str, dict[int, str]]:
lines = text.splitlines()
header_idx = -1
for i, line in enumerate(lines):
if _SOURCES_HEADER_RE.match(line):
header_idx = i
listed: dict[int, str] = {}
if header_idx >= 0:
for line in lines[header_idx + 1:]:
m = _SOURCE_LINE_RE.match(line)
if m:
raw_target = m.group(2).strip("`")
listed[int(m.group(1))] = raw_target
body_lines = lines[:header_idx]
else:
body_lines = lines
prose: list[str] = []
in_fence = False
for line in body_lines:
if _FENCE_RE.match(line):
in_fence = not in_fence
continue
if not in_fence:
prose.append(line)
return "\n".join(prose), listed
def _strip_sources_block(text: str) -> str:
lines = text.splitlines()
header_idx = -1
for i, line in enumerate(lines):
if _SOURCES_HEADER_RE.match(line):
header_idx = i
if header_idx < 0:
return text
return "\n".join(lines[:header_idx])
def _sentences(prose: str) -> list[str]:
out: list[str] = []
for line in prose.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#") or stripped.startswith("|") or stripped == "---":
continue
if stripped.startswith(">"):
stripped = stripped.lstrip("> ").strip()
for part in re.split(r"(?<=[.!?])\s+", stripped):
part = part.strip()
if len(part.split()) >= 4:
out.append(part)
return out
def verify_draft(
draft_path: Path,
sources: list[dict[str, Any]],
strict: bool = False,
min_coverage: float | None = None,
require_evidence: bool = False,
) -> tuple[int, list[str], list[str]]:
text = draft_path.read_text(encoding="utf-8")
prose, listed = _split_draft(text)
by_id = {s["id"]: s for s in sources}
errors: list[str] = []
warnings: list[str] = []
# Collect citations from both prose and markdown tables
body_without_sources = _strip_sources_block(text)
cited = [int(m) for m in _CITE_RE.findall(body_without_sources)]
cited_set = set(cited)
unknown = sorted(i for i in cited_set if i not in by_id)
if unknown:
errors.append("citations not in the ledger: " + ", ".join(f"[{i}]" for i in unknown))
if cited_set and not listed:
errors.append("draft cites sources but has no `Sources` block")
missing_from_block = sorted(cited_set - set(listed)) if listed else []
if missing_from_block:
errors.append("cited but absent from the Sources block: " + ", ".join(f"[{i}]" for i in missing_from_block))
for sid, url in sorted(listed.items()):
entry = by_id.get(sid)
if entry is None:
errors.append(f"Sources block lists [{sid}], which is not in the ledger")
continue
if normalize_url(url) != entry["url"]:
errors.append(f"Sources block URL for [{sid}] does not match ledger ({url} vs {entry['url']})")
if require_evidence:
unevidenced = sorted(i for i in cited_set if i in by_id and not by_id[i].get("quotes"))
if unevidenced:
errors.append("cited sources carry no verbatim evidence quote: " + ", ".join(f"[{i}]" for i in unevidenced))
sentences = _sentences(prose)
covered = [s for s in sentences if _CITE_RE.search(s) or _UNVERIFIED_RE.search(s)]
coverage = (len(covered) / len(sentences)) if sentences else 0.0
if min_coverage is not None and sentences and coverage < min_coverage:
errors.append(f"citation coverage {coverage:.0%} is below {min_coverage:.0%}")
quoted = sum(1 for s in sources if s.get("quotes"))
warnings.insert(
0,
f"stats: {len(sentences)} prose sentences, {len(covered)} cited ({coverage:.0%}); "
f"{len(cited_set)} distinct sources cited, {len(by_id)} in ledger ({quoted} with evidence quotes)",
)
code = 1 if errors else 0
return code, errors, warnings
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="sources.py")
parser.add_argument("--ledger", required=True)
sub = parser.add_subparsers(dest="cmd", required=True)
sub.add_parser("reset")
p_render = sub.add_parser("render")
p_render.add_argument("--style", default="evidence", choices=["markdown", "evidence"])
p_render.add_argument("--replace-in", required=True)
p_ver = sub.add_parser("verify")
p_ver.add_argument("draft")
p_ver.add_argument("--min-coverage", type=float, default=None)
p_ver.add_argument("--evidence", action="store_true")
args = parser.parse_args(argv)
path = Path(args.ledger)
if args.cmd == "reset":
save_ledger(path, {"version": SCHEMA_VERSION, "sources": []})
return 0
data = load_ledger(path)
sources = sorted(data["sources"], key=lambda s: s["id"])
if args.cmd == "render":
target = Path(args.replace_in)
body = _strip_sources_block(target.read_text(encoding="utf-8"))
cited = {int(m) for m in _CITE_RE.findall(body)}
block = render_sources(sources, style=args.style, only=cited)
target.write_text(body.rstrip("\n") + "\n\n---\n\n" + block + "\n", encoding="utf-8")
print(f"Rendered {len(cited)} cited sources into {target}")
return 0
if args.cmd == "verify":
code, errors, warnings = verify_draft(
Path(args.draft),
sources,
min_coverage=args.min_coverage,
require_evidence=args.evidence,
)
for w in warnings:
print(w)
for e in errors:
print(f"FAIL: {e}", file=sys.stderr)
print("citations OK" if code == 0 else "verification failed")
return code
return 0
from hyperstitionstud_io.ci.citation_sources import ( # noqa: E402
SCHEMA_VERSION,
_CITE_RE,
_FENCE_RE,
_LedgerLock,
_MD_LINK_RE,
_MD_NOISE_RE,
_SOURCES_HEADER_RE,
_SOURCE_LINE_RE,
_UNVERIFIED_RE,
_URL_IN_TEXT_RE,
add_sources,
attach_quote,
load_ledger,
main,
normalize_url,
quote_in_evidence,
render_sources,
resolve_citation_target,
resolve_ledger_path,
resolve_repo_url_or_path,
save_ledger,
urls_from_json,
verify_draft,
)
__all__ = [
"SCHEMA_VERSION",
"_CITE_RE",
"_FENCE_RE",
"_LedgerLock",
"_MD_LINK_RE",
"_MD_NOISE_RE",
"_SOURCES_HEADER_RE",
"_SOURCE_LINE_RE",
"_UNVERIFIED_RE",
"_URL_IN_TEXT_RE",
"add_sources",
"attach_quote",
"load_ledger",
"main",
"normalize_url",
"quote_in_evidence",
"render_sources",
"resolve_citation_target",
"resolve_ledger_path",
"resolve_repo_url_or_path",
"save_ledger",
"urls_from_json",
"verify_draft",
]
if __name__ == "__main__":
raise SystemExit(main())