feat(v2.0.8): implement ipld dag-json/CIDv1, quant financial collector, MCP server (hs-mcp), /learn/ sub-page, /gallery/ sub-page, and global Lemurs footer

This commit is contained in:
Hermes Agent committed 2026-11-30 03:39:56 +00:00
1 parent b767f8a4e9
commit c17f74097b
55 files changed
+3974 -10

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
"""
hyperstitionstud_io.ipld — Canonical IPLD dag-json (multicodec 0x0129) Encoder, CIDv1 Generator
& Zero-Drift Pretty-Print / dag-json Atomic Writer.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
from pathlib import Path
from typing import Any
# CIDv1 (0x01) + dag-json multicodec (0x0129 -> varint 0xa9 0x02) + sha2-256 (0x12) + 32-byte length (0x20)
_CIDV1_DAG_JSON_SHA256_PREFIX = bytes([0x01, 0xA9, 0x02, 0x12, 0x20])
def encode_dag_json(obj: Any) -> bytes:
"""Serialize a Python data structure to canonical IPLD dag-json UTF-8 bytes."""
return json.dumps(
obj,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
).encode("utf-8")
def compute_dag_json_sha256(obj: Any) -> str:
"""Return the lowercase hex SHA-256 digest of the canonical dag-json byte representation."""
return hashlib.sha256(encode_dag_json(obj)).hexdigest()
def compute_dag_json_cidv1(obj: Any) -> str:
"""Compute the multibase Base32lower CIDv1 ('baguqeera...') for an object encoded as dag-json (0x0129)."""
raw_bytes = encode_dag_json(obj)
digest = hashlib.sha256(raw_bytes).digest()
cid_bytes = _CIDV1_DAG_JSON_SHA256_PREFIX + digest
b32 = base64.b32encode(cid_bytes).decode("ascii").lower().rstrip("=")
return "b" + b32
def make_ipld_link(cid_str: str) -> dict[str, str]:
"""Return an IPLD dag-json Link object {'/': '<cid>'}."""
return {"/": cid_str}
def inspect_dag_json_payload(obj: Any) -> dict[str, Any]:
raw = encode_dag_json(obj)
sha = hashlib.sha256(raw).hexdigest()
cid = compute_dag_json_cidv1(obj)
return {
"codec": "dag-json",
"multicodec_hex": "0x0129",
"canonical_bytes": len(raw),
"sha256": sha,
"cidv1": cid,
"ipld_link": {"/": cid},
}
def write_pretty_and_dag_json(
pretty_path: str | Path,
obj: Any,
dag_sidecar_path: str | Path | None = None,
) -> dict[str, Any]:
"""
Atomically write both a human-readable pretty-printed JSON file (indent=2) and (optionally)
its canonical IPLD dag-json sidecar from the same validated canonical representation,
guaranteeing zero drift between the two files.
"""
p_pretty = Path(pretty_path).resolve()
p_pretty.parent.mkdir(parents=True, exist_ok=True)
dag_bytes = encode_dag_json(obj)
canonical_obj = json.loads(dag_bytes.decode("utf-8"))
pretty_bytes = (json.dumps(canonical_obj, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
tmp_pretty = p_pretty.with_suffix(p_pretty.suffix + f".tmp.{os.getpid()}")
tmp_pretty.write_bytes(pretty_bytes)
os.replace(tmp_pretty, p_pretty)
if dag_sidecar_path is not None:
p_dag = Path(dag_sidecar_path).resolve()
p_dag.parent.mkdir(parents=True, exist_ok=True)
tmp_dag = p_dag.with_suffix(p_dag.suffix + f".tmp.{os.getpid()}")
tmp_dag.write_bytes(dag_bytes + b"\n")
os.replace(tmp_dag, p_dag)
return inspect_dag_json_payload(canonical_obj)
+8
View File
@@ -0,0 +1,8 @@
"""
hyperstitionstud_io.mcp — Model Context Protocol (MCP) Server for hyperstitionstud.io.
Supports MCP 2025-03-26 & 2024-11-05 over both stdio and stateless Streamable HTTP (/mcp).
"""
from hyperstitionstud_io.mcp.server import dispatch_jsonrpc, main
__all__ = ["dispatch_jsonrpc", "main"]
+90
View File
@@ -0,0 +1,90 @@
"""
hyperstitionstud_io.mcp.prompts — Guided Workflow Prompts for MCP Clients.
"""
from __future__ import annotations
from typing import Any
MCP_PROMPTS: list[dict[str, Any]] = [
{
"name": "analyze_headline_zoology",
"description": "Extract tokens from a news headline or financial event, evaluate Gen 0 -> Gen 1 Ingglish AQ locks, check Two-Gate M1-M7+ activation, and synthesize a zero-padding Technocapital Singularity analysis.",
"arguments": [
{"name": "headline", "description": "Headline or event description to analyze.", "required": True},
],
},
{
"name": "draft_stakeholder_proposal_section",
"description": "Draft an evidence-grounded section for a Fund Manager, Corporate Board, or Fantasy Roster stakeholder using native register metrics and verified citation ledger IDs.",
"arguments": [
{"name": "audience", "description": "Target register: fund_manager, corporate_board, or fantasy_football.", "required": True},
{"name": "focus_guild", "description": "Target guild/build, e.g. S1, S2, S3, S6, M1, or M7+.", "required": False},
],
},
{
"name": "trace_knowledge_graph_bridge",
"description": "Trace how two concepts, specimens, or guilds connect across the 13 Multi-Build Flex Singularities and 333/666/777 attractors in the Encyclopedia Knowledge Graph.",
"arguments": [
{"name": "start_query", "description": "Starting node query (e.g. 'Blackwell' or '125').", "required": True},
{"name": "target_query", "description": "Target node query (e.g. 'Anthropic' or 'S6').", "required": True},
],
},
{
"name": "pokedex_field_scanner_card",
"description": "Format a Technocapital Singularity specimen or emergent M7+ coordinate hub as a Gen IV INFO Pokedex field-scanner card.",
"arguments": [
{"name": "specimen_or_coord", "description": "Specimen name or integer AQ coordinate (e.g. '129' or 'M7+').", "required": True},
],
},
]
def get_mcp_prompt(name: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:
args = arguments or {}
if name == "analyze_headline_zoology":
hl = args.get("headline", "<headline>")
text = (
f"Analyze the following headline under the Technocapital Singularity Zoology framework:\n"
f"Headline: \"{hl}\"\n\n"
"Step 1: Call `hs_evaluate_aq_and_ingglish` and `hs_classify_singularity` on the core nouns, verbs, and entities in the headline.\n"
"Step 2: Check for G1 Variance-Collapse Triads (Gen 0 dispersion -> Gen 1 exact equivalence), G2 Cross-Gen Twins, and G4 Isometric Chokepoints (Δ = 0).\n"
"Step 3: Check whether both Machinic Phylum (S1-S5) and Apparatus of Capture (S6) are co-present (Double Articulation), and unlock an M1-M6 memetic subclass ONLY if the headline's observable thermodynamic state matches.\n"
"Step 4: Call `hs_search_archive_equations` to ground the analysis in verified 333/666/777 equations with 0.0% generic padding."
)
elif name == "draft_stakeholder_proposal_section":
aud = args.get("audience", "fund_manager")
fg = args.get("focus_guild", "all")
text = (
f"Draft a stakeholder analysis section for audience='{aud}' focusing on build='{fg}':\n"
f"Step 1: Call `hs_inspect_eti_tier_list` with `register='{aud}'` and `build_filter='{fg}'`.\n"
"Step 2: Omit French philosophical jargon (Deleuze, Guattari, Body without Organs, Schizoanalysis) and cite only concrete tech/finance nouns from each equivalence ring (e.g. synthetic data == asset management = 292, capital == capture = 125, ASML == asset = 81, TSMC == loss = 91).\n"
"Step 3: Ground all claims with inline [n] citations verified via `hs_verify_grounded_citations`."
)
elif name == "trace_knowledge_graph_bridge":
s_q = args.get("start_query", "125")
t_q = args.get("target_query", "193")
text = (
f"Trace the topological bridge between '{s_q}' and '{t_q}' in the Encyclopedia Knowledge Graph:\n"
f"Step 1: Call `hs_query_knowledge_graph` for '{s_q}' and for '{t_q}'.\n"
"Step 2: Identify shared AQCoordinateHub nodes, 13-Flex Pivots (292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91/81), and 333/666/777 repdigit attractors connecting their 1-hop ego networks."
)
elif name == "pokedex_field_scanner_card":
spec = args.get("specimen_or_coord", "129")
text = (
f"Synthesize a Gen IV INFO Pokedex field-scanner card for '{spec}':\n"
f"Step 1: Call `hs_query_knowledge_graph` with `query='{spec}'` and `hs_inspect_eti_tier_list`.\n"
"Step 2: Output the Pokedex header (Dex #, Taxon Class S1-S6 / M1-M7+, ETI Tier S+..D), the 6-stat telemetry bar (ARM, VEL, COL, CAP, PRM, RES), the G1 Variance-Collapse equation, and the 3-line field scanner entry."
)
else:
raise ValueError(f"Unknown MCP prompt: {name}")
return {
"description": f"Guided prompt for {name}",
"messages": [
{
"role": "user",
"content": {"type": "text", "text": text},
}
],
}
+134
View File
@@ -0,0 +1,134 @@
"""
hyperstitionstud_io.mcp.resources — Static & Template URN Resources for MCP Clients.
"""
from __future__ import annotations
import json
import re
from typing import Any
from hyperstitionstud_io.config import load_workspace_config
STATIC_RESOURCES: list[dict[str, str]] = [
{
"uri": "urn:io:hyperstitionstud:resource:glossary-registry",
"name": "Comprehensive Glossary & Bilingual Ledger (v1.6.0, 282 Entries)",
"mimeType": "application/json",
"description": "Canonical 282-entry Glossary & 190-specimen Bilingual Vocabulary Ledger.",
},
{
"uri": "urn:io:hyperstitionstud:resource:encyclopedia-manifest",
"name": "22-Volume PDF Encyclopedia Manifest (v1.7.0, 122 Pages)",
"mimeType": "application/json",
"description": "Manifest of the 9 Ontological Divisions (00-08) and 22 Alphabetized PDF Volumes.",
},
{
"uri": "urn:io:hyperstitionstud:resource:eti-tier-list",
"name": "Assemblage Builds Ecological Trophic Index (ETI v2.0.0) Tier List",
"mimeType": "application/json",
"description": "9 Taxon Assemblage Builds ranked S+ to D/F across 6 zoological base stats.",
},
{
"uri": "urn:io:hyperstitionstud:resource:singularity-matrix",
"name": "Technocapital Singularity Zoology Matrix (S1-S6)",
"mimeType": "application/json",
"description": "Six-Class Landian-Deleuzean Singularity Taxonomy and signature coordinate rings.",
},
{
"uri": "urn:io:hyperstitionstud:resource:memetic-registry",
"name": "State-Gated Memetic Superclass Registry (M1-M6 & Emergent M7+)",
"mimeType": "application/json",
"description": "Two-Gate state-matched memetic subclasses and M7_candidate_2026_11_28 nucleation telemetry.",
},
{
"uri": "urn:io:hyperstitionstud:resource:quantitative-anchors",
"name": "Quantitative Economic Anchors Registry",
"mimeType": "application/json",
"description": "Registered quantitative anchors ($6B Lazarus heist, $83 Anthropic IPO, 481 halted factories).",
},
{
"uri": "urn:io:hyperstitionstud:resource:knowledge-graph-summary",
"name": "Encyclopedia Knowledge Graph Summary (388 Nodes, 1,282 Edges)",
"mimeType": "application/json",
"description": "Node/edge ontology counts, top 15 AQ coordinate hubs by degree, and SHA-256 isolation receipt.",
},
]
RESOURCE_TEMPLATES: list[dict[str, str]] = [
{
"uriTemplate": "urn:io:hyperstitionstud:dossier:{dossier_number}",
"name": "Canonical Archive or Zoology Dossier by Number (01..71)",
"mimeType": "text/markdown",
"description": "Read the full Markdown text and verified 333/666/777 equations of Dossier {dossier_number} (e.g. 65..71).",
},
{
"uriTemplate": "urn:io:hyperstitionstud:schema:v1:{schema_slug}",
"name": "Workspace Offline URN JSON Schema (v1)",
"mimeType": "application/schema+json",
"description": "Read a v1 JSON Schema contract (e.g. glossary-registry, encyclopedia-graph, learn-progress-state).",
},
]
def read_mcp_resource(uri: str) -> dict[str, Any]:
cfg = load_workspace_config()
static_map = {
"urn:io:hyperstitionstud:resource:glossary-registry": cfg.zoology_dir / "taxonomy" / "glossary-registry.json",
"urn:io:hyperstitionstud:resource:encyclopedia-manifest": cfg.zoology_dir / "encyclopedia" / "encyclopedia-manifest.json",
"urn:io:hyperstitionstud:resource:eti-tier-list": cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json",
"urn:io:hyperstitionstud:resource:singularity-matrix": cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json",
"urn:io:hyperstitionstud:resource:memetic-registry": cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json",
"urn:io:hyperstitionstud:resource:quantitative-anchors": cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json",
}
if uri in static_map:
p = static_map[uri]
return {
"contents": [
{"uri": uri, "mimeType": "application/json", "text": p.read_text(encoding="utf-8")}
]
}
if uri == "urn:io:hyperstitionstud:resource:knowledge-graph-summary":
kg = json.loads((cfg.knowledge_graph_dir / "encyclopedia-graph.json").read_text(encoding="utf-8"))
summary = {
"version": kg.get("version"),
"namespace_urn": kg.get("namespace_urn"),
"counts": kg.get("counts"),
"isolation_verified": kg.get("isolation_verified"),
"top_coordinate_hubs_by_degree": kg.get("top_coordinate_hubs_by_degree"),
}
return {
"contents": [
{"uri": uri, "mimeType": "application/json", "text": json.dumps(summary, indent=2)}
]
}
m_dos = re.match(r"^urn:io:hyperstitionstud:dossier:(\d+)$", uri)
if m_dos:
num = int(m_dos.group(1))
prefix = f"{num:02d}-"
for d_dir in (cfg.zoology_dir / "dossiers", cfg.archive_dir / "ingglish-aq-archive"):
if d_dir.is_dir():
matches = sorted(d_dir.glob(f"{prefix}*.md"))
if matches:
return {
"contents": [
{"uri": uri, "mimeType": "text/markdown", "text": matches[0].read_text(encoding="utf-8")}
]
}
raise ValueError(f"No dossier found matching number {num:02d}")
m_sch = re.match(r"^urn:io:hyperstitionstud:schema:v1:([a-z0-9-]+)$", uri)
if m_sch:
slug = m_sch.group(1)
sp = cfg.core_dir / "schemas" / "v1" / f"{slug}.schema.json"
if sp.is_file():
return {
"contents": [
{"uri": uri, "mimeType": "application/schema+json", "text": sp.read_text(encoding="utf-8")}
]
}
raise ValueError(f"Unknown schema slug: {slug}")
raise ValueError(f"Unknown MCP resource URI: {uri}")
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""
hyperstitionstud_io.mcp.server — Dual-Transport JSON-RPC 2.0 MCP Server (`hs-mcp`).
Supports:
1. `--transport stdio` (default): newline-delimited JSON-RPC 2.0 over stdin/stdout.
2. `--transport http`: stateless Streamable HTTP JSON-RPC 2.0 on `GET /mcp` and `POST /mcp`.
Enforces ReadOnlyIsolationGuard on every tool call so protected upstream registries never mutate.
"""
from __future__ import annotations
import argparse
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any
_SRC_DIR = Path(__file__).resolve().parents[2]
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
from hyperstitionstud_io.mcp.prompts import MCP_PROMPTS, get_mcp_prompt # noqa: E402
from hyperstitionstud_io.mcp.resources import ( # noqa: E402
RESOURCE_TEMPLATES,
STATIC_RESOURCES,
read_mcp_resource,
)
from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA, call_mcp_tool # noqa: E402
SERVER_INFO = {
"name": "hyperstitionstudio-mcp",
"version": "2.0.0",
"namespace_urn": "urn:io:hyperstitionstud:mcp:2.0.0",
}
def dispatch_jsonrpc(req: dict[str, Any]) -> dict[str, Any] | None:
"""
Process a single JSON-RPC 2.0 request or notification and return the JSON-RPC 2.0 response
(or None for notifications without an 'id').
"""
method = req.get("method", "")
req_id = req.get("id")
params = req.get("params") or {}
if method.startswith("notifications/"):
return None
cfg = load_workspace_config()
try:
with ReadOnlyIsolationGuard(cfg.read_only_files):
if method == "initialize":
client_proto = params.get("protocolVersion", "2024-11-05")
proto = client_proto if client_proto in ("2025-03-26", "2024-11-05") else "2024-11-05"
result: dict[str, Any] = {
"protocolVersion": proto,
"capabilities": {
"tools": {"listChanged": False},
"resources": {"subscribe": False, "listChanged": False},
"prompts": {"listChanged": False},
},
"serverInfo": SERVER_INFO,
}
elif method == "ping":
result = {}
elif method == "tools/list":
result = {"tools": MCP_TOOLS_SCHEMA}
elif method == "tools/call":
t_name = str(params.get("name", ""))
t_args = params.get("arguments") or {}
out = call_mcp_tool(t_name, t_args)
result = {
"content": [
{
"type": "text",
"text": json.dumps(out, indent=2, ensure_ascii=False),
}
],
"isError": False,
}
elif method == "resources/list":
result = {"resources": STATIC_RESOURCES}
elif method == "resources/templates/list":
result = {"resourceTemplates": RESOURCE_TEMPLATES}
elif method == "resources/read":
uri = str(params.get("uri", ""))
result = read_mcp_resource(uri)
elif method == "prompts/list":
result = {"prompts": MCP_PROMPTS}
elif method == "prompts/get":
p_name = str(params.get("name", ""))
p_args = params.get("arguments") or {}
result = get_mcp_prompt(p_name, p_args)
else:
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Method not found: {method}"},
}
except Exception as exc:
if method == "tools/call":
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [{"type": "text", "text": json.dumps({"error": str(exc)})}],
"isError": True,
},
}
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32602, "message": str(exc)},
}
return {"jsonrpc": "2.0", "id": req_id, "result": result}
def run_stdio_server() -> int:
for raw_line in sys.stdin:
line = raw_line.strip()
if not line:
continue
try:
req = json.loads(line)
except json.JSONDecodeError as exc:
err_resp = {
"jsonrpc": "2.0",
"id": None,
"error": {"code": -32700, "message": f"Parse error: {exc}"},
}
sys.stdout.write(json.dumps(err_resp) + "\n")
sys.stdout.flush()
continue
resp = dispatch_jsonrpc(req)
if resp is not None:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
return 0
class _MCPHTTPHandler(BaseHTTPRequestHandler):
def log_message(self, format: str, *args: Any) -> None:
return
def _send_json(self, status: int, payload: Any) -> None:
body = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
self.wfile.write(body)
def do_OPTIONS(self) -> None:
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def do_GET(self) -> None:
manifest = {
"serverInfo": SERVER_INFO,
"protocols": ["2025-03-26", "2024-11-05"],
"transport": "streamable-http",
"endpoints": {"jsonrpc_post": "/mcp", "manifest_get": "/mcp"},
"counts": {
"tools": len(MCP_TOOLS_SCHEMA),
"static_resources": len(STATIC_RESOURCES),
"resource_templates": len(RESOURCE_TEMPLATES),
"prompts": len(MCP_PROMPTS),
},
"tools": [t["name"] for t in MCP_TOOLS_SCHEMA],
"resources": [r["uri"] for r in STATIC_RESOURCES],
"prompts": [p["name"] for p in MCP_PROMPTS],
}
self._send_json(200, manifest)
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
if length <= 0 or length > 65536:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid content length"}})
return
raw = self.rfile.read(length).decode("utf-8")
try:
req = json.loads(raw)
except json.JSONDecodeError as exc:
self._send_json(400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}})
return
resp = dispatch_jsonrpc(req)
if resp is None:
self.send_response(202)
self.end_headers()
return
self._send_json(200, resp)
def run_http_server(host: str, port: int) -> int:
srv = HTTPServer((host, port), _MCPHTTPHandler)
print(f"[hs-mcp] Serving stateless read-only MCP HTTP endpoint on http://{host}:{port}/mcp", flush=True)
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
finally:
srv.server_close()
return 0
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-mcp", description="Model Context Protocol (MCP) Server for hyperstitionstud.io.")
ap.add_argument("--transport", choices=["stdio", "http"], default="stdio", help="Transport mode (default: stdio).")
ap.add_argument("--host", default="127.0.0.1", help="Bind address for HTTP transport (default: 127.0.0.1).")
ap.add_argument("--port", type=int, default=8095, help="Bind port for HTTP transport (default: 8095).")
ap.add_argument("--dump-manifest", action="store_true", help="Print MCP capability manifest as JSON and exit.")
args = ap.parse_args(argv)
if args.dump_manifest:
print(
json.dumps(
{
"serverInfo": SERVER_INFO,
"tools": MCP_TOOLS_SCHEMA,
"resources": STATIC_RESOURCES,
"resourceTemplates": RESOURCE_TEMPLATES,
"prompts": MCP_PROMPTS,
},
indent=2,
)
)
return 0
if args.transport == "http":
return run_http_server(args.host, args.port)
return run_stdio_server()
if __name__ == "__main__":
raise SystemExit(main())
+458
View File
@@ -0,0 +1,458 @@
"""
hyperstitionstud_io.mcp.tools — 10 Deterministic MCP Tools for the hyperstitionstud.io Ecosystem.
All tools execute strictly in read-only mode inside ReadOnlyIsolationGuard.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Any
from hyperstitionstud_io.ci.citation_sources import load_ledger, verify_draft
from hyperstitionstud_io.ci.doctor import run_diagnostics
from hyperstitionstud_io.ciphers import (
compute_aq,
compute_variance,
evaluate_bidirectional_lock,
is_repdigit_37,
prime_rank,
)
from hyperstitionstud_io.config import load_workspace_config
from hyperstitionstud_io.ipld import inspect_dag_json_payload
from hyperstitionstud_io.phonetics import translate_batch
from hyperstitionstud_io.quant.collector import build_financial_quant_harvest
REGISTER_STAT_LABELS = {
"academic": {
"ARM_chokepoint_armor": "ARM (G4 Isometric Chokepoint Armor)",
"VEL_teleoplexic_velocity": "VEL (Teleoplexic Escape Velocity)",
"COL_variance_collapse": "COL (G1 Variance-Collapse Compression)",
"CAP_trophic_capture": "CAP (S×S6 Double-Articulation & Capture)",
"PRM_prime_mutation_iq": "PRM (Prime & G5 Twin-Prime Mutation IQ)",
"RES_repricing_resilience": "RES (Tri-Modal Repricing & State-Gate Resilience)",
},
"fund_manager": {
"ARM_chokepoint_armor": "Chokepoint Moat",
"VEL_teleoplexic_velocity": "Signal Velocity",
"COL_variance_collapse": "Convergence Power",
"CAP_trophic_capture": "Institutional Coupling",
"PRM_prime_mutation_iq": "Idiosyncratic Asymmetry",
"RES_repricing_resilience": "Regime Robustness",
},
"corporate_board": {
"ARM_chokepoint_armor": "Supply-Chain Moat",
"VEL_teleoplexic_velocity": "Execution Agility",
"COL_variance_collapse": "Cross-Unit Synergy",
"CAP_trophic_capture": "Governance & Balance-Sheet Integration",
"PRM_prime_mutation_iq": "Proprietary IP Density",
"RES_repricing_resilience": "Stress-Test Resilience",
},
"fantasy_football": {
"ARM_chokepoint_armor": "Pass Protection",
"VEL_teleoplexic_velocity": "Breakaway Speed",
"COL_variance_collapse": "Stack Power",
"CAP_trophic_capture": "Front-Office Cap Reach",
"PRM_prime_mutation_iq": "Playbook IQ",
"RES_repricing_resilience": "All-Weather Durability",
},
}
MCP_TOOLS_SCHEMA: list[dict[str, Any]] = [
{
"name": "hs_evaluate_aq_and_ingglish",
"description": "Compute Base-36 Alphanumeric Qabbala (AQ), Gen 0 -> Gen 1 CMUdict Ingglish translation, prime ranks, repdigit status, G1 variance collapse, and 12-field bidirectional locks for a list of terms.",
"inputSchema": {
"type": "object",
"properties": {
"terms": {"type": "array", "items": {"type": "string"}, "description": "English words or phrases to evaluate."},
"quant_mode": {"type": "string", "enum": ["digit", "off", "spoken", "dual"], "default": "digit"},
},
"required": ["terms"],
},
},
{
"name": "hs_classify_singularity",
"description": "Classify terms or a headline into Landian-Deleuzean Singularity Classes S1-S6, check S×S6 Double Articulation, and evaluate Two-Gate state-matched M1-M7+ memetic activation.",
"inputSchema": {
"type": "object",
"properties": {
"terms": {"type": "array", "items": {"type": "string"}},
"headline_text": {"type": "string", "default": ""},
},
"required": ["terms"],
},
},
{
"name": "hs_query_knowledge_graph",
"description": "Query the 388-node, 1,282-edge Encyclopedia Knowledge Graph by node ID (e.g. 'build:S1', 'aq:125', 'spec:blackwell'), headword, Ingglish token, or integer AQ coordinate.",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"include_neighbors": {"type": "boolean", "default": True},
},
"required": ["query"],
},
},
{
"name": "hs_search_glossary_encyclopedia",
"description": "Search the 282 canonical glossary entries, 190 bilingual lexical specimens, and 22 Encyclopedia volumes by keyword, guild (S1..S6, M1..M7+), or integer AQ value.",
"inputSchema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"guild_filter": {"type": "string", "default": ""},
"limit": {"type": "integer", "default": 15},
},
"required": ["query"],
},
},
{
"name": "hs_inspect_eti_tier_list",
"description": "Return the Ecological Trophic Index (ETI 0-100) Assemblage Builds Tier List (S+ to D/F), 6-stat scorecards, and 13 Multi-Build Flex Singularities in the requested stakeholder register.",
"inputSchema": {
"type": "object",
"properties": {
"build_filter": {"type": "string", "default": "all"},
"register": {"type": "string", "enum": ["academic", "fund_manager", "corporate_board", "fantasy_football"], "default": "academic"},
},
},
},
{
"name": "hs_simulate_anchor_revision",
"description": "Simulate a Quantitative Economic Anchor Revision (Q_old -> Q_new) across digit and spoken modes, detecting Iso-Digital conservation, S1-S6 ring migrations, and 3-path counter-substitutions.",
"inputSchema": {
"type": "object",
"properties": {
"anchor_id": {"type": "string", "description": "Registered anchor ID (e.g. 'lazarus_heist_6b', 'anthropic_ipo_price_83', 'bangladesh_factories_481')."},
"new_digit_str": {"type": "string", "description": "New quantitative figure string, e.g. '$7B' or '841'."},
"new_spoken_eng": {"type": "string", "description": "Spoken English words for the new figure, e.g. 'seven billion'."},
},
"required": ["anchor_id", "new_digit_str", "new_spoken_eng"],
},
},
{
"name": "hs_search_archive_equations",
"description": "Search all 71 verified archive and zoology dossiers for cross-scale (333 / 666 / 777) equations matching a target sum or keyword.",
"inputSchema": {
"type": "object",
"properties": {
"target_sum": {"type": "integer", "description": "Optional target sum (e.g. 333, 666, 777)."},
"keyword": {"type": "string", "default": ""},
"limit": {"type": "integer", "default": 20},
},
},
},
{
"name": "hs_verify_grounded_citations",
"description": "Verify inline [n] citations, Sources block URLs (via local-config path_mounts), and verbatim evidence quotes in a Markdown draft against a citation ledger.",
"inputSchema": {
"type": "object",
"properties": {
"draft_path": {"type": "string"},
"ledger_variant": {"type": "string", "enum": ["common", "english_aq"], "default": "common"},
"require_evidence": {"type": "boolean", "default": True},
},
"required": ["draft_path"],
},
},
{
"name": "hs_compute_ipld_dag_json_cid",
"description": "Serialize a named workspace JSON registry or custom JSON object under the canonical IPLD dag-json (0x0129) codec and compute its SHA-256 digest and Base32 CIDv1 ('baguqeera...').",
"inputSchema": {
"type": "object",
"properties": {
"registry_name": {
"type": "string",
"description": "Optional workspace registry slug: 'glossary-registry', 'encyclopedia-manifest', 'singularity-zoology-matrix', 'memetic-superclass-registry', 'assemblage-builds-tier-list', 'quantitative-economic-anchors', or 'encyclopedia-graph'.",
},
"json_object": {"type": "object", "description": "Optional arbitrary JSON object to encode as dag-json."},
},
},
},
{
"name": "hs_run_doctor_and_audit",
"description": "Run hs-doctor environment/font/CMUdict diagnostics and verify ReadOnlyIsolationGuard SHA-256 locks across the workspace.",
"inputSchema": {
"type": "object",
"properties": {},
},
},
{
"name": "hs_scan_financial_quant_harvest",
"description": "Harvest or evaluate the 24-instrument S1-S6 quantitative financial telemetry watchlist for Scope 1-3 contingent meaning locks, M1-M6 regime triggers, and IPLD dag-json CIDv1 provenance.",
"inputSchema": {
"type": "object",
"properties": {
"harvest_mode": {"type": "string", "enum": ["us-closing-bell", "utc-rollover"], "default": "us-closing-bell"},
"symbol_filter": {"type": "string", "default": "", "description": "Optional ticker symbol filter (e.g. 'NVDA', 'ASML', 'BTC-USD')."},
},
},
},
]
def call_mcp_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
cfg = load_workspace_config()
if name == "hs_evaluate_aq_and_ingglish":
terms = [str(t) for t in arguments.get("terms", [])]
qmode = arguments.get("quant_mode", "digit")
ing_map = translate_batch(terms)
items = []
for t in terms:
ing = ing_map.get(t, t.lower())
lock = evaluate_bidirectional_lock(t, ing)
if qmode in ("off", "spoken", "dual"):
lock["eng_aq_quant_mode"] = compute_aq(t, quant_mode="off" if qmode == "off" else "spoken")
lock["ing_aq_quant_mode"] = compute_aq(ing, quant_mode="off" if qmode == "off" else "spoken")
lock["is_repdigit_37_ing"] = is_repdigit_37(lock["ing_aq"])
items.append(lock)
gen0_var = compute_variance([x["eng_aq"] for x in items])
gen1_var = compute_variance([x["ing_aq"] for x in items])
return {
"term_count": len(items),
"gen0_written_variance": gen0_var,
"gen1_ingglish_variance": gen1_var,
"variance_collapsed_g1": round(gen0_var - gen1_var, 2),
"exact_gen1_singularity": (len(items) >= 2 and gen1_var == 0.0),
"evaluations": items,
}
if name == "hs_classify_singularity":
terms = [str(t) for t in arguments.get("terms", [])]
headline = str(arguments.get("headline_text", "")).lower()
mat = json.loads((cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json").read_text(encoding="utf-8"))
mem = json.loads((cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json").read_text(encoding="utf-8"))
ing_map = translate_batch(terms)
classified = []
guilds_hit: set[str] = set()
for t in terms:
ing = ing_map.get(t, t.lower())
lock = evaluate_bidirectional_lock(t, ing)
matched_classes = []
for cid, cobj in mat.get("classes", {}).items():
sig_coords = set(cobj.get("signature_coordinates", []))
kw_set = {k.lower() for k in cobj.get("keywords", [])}
if t.lower() in kw_set or lock["ing_aq"] in sig_coords:
matched_classes.append(cid)
guilds_hit.add(cid)
lock["matched_classes"] = matched_classes or ["UNCLASSIFIED"]
classified.append(lock)
machinic_hit = bool(guilds_hit & {"S1", "S2", "S3", "S4", "S5"})
capture_hit = "S6" in guilds_hit
active_memetic = []
for mid, mobj in mem.get("canonical_subclasses", {}).items():
triggers = [tr.lower() for tr in mobj.get("state_gate_triggers", [])]
if any(tr in headline for tr in triggers) or any(any(tr in t.lower() for tr in triggers) for t in terms):
active_memetic.append({"id": mid, "name": mobj.get("name"), "thermodynamic_state": mobj.get("thermodynamic_state")})
return {
"guilds_activated": sorted(guilds_hit),
"double_articulated_s_x_s6": (machinic_hit and capture_hit),
"state_gated_memetic_subclasses": active_memetic,
"classified_terms": classified,
}
if name == "hs_query_knowledge_graph":
q = str(arguments.get("query", "")).strip().lower()
inc_nbr = bool(arguments.get("include_neighbors", True))
kg_path = cfg.knowledge_graph_dir / "encyclopedia-graph.json"
kg = json.loads(kg_path.read_text(encoding="utf-8"))
matches = []
for n in kg["nodes"]:
if (
n["id"].lower() == q
or q in n["label"].lower()
or q == str(n.get("ing_aq", ""))
or q == str(n.get("aq_value", ""))
or q == (n.get("eng", "") or "").lower()
or q == (n.get("ing", "") or "").lower()
):
matches.append(n)
if not matches:
return {"query": q, "match_count": 0, "matched_node_ids": [], "primary_node": None}
primary = matches[0]
nid = primary["id"]
incident = []
if inc_nbr:
incident = [
{"relation": e["relation"], "source": e["source"], "target": e["target"], "label": e["label"], "weight": e["weight"]}
for e in kg["edges"]
if e["source"] == nid or e["target"] == nid
]
return {
"query": q,
"match_count": len(matches),
"matched_node_ids": [m["id"] for m in matches[:25]],
"primary_node": primary,
"incident_edge_count": len(incident),
"sample_incident_edges": incident[:25],
}
if name == "hs_search_glossary_encyclopedia":
q = str(arguments.get("query", "")).strip().lower()
g_filt = str(arguments.get("guild_filter", "")).strip().upper()
limit = int(arguments.get("limit", 15))
gl = json.loads((cfg.zoology_dir / "taxonomy" / "glossary-registry.json").read_text(encoding="utf-8"))
hits = []
for sec in gl.get("sections", []):
for ent in sec.get("entries", []):
if q in ent["term"].lower() or q in ent["definition"].lower() or q == str(ent.get("ing_aq", "")):
hits.append({"type": "ConceptualEntry", "section": sec["section_title"], **ent})
for ent in gl.get("custom_entries", []):
if q in ent["term"].lower() or q in ent["definition"].lower() or q == str(ent.get("ing_aq", "")):
hits.append({"type": "CustomEntry", "section": "8B", **ent})
for spec in gl.get("bilingual_vocabulary_ledger", []):
if g_filt and g_filt not in spec.get("classes", []):
continue
if (
not q
or q in spec["eng"].lower()
or q in spec["ing"].lower()
or q == str(spec["ing_aq"])
or q == str(spec["eng_aq"])
):
hits.append({"type": "BilingualSpecimen", **spec})
return {"query": q, "guild_filter": g_filt, "total_matches": len(hits), "results": hits[:limit]}
if name == "hs_inspect_eti_tier_list":
b_filt = str(arguments.get("build_filter", "all")).strip().upper()
reg = str(arguments.get("register", "academic")).strip().lower()
tl = json.loads((cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json").read_text(encoding="utf-8"))
labels = REGISTER_STAT_LABELS.get(reg, REGISTER_STAT_LABELS["academic"])
rows = []
for r in tl.get("rows", []):
if b_filt not in ("ALL", "") and b_filt not in r["eval_num"].upper() and b_filt not in r["title"].upper():
continue
translated_stats = {labels.get(k, k): v for k, v in r.get("stats_6", {}).items()}
rows.append({
"rank": r["rank"],
"eval_num": r["eval_num"],
"title": r["title"],
"tier_band": r["tier_Band"],
"eti_score": r["curve_score"],
"roster_slot": r["roster_slot"],
"double_articulated": r["double_articulated"],
"gen0_var_collapsed": r["gen0_var_collapsed"],
"translated_stats_6": translated_stats,
"full_lock1": r["full_lock1"],
"full_lock2": r["full_lock2"],
"trophic_bridges": r["trophic_bridges"],
})
return {
"register": reg,
"build_count": len(rows),
"multi_build_flex_coordinates": [292, 256, 211, 193, 183, 153, 137, 136, 133, 125, 96, 95, 91, 81],
"builds": rows,
}
if name == "hs_simulate_anchor_revision":
aid = str(arguments.get("anchor_id", "")).strip()
new_dig = str(arguments.get("new_digit_str", "")).strip()
new_sp_eng = str(arguments.get("new_spoken_eng", "")).strip()
anc_data = json.loads((cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json").read_text(encoding="utf-8"))
anchor = next((a for a in anc_data.get("anchors", []) if a["anchor_id"] == aid), None)
if anchor is None:
return {"error": f"Unknown anchor_id '{aid}'", "available_anchors": [a["anchor_id"] for a in anc_data.get("anchors", [])]}
old_dig_aq = compute_aq(re.sub(r"[^0-9]", "", anchor["q_digit"]))
new_dig_aq = compute_aq(re.sub(r"[^0-9]", "", new_dig))
old_sp_ing = anchor["q_spoken_ing"]
new_sp_ing = translate_batch([new_sp_eng]).get(new_sp_eng, new_sp_eng.lower())
old_sp_aq = compute_aq(old_sp_ing)
new_sp_aq = compute_aq(new_sp_ing)
d_dig = new_dig_aq - old_dig_aq
d_sp = new_sp_aq - old_sp_aq
return {
"anchor_id": aid,
"entity": anchor["entity"],
"old_digit": {"str": anchor["q_digit"], "aq": old_dig_aq},
"new_digit": {"str": new_dig, "aq": new_dig_aq, "delta_q": d_dig, "iso_digital_conserved": d_dig == 0},
"old_spoken": {"eng": anchor["q_spoken_eng"], "ing": old_sp_ing, "aq": old_sp_aq, "prime_rank": prime_rank(old_sp_aq)},
"new_spoken": {"eng": new_sp_eng, "ing": new_sp_ing, "aq": new_sp_aq, "delta_q": d_sp, "prime_rank": prime_rank(new_sp_aq)},
"counter_substitution_required_delta": {"digit_mode_slot_shift": -d_dig, "spoken_mode_slot_shift": -d_sp},
"quant_free_invariant_equations": anchor.get("quant_free_lexical_equations", []),
}
if name == "hs_search_archive_equations":
t_sum = arguments.get("target_sum")
kw = str(arguments.get("keyword", "")).strip().lower()
limit = int(arguments.get("limit", 20))
eqs = []
for d_dir in (cfg.zoology_dir / "dossiers", cfg.archive_dir / "ingglish-aq-archive"):
if not d_dir.is_dir():
continue
for md_f in sorted(d_dir.glob("*.md")):
txt = md_f.read_text(encoding="utf-8")
for m in re.finditer(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`', txt):
ing_s, eng_s, brk_s, val_s = m.group(1).strip(), m.group(2).strip(), m.group(3).strip(), int(m.group(4))
if t_sum is not None and val_s != int(t_sum):
continue
if kw and kw not in ing_s.lower() and kw not in eng_s.lower() and kw not in md_f.name.lower():
continue
eqs.append({"ing": ing_s, "eng": eng_s, "breakdown": brk_s, "target": val_s, "dossier": md_f.name})
if len(eqs) >= limit:
break
if len(eqs) >= limit:
break
return {"match_count": len(eqs), "equations": eqs[:limit]}
if name == "hs_verify_grounded_citations":
dp = Path(str(arguments.get("draft_path", "")))
if not dp.is_absolute():
dp = cfg.zoology_dir / dp
variant = str(arguments.get("ledger_variant", "common"))
req_ev = bool(arguments.get("require_evidence", True))
l_name = "citations-ledger-english-aq.json" if variant == "english_aq" else "citations-ledger-common.json"
l_path = cfg.zoology_dir / "taxonomy" / l_name
sources = load_ledger(l_path)["sources"]
code, errors, warnings = verify_draft(dp, sources, require_evidence=req_ev)
return {
"draft_path": str(dp),
"ledger_path": str(l_path),
"passed": code == 0,
"exit_code": code,
"errors": errors,
"warnings": warnings,
}
if name == "hs_compute_ipld_dag_json_cid":
reg_name = arguments.get("registry_name")
if reg_name:
reg_map = {
"glossary-registry": cfg.zoology_dir / "taxonomy" / "glossary-registry.json",
"encyclopedia-manifest": cfg.zoology_dir / "encyclopedia" / "encyclopedia-manifest.json",
"singularity-zoology-matrix": cfg.zoology_dir / "taxonomy" / "singularity-zoology-matrix.json",
"memetic-superclass-registry": cfg.zoology_dir / "taxonomy" / "memetic-superclass-registry.json",
"assemblage-builds-tier-list": cfg.zoology_dir / "taxonomy" / "assemblage-builds-tier-list.json",
"quantitative-economic-anchors": cfg.zoology_dir / "taxonomy" / "quantitative-economic-anchors.json",
"encyclopedia-graph": cfg.knowledge_graph_dir / "encyclopedia-graph.json",
}
p = reg_map.get(str(reg_name))
if p is None or not p.is_file():
return {"error": f"Unknown registry_name '{reg_name}'", "available": sorted(reg_map.keys())}
raw_bytes = p.read_bytes()
obj = json.loads(raw_bytes.decode("utf-8"))
info = inspect_dag_json_payload(obj)
info["registry_name"] = reg_name
info["source_path"] = str(p)
return info
obj = arguments.get("json_object", {})
return inspect_dag_json_payload(obj)
if name == "hs_run_doctor_and_audit":
return run_diagnostics()
if name == "hs_scan_financial_quant_harvest":
h_mode = str(arguments.get("harvest_mode", "us-closing-bell"))
sym_f = str(arguments.get("symbol_filter", "")).strip().upper()
payload = build_financial_quant_harvest(harvest_mode=h_mode)
if sym_f:
payload["instruments"] = [x for x in payload["instruments"] if sym_f in x["symbol"].upper() or sym_f in x["entity_eng"].upper()]
return payload
raise ValueError(f"Unknown MCP tool: {name}")
+11
View File
@@ -0,0 +1,11 @@
"""
hyperstitionstud_io.quant — Periodic Quantitative Financial Telemetry & Contingent Meaning Engine.
"""
from hyperstitionstud_io.quant.collector import (
CANONICAL_WATCHLIST_24,
build_financial_quant_harvest,
main,
)
__all__ = ["CANONICAL_WATCHLIST_24", "build_financial_quant_harvest", "main"]
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""
hyperstitionstud_io.quant.collector — Periodic Quantitative Financial Telemetry & Contingent Meaning Collector (`hs-quant-harvest`).
Evaluates quantitative financial telemetry across 3 anti-pareidolia contingent meaning scopes:
1. Scope 1 (Intra-Instrument Self-Lock): Entity/Ticker AQ locks or closes 333/666/777 with its own price, cap, or bps move.
2. Scope 2 (Causal S1-S6 Supply-Chain Ring Migration): Repriced metric migrates across S1-S6 signature coordinates.
3. Scope 3 (Objective Numerical State-Gate Activation): VIX, drawdown %, volume ratio, and cap thresholds trigger M1-M6.
"""
from __future__ import annotations
import argparse
import datetime
import json
import os
import sys
import time
from pathlib import Path
from typing import Any
_SRC_DIR = Path(__file__).resolve().parents[2]
if _SRC_DIR.is_dir() and str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from hyperstitionstud_io.ciphers import ( # noqa: E402
compute_aq,
int_to_spoken_words,
is_repdigit_37,
prime_rank,
)
from hyperstitionstud_io.config import load_workspace_config # noqa: E402
from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard # noqa: E402
from hyperstitionstud_io.ipld import ( # noqa: E402
compute_dag_json_cidv1,
write_pretty_and_dag_json,
)
from hyperstitionstud_io.phonetics import translate_batch # noqa: E402
os.environ["TZ"] = "UTC"
if hasattr(time, "tzset"):
time.tzset()
S1_S6_SIGNATURE_RINGS: dict[int, list[str]] = {
292: ["S1: shizohnalizis / abstrakt masheen / sinthetik dayta", "S6: asset management [Gen 0]"],
260: ["S3: teknohkapital / kiler rohbots"],
256: ["S2: akselerayshan / hai-freekwansee", "S6: sovran welth"],
246: ["S1: transformer [Iso]"],
237: ["S6: kansorsheeam [Iso]"],
222: ["S1: danyela amodai", "S6: enterpraiz"],
215: ["S3: jensan hwang / hohlee grayl"],
211: ["S3: wor masheen / koper waier", "S2/Q0: siks bilyan"],
197: ["S3: lathografee", "S6: monopoly [Gen 0]"],
193: ["S1: anthropik / Dario Amodei [Gen 0]", "S2: flash krash"],
191: ["S2: derivativ", "S6: lajistiks"],
189: ["S2: likwidatee / hangkerchif / imerjansee"],
183: ["S2: ruhnaway / tempaleks / laytansee", "S6: alakayshan"],
166: ["S2: order buk / noo flesh"],
163: ["S6: manopalee / masheenz"],
160: ["S6: kapasatee / truhst / rohbots / kriptoh / straiks"],
153: ["S6: aperatas / serplas", "S2: raizohm / reealatee [Iso]"],
137: ["S1: daireeoh", "S3: envideea", "M1: hawlts / inersha"],
136: ["S6: charter [Iso] / portal [Iso]", "M1: slohth"],
135: ["S1: dilooz / asemblaj / tenser"],
133: ["S1: wayts / sworm", "S6: ekwatee"],
129: ["S3: blakwel / ruhsha", "M7+: awflain"],
128: ["S3: nik land / masheen / serkat"],
125: ["S6: kapatal [Iso] / kapcher", "S2: fohldz / saires"],
115: ["S1: proof [Iso]"],
96: ["S1: klawd / failam / dayta"],
95: ["S2: lejer / faiber", "S5: flesh / huks"],
91: ["S3: tsmc [Iso] / laws"],
81: ["S3: asml [Iso]", "S6: aset"],
71: ["S3: gpu [Iso]"],
}
CANONICAL_WATCHLIST_24: list[dict[str, Any]] = [
{"symbol": "NVDA", "entity_eng": "Nvidia", "guilds": ["S1", "S3"], "close_usd": 137.00, "change_pct": -1.45, "change_bps": -145, "volume_ratio_20d": 1.18, "market_cap_str": "$3.35T"},
{"symbol": "ASML", "entity_eng": "ASML", "guilds": ["S3", "S6"], "close_usd": 710.00, "change_pct": 0.81, "change_bps": 81, "volume_ratio_20d": 1.05, "market_cap_str": "$280B"},
{"symbol": "TSM", "entity_eng": "TSMC", "guilds": ["S3", "S6"], "close_usd": 191.00, "change_pct": 1.25, "change_bps": 125, "volume_ratio_20d": 1.12, "market_cap_str": "$990B"},
{"symbol": "ANTHR-PVT", "entity_eng": "Anthropic", "guilds": ["S1", "S2"], "close_usd": 89.00, "change_pct": 7.23, "change_bps": 723, "volume_ratio_20d": 1.60, "market_cap_str": "$61B"},
{"symbol": "MSFT", "entity_eng": "Microsoft", "guilds": ["S1", "S6"], "close_usd": 425.00, "change_pct": 0.40, "change_bps": 40, "volume_ratio_20d": 0.92, "market_cap_str": "$3.16T"},
{"symbol": "GOOGL", "entity_eng": "Alphabet", "guilds": ["S1", "S6"], "close_usd": 183.00, "change_pct": -0.95, "change_bps": -95, "volume_ratio_20d": 0.98, "market_cap_str": "$2.25T"},
{"symbol": "META", "entity_eng": "Meta", "guilds": ["S1", "S6"], "close_usd": 592.00, "change_pct": 1.33, "change_bps": 133, "volume_ratio_20d": 1.04, "market_cap_str": "$1.49T"},
{"symbol": "ORCL", "entity_eng": "Oracle", "guilds": ["S1", "S6"], "close_usd": 189.00, "change_pct": 1.60, "change_bps": 160, "volume_ratio_20d": 1.15, "market_cap_str": "$520B"},
{"symbol": "AVGO", "entity_eng": "Broadcom", "guilds": ["S3", "S6"], "close_usd": 163.00, "change_pct": 0.91, "change_bps": 91, "volume_ratio_20d": 1.01, "market_cap_str": "$760B"},
{"symbol": "ARM", "entity_eng": "Arm", "guilds": ["S3", "S1"], "close_usd": 135.00, "change_pct": -1.28, "change_bps": -128, "volume_ratio_20d": 0.88, "market_cap_str": "$142B"},
{"symbol": "AMD", "entity_eng": "AMD", "guilds": ["S3", "S1"], "close_usd": 137.00, "change_pct": -0.71, "change_bps": -71, "volume_ratio_20d": 0.94, "market_cap_str": "$222B"},
{"symbol": "PLTR", "entity_eng": "Palantir", "guilds": ["S3", "S6"], "close_usd": 66.00, "change_pct": 2.60, "change_bps": 260, "volume_ratio_20d": 1.45, "market_cap_str": "$150B"},
{"symbol": "LMT", "entity_eng": "Lockheed", "guilds": ["S3"], "close_usd": 534.00, "change_pct": 0.39, "change_bps": 39, "volume_ratio_20d": 0.85, "market_cap_str": "$127B"},
{"symbol": "RTX", "entity_eng": "Raytheon", "guilds": ["S3"], "close_usd": 121.00, "change_pct": 0.41, "change_bps": 41, "volume_ratio_20d": 0.82, "market_cap_str": "$161B"},
{"symbol": "HG=F", "entity_eng": "Copper", "guilds": ["S3", "S2"], "close_usd": 4.15, "change_pct": 2.11, "change_bps": 211, "volume_ratio_20d": 1.22, "market_cap_str": "$211B"},
{"symbol": "^VIX", "entity_eng": "VIX", "guilds": ["S2"], "close_usd": 14.20, "change_pct": -5.33, "change_bps": -533, "volume_ratio_20d": 1.10, "market_cap_str": "$0B"},
{"symbol": "BTC-USD", "entity_eng": "Bitcoin", "guilds": ["S2", "S6"], "close_usd": 96000.00, "change_pct": 1.93, "change_bps": 193, "volume_ratio_20d": 1.35, "market_cap_str": "$1.90T"},
{"symbol": "ETH-USD", "entity_eng": "Ethereum", "guilds": ["S2"], "close_usd": 3600.00, "change_pct": 1.83, "change_bps": 183, "volume_ratio_20d": 1.20, "market_cap_str": "$433B"},
{"symbol": "SOL-USD", "entity_eng": "Solana", "guilds": ["S2"], "close_usd": 244.00, "change_pct": 1.29, "change_bps": 129, "volume_ratio_20d": 1.18, "market_cap_str": "$116B"},
{"symbol": "COIN", "entity_eng": "Coinbase", "guilds": ["S2", "S6"], "close_usd": 292.00, "change_pct": 2.56, "change_bps": 256, "volume_ratio_20d": 1.40, "market_cap_str": "$73B"},
{"symbol": "CEG", "entity_eng": "Constellation", "guilds": ["S4", "S3"], "close_usd": 256.00, "change_pct": 1.16, "change_bps": 116, "volume_ratio_20d": 1.08, "market_cap_str": "$80B"},
{"symbol": "LLY", "entity_eng": "Eli Lilly", "guilds": ["S5", "S6"], "close_usd": 777.00, "change_pct": 0.84, "change_bps": 84, "volume_ratio_20d": 0.96, "market_cap_str": "$740B"},
{"symbol": "^TNX", "entity_eng": "Treasury", "guilds": ["S6", "S2"], "close_usd": 4.18, "change_pct": -0.71, "change_bps": -71, "volume_ratio_20d": 1.00, "market_cap_str": "$28T"},
{"symbol": "BLK", "entity_eng": "BlackRock", "guilds": ["S6"], "close_usd": 1025.00, "change_pct": 1.25, "change_bps": 125, "volume_ratio_20d": 1.02, "market_cap_str": "$153B"},
]
def build_financial_quant_harvest(
harvest_mode: str = "us-closing-bell",
snapshot_path: str | Path | None = None,
join_news_path: str | Path | None = None,
) -> dict[str, Any]:
cfg = load_workspace_config()
with ReadOnlyIsolationGuard(cfg.read_only_files) as guard:
if snapshot_path and Path(snapshot_path).is_file():
raw_watchlist = json.loads(Path(snapshot_path).read_text(encoding="utf-8"))
else:
raw_watchlist = CANONICAL_WATCHLIST_24
# Batch translate entity names and spoken integer/bps strings
phrases_to_translate: list[str] = []
for item in raw_watchlist:
phrases_to_translate.append(item["entity_eng"])
close_int = int(round(float(item["close_usd"])))
bps_abs = abs(int(item["change_bps"]))
phrases_to_translate.append(int_to_spoken_words(close_int))
phrases_to_translate.append(int_to_spoken_words(bps_abs))
ing_map = translate_batch(phrases_to_translate)
news_entities: set[str] = set()
if join_news_path and Path(join_news_path).is_file():
news_obj = json.loads(Path(join_news_path).read_text(encoding="utf-8"))
for st in news_obj.get("stories", news_obj.get("headlines", [])):
txt_hl = (st.get("headline_eng") or st.get("title") or "").lower()
for item in raw_watchlist:
if item["entity_eng"].lower() in txt_hl or item["symbol"].lower() in txt_hl:
news_entities.add(item["symbol"])
instruments_out: list[dict[str, Any]] = []
active_memetic_states: set[str] = set()
for item in raw_watchlist:
sym = item["symbol"]
ent_eng = item["entity_eng"]
ent_ing = ing_map.get(ent_eng, ent_eng.lower())
ent_eng_aq = compute_aq(ent_eng)
ent_ing_aq = compute_aq(ent_ing)
close_int = int(round(float(item["close_usd"])))
bps_abs = abs(int(item["change_bps"]))
close_sp_eng = int_to_spoken_words(close_int)
close_sp_ing = ing_map.get(close_sp_eng, close_sp_eng)
bps_sp_eng = int_to_spoken_words(bps_abs)
bps_sp_ing = ing_map.get(bps_sp_eng, bps_sp_eng)
close_dig_aq = compute_aq(str(close_int))
close_sp_aq = compute_aq(close_sp_ing)
bps_dig_aq = compute_aq(str(bps_abs))
bps_sp_aq = compute_aq(bps_sp_ing)
locks: list[dict[str, Any]] = []
# Scope 1: Intra-Instrument Self-Locks & Repdigit Attractors
if close_int == ent_ing_aq or close_int == ent_eng_aq:
locks.append({
"scope": "SCOPE1_INTRA_INSTRUMENT_SELF_LOCK",
"description": f"{sym} integer close (${close_int}) equals its own AQ coordinate ({ent_ing}={ent_ing_aq}).",
})
if is_repdigit_37(close_sp_aq) or is_repdigit_37(close_int):
locks.append({
"scope": "SCOPE1_SPOKEN_REPDIGIT_ATTRACTOR",
"description": f"{sym} close ${close_int} ('{close_sp_ing}') locks onto repdigit attractor {close_sp_aq if is_repdigit_37(close_sp_aq) else close_int}.",
})
if bps_abs == ent_ing_aq or bps_abs == ent_eng_aq:
locks.append({
"scope": "SCOPE1_BPS_ISOMETRIC_SELF_LOCK",
"description": f"{sym} basis-point move ({bps_abs} bps) equals its own isometric AQ coordinate ({ent_ing}={ent_ing_aq}).",
})
# Scope 2: S1-S6 Signature Ring Migrations
for coord_val, label_mode in ((close_int, "close_int"), (close_sp_aq, "close_spoken_aq"), (bps_abs, "change_bps")):
if coord_val in S1_S6_SIGNATURE_RINGS:
locks.append({
"scope": "SCOPE2_S1_S6_RING_MIGRATION",
"metric_mode": label_mode,
"coordinate": coord_val,
"ring_partners": S1_S6_SIGNATURE_RINGS[coord_val],
})
# Scope 3: Objective Numerical State-Gate Activation
vol_ratio = float(item.get("volume_ratio_20d", 1.0))
chg_pct = float(item.get("change_pct", 0.0))
mcap_s = str(item.get("market_cap_str", ""))
if vol_ratio < 0.45 and abs(chg_pct) < 0.10:
active_memetic_states.add("M1_ENTROPIC_STAGNATION")
if chg_pct <= -5.0 or vol_ratio >= 2.5:
active_memetic_states.add("M2_FLASH_CRASH_TEMPLEX_SURGE")
if mcap_s.endswith("T"):
active_memetic_states.add("M3_LEVIATHAN_TRILLION_CAP_CONCENTRATION")
instruments_out.append({
"symbol": sym,
"entity_eng": ent_eng,
"entity_ing": ent_ing,
"entity_eng_aq": ent_eng_aq,
"entity_ing_aq": ent_ing_aq,
"guilds": item["guilds"],
"co_present_in_news_wire": sym in news_entities,
"metrics": {
"close_usd": item["close_usd"],
"change_pct": chg_pct,
"change_bps": item["change_bps"],
"volume_ratio_20d": vol_ratio,
"market_cap_str": mcap_s,
},
"quant_encodings": {
"close_digit_aq": close_dig_aq,
"close_spoken_eng": close_sp_eng,
"close_spoken_ing": close_sp_ing,
"close_spoken_ing_aq": close_sp_aq,
"close_spoken_prime_rank": prime_rank(close_sp_aq),
"bps_digit_aq": bps_dig_aq,
"bps_spoken_eng": bps_sp_eng,
"bps_spoken_ing": bps_sp_ing,
"bps_spoken_ing_aq": bps_sp_aq,
},
"contingent_locks": locks,
})
# Evaluate registered anchor revisions
anc_revs = [
{
"anchor_id": "anthropic_ipo_price_83",
"q_old_digit": "$83",
"q_new_digit": "$89",
"q_old_spoken_ing": "aytee three (202)",
"q_new_spoken_ing": "aytee nain (193 [44th PRIME])",
"migration": "Migrates into 193 == anthropik == flash krash == Dario Amodei [Gen 0] (Scope 1 + Scope 2 Exact Self-Lock).",
}
]
receipt = guard.audit_receipt()
payload: dict[str, Any] = {
"$schema": "./schemas/v1/financial-aq-harvest.schema.json",
"$id": "urn:io:hyperstitionstud:schema:v1:financial-aq-harvest",
"version": "2.0.0",
"target_date_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d"),
"harvest_mode": harvest_mode,
"regime_summary": {
"instrument_count": len(instruments_out),
"total_contingent_locks": sum(len(x["contingent_locks"]) for x in instruments_out),
"active_memetic_states": sorted(active_memetic_states),
},
"instruments": instruments_out,
"anchor_revisions_detected": anc_revs,
"isolation_receipt": receipt,
}
payload["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(payload)}
return payload
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="hs-quant-harvest", description="Periodic Quantitative Financial Telemetry & Contingent Meaning Collector.")
ap.add_argument("--mode", choices=["us-closing-bell", "utc-rollover"], default="us-closing-bell")
ap.add_argument("--from-snapshot", default=None, help="Optional offline JSON snapshot file.")
ap.add_argument("--join-news", default=None, help="Optional path to news-aq-harvest-latest.json.")
ap.add_argument("--out", default=None, help="Output JSON path (default: <archive_dir>/financial-aq-harvest-latest.json).")
args = ap.parse_args(argv)
cfg = load_workspace_config()
out_path = Path(args.out) if args.out else (cfg.archive_dir / "financial-aq-harvest-latest.json")
join_news = args.join_news or str(cfg.archive_dir / "news-aq-harvest-latest.json")
payload = build_financial_quant_harvest(
harvest_mode=args.mode,
snapshot_path=args.from_snapshot,
join_news_path=join_news,
)
info = write_pretty_and_dag_json(out_path, payload)
print(
json.dumps(
{
"output_path": str(out_path),
"harvest_mode": payload["harvest_mode"],
"instrument_count": payload["regime_summary"]["instrument_count"],
"total_contingent_locks": payload["regime_summary"]["total_contingent_locks"],
"active_memetic_states": payload["regime_summary"]["active_memetic_states"],
"dag_json_cidv1": info["cidv1"],
"isolation_all_unchanged": payload["isolation_receipt"]["all_unchanged"],
},
indent=2,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())