feat(core): initialize hyperstitionstudio-core (hyperstitionstud_io.* / urn:io:hyperstitionstud:*) shared library, 4897-entry offline CMUdict fallback, local-config citation resolver, CLI entrypoints, and test suite (v1.2.0)
This commit is contained in:
commit
f8235a2037
32 files changed
+6646
No files matched your search
@@ -0,0 +1,7 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.egg-info/
|
||||
src/*.egg-info/
|
||||
build/
|
||||
dist/
|
||||
*.tmp
|
||||
@@ -0,0 +1,39 @@
|
||||
# `hyperstitionstudio-core` (`hyperstitionstud_io.*` — `v1.2.0`)
|
||||
|
||||
Shared PEP 420 Python common library (`hyperstitionstud_io.*`), offline `URN:` JSON Schema registry (`urn:io:hyperstitionstud:schema:v1:*`), and offline browser/ESM modules (`@hyperstitionstud.io/*` / `window.HyperstitionStudio.*`) across all `/workspace` projects.
|
||||
|
||||
---
|
||||
|
||||
## Key Features (`v1.2.0`)
|
||||
|
||||
1. **100% Offline & Portable Namespace Architecture (Zero `https://` Network Calls):**
|
||||
- Python PEP 420 namespace: `hyperstitionstud_io.{config,ciphers,phonetics,publishing,glossary,graph,ci,audio}`
|
||||
- Offline JSON Schema `$id` URNs: `urn:io:hyperstitionstud:schema:v1:*` (local relative `$schema` resolution)
|
||||
- GraphML / GEXF XML namespace: `xmlns:hs="urn:io:hyperstitionstud:ns:kg:1.0"`
|
||||
- Browser global & ESM scope: `window.HyperstitionStudio.*` and `@hyperstitionstud.io/*`
|
||||
2. **Local-Configuration Citation URL Resolution (`[citations.path_mounts]` in `/workspace/workspace.toml`):**
|
||||
- Resolves local dossier paths into remote citation URLs **only** when explicitly configured in local `workspace.toml`, falling back deterministically to the verified local filesystem path (`/workspace/...`).
|
||||
- Zero version-control subprocess calls; zero global package namespace URL synthesis.
|
||||
3. **4,897-Entry Offline `CMUdict` Phonetics Lookup (`cmudict_fallback.json`):**
|
||||
- Translates `Gen 0` English tokens to `Gen 1` Ingglish 100% offline without requiring `--workdir /workspace/ingglish-hyperdope-gematria`.
|
||||
4. **Dual Deployment Support (`Scenario A: file://` Offline Browser & `Scenario B: http://` Static Server):**
|
||||
- Supports both direct `file://` browser execution and static HTTP server hosting (either rooted at `/workspace` or rooted inside `/workspace/encyclopedia-knowledge-graph` via `--bundle-encyclopedia`).
|
||||
|
||||
---
|
||||
|
||||
## Quickstart & Diagnostics
|
||||
|
||||
```bash
|
||||
# 1. Install in editable mode
|
||||
pip install --no-deps -e /workspace/hyperstitionstudio-core
|
||||
|
||||
# 2. Run single-command environment, font, schema & SHA-256 isolation check
|
||||
hs-doctor
|
||||
|
||||
# 3. Verify grounded citations against local configuration & evidence quotes
|
||||
hs-citations --ledger /workspace/technocapital-singularity-zoology/taxonomy/citations-ledger-common.json \
|
||||
verify /workspace/technocapital-singularity-zoology/proposal-corporate-board-technocapital-allocation.md --evidence
|
||||
|
||||
# 4. Run full pytest suite
|
||||
pytest /workspace/hyperstitionstudio-core/tests/
|
||||
```
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@hyperstitionstud.io/workspace-core",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "Offline-first ESM & browser global (@hyperstitionstud.io/* / window.HyperstitionStudio.*) packages for Base-36 AQ ciphers and interactive knowledge graph workbenches.",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"packages-js/*"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @hyperstitionstud.io/ciphers-aq (urn:io:hyperstitionstud:js:ciphers-aq:1.2.0)
|
||||
* 100% Offline Base-36 Alphanumeric Qabbala (AQ) & Repdigit Evaluator for Browser (file:// & http://) and Node ESM.
|
||||
*/
|
||||
|
||||
export function computeAQ(text) {
|
||||
let total = 0;
|
||||
const s = String(text || "").toLowerCase();
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const code = s.charCodeAt(i);
|
||||
if (code >= 48 && code <= 57) {
|
||||
total += code - 48;
|
||||
} else if (code >= 97 && code <= 122) {
|
||||
total += code - 87;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
export function isRepdigit37(n) {
|
||||
return n > 0 && n % 111 === 0;
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.HyperstitionStudio = window.HyperstitionStudio || {};
|
||||
window.HyperstitionStudio.Ciphers = { computeAQ, isRepdigit37 };
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"name": "@hyperstitionstud.io/ciphers-aq",
|
||||
"version": "1.2.0",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"license": "MIT"
|
||||
}
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REMOTE_URL="${1:-${ORIGIN_URL:-}}"
|
||||
if [[ -z "${REMOTE_URL}" ]]; then
|
||||
echo "Usage: $0 <remote-git-url>"
|
||||
exit 1
|
||||
fi
|
||||
cd "${REPO_DIR}"
|
||||
if git remote get-url origin >/dev/null 2>&1; then
|
||||
git remote set-url origin "${REMOTE_URL}"
|
||||
else
|
||||
git remote add origin "${REMOTE_URL}"
|
||||
fi
|
||||
python3 "${REPO_DIR}/tests/test_core_suite.py"
|
||||
git push -u origin main
|
||||
git push origin v1.2.0
|
||||
@@ -0,0 +1,33 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=65.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "hyperstitionstudio-core"
|
||||
version = "1.2.0"
|
||||
description = "Shared PEP 420 common library (hyperstitionstud_io.*) for Base-36 AQ ciphers, offline CMUdict Ingglish phonetics, ReportLab/Pillow publishing, SHA-256 glossary isolation guards, local-config citation verification, and multi-format knowledge graphs."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = {text = "MIT"}
|
||||
authors = [
|
||||
{name = "m00t & Hermes Agent"}
|
||||
]
|
||||
dependencies = [
|
||||
"Pillow>=10.0.0",
|
||||
"reportlab>=4.0.0",
|
||||
"pypdf>=4.0.0",
|
||||
"pdfplumber>=0.10.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
hs-doctor = "hyperstitionstud_io.ci.doctor:main"
|
||||
hs-citations = "hyperstitionstud_io.ci.citation_sources:main"
|
||||
hs-pdf-build = "hyperstitionstud_io.publishing.pdf_compiler:main"
|
||||
hs-kg-build = "hyperstitionstud_io.graph.cli:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
namespaces = true
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"hyperstitionstud_io.phonetics" = ["*.json"]
|
||||
@@ -0,0 +1,5 @@
|
||||
# Python runtime dependencies for hyperstitionstudio-core (io.hyperstitionstud.*)
|
||||
Pillow>=10.0.0
|
||||
reportlab>=4.0.0
|
||||
pypdf>=4.0.0
|
||||
pdfplumber>=0.10.0
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:assemblage-builds-tier-list",
|
||||
"title": "Assemblage Builds ETI Tier List Schema (v2)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"rows"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:citations-ledger",
|
||||
"title": "Grounded Citations Local-Config Ledger Schema (v1/v2)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"sources"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph",
|
||||
"title": "Encyclopedia Multi-Partite Knowledge Graph Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"counts",
|
||||
"nodes",
|
||||
"edges"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:encyclopedia-manifest",
|
||||
"title": "22-Volume PDF Encyclopedia Manifest Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"divisions",
|
||||
"volumes"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:glossary-registry",
|
||||
"title": "Comprehensive Glossary Registry Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"sections",
|
||||
"bilingual_vocabulary_ledger"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:memetic-superclass-registry",
|
||||
"title": "Memetic Superclass M1-M7+ Registry Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"canonical_subclasses"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:quantitative-economic-anchors",
|
||||
"title": "Quantitative Economic Anchors Registry Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"anchors"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "urn:ietf:params:scim:schemas:core:2.0",
|
||||
"$id": "urn:io:hyperstitionstud:schema:v1:singularity-zoology-matrix",
|
||||
"title": "Technocapital Singularity Zoology Matrix Schema (v1)",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"version",
|
||||
"classes"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
"""hyperstitionstud_io — Shared Common Library for the hyperstitionstud.io workspace (v1.2.0)."""
|
||||
__version__ = "1.2.0"
|
||||
NAMESPACE_URN = "urn:io:hyperstitionstud"
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
hyperstitionstud_io.audio — Multi-Voice Neural TTS Lecture & Podcast Duration Verifier.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def verify_mp3_duration(mp3_path: str | Path, max_seconds: float = 5400.0) -> dict[str, Any]:
|
||||
from mutagen.mp3 import MP3
|
||||
|
||||
p = Path(mp3_path).resolve()
|
||||
info = MP3(str(p)).info
|
||||
secs = round(float(info.length), 2)
|
||||
return {
|
||||
"path": str(p),
|
||||
"bytes": p.stat().st_size,
|
||||
"duration_seconds": secs,
|
||||
"duration_minutes": round(secs / 60.0, 2),
|
||||
"within_cap": secs < max_seconds,
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
hyperstitionstud_io.ci — Citation Provenance Verification, 4-Gate Hyperdope CI & Environment Doctor.
|
||||
"""
|
||||
|
||||
from hyperstitionstud_io.ci.citation_sources import (
|
||||
SCHEMA_VERSION,
|
||||
_LedgerLock,
|
||||
add_sources,
|
||||
attach_quote,
|
||||
load_ledger,
|
||||
main as citations_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",
|
||||
"_LedgerLock",
|
||||
"add_sources",
|
||||
"attach_quote",
|
||||
"citations_main",
|
||||
"load_ledger",
|
||||
"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",
|
||||
]
|
||||
@@ -0,0 +1,567 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.ci.citation_sources
|
||||
Complete Grounded-Citations Ledger & Fact-Checking Engine (100% Offline & Local-Config Driven).
|
||||
|
||||
Implements the full 11-function Python API and all 7 CLI subcommands of grounded-citations
|
||||
(`reset`, `add`, `ingest`, `quote`, `list`, `render`, `verify`) while enforcing:
|
||||
1. Pure local-configuration URL resolution (`[citations.path_mounts]` in workspace.toml) —
|
||||
zero git/VCS subprocess calls and zero global package namespace URL synthesis.
|
||||
2. Dual-scheme URL & local-path parsing (`http://`, `https://`, `file://`, and `/workspace/...`,
|
||||
with automatic backtick stripping in `_split_draft`).
|
||||
3. Backwards-compatible `local_path` handling for existing v1 citation ledgers.
|
||||
4. Fenced code-block exclusion + Markdown table citation support in `verify_draft()`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
_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?://|file://|/)[^\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_ledger_path(explicit: str | None = None) -> Path:
|
||||
if explicit:
|
||||
return Path(explicit).expanduser()
|
||||
env = os.environ.get("HERMES_CITATION_LEDGER", "").strip()
|
||||
if env:
|
||||
return Path(env).expanduser()
|
||||
cfg = load_workspace_config()
|
||||
default_common = cfg.zoology_dir / "taxonomy" / "citations-ledger-common.json"
|
||||
if default_common.is_file():
|
||||
return default_common
|
||||
return Path.home() / ".hermes" / "cache" / "citations" / "ledger.json"
|
||||
|
||||
|
||||
def resolve_citation_target(
|
||||
local_path: str | Path,
|
||||
path_mounts: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
Resolve a local file path to a remote URL ONLY if its directory prefix is explicitly
|
||||
mapped in local configuration (`[citations.path_mounts]`). Otherwise, return the
|
||||
resolved local filesystem path unchanged. Zero VCS subprocess calls; zero global namespace URLs.
|
||||
"""
|
||||
raw_str = str(local_path).strip()
|
||||
if raw_str.startswith(("http://", "https://", "file://")):
|
||||
return normalize_url(raw_str)
|
||||
resolved = Path(raw_str).resolve()
|
||||
resolved_str = resolved.as_posix()
|
||||
mounts = path_mounts if path_mounts is not None else load_workspace_config().citation_path_mounts
|
||||
for local_prefix, remote_base in sorted(mounts.items(), key=lambda kv: -len(kv[0])):
|
||||
norm_prefix = Path(local_prefix).resolve().as_posix().rstrip("/")
|
||||
if resolved_str == norm_prefix or resolved_str.startswith(norm_prefix + "/"):
|
||||
rel_suffix = resolved_str[len(norm_prefix) :].lstrip("/")
|
||||
base = remote_base.rstrip("/")
|
||||
return f"{base}/{rel_suffix}" if rel_suffix else base
|
||||
return resolved_str
|
||||
|
||||
|
||||
def resolve_repo_url_or_path(
|
||||
local_full_path: str,
|
||||
prefer_local_if_no_remote: bool = True,
|
||||
path_mounts: dict[str, str] | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
Backwards-compatible entry point replacing the legacy git-subprocess resolver.
|
||||
Resolves purely from local configuration (`[citations.path_mounts]`) or returns
|
||||
the verified local filesystem path.
|
||||
"""
|
||||
return resolve_citation_target(local_full_path, path_mounts=path_mounts)
|
||||
|
||||
|
||||
def normalize_url(url: str) -> str:
|
||||
u = (url or "").strip().strip("`")
|
||||
if "#" in u and u.startswith(("http://", "https://", "file://")):
|
||||
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": []}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
raise SystemExit(f"error: ledger at {path} is unreadable ({exc}); run `reset` to start over")
|
||||
if not isinstance(data, dict) or not isinstance(data.get("sources"), list):
|
||||
raise SystemExit(f"error: ledger at {path} has an unexpected shape; run `reset`")
|
||||
for entry in data["sources"]:
|
||||
if "local_path" not in entry and isinstance(entry.get("url"), str) and entry["url"].startswith("/"):
|
||||
entry["local_path"] = entry["url"]
|
||||
return data
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class _LedgerLock:
|
||||
"""Best-effort cross-process lock (O_EXCL lockfile, stdlib only)."""
|
||||
|
||||
def __init__(self, path: Path, timeout: float = 5.0) -> None:
|
||||
self.lock_path = path.with_suffix(path.suffix + ".lock")
|
||||
self.timeout = timeout
|
||||
self.fd: int | None = None
|
||||
|
||||
def __enter__(self) -> _LedgerLock:
|
||||
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
deadline = time.monotonic() + self.timeout
|
||||
while True:
|
||||
try:
|
||||
self.fd = os.open(str(self.lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
return self
|
||||
except FileExistsError:
|
||||
if time.monotonic() >= deadline:
|
||||
try:
|
||||
self.lock_path.unlink()
|
||||
except OSError:
|
||||
return self
|
||||
continue
|
||||
time.sleep(0.05)
|
||||
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
if self.fd is not None:
|
||||
try:
|
||||
os.close(self.fd)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
self.lock_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def add_sources(
|
||||
path: Path,
|
||||
urls: Iterable[str],
|
||||
title: str | None = None,
|
||||
accessed: str | None = None,
|
||||
path_mounts: dict[str, 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 []
|
||||
with _LedgerLock(path):
|
||||
data = load_ledger(path)
|
||||
sources = data["sources"]
|
||||
by_url = {s["url"]: s for s in sources}
|
||||
by_local = {s["local_path"]: s for s in sources if s.get("local_path")}
|
||||
out: list[dict[str, Any]] = []
|
||||
changed = False
|
||||
for raw in urls:
|
||||
is_local = raw.startswith("/") or Path(raw).exists()
|
||||
local_key = Path(raw).resolve().as_posix() if is_local and not raw.startswith(("http://", "https://", "file://")) else None
|
||||
resolved_url = resolve_citation_target(local_key, path_mounts=path_mounts) if local_key else normalize_url(raw)
|
||||
|
||||
existing = (by_local.get(local_key) if local_key else None) or by_url.get(resolved_url)
|
||||
if existing is not None:
|
||||
if title and not existing.get("title"):
|
||||
existing["title"] = title
|
||||
changed = True
|
||||
if local_key and not existing.get("local_path"):
|
||||
existing["local_path"] = local_key
|
||||
changed = True
|
||||
out.append(existing)
|
||||
continue
|
||||
|
||||
entry: dict[str, Any] = {
|
||||
"id": len(sources) + 1,
|
||||
"url": resolved_url,
|
||||
"title": (title or "").strip(),
|
||||
"accessed": accessed or time.strftime("%Y-%m-%d"),
|
||||
}
|
||||
if local_key:
|
||||
entry["local_path"] = local_key
|
||||
by_local[local_key] = entry
|
||||
sources.append(entry)
|
||||
by_url[resolved_url] = entry
|
||||
out.append(entry)
|
||||
changed = True
|
||||
if changed:
|
||||
save_ledger(path, data)
|
||||
return out
|
||||
|
||||
|
||||
def urls_from_json(payload: Any) -> list[tuple[str, str]]:
|
||||
found: list[tuple[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def walk(node: Any) -> None:
|
||||
if isinstance(node, dict):
|
||||
url = node.get("url") or node.get("link") or node.get("source_url")
|
||||
if isinstance(url, str) and url.startswith(("http://", "https://", "/")):
|
||||
key = normalize_url(url)
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
raw_title = node.get("title") or node.get("name") or ""
|
||||
found.append((url, raw_title if isinstance(raw_title, str) else ""))
|
||||
for value in node.values():
|
||||
walk(value)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
walk(item)
|
||||
|
||||
walk(payload)
|
||||
return found
|
||||
|
||||
|
||||
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 | None = None) -> 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")
|
||||
with _LedgerLock(path):
|
||||
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")
|
||||
if evidence is None and entry.get("local_path") and Path(entry["local_path"]).is_file():
|
||||
evidence = Path(entry["local_path"]).read_text(encoding="utf-8")
|
||||
if evidence is None:
|
||||
raise SystemExit("error: no evidence text provided and source has no readable local_path")
|
||||
if not quote_in_evidence(quote, evidence):
|
||||
raise SystemExit(f"error: quote not found verbatim in the evidence text: {quote[:80]}")
|
||||
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] = []
|
||||
if style == "bibtex":
|
||||
for s in picked:
|
||||
key = f"source{s['id']}"
|
||||
title = s.get("title") or s["url"]
|
||||
lines.append(
|
||||
"@misc{{{},\n title = {{{}}},\n howpublished = {{\\url{{{}}}}},\n note = {{Accessed {}}}\n}}".format(
|
||||
key, title, s["url"], s.get("accessed", "")
|
||||
)
|
||||
)
|
||||
return "\n".join(lines)
|
||||
if style == "footnotes":
|
||||
for s in picked:
|
||||
title = s.get("title")
|
||||
suffix = f" — {title}" if title else ""
|
||||
lines.append(f"[^{s['id']}]: {s['url']}{suffix}")
|
||||
return "\n".join(lines)
|
||||
header = "Sources:" if style == "plain" else "## Sources"
|
||||
lines.append(header)
|
||||
if style != "plain":
|
||||
lines.append("")
|
||||
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("`")
|
||||
url_match = _URL_IN_TEXT_RE.search(raw_target)
|
||||
listed[int(m.group(1))] = (url_match.group(0) if url_match else raw_target).strip("`")
|
||||
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] = []
|
||||
|
||||
cited = [int(m) for m in _CITE_RE.findall(prose)]
|
||||
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
|
||||
valid_targets = {normalize_url(entry["url"])}
|
||||
if entry.get("local_path"):
|
||||
valid_targets.add(normalize_url(entry["local_path"]))
|
||||
valid_targets.add(normalize_url(resolve_citation_target(entry["local_path"])))
|
||||
if normalize_url(url) not in valid_targets:
|
||||
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 (1 if (strict and warnings) else 0)
|
||||
return code, errors, warnings
|
||||
|
||||
|
||||
def _parse_only(spec: str | None) -> set[int] | None:
|
||||
if not spec:
|
||||
return None
|
||||
out: set[int] = set()
|
||||
for chunk in spec.replace(" ", "").split(","):
|
||||
if not chunk:
|
||||
continue
|
||||
if "-" in chunk:
|
||||
lo, _, hi = chunk.partition("-")
|
||||
out.update(range(int(lo), int(hi) + 1))
|
||||
else:
|
||||
out.add(int(chunk))
|
||||
return out
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="sources.py", description="Citation ledger for grounded answers and documents.")
|
||||
parser.add_argument("--ledger", help="ledger file path (overrides env / default)")
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
sub.add_parser("reset", help="start a clean ledger")
|
||||
|
||||
p_add = sub.add_parser("add", help="register source url(s) or local paths, print their ids")
|
||||
p_add.add_argument("urls", nargs="+")
|
||||
p_add.add_argument("--title", help="title for the source (single-url calls)")
|
||||
p_add.add_argument("--accessed", help="access date (default: today)")
|
||||
p_add.add_argument("--json", action="store_true", help="emit JSON instead of ids")
|
||||
|
||||
p_ing = sub.add_parser("ingest", help="register every url in JSON tool output")
|
||||
p_ing.add_argument("file", help="JSON file, or - for stdin")
|
||||
|
||||
p_q = sub.add_parser("quote", help="attach verbatim supporting evidence to a source")
|
||||
p_q.add_argument("id", type=int, help="ledger id of the source the quote supports")
|
||||
p_q.add_argument("--text", required=True, help="the exact quote, copied from the page")
|
||||
p_q.add_argument("--from", dest="evidence", default=None, help="file with evidence text (or - for stdin; defaults to local_path if available)")
|
||||
|
||||
p_list = sub.add_parser("list", help="show the ledger")
|
||||
p_list.add_argument("--json", action="store_true")
|
||||
|
||||
p_render = sub.add_parser("render", help="render a Sources block")
|
||||
p_render.add_argument("--style", default="evidence", choices=["markdown", "plain", "footnotes", "bibtex", "evidence"])
|
||||
p_render.add_argument("--only", help="ids to include, e.g. 1,3,5-7")
|
||||
p_render.add_argument("--cited-in", help="include only ids cited in this draft file")
|
||||
p_render.add_argument("--replace-in", help="rewrite this draft's Sources block in place")
|
||||
|
||||
p_ver = sub.add_parser("verify", help="check a draft's citations against the ledger")
|
||||
p_ver.add_argument("draft")
|
||||
p_ver.add_argument("--strict", action="store_true", help="treat warnings as failures")
|
||||
p_ver.add_argument("--min-coverage", type=float, default=None)
|
||||
p_ver.add_argument("--evidence", action="store_true", help="require every cited source to carry at least one verbatim quote")
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
path = resolve_ledger_path(args.ledger)
|
||||
|
||||
if args.cmd == "reset":
|
||||
with _LedgerLock(path):
|
||||
save_ledger(path, {"version": SCHEMA_VERSION, "sources": []})
|
||||
return 0
|
||||
|
||||
if args.cmd == "add":
|
||||
title = args.title if len(args.urls) == 1 else None
|
||||
entries = add_sources(path, args.urls, title=title, accessed=args.accessed)
|
||||
if args.json:
|
||||
print(json.dumps(entries, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
for e in entries:
|
||||
print(f"[{e['id']}] {e['url']}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "ingest":
|
||||
raw = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8")
|
||||
payload = json.loads(raw)
|
||||
pairs = urls_from_json(payload)
|
||||
if not pairs:
|
||||
print("no urls found in input", file=sys.stderr)
|
||||
return 1
|
||||
for url, title in pairs:
|
||||
entry = add_sources(path, [url], title=title or None)[0]
|
||||
print(f"[{entry['id']}] {entry['url']}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "quote":
|
||||
raw = None
|
||||
if args.evidence == "-":
|
||||
raw = sys.stdin.read()
|
||||
elif args.evidence:
|
||||
raw = Path(args.evidence).read_text(encoding="utf-8")
|
||||
entry = attach_quote(path, args.id, args.text, raw)
|
||||
print(f"[{entry['id']}] evidence attached ({len(entry.get('quotes', []))} quote(s))")
|
||||
return 0
|
||||
|
||||
data = load_ledger(path)
|
||||
sources = sorted(data["sources"], key=lambda s: s["id"])
|
||||
|
||||
if args.cmd == "list":
|
||||
if args.json:
|
||||
print(json.dumps(sources, indent=2, ensure_ascii=False))
|
||||
else:
|
||||
for s in sources:
|
||||
title = f" {s['title']}" if s.get("title") else ""
|
||||
nq = len(s.get("quotes", []))
|
||||
mark = f" ({nq} quote{'s' if nq != 1 else ''})" if nq else ""
|
||||
print(f"[{s['id']}] {s['url']}{title}{mark}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "render":
|
||||
only = _parse_only(args.only)
|
||||
draft_for_ids = args.replace_in or args.cited_in
|
||||
if draft_for_ids:
|
||||
draft = Path(draft_for_ids).read_text(encoding="utf-8")
|
||||
prose, _ = _split_draft(draft)
|
||||
cited = {int(m) for m in _CITE_RE.findall(prose)}
|
||||
only = cited if only is None else (only & cited)
|
||||
block = render_sources(sources, style=args.style, only=only)
|
||||
if not block:
|
||||
print("no sources to render", file=sys.stderr)
|
||||
return 1
|
||||
if args.replace_in:
|
||||
target = Path(args.replace_in)
|
||||
body = _strip_sources_block(target.read_text(encoding="utf-8"))
|
||||
target.write_text(body.rstrip("\n") + "\n\n---\n\n" + block + "\n", encoding="utf-8")
|
||||
print(f"Rendered {len(only or sources)} cited sources into {target}")
|
||||
return 0
|
||||
print(block)
|
||||
return 0
|
||||
|
||||
if args.cmd == "verify":
|
||||
code, errors, warnings = verify_draft(
|
||||
Path(args.draft),
|
||||
sources,
|
||||
strict=args.strict,
|
||||
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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.ci.doctor — Single-Command Offline Readiness, Font, Schema & SHA-256 Diagnostic (`hs-doctor`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.metadata
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
from hyperstitionstud_io.glossary import sha256_file
|
||||
|
||||
EXPECTED_SHA256 = {
|
||||
"/workspace/technocapital-singularity-zoology/taxonomy/glossary-registry.json": "7564ef40fb3e0e18d1d8547522db431b6a369c40139713b573df6e58b972d43d",
|
||||
"/workspace/technocapital-singularity-zoology/encyclopedia/encyclopedia-manifest.json": "0d7ce833bb0aa0eea069bf764b2e3b0b36ac2631821c42f3d6bcb897335f8a7d",
|
||||
}
|
||||
|
||||
REQUIRED_FONTS = [
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf",
|
||||
]
|
||||
|
||||
|
||||
def run_diagnostics() -> dict[str, Any]:
|
||||
cfg = load_workspace_config()
|
||||
pkgs = {}
|
||||
for p in ("Pillow", "reportlab", "pypdf", "pdfplumber"):
|
||||
try:
|
||||
pkgs[p] = importlib.metadata.version(p)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
pkgs[p] = None
|
||||
|
||||
fonts_ok = {f: Path(f).is_file() for f in REQUIRED_FONTS}
|
||||
dirs_ok = {k: v.is_dir() for k, v in cfg.paths.items()}
|
||||
|
||||
isolation_checks = {}
|
||||
for p in cfg.read_only_files:
|
||||
p_str = str(p)
|
||||
actual = sha256_file(p) if p.is_file() else None
|
||||
expected = EXPECTED_SHA256.get(p_str)
|
||||
isolation_checks[p_str] = {
|
||||
"exists": p.is_file(),
|
||||
"sha256": actual,
|
||||
"matches_baseline": (actual == expected) if expected else (actual is not None),
|
||||
}
|
||||
|
||||
fb_path = Path(__file__).resolve().parent.parent / "phonetics" / "cmudict_fallback.json"
|
||||
fb_count = len(json.loads(fb_path.read_text(encoding="utf-8"))) if fb_path.is_file() else 0
|
||||
|
||||
all_ok = (
|
||||
all(v is not None for v in pkgs.values())
|
||||
and all(fonts_ok.values())
|
||||
and all(v["matches_baseline"] for v in isolation_checks.values())
|
||||
and fb_count >= 190
|
||||
)
|
||||
|
||||
return {
|
||||
"namespace_urn": cfg.namespace_urn,
|
||||
"schema_version": cfg.schema_version,
|
||||
"workspace_config_file": str(cfg.source_file) if cfg.source_file else None,
|
||||
"all_checks_passed": all_ok,
|
||||
"python_packages": pkgs,
|
||||
"truetype_fonts": fonts_ok,
|
||||
"workspace_directories": dirs_ok,
|
||||
"offline_cmudict_fallback_entries": fb_count,
|
||||
"citation_path_mounts": cfg.citation_path_mounts,
|
||||
"isolation_locks": isolation_checks,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
res = run_diagnostics()
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0 if res["all_checks_passed"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
hyperstitionstud_io.ciphers — Unified Base-36 Alphanumeric Qabbala (AQ), Prime & G1-G6 Vector Engine.
|
||||
Strictly enforces the Zero-d-Filter invariant across Zoology and Knowledge Graph artifacts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from typing import Any, Iterable, Literal
|
||||
|
||||
QuantMode = Literal["off", "spoken", "digit", "dual"]
|
||||
|
||||
_SMALL_NUMS = {
|
||||
0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five",
|
||||
6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten",
|
||||
11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen",
|
||||
16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen",
|
||||
20: "twenty", 30: "thirty", 40: "forty", 50: "fifty",
|
||||
60: "sixty", 70: "seventy", 80: "eighty", 90: "ninety",
|
||||
}
|
||||
|
||||
G3_QUANTIZED_STEPS = frozenset({0, 1, 10, 18, 20, 36, 37, 40, 74})
|
||||
REPDIGIT_37_ATTRACTORS = frozenset({111, 222, 333, 444, 555, 666, 777, 888, 999})
|
||||
|
||||
|
||||
def int_to_spoken_words(n: int) -> str:
|
||||
if n < 0:
|
||||
return "minus " + int_to_spoken_words(-n)
|
||||
if n in _SMALL_NUMS:
|
||||
return _SMALL_NUMS[n]
|
||||
if n < 100:
|
||||
return _SMALL_NUMS[(n // 10) * 10] + " " + _SMALL_NUMS[n % 10]
|
||||
if n < 1000:
|
||||
rem = n % 100
|
||||
return _SMALL_NUMS[n // 100] + " hundred" + (" " + int_to_spoken_words(rem) if rem else "")
|
||||
for scale_val, scale_name in ((1_000_000_000_000, "trillion"), (1_000_000_000, "billion"), (1_000_000, "million"), (1000, "thousand")):
|
||||
if n >= scale_val:
|
||||
rem = n % scale_val
|
||||
return int_to_spoken_words(n // scale_val) + " " + scale_name + (" " + int_to_spoken_words(rem) if rem else "")
|
||||
return str(n)
|
||||
|
||||
|
||||
def expand_quant_spoken(text: str) -> str:
|
||||
def _repl_curr(m: re.Match[str]) -> str:
|
||||
num_str = m.group(1).replace(",", "")
|
||||
unit = (m.group(2) or "").upper()
|
||||
unit_word = {"B": "billion", "M": "million", "T": "trillion", "K": "thousand"}.get(unit, "")
|
||||
if "." in num_str:
|
||||
parts = num_str.split(".")
|
||||
w = int_to_spoken_words(int(parts[0])) + " point " + " ".join(int_to_spoken_words(int(d)) for d in parts[1])
|
||||
else:
|
||||
w = int_to_spoken_words(int(num_str))
|
||||
return (w + " " + unit_word).strip()
|
||||
|
||||
s = re.sub(r"\$?(\d[\d,]*(?:\.\d+)?)\s*([BMTKbmtk])\b", _repl_curr, text)
|
||||
s = re.sub(r"\b(\d[\d,]*)\b", lambda m: int_to_spoken_words(int(m.group(1).replace(",", ""))), s)
|
||||
return s
|
||||
|
||||
|
||||
def compute_aq(text: str, quant_mode: QuantMode = "digit") -> int:
|
||||
"""
|
||||
Compute Base-36 Alphanumeric Qabbala (AQ) sum: 0-9 = 0..9, A-Z = 10..35.
|
||||
- quant_mode="digit" (default standard AQ): sums letters (10..35) + literal digits (0..9).
|
||||
- quant_mode="off": strips digits before summing (100% pure qualitative lexical AQ).
|
||||
- quant_mode="spoken": expands numbers/currencies ($6B -> six billion) before summing.
|
||||
"""
|
||||
if quant_mode == "off":
|
||||
text = re.sub(r"[0-9]+", "", text)
|
||||
elif quant_mode == "spoken":
|
||||
text = expand_quant_spoken(text)
|
||||
total = 0
|
||||
for ch in text.lower():
|
||||
if "0" <= ch <= "9":
|
||||
total += ord(ch) - 48
|
||||
elif "a" <= ch <= "z":
|
||||
total += ord(ch) - 87
|
||||
return total
|
||||
|
||||
|
||||
def is_prime(n: int) -> bool:
|
||||
if n < 2:
|
||||
return False
|
||||
if n in (2, 3):
|
||||
return True
|
||||
if n % 2 == 0 or n % 3 == 0:
|
||||
return False
|
||||
limit = int(math.isqrt(n))
|
||||
for k in range(5, limit + 1, 6):
|
||||
if n % k == 0 or n % (k + 2) == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_PRIME_CACHE: list[int] = [p for p in range(2, 4000) if is_prime(p)]
|
||||
_PRIME_RANK_MAP: dict[int, int] = {p: idx + 1 for idx, p in enumerate(_PRIME_CACHE)}
|
||||
|
||||
|
||||
def prime_rank(n: int) -> int | None:
|
||||
if n in _PRIME_RANK_MAP:
|
||||
return _PRIME_RANK_MAP[n]
|
||||
if not is_prime(n):
|
||||
return None
|
||||
while _PRIME_CACHE[-1] < n:
|
||||
cand = _PRIME_CACHE[-1] + 2
|
||||
while not is_prime(cand):
|
||||
cand += 2
|
||||
_PRIME_CACHE.append(cand)
|
||||
_PRIME_RANK_MAP[cand] = len(_PRIME_CACHE)
|
||||
return _PRIME_RANK_MAP.get(n)
|
||||
|
||||
|
||||
def is_repdigit_37(n: int) -> bool:
|
||||
return n > 0 and n % 111 == 0
|
||||
|
||||
|
||||
def compute_variance(values: Iterable[float | int]) -> float:
|
||||
vals = [float(x) for x in values]
|
||||
if len(vals) < 2:
|
||||
return 0.0
|
||||
mean = sum(vals) / len(vals)
|
||||
return round(sum((x - mean) ** 2 for x in vals) / len(vals), 2)
|
||||
|
||||
|
||||
def evaluate_bidirectional_lock(eng: str, ing: str) -> dict[str, Any]:
|
||||
eng_aq = compute_aq(eng, quant_mode="digit")
|
||||
ing_aq = compute_aq(ing, quant_mode="digit")
|
||||
eng_pr = prime_rank(eng_aq)
|
||||
ing_pr = prime_rank(ing_aq)
|
||||
delta = ing_aq - eng_aq
|
||||
return {
|
||||
"eng": eng,
|
||||
"eng_aq": eng_aq,
|
||||
"eng_prime_rank": eng_pr,
|
||||
"is_prime_eng": eng_pr is not None,
|
||||
"ing": ing,
|
||||
"ing_aq": ing_aq,
|
||||
"ing_prime_rank": ing_pr,
|
||||
"is_prime": ing_pr is not None,
|
||||
"delta": delta,
|
||||
"isometric": delta == 0,
|
||||
"twin_prime_mutation": (eng_pr is not None and ing_pr is not None and delta != 0),
|
||||
"g3_quantized_step": abs(delta) in G3_QUANTIZED_STEPS,
|
||||
}
|
||||
|
||||
|
||||
def assert_zero_d_filter(text: str, artifact_label: str = "artifact") -> None:
|
||||
forbidden = ("d-filter", "decagram filter", "10-letter d ")
|
||||
low = text.lower()
|
||||
for pat in forbidden:
|
||||
if pat in low:
|
||||
raise ValueError(f"Zero-d-Filter boundary violation in {artifact_label}: matched '{pat}'")
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
hyperstitionstud_io.config — Declarative Local Workspace Configuration Loader.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tomllib
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
DEFAULT_WORKSPACE_TOML = Path("/workspace/workspace.toml")
|
||||
USER_WORKSPACE_TOML = Path.home() / ".config" / "hyperstitionstud.io" / "workspace.toml"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkspaceConfig:
|
||||
schema_version: str = "1.2.0"
|
||||
namespace_urn: str = "urn:io:hyperstitionstud"
|
||||
paths: dict[str, Path] = field(default_factory=dict)
|
||||
read_only_files: list[Path] = field(default_factory=list)
|
||||
citation_path_mounts: dict[str, str] = field(default_factory=dict)
|
||||
source_file: Path | None = None
|
||||
|
||||
@property
|
||||
def core_dir(self) -> Path:
|
||||
return self.paths.get("core_dir", Path("/workspace/hyperstitionstudio-core"))
|
||||
|
||||
@property
|
||||
def archive_dir(self) -> Path:
|
||||
return self.paths.get("archive_dir", Path("/workspace/ingglish-hyperdope-gematria"))
|
||||
|
||||
@property
|
||||
def zoology_dir(self) -> Path:
|
||||
return self.paths.get("zoology_dir", Path("/workspace/technocapital-singularity-zoology"))
|
||||
|
||||
@property
|
||||
def knowledge_graph_dir(self) -> Path:
|
||||
return self.paths.get("knowledge_graph_dir", Path("/workspace/encyclopedia-knowledge-graph"))
|
||||
|
||||
@property
|
||||
def ci_build_dir(self) -> Path:
|
||||
return self.paths.get("ci_build_dir", Path("/workspace/hyperdope-ci-build"))
|
||||
|
||||
|
||||
def load_workspace_config(explicit_path: str | Path | None = None) -> WorkspaceConfig:
|
||||
candidates: list[Path] = []
|
||||
if explicit_path:
|
||||
candidates.append(Path(explicit_path))
|
||||
env_p = os.environ.get("HYPERSTITIONSTUDIO_CONFIG", "").strip()
|
||||
if env_p:
|
||||
candidates.append(Path(env_p))
|
||||
candidates.extend([DEFAULT_WORKSPACE_TOML, USER_WORKSPACE_TOML])
|
||||
|
||||
chosen: Path | None = None
|
||||
for c in candidates:
|
||||
if c.is_file():
|
||||
chosen = c
|
||||
break
|
||||
|
||||
if chosen is None:
|
||||
return WorkspaceConfig(
|
||||
paths={
|
||||
"core_dir": Path("/workspace/hyperstitionstudio-core"),
|
||||
"archive_dir": Path("/workspace/ingglish-hyperdope-gematria"),
|
||||
"zoology_dir": Path("/workspace/technocapital-singularity-zoology"),
|
||||
"knowledge_graph_dir": Path("/workspace/encyclopedia-knowledge-graph"),
|
||||
"ci_build_dir": Path("/workspace/hyperdope-ci-build"),
|
||||
"gematria_js_dir": Path("/workspace/hyperdope-gematria"),
|
||||
"memes_dir": Path("/workspace/memes"),
|
||||
},
|
||||
read_only_files=[
|
||||
Path("/workspace/technocapital-singularity-zoology/taxonomy/glossary-registry.json"),
|
||||
Path("/workspace/technocapital-singularity-zoology/encyclopedia/encyclopedia-manifest.json"),
|
||||
],
|
||||
citation_path_mounts={},
|
||||
source_file=None,
|
||||
)
|
||||
|
||||
raw: dict[str, Any] = tomllib.loads(chosen.read_text(encoding="utf-8"))
|
||||
raw_paths = raw.get("paths", {})
|
||||
raw_iso = raw.get("isolation", {})
|
||||
raw_cit = raw.get("citations", {}).get("path_mounts", {})
|
||||
|
||||
return WorkspaceConfig(
|
||||
schema_version=str(raw.get("schema_version", "1.2.0")),
|
||||
namespace_urn=str(raw.get("namespace_urn", "urn:io:hyperstitionstud")),
|
||||
paths={k: Path(v) for k, v in raw_paths.items()},
|
||||
read_only_files=[Path(p) for p in raw_iso.get("read_only_files", [])],
|
||||
citation_path_mounts={str(k): str(v) for k, v in raw_cit.items()},
|
||||
source_file=chosen,
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
hyperstitionstud_io.glossary — Provenance-Keyed Glossary Registry & Cryptographic SHA-256 Isolation Guard.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
|
||||
def sha256_file(path: str | Path) -> str:
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
class ReadOnlyIsolationGuard:
|
||||
"""
|
||||
Context manager verifying via pure-Python hashlib.sha256 that protected upstream
|
||||
registries (such as glossary-registry.json and encyclopedia-manifest.json) remain
|
||||
100% byte-for-byte unchanged across a build or verification pass. Zero VCS calls.
|
||||
"""
|
||||
|
||||
def __init__(self, protected_paths: Iterable[str | Path]) -> None:
|
||||
self.paths: list[Path] = [Path(p).resolve() for p in protected_paths]
|
||||
self.pre_digests: dict[str, str] = {}
|
||||
self.post_digests: dict[str, str] = {}
|
||||
|
||||
def __enter__(self) -> ReadOnlyIsolationGuard:
|
||||
self.pre_digests = {str(p): sha256_file(p) for p in self.paths if p.is_file()}
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
||||
self.post_digests = {str(p): sha256_file(p) for p in self.paths if p.is_file()}
|
||||
for p_str, pre_sha in self.pre_digests.items():
|
||||
post_sha = self.post_digests.get(p_str)
|
||||
if pre_sha != post_sha:
|
||||
raise AssertionError(
|
||||
f"ISOLATION BREACH on {p_str}: pre-SHA256={pre_sha} != post-SHA256={post_sha}"
|
||||
)
|
||||
|
||||
def audit_receipt(self) -> dict[str, Any]:
|
||||
if not self.post_digests:
|
||||
self.post_digests = {str(p): sha256_file(p) for p in self.paths if p.is_file()}
|
||||
all_unchanged = all(self.pre_digests.get(k) == self.post_digests.get(k) for k in self.pre_digests)
|
||||
return {
|
||||
"namespace_urn": "urn:io:hyperstitionstud:isolation-receipt:v1",
|
||||
"all_unchanged": all_unchanged,
|
||||
"files": {
|
||||
k: {
|
||||
"pre_sha256": self.pre_digests.get(k),
|
||||
"post_sha256": self.post_digests.get(k),
|
||||
"unchanged": self.pre_digests.get(k) == self.post_digests.get(k),
|
||||
}
|
||||
for k in self.pre_digests
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
hyperstitionstud_io.graph — Multi-Partite Property Graph Compiler & URN Namespace Exporter.
|
||||
"""
|
||||
|
||||
URN_GRAPH_NS = "urn:io:hyperstitionstud:ns:kg:1.0"
|
||||
URN_SCHEMA_GRAPH = "urn:io:hyperstitionstud:schema:v1:encyclopedia-graph"
|
||||
|
||||
|
||||
def make_entity_urn(domain: str, entity_type: str, entity_id: str | int) -> str:
|
||||
return f"urn:io:hyperstitionstud:{domain}:{entity_type}:{entity_id}"
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.graph.cli — Location-Independent Knowledge Graph CLI Entrypoint (`hs-kg-build`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
|
||||
|
||||
def main() -> int:
|
||||
cfg = load_workspace_config()
|
||||
kg_script = cfg.knowledge_graph_dir / "scripts" / "build_encyclopedia_knowledge_graph.py"
|
||||
res = subprocess.run([sys.executable, str(kg_script), *sys.argv[1:]])
|
||||
return res.returncode
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
hyperstitionstud_io.phonetics — Self-Contained Gen 0 -> Gen 1 Ingglish (CMUdict) Phonemic Translator.
|
||||
Provides a deterministic offline lookup table (cmudict_fallback.json) plus an optional Node.js
|
||||
bridge when node_modules/ingglish is available, eliminating cross-repository --workdir coupling.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
|
||||
_FALLBACK_PATH = Path(__file__).resolve().parent / "cmudict_fallback.json"
|
||||
_FALLBACK_CACHE: dict[str, str] | None = None
|
||||
|
||||
|
||||
def _load_fallback() -> dict[str, str]:
|
||||
global _FALLBACK_CACHE
|
||||
if _FALLBACK_CACHE is None:
|
||||
if _FALLBACK_PATH.is_file():
|
||||
_FALLBACK_CACHE = json.loads(_FALLBACK_PATH.read_text(encoding="utf-8"))
|
||||
else:
|
||||
_FALLBACK_CACHE = {}
|
||||
return _FALLBACK_CACHE
|
||||
|
||||
|
||||
def translate_batch(terms: list[str], workdir: str | Path | None = None) -> dict[str, str]:
|
||||
"""
|
||||
Translate a batch of Gen 0 English words/phrases into Gen 1 Phonemic Ingglish.
|
||||
1. Resolves known vocabulary immediately from the bundled offline cmudict_fallback.json.
|
||||
2. For any remaining novel tokens, invokes node_modules/ingglish if available locally
|
||||
or in the configured archive_dir, falling back deterministically to lowercase tokens
|
||||
if Node.js is offline/unavailable.
|
||||
"""
|
||||
fallback = _load_fallback()
|
||||
results: dict[str, str] = {}
|
||||
missing: list[str] = []
|
||||
|
||||
for t in terms:
|
||||
key = t.strip()
|
||||
if not key:
|
||||
results[t] = ""
|
||||
elif key.lower() in fallback:
|
||||
results[t] = fallback[key.lower()]
|
||||
else:
|
||||
words = key.lower().split()
|
||||
if words and all(w in fallback for w in words):
|
||||
results[t] = " ".join(fallback[w] for w in words)
|
||||
else:
|
||||
missing.append(t)
|
||||
|
||||
if not missing:
|
||||
return results
|
||||
|
||||
cfg = load_workspace_config()
|
||||
wdir = Path(workdir) if workdir else cfg.archive_dir
|
||||
node_bin = shutil.which("node")
|
||||
if node_bin and (wdir / "node_modules" / "ingglish").is_dir():
|
||||
js = (
|
||||
"import { translateSync } from 'ingglish';\n"
|
||||
"import fs from 'fs';\n"
|
||||
"const terms = JSON.parse(fs.readFileSync(0, 'utf8'));\n"
|
||||
"const out = {};\n"
|
||||
"for (const t of terms) { out[t] = translateSync(t).toLowerCase(); }\n"
|
||||
"process.stdout.write(JSON.stringify(out));\n"
|
||||
)
|
||||
res = subprocess.run(
|
||||
[node_bin, "--input-type=module", "-e", js],
|
||||
input=json.dumps(missing),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=str(wdir),
|
||||
)
|
||||
if res.returncode == 0 and res.stdout.strip():
|
||||
translated = json.loads(res.stdout)
|
||||
results.update(translated)
|
||||
return results
|
||||
|
||||
for t in missing:
|
||||
results[t] = t.lower()
|
||||
return results
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
hyperstitionstud_io.publishing — Unified ReportLab PDF & Pillow Visual Rendering Engine.
|
||||
"""
|
||||
|
||||
from hyperstitionstud_io.publishing.pdf_compiler import compile_markdown_to_pdf
|
||||
|
||||
__all__ = ["compile_markdown_to_pdf"]
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
hyperstitionstud_io.publishing.pdf_compiler
|
||||
Unified ReportLab Markdown-to-PDF Compiler with Atomic Temp-File Replacement & pypdf Verification.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _format_inline(text: str) -> str:
|
||||
code_spans: list[str] = []
|
||||
|
||||
def _save_code(m: re.Match[str]) -> str:
|
||||
idx = len(code_spans)
|
||||
code_spans.append(f'<font name="DejaVuMono" size="8.5" color="#8B1A1A">{html.escape(m.group(1), quote=False)}</font>')
|
||||
return f"\x00CODE{idx}\x00"
|
||||
|
||||
s = re.sub(r"`([^`]+)`", _save_code, text)
|
||||
s = html.escape(s, quote=False)
|
||||
s = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", s)
|
||||
s = re.sub(r"\*([^*]+)\*", r"<i>\1</i>", s)
|
||||
for idx, val in enumerate(code_spans):
|
||||
s = s.replace(f"\x00CODE{idx}\x00", val)
|
||||
return s
|
||||
|
||||
|
||||
def compile_markdown_to_pdf(
|
||||
md_path: str | Path,
|
||||
pdf_path: str | Path,
|
||||
title: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
from pypdf import PdfReader
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
||||
from reportlab.lib.units import inch
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.platypus import (
|
||||
HRFlowable,
|
||||
KeepTogether,
|
||||
Paragraph,
|
||||
Preformatted,
|
||||
SimpleDocTemplate,
|
||||
Spacer,
|
||||
Table,
|
||||
TableStyle,
|
||||
)
|
||||
|
||||
md_p = Path(md_path).resolve()
|
||||
pdf_p = Path(pdf_path).resolve()
|
||||
pdf_p.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_p = pdf_p.with_suffix(f".tmp.{os.getpid()}.pdf")
|
||||
|
||||
oblique_ttf = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf"
|
||||
bold_oblique_ttf = "/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf"
|
||||
pdfmetrics.registerFont(TTFont("DejaVu", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Bold", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-Oblique", oblique_ttf if Path(oblique_ttf).is_file() else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVu-BoldOblique", bold_oblique_ttf if Path(bold_oblique_ttf).is_file() else "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"))
|
||||
pdfmetrics.registerFont(TTFont("DejaVuMono-Bold", "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf"))
|
||||
pdfmetrics.registerFontFamily(
|
||||
"DejaVu",
|
||||
normal="DejaVu",
|
||||
bold="DejaVu-Bold",
|
||||
italic="DejaVu-Oblique",
|
||||
boldItalic="DejaVu-BoldOblique",
|
||||
)
|
||||
|
||||
styles = getSampleStyleSheet()
|
||||
st_h1 = ParagraphStyle("HS_H1", parent=styles["Heading1"], fontName="DejaVu-Bold", fontSize=15, leading=19, textColor=colors.HexColor("#111827"), spaceAfter=8)
|
||||
st_h2 = ParagraphStyle("HS_H2", parent=styles["Heading2"], fontName="DejaVu-Bold", fontSize=12, leading=15, textColor=colors.HexColor("#8B1A1A"), spaceBefore=10, spaceAfter=5)
|
||||
st_h3 = ParagraphStyle("HS_H3", parent=styles["Heading3"], fontName="DejaVu-Bold", fontSize=10.5, leading=13.5, textColor=colors.HexColor("#1F2937"), spaceBefore=7, spaceAfter=4)
|
||||
st_body = ParagraphStyle("HS_Body", parent=styles["BodyText"], fontName="DejaVu", fontSize=9.2, leading=13, textColor=colors.HexColor("#1F2937"), spaceAfter=5)
|
||||
st_bullet = ParagraphStyle("HS_Bullet", parent=st_body, leftIndent=14, firstLineIndent=-8, spaceAfter=3)
|
||||
st_code = ParagraphStyle("HS_Code", fontName="DejaVuMono", fontSize=7.5, leading=10, textColor=colors.HexColor("#111827"), backColor=colors.HexColor("#F3F4F6"), leftIndent=6, rightIndent=6, spaceBefore=4, spaceAfter=6)
|
||||
st_th = ParagraphStyle("HS_TH", fontName="DejaVu-Bold", fontSize=8.0, leading=10.5, textColor=colors.white)
|
||||
st_td = ParagraphStyle("HS_TD", fontName="DejaVu", fontSize=8.0, leading=10.5, textColor=colors.HexColor("#111827"))
|
||||
|
||||
raw_lines = md_p.read_text(encoding="utf-8").splitlines()
|
||||
story: list[Any] = []
|
||||
if title:
|
||||
story.append(Paragraph(_format_inline(title), st_h1))
|
||||
story.append(HRFlowable(width="100%", thickness=1.2, color=colors.HexColor("#8B1A1A"), spaceAfter=8))
|
||||
|
||||
in_code = False
|
||||
code_buf: list[str] = []
|
||||
table_buf: list[list[str]] = []
|
||||
|
||||
def _flush_table() -> None:
|
||||
nonlocal table_buf
|
||||
if not table_buf:
|
||||
return
|
||||
rows_clean = [r for r in table_buf if not all(set(c.strip()) <= {"-", ":"} for c in r)]
|
||||
table_buf = []
|
||||
if not rows_clean:
|
||||
return
|
||||
ncols = max(len(r) for r in rows_clean)
|
||||
avail_w = 7.0 * inch
|
||||
col_w = [avail_w / ncols] * ncols
|
||||
data_cells = []
|
||||
for r_idx, r in enumerate(rows_clean):
|
||||
padded = (r + [""] * ncols)[:ncols]
|
||||
st = st_th if r_idx == 0 else st_td
|
||||
data_cells.append([Paragraph(_format_inline(c.strip()), st) for c in padded])
|
||||
tbl = Table(data_cells, colWidths=col_w, repeatRows=1)
|
||||
tbl.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#1F2937")),
|
||||
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#F9FAFB")]),
|
||||
("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#D1D5DB")),
|
||||
("VALIGN", (0, 0), (-1, -1), "TOP"),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 4),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
|
||||
("LEFTPADDING", (0, 0), (-1, -1), 5),
|
||||
("RIGHTPADDING", (0, 0), (-1, -1), 5),
|
||||
]
|
||||
)
|
||||
)
|
||||
story.append(tbl)
|
||||
story.append(Spacer(1, 6))
|
||||
|
||||
for ln in raw_lines:
|
||||
if ln.strip().startswith("```"):
|
||||
_flush_table()
|
||||
if in_code:
|
||||
story.append(Preformatted("\n".join(code_buf), st_code))
|
||||
code_buf = []
|
||||
in_code = False
|
||||
else:
|
||||
in_code = True
|
||||
continue
|
||||
if in_code:
|
||||
code_buf.append(ln)
|
||||
continue
|
||||
if ln.strip().startswith("|") and ln.strip().endswith("|"):
|
||||
cells = [c.strip() for c in ln.strip()[1:-1].split("|")]
|
||||
table_buf.append(cells)
|
||||
continue
|
||||
else:
|
||||
_flush_table()
|
||||
|
||||
stripped = ln.strip()
|
||||
if not stripped:
|
||||
story.append(Spacer(1, 4))
|
||||
elif stripped == "---":
|
||||
story.append(HRFlowable(width="100%", thickness=0.6, color=colors.HexColor("#D1D5DB"), spaceBefore=4, spaceAfter=4))
|
||||
elif stripped.startswith("# "):
|
||||
if not title:
|
||||
story.append(Paragraph(_format_inline(stripped[2:].strip()), st_h1))
|
||||
elif stripped.startswith("## "):
|
||||
story.append(KeepTogether([Paragraph(_format_inline(stripped[3:].strip()), st_h2)]))
|
||||
elif stripped.startswith("### "):
|
||||
story.append(KeepTogether([Paragraph(_format_inline(stripped[4:].strip()), st_h3)]))
|
||||
elif stripped.startswith(("- ", "* ")):
|
||||
story.append(Paragraph("• " + _format_inline(stripped[2:].strip()), st_bullet))
|
||||
elif re.match(r"^\d+\.\s+", stripped):
|
||||
story.append(Paragraph(_format_inline(stripped), st_bullet))
|
||||
else:
|
||||
story.append(Paragraph(_format_inline(stripped), st_body))
|
||||
|
||||
_flush_table()
|
||||
if code_buf:
|
||||
story.append(Preformatted("\n".join(code_buf), st_code))
|
||||
|
||||
doc = SimpleDocTemplate(
|
||||
str(tmp_p),
|
||||
pagesize=letter,
|
||||
leftMargin=0.65 * inch,
|
||||
rightMargin=0.65 * inch,
|
||||
topMargin=0.60 * inch,
|
||||
bottomMargin=0.60 * inch,
|
||||
title=title or md_p.stem,
|
||||
)
|
||||
doc.build(story)
|
||||
os.replace(tmp_p, pdf_p)
|
||||
|
||||
reader = PdfReader(str(pdf_p))
|
||||
extracted_chars = sum(len(page.extract_text() or "") for page in reader.pages)
|
||||
return {
|
||||
"md_path": str(md_p),
|
||||
"pdf_path": str(pdf_p),
|
||||
"page_count": len(reader.pages),
|
||||
"extracted_chars": extracted_chars,
|
||||
}
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="hs-pdf-build", description="Compile Markdown to verified ReportLab PDF.")
|
||||
ap.add_argument("--md", required=True)
|
||||
ap.add_argument("--pdf", required=True)
|
||||
ap.add_argument("--title", default=None)
|
||||
args = ap.parse_args(argv)
|
||||
res = compile_markdown_to_pdf(args.md, args.pdf, title=args.title)
|
||||
print(json.dumps(res, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
Pytest verification suite for hyperstitionstudio-core (hyperstitionstud_io.*).
|
||||
Tests:
|
||||
1. Zero-HTTPS offline namespace & HTML portability (urn:io:hyperstitionstud:*).
|
||||
2. Base-36 AQ, Prime Rank, and G1-G6 vector parity across all 190 bilingual specimens.
|
||||
3. Offline CMUdict phonetics fallback (zero --workdir dependency).
|
||||
4. ReadOnlyIsolationGuard SHA-256 verification on glossary-registry.json & encyclopedia-manifest.json.
|
||||
5. Local-config citation URL resolution ([citations.path_mounts]) and verify_draft() across all 5 proposals.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from hyperstitionstud_io.ciphers import (
|
||||
assert_zero_d_filter,
|
||||
compute_aq,
|
||||
evaluate_bidirectional_lock,
|
||||
is_repdigit_37,
|
||||
prime_rank,
|
||||
)
|
||||
from hyperstitionstud_io.ci.citation_sources import (
|
||||
load_ledger,
|
||||
resolve_citation_target,
|
||||
verify_draft,
|
||||
)
|
||||
from hyperstitionstud_io.ci.doctor import run_diagnostics
|
||||
from hyperstitionstud_io.config import load_workspace_config
|
||||
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard
|
||||
from hyperstitionstud_io.graph import URN_GRAPH_NS, make_entity_urn
|
||||
from hyperstitionstud_io.phonetics import translate_batch
|
||||
|
||||
|
||||
def test_offline_urn_namespaces_and_no_external_https_fonts() -> None:
|
||||
assert URN_GRAPH_NS == "urn:io:hyperstitionstud:ns:kg:1.0"
|
||||
assert make_entity_urn("zoology", "build", "S1") == "urn:io:hyperstitionstud:zoology:build:S1"
|
||||
|
||||
cfg = load_workspace_config()
|
||||
for html_p in (
|
||||
cfg.knowledge_graph_dir / "index.html",
|
||||
cfg.knowledge_graph_dir / "docs" / "cross-repo-dependency-and-audit-flow-diagram.html",
|
||||
):
|
||||
txt = html_p.read_text(encoding="utf-8")
|
||||
assert "fonts.googleapis.com" not in txt
|
||||
assert "https://hyperstitionstud.io" not in txt
|
||||
|
||||
schemas_dir = cfg.core_dir / "schemas" / "v1"
|
||||
for sp in schemas_dir.glob("*.schema.json"):
|
||||
s_obj = json.loads(sp.read_text(encoding="utf-8"))
|
||||
assert s_obj["$id"].startswith("urn:io:hyperstitionstud:schema:v1:")
|
||||
assert "https://hyperstitionstud.io" not in sp.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_ciphers_and_bilingual_ledger_parity() -> None:
|
||||
cfg = load_workspace_config()
|
||||
gl_path = cfg.zoology_dir / "taxonomy" / "glossary-registry.json"
|
||||
gl_data = json.loads(gl_path.read_text(encoding="utf-8"))
|
||||
for item in gl_data["bilingual_vocabulary_ledger"]:
|
||||
lock = evaluate_bidirectional_lock(item["eng"], item["ing"])
|
||||
assert lock["eng_aq"] == item["eng_aq"]
|
||||
assert lock["ing_aq"] == item["ing_aq"]
|
||||
assert lock["delta"] == item["delta"]
|
||||
assert lock["isometric"] == item["isometric"]
|
||||
assert lock["twin_prime_mutation"] == item["twin_prime"]
|
||||
assert compute_aq("Dario Amodei") == 193
|
||||
assert prime_rank(193) == 44
|
||||
assert is_repdigit_37(333) and is_repdigit_37(666) and is_repdigit_37(777)
|
||||
assert_zero_d_filter("Pure Base-36 Alphanumeric Qabbala")
|
||||
|
||||
|
||||
def test_offline_phonetics_fallback_zero_workdir() -> None:
|
||||
res = translate_batch(
|
||||
["schizoanalysis", "abstract machine", "synthetic data", "Anthropic", "flash crash", "Blackwell"],
|
||||
workdir="/nonexistent/offline/path",
|
||||
)
|
||||
assert res["schizoanalysis"] == "shizohnalizis"
|
||||
assert res["abstract machine"] == "abstrakt masheen"
|
||||
assert res["synthetic data"] == "sinthetik dayta"
|
||||
assert res["Anthropic"] == "anthropik"
|
||||
assert res["flash crash"] == "flash krash"
|
||||
assert res["Blackwell"] == "blakwel"
|
||||
|
||||
|
||||
def test_read_only_isolation_guard() -> None:
|
||||
cfg = load_workspace_config()
|
||||
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
|
||||
_ = [p.stat().st_size for p in cfg.read_only_files]
|
||||
receipt = guard.audit_receipt()
|
||||
assert receipt["all_unchanged"] is True
|
||||
|
||||
|
||||
def test_local_config_citation_resolution_and_proposals() -> None:
|
||||
mounts = {
|
||||
"/workspace/ingglish-hyperdope-gematria": "https://git.libre.audio/m00t/ingglish-hyperdope-gematria/src/branch/main"
|
||||
}
|
||||
# Mapped prefix resolves to configured remote URL
|
||||
u1 = resolve_citation_target(
|
||||
"/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/70-dossier-news-2026-11-28.md",
|
||||
path_mounts=mounts,
|
||||
)
|
||||
assert u1 == "https://git.libre.audio/m00t/ingglish-hyperdope-gematria/src/branch/main/ingglish-aq-archive/70-dossier-news-2026-11-28.md"
|
||||
|
||||
# Unmapped prefix NEVER resolves to a global namespace URL; stays local filesystem path
|
||||
u2 = resolve_citation_target(
|
||||
"/workspace/technocapital-singularity-zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md",
|
||||
path_mounts=mounts,
|
||||
)
|
||||
assert u2 == "/workspace/technocapital-singularity-zoology/dossiers/65-dossier-technocapital-singularity-autoregressive-ai.md"
|
||||
|
||||
cfg = load_workspace_config()
|
||||
common_sources = load_ledger(cfg.zoology_dir / "taxonomy" / "citations-ledger-common.json")["sources"]
|
||||
for fname in (
|
||||
"proposal-fantasy-football-technocapital-roster-engine.md",
|
||||
"proposal-corporate-board-technocapital-allocation.md",
|
||||
"proposal-fund-manager-novel-investment-discovery.md",
|
||||
):
|
||||
code, errors, _ = verify_draft(cfg.zoology_dir / fname, common_sources, require_evidence=True)
|
||||
assert code == 0, f"{fname} failed: {errors}"
|
||||
|
||||
eng_sources = load_ledger(cfg.zoology_dir / "taxonomy" / "citations-ledger-english-aq.json")["sources"]
|
||||
for fname in (
|
||||
"proposal-corporate-board-standard-english-aq.md",
|
||||
"proposal-fund-manager-standard-english-aq.md",
|
||||
):
|
||||
code, errors, _ = verify_draft(cfg.zoology_dir / fname, eng_sources, require_evidence=True)
|
||||
assert code == 0, f"{fname} failed: {errors}"
|
||||
|
||||
|
||||
def test_doctor_all_checks_pass() -> None:
|
||||
diag = run_diagnostics()
|
||||
assert diag["all_checks_passed"] is True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_offline_urn_namespaces_and_no_external_https_fonts()
|
||||
print("[PASS] test_offline_urn_namespaces_and_no_external_https_fonts")
|
||||
test_ciphers_and_bilingual_ledger_parity()
|
||||
print("[PASS] test_ciphers_and_bilingual_ledger_parity")
|
||||
test_offline_phonetics_fallback_zero_workdir()
|
||||
print("[PASS] test_offline_phonetics_fallback_zero_workdir")
|
||||
test_read_only_isolation_guard()
|
||||
print("[PASS] test_read_only_isolation_guard")
|
||||
test_local_config_citation_resolution_and_proposals()
|
||||
print("[PASS] test_local_config_citation_resolution_and_proposals")
|
||||
test_doctor_all_checks_pass()
|
||||
print("[PASS] test_doctor_all_checks_pass")
|
||||
print("ALL 6 TEST SUITES PASSED.")
|
||||
@@ -0,0 +1,23 @@
|
||||
# workspace.example.toml — Template for /workspace/workspace.toml or ~/.config/hyperstitionstud.io/workspace.toml
|
||||
schema_version = "1.2.0"
|
||||
namespace_urn = "urn:io:hyperstitionstud"
|
||||
|
||||
[paths]
|
||||
core_dir = "/workspace/hyperstitionstudio-core"
|
||||
archive_dir = "/workspace/ingglish-hyperdope-gematria"
|
||||
zoology_dir = "/workspace/technocapital-singularity-zoology"
|
||||
knowledge_graph_dir = "/workspace/encyclopedia-knowledge-graph"
|
||||
ci_build_dir = "/workspace/hyperdope-ci-build"
|
||||
gematria_js_dir = "/workspace/hyperdope-gematria"
|
||||
memes_dir = "/workspace/memes"
|
||||
|
||||
[isolation]
|
||||
read_only_files = [
|
||||
"/workspace/technocapital-singularity-zoology/taxonomy/glossary-registry.json",
|
||||
"/workspace/technocapital-singularity-zoology/encyclopedia/encyclopedia-manifest.json",
|
||||
]
|
||||
|
||||
[citations.path_mounts]
|
||||
# Map local repository prefixes to remote viewer URLs only when desired.
|
||||
# Unlisted paths remain verified local filesystem paths (/workspace/...).
|
||||
"/workspace/ingglish-hyperdope-gematria" = "https://git.libre.audio/m00t/ingglish-hyperdope-gematria/src/branch/main"
|
||||
Reference in new issue
Block a user