Files
hyperstitionstudio-core/src/hyperstitionstud_io/mcp/tools.py
T

968 lines
50 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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')."},
},
},
},
{
"name": "hs_inspect_quant_timeseries",
"description": "Inspect the lens-neutral periodic quantitative financial & memetic gematria time-series bundle (30 UTC days x 24 S1-S6 tickers x 21 dated news dossiers), TradingView Superchart URLs, pluggable LENS_REGISTRY projections, and optional one-shot .png + .json stats card bundle.",
"inputSchema": {
"type": "object",
"properties": {
"symbol": {"type": "string", "default": "", "description": "Optional ticker symbol or DEX coordinate (e.g. 'NVDA', '137', 'ASML')."},
"lens": {
"type": "string",
"enum": ["fund_manager", "neutral_math", "corporate_board", "tierzoo_ecology", "fantasy_sabermetrics", "pokedex_scanner"],
"default": "fund_manager",
},
"include_card": {
"type": "boolean",
"default": False,
"description": "When true and a symbol is specified, generates and attaches the one-shot .png + .json ticker stats card bundle.",
},
},
},
},
{
"name": "hs_generate_ticker_stats_card",
"description": "Generate a one-shot hybrid Pokémon/Sports/TCG/TierZoo ticker stats card (.png + .json) in the Group 3 haiperdohp-jemaytreeah × hyperstitionstud.io design system using 100% real exchange and news-wire observations (null / 'No data available' when absent).",
"inputSchema": {
"type": "object",
"properties": {
"symbol": {"type": "string", "default": "NVDA", "description": "Ticker symbol or DEX coordinate (e.g. 'NVDA', 'PLTR', 'SOL-USD', 'ANTHR-PVT', '137')."},
"lens": {
"type": "string",
"enum": ["tierzoo_ecology", "fund_manager", "neutral_math", "corporate_board", "fantasy_sabermetrics", "pokedex_scanner"],
"default": "tierzoo_ecology",
},
"date_utc": {"type": "string", "default": "", "description": "Optional YYYY-MM-DD UTC date (defaults to latest available real trading date)."},
"include_base64_png": {"type": "boolean", "default": True, "description": "Whether to embed base64-encoded PNG bytes in the JSON response."},
},
"required": ["symbol"],
},
},
{
"name": "hs_inspect_macro_indicators",
"description": "Inspect real Federal Reserve (FRED) macroeconomic, monetary, and aggregate output indicators (CPI, PPI, US10Y, EFFR, SOFR, M1, M2, M1 vs. M2 Spread, Real M2 Growth, GDP, GNP, OUTBS, INDPRO) with native cadence preservation and bidirectional eng_aq/ing_aq evaluations.",
"inputSchema": {
"type": "object",
"properties": {
"indicator_slug": {"type": "string", "default": "", "description": "Optional indicator slug filter (e.g. 'cpi', 'ppi', 'us10y', 'effr', 'sofr', 'm1', 'm2', 'real_m2', 'gdp_nominal', 'gdp_real', 'gnp_gross_product', 'business_gross_output', 'industrial_production')."},
},
},
},
{
"name": "hs_generate_daily_portfolio_brief",
"description": "Generate or inspect the 5-Agenda Zero-Synthetic-Data Daily Portfolio & Memetic Regime Update (Executive Summary + 3-State Bayesian Best/Base/Worst-Case Scenarios, Confirming Signals, Challenging Divergences, Delta Since Last Run, and Daily Key Macro Question + Compounding Rigor).",
"inputSchema": {
"type": "object",
"properties": {
"refresh": {"type": "boolean", "default": False, "description": "When true, recomputes the daily brief and advances the Bayesian prior/posterior state ledger."},
},
},
},
{
"name": "hs_inspect_engineering_and_math_docs",
"description": "Inspect the live-introspected Software Engineering (/engineering/ Units E0-E5) and Applied Mathematics (/math/ Units M0-M5) explication hubs, subpage sections, algebraic conservation invariants, CLI scripts table, Novice Prerequisite Ladders, and 3-language polyglot cartridges (Guile Scheme, TypeScript, Rust).",
"inputSchema": {
"type": "object",
"properties": {
"domain": {"type": "string", "enum": ["all", "engineering", "math"], "default": "all"},
"unit_filter": {"type": "string", "default": "", "description": "Optional unit ID or subpage slug (e.g. 'E0'..'E5', 'M0'..'M5', 'ciphers-and-phonetics')."},
"include_polyglot_cartridges": {"type": "boolean", "default": True},
},
},
},
{
"name": "hs_inspect_documentation_and_manuals",
"description": "Search, list, and retrieve full Markdown text and PDF deep-links across all documentation tiers: Operator's Manuals, VPS/CI Guides, Stakeholder Proposals & Specs, Interactive /learn/ Curriculum, /quant/ Guided Tutorials & 27 [i] Glossary Popovers, Active/Deferred Plans, and Cold-Rotated Completed Plans (read in-memory from completed-plans-archive.tar.gz).",
"inputSchema": {
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["all", "manuals", "proposals_and_specs", "active_and_deferred_plans", "archived_plans", "learn_and_tutorials", "quant_glossary_popovers"],
"default": "all",
},
"doc_id": {"type": "string", "default": "", "description": "Optional document filename or plan ID (e.g. 'OPERATORS-MANUAL-LLM-TOKEN-DEPENDENT-DATA-PIPELINES', 'PLAN-HS-PDF-BUILD-DARK-MODE-AND-GLYPH-SANITIZATION')."},
"search_query": {"type": "string", "default": "", "description": "Optional case-insensitive keyword to search across manuals and plans."},
"include_full_markdown": {"type": "boolean", "default": False},
},
},
},
{
"name": "hs_evaluate_guile_scheme_z_calculus",
"description": "Evaluate a pure functional Guile Scheme (Z-combinator), TypeScript, or Rust expression inside the 4-Ring Zero-Escape AST Sandbox (supporting exact rationals p/q, float conversion, step traces, and guile_prelude.scm inspection).",
"inputSchema": {
"type": "object",
"properties": {
"expression": {"type": "string", "default": '(aq-base36 "LEMUR")'},
"lang": {"type": "string", "enum": ["guile", "ts", "rust"], "default": "guile"},
"prefer_float": {"type": "boolean", "default": False},
"include_trace": {"type": "boolean", "default": True},
"include_prelude_source": {"type": "boolean", "default": False},
},
},
},
{
"name": "hs_query_workspace_catalog_and_release_state",
"description": "Query the unified SQLite FTS5 catalog (registry manifests, FTS5 BM25 search, cross-corpus AQ coordinate joins, indexed time-series bar queries), inspect zero-token programmatic semantic version bump heuristics (hs-sync-version --explain-bump), and read the cached EROFS/public-regression baseline and API telemetry summary.",
"inputSchema": {
"type": "object",
"properties": {
"fts_query": {"type": "string", "default": "", "description": "Optional full-text search query across glossary entries, graph nodes, equations, and dossiers."},
"doc_type": {"type": "string", "enum": ["all", "glossary", "equation", "node", "dossier", "instrument"], "default": "all"},
"registry": {"type": "string", "default": "", "description": "Optional registry slug to query from SQLite registry_manifests (or 'all' for all manifests)."},
"aq_int": {"type": "integer", "default": 0, "description": "Optional integer AQ coordinate (1..999) for cross-corpus SQLite coordinate join."},
"symbol": {"type": "string", "default": "", "description": "Optional ticker symbol for indexed SQLite quant_timeseries_bars query."},
"start_date": {"type": "string", "default": ""},
"end_date": {"type": "string", "default": ""},
"min_points": {"type": "number", "default": 0.0},
"include_version_bump_heuristics": {"type": "boolean", "default": True},
"include_baseline_and_telemetry": {"type": "boolean", "default": True},
},
},
},
{
"name": "hs_generate_highlights_summary",
"description": "Generate an ad-hoc <= 2 paragraph (<= 1,100 char, zero-HTML/LaTeX/table) phone-messenger highlights summary for software engineers (Paragraph 1) and mathematics enthusiasts (Paragraph 2) at 0 LLM tokens, writing output artifacts exclusively to /workspace/untracked/recent-highlights/.",
"inputSchema": {
"type": "object",
"properties": {
"focus": {"type": "string", "enum": ["both", "eng", "math"], "default": "both"},
"max_chars": {"type": "integer", "default": 1100},
},
},
},
]
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 {
"is_simulated": True,
"simulation_warning": "SIMULATED COUNTERFACTUAL ANCHOR REVISION — NOT LIVE MARKET DATA",
"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":
raw_dp = str(arguments.get("draft_path", "")).strip() or "proposal-fund-manager-novel-investment-discovery.md"
dp = Path(raw_dp)
if not dp.is_absolute():
dp = cfg.zoology_dir / dp
if dp.is_dir():
dp = cfg.zoology_dir / "proposal-fund-manager-novel-investment-discovery.md"
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",
"quant-timeseries": cfg.core_dir / "site" / "quant" / "quant-timeseries.json",
"real-macro-indicators": cfg.core_dir / "site" / "quant" / "real-macro-indicators.json",
"daily-brief-latest": cfg.core_dir / "site" / "quant" / "daily-brief-latest.json",
"engineering-manifest": cfg.core_dir / "site" / "engineering" / "engineering-manifest.json",
"math-manifest": cfg.core_dir / "site" / "math" / "math-manifest.json",
"archive-manifest": cfg.knowledge_graph_dir / "docs" / "archive" / "archive-manifest.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
if name == "hs_inspect_quant_timeseries":
from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle
sym_q = str(arguments.get("symbol", "")).strip().upper()
lens_q = str(arguments.get("lens", "fund_manager")).strip()
ts_json_path = cfg.core_dir / "site" / "quant" / "quant-timeseries.json"
if ts_json_path.is_file():
bundle = json.loads(ts_json_path.read_text(encoding="utf-8"))
else:
bundle = build_quant_timeseries_bundle(write_files=False)
if sym_q:
matched = [
inst
for inst in bundle["instruments"]
if inst["symbol"].upper() == sym_q
or inst["entity_eng"].upper() == sym_q
or str(inst["entity_ing_aq"]) == sym_q.lstrip("#DEX ")
]
out_res: dict[str, Any] = {
"version": bundle["version"],
"periodicity_gate": bundle["periodicity_gate"],
"selected_lens": lens_q,
"instruments": matched,
"ipld_dag_json_cidv1": bundle["ipld_dag_json_cidv1"],
}
if bool(arguments.get("include_card")) and matched:
from hyperstitionstud_io.quant.cards import export_ticker_stats_card_pair
out_res["stats_card"] = export_ticker_stats_card_pair(
symbol=matched[0]["symbol"],
lens=lens_q,
include_base64_png=True,
)
return out_res
return {
"version": bundle["version"],
"periodicity_gate": bundle["periodicity_gate"],
"enabled_lenses": bundle["enabled_lenses"],
"dates_utc": bundle["dates_utc"],
"instrument_count": len(bundle["instruments"]),
"builds": bundle["builds"],
"anchor_revision_series": bundle["anchor_revision_series"],
"ipld_dag_json_cidv1": bundle["ipld_dag_json_cidv1"],
}
if name == "hs_generate_ticker_stats_card":
from hyperstitionstud_io.quant.cards import export_ticker_stats_card_pair
sym_c = str(arguments.get("symbol", "NVDA")).strip() or "NVDA"
lens_c = str(arguments.get("lens", "tierzoo_ecology")).strip() or "tierzoo_ecology"
dt_c = str(arguments.get("date_utc", "")).strip() or None
inc_b64 = bool(arguments.get("include_base64_png", True))
return export_ticker_stats_card_pair(
symbol=sym_c,
lens=lens_c,
date_utc=dt_c,
include_base64_png=inc_b64,
)
if name == "hs_inspect_macro_indicators":
from hyperstitionstud_io.quant.macro import build_macro_indicators_bundle
slug_f = str(arguments.get("indicator_slug", "")).strip().lower()
m_path = cfg.core_dir / "site" / "quant" / "real-macro-indicators.json"
if m_path.is_file():
m_bundle = json.loads(m_path.read_text(encoding="utf-8"))
else:
m_bundle = build_macro_indicators_bundle(allow_live_network=False, write_files=False)
if slug_f and slug_f in (m_bundle.get("series") or {}):
return {
"version": m_bundle["version"],
"synthetic_data_eliminated": m_bundle["synthetic_data_eliminated"],
"indicator": m_bundle["series"][slug_f],
"derived_indicators": m_bundle["derived_indicators"],
"ipld_dag_json_cidv1": m_bundle["ipld_dag_json_cidv1"],
}
return m_bundle
if name == "hs_generate_daily_portfolio_brief":
from hyperstitionstud_io.quant.daily_brief import build_daily_portfolio_brief
b_path = cfg.core_dir / "site" / "quant" / "daily-brief-latest.json"
if bool(arguments.get("refresh")) or not b_path.is_file():
return build_daily_portfolio_brief(allow_live_network=False, write_files=False)
return json.loads(b_path.read_text(encoding="utf-8"))
if name == "hs_inspect_engineering_and_math_docs":
from hyperstitionstud_io.publishing.engineering_docs import (
ENGINEERING_GUILE_CARTRIDGES,
introspect_engineering_manifest,
)
from hyperstitionstud_io.publishing.math_docs import (
MATH_GUILE_CARTRIDGES,
introspect_math_manifest,
)
dom = str(arguments.get("domain", "all")).strip().lower()
u_filt = str(arguments.get("unit_filter", "")).strip().upper()
inc_cart = bool(arguments.get("include_polyglot_cartridges", True))
eng_p = cfg.core_dir / "site" / "engineering" / "engineering-manifest.json"
math_p = cfg.core_dir / "site" / "math" / "math-manifest.json"
eng_m = json.loads(eng_p.read_text(encoding="utf-8")) if eng_p.is_file() else introspect_engineering_manifest()
math_m = json.loads(math_p.read_text(encoding="utf-8")) if math_p.is_file() else introspect_math_manifest()
out_docs: dict[str, Any] = {"version": eng_m["version"], "domain": dom}
if dom in ("all", "engineering"):
out_docs["engineering"] = eng_m
if inc_cart:
out_docs["engineering_polyglot_cartridges"] = ENGINEERING_GUILE_CARTRIDGES
if dom in ("all", "math"):
out_docs["math"] = math_m
if inc_cart:
out_docs["math_polyglot_cartridges"] = MATH_GUILE_CARTRIDGES
if u_filt:
matched_units: dict[str, Any] = {}
for k, v in ENGINEERING_GUILE_CARTRIDGES.items():
if u_filt in k.upper() or u_filt in v["title"].upper():
matched_units[f"engineering:{k}"] = v
for k, v in MATH_GUILE_CARTRIDGES.items():
if u_filt in k.upper() or u_filt in v["title"].upper():
matched_units[f"math:{k}"] = v
out_docs["filtered_units"] = matched_units
return out_docs
if name == "hs_inspect_documentation_and_manuals":
import tarfile
cat = str(arguments.get("category", "all")).strip().lower()
doc_id = str(arguments.get("doc_id", "")).strip()
sq = str(arguments.get("search_query", "")).strip().lower()
inc_md = bool(arguments.get("include_full_markdown", False)) or bool(doc_id)
manuals_list = [
{
"id": "OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH",
"category": "manuals",
"md_path": cfg.core_dir / "site" / "quant" / "OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.md",
"web_pdf_route": "/quant/OPERATORS-MANUAL-QUANT-TIMESERIES-WORKBENCH.pdf",
},
{
"id": "OPERATORS-MANUAL-ENCYCLOPEDIA-KNOWLEDGE-GRAPH",
"category": "manuals",
"md_path": cfg.knowledge_graph_dir / "OPERATORS-MANUAL-ENCYCLOPEDIA-KNOWLEDGE-GRAPH.md",
"web_pdf_route": "/graph/OPERATORS-MANUAL-ENCYCLOPEDIA-KNOWLEDGE-GRAPH.pdf",
},
{
"id": "OPERATORS-MANUAL-LLM-TOKEN-DEPENDENT-DATA-PIPELINES",
"category": "manuals",
"md_path": cfg.knowledge_graph_dir / "docs" / "OPERATORS-MANUAL-LLM-TOKEN-DEPENDENT-DATA-PIPELINES.md",
"web_pdf_route": "/graph/docs/OPERATORS-MANUAL-LLM-TOKEN-DEPENDENT-DATA-PIPELINES.pdf",
},
{
"id": "VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE",
"category": "manuals",
"md_path": cfg.knowledge_graph_dir / "docs" / "VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.md",
"web_pdf_route": "/graph/docs/VPS-AND-GIT-OPERATOR-DEPLOYMENT-GUIDE.pdf",
},
{
"id": "ONBOARDING-INGGLISH-AQ",
"category": "manuals",
"md_path": (cfg.paths.get("ci_repo_dir") or (cfg.workspace_root / "hyperdope-ci-build")) / "ONBOARDING-INGGLISH-AQ.md",
"web_pdf_route": "/ci/ONBOARDING-INGGLISH-AQ.pdf",
},
{
"id": "specification-concentric-eti-tier-ring-radar-d-periphery",
"category": "proposals_and_specs",
"md_path": cfg.knowledge_graph_dir / "docs" / "specification-concentric-eti-tier-ring-radar-d-periphery.md",
"web_pdf_route": "/graph/docs/specification-concentric-eti-tier-ring-radar-d-periphery.pdf",
},
{
"id": "proposal-fund-manager-novel-investment-discovery",
"category": "proposals_and_specs",
"md_path": cfg.zoology_dir / "proposal-fund-manager-novel-investment-discovery.md",
"web_pdf_route": "/zoology/proposal-fund-manager-novel-investment-discovery.pdf",
},
{
"id": "proposal-corporate-board-technocapital-allocation",
"category": "proposals_and_specs",
"md_path": cfg.zoology_dir / "proposal-corporate-board-technocapital-allocation.md",
"web_pdf_route": "/zoology/proposal-corporate-board-technocapital-allocation.pdf",
},
{
"id": "m7-emergent-subclass-bidirectional-aq-nucleation",
"category": "proposals_and_specs",
"md_path": cfg.zoology_dir / "m7-emergent-subclass-bidirectional-aq-nucleation.md",
"web_pdf_route": "/zoology/m7-emergent-subclass-bidirectional-aq-nucleation.pdf",
},
]
for p_plan in sorted((cfg.knowledge_graph_dir / "docs").glob("PLAN-*.md")):
manuals_list.append({
"id": p_plan.stem,
"category": "active_and_deferred_plans",
"md_path": p_plan,
"web_pdf_route": f"/graph/docs/{p_plan.stem}.pdf",
})
docs_out: list[dict[str, Any]] = []
for entry in manuals_list:
if cat not in ("all", entry["category"]):
continue
if doc_id and doc_id.lower() not in entry["id"].lower():
continue
mp: Path = entry["md_path"]
if not mp.is_file():
continue
txt = mp.read_text(encoding="utf-8")
if sq and sq not in txt.lower() and sq not in entry["id"].lower():
continue
item_d: dict[str, Any] = {
"id": entry["id"],
"category": entry["category"],
"web_pdf_route": entry["web_pdf_route"],
"char_count": len(txt),
}
if sq:
item_d["matched_lines"] = [ln for ln in txt.splitlines() if sq in ln.lower()][:10]
if inc_md:
item_d["markdown"] = txt
docs_out.append(item_d)
archived_out: list[dict[str, Any]] = []
if cat in ("all", "archived_plans"):
for arc_dir in (cfg.knowledge_graph_dir / "docs" / "archive", cfg.zoology_dir / "docs" / "archive"):
tgz_p = arc_dir / "completed-plans-archive.tar.gz"
if not tgz_p.is_file():
continue
with tarfile.open(tgz_p, "r:gz") as tf:
for m in tf.getmembers():
if not m.name.endswith(".md"):
continue
stem = Path(m.name).stem
if doc_id and doc_id.lower() not in stem.lower():
continue
f_obj = tf.extractfile(m)
if f_obj is None:
continue
m_txt = f_obj.read().decode("utf-8", errors="replace")
if sq and sq not in m_txt.lower() and sq not in stem.lower():
continue
arc_item: dict[str, Any] = {
"id": stem,
"category": "archived_plans",
"bundle": str(tgz_p.name),
"member_name": m.name,
"char_count": len(m_txt),
}
if sq:
arc_item["matched_lines"] = [ln for ln in m_txt.splitlines() if sq in ln.lower()][:10]
if inc_md:
arc_item["markdown"] = m_txt
archived_out.append(arc_item)
res_doc: dict[str, Any] = {
"category_filter": cat,
"doc_id_filter": doc_id,
"search_query": sq,
"documents_count": len(docs_out),
"documents": docs_out,
"archived_plans_count": len(archived_out),
"archived_plans": archived_out,
}
if cat in ("all", "learn_and_tutorials", "quant_glossary_popovers"):
q_app_js = (cfg.core_dir / "site" / "quant" / "quant-app.js").read_text(encoding="utf-8")
pop_keys = re.findall(r'"([a-z0-9_]+)":\s*\{\s*title:\s*"([^"]+)"', q_app_js)
res_doc["quant_glossary_popovers"] = [{"key": k, "title": t} for k, t in pop_keys]
res_doc["quant_glossary_popover_count"] = len(pop_keys)
return res_doc
if name == "hs_evaluate_guile_scheme_z_calculus":
from hyperstitionstud_io.publishing.polyglot_sandbox import evaluate_polyglot_sandbox
expr_s = str(arguments.get("expression", '(aq-base36 "LEMUR")')).strip() or '(aq-base36 "LEMUR")'
lang_s = str(arguments.get("lang", "guile")).strip().lower() or "guile"
pref_f = bool(arguments.get("prefer_float", False))
inc_tr = bool(arguments.get("include_trace", True))
inc_pr = bool(arguments.get("include_prelude_source", False))
eval_res = evaluate_polyglot_sandbox(
expression=expr_s,
lang=lang_s,
prefer_float=pref_f,
include_trace=inc_tr,
)
if inc_pr:
pr_p = cfg.core_dir / "src" / "hyperstitionstud_io" / "publishing" / "guile_prelude.scm"
if pr_p.is_file():
eval_res["guile_prelude_source"] = pr_p.read_text(encoding="utf-8")
return eval_res
if name == "hs_query_workspace_catalog_and_release_state":
from hyperstitionstud_io.ci.public_regression import get_default_baseline_cache_path
from hyperstitionstud_io.db.sqlite_meta import (
get_api_telemetry_summary,
get_longitudinal_telemetry_summary,
query_coordinate_join,
query_fts_catalog,
query_registry_manifests,
query_timeseries_bars,
)
from hyperstitionstud_io.version_sync import compute_programmatic_version_bump
fts_q = str(arguments.get("fts_query", "")).strip()
doc_t = str(arguments.get("doc_type", "all")).strip() or "all"
reg_q = str(arguments.get("registry", "")).strip()
aq_i = int(arguments.get("aq_int", 0) or 0)
sym_q = str(arguments.get("symbol", "")).strip()
st_d = str(arguments.get("start_date", "")).strip() or None
en_d = str(arguments.get("end_date", "")).strip() or None
min_p = float(arguments["min_points"]) if "min_points" in arguments and arguments["min_points"] else None
inc_bump = bool(arguments.get("include_version_bump_heuristics", True))
inc_base = bool(arguments.get("include_baseline_and_telemetry", True))
out_cat: dict[str, Any] = {"ok": True}
if fts_q:
try:
out_cat["fts_search"] = query_fts_catalog(fts_q, doc_type=doc_t, limit=15)
except Exception:
out_cat["fts_search"] = call_mcp_tool("hs_search_glossary_encyclopedia", {"query": fts_q, "limit": 10})
if reg_q:
try:
out_cat["registry_manifests"] = query_registry_manifests(registry=None if reg_q == "all" else reg_q)
except Exception:
out_cat["registry_manifests"] = []
if aq_i > 0:
try:
out_cat["coordinate_join"] = query_coordinate_join(aq_i)
except Exception:
out_cat["coordinate_join"] = {"coordinate_aq": aq_i}
if sym_q or st_d or en_d or min_p is not None:
try:
out_cat["timeseries_bars"] = query_timeseries_bars(
symbol=sym_q or None,
start_date=st_d,
end_date=en_d,
min_points=min_p,
)
except Exception:
out_cat["timeseries_bars"] = []
if inc_bump:
out_cat["version_bump_heuristics"] = compute_programmatic_version_bump()
if inc_base:
bp = get_default_baseline_cache_path()
if bp.is_file():
b_obj = json.loads(bp.read_text(encoding="utf-8"))
out_cat["internal_test_baseline"] = {
"expected_version": b_obj.get("expected_version"),
"expected_mcp_tool_count": b_obj.get("expected_mcp_tool_count"),
"expected_cidv1_by_artifact": b_obj.get("expected_cidv1_by_artifact"),
"erofs_protect_system_strict_audit": b_obj.get("erofs_protect_system_strict_audit"),
}
try:
out_cat["api_telemetry_summary"] = get_api_telemetry_summary()
if arguments.get("include_rotated_history"):
out_cat["longitudinal_telemetry_summary"] = get_longitudinal_telemetry_summary()
except Exception:
out_cat["api_telemetry_summary"] = {"quiescent": True}
return out_cat
if name == "hs_generate_highlights_summary":
from hyperstitionstud_io.publishing.highlights import build_recent_highlights_summary
foc = str(arguments.get("focus", "both")).strip() or "both"
m_ch = int(arguments.get("max_chars", 1100))
return build_recent_highlights_summary(focus=foc, max_chars=m_ch)
raise ValueError(f"Unknown MCP tool: {name}")