Files
ingglish-hyperdope-gematria/packaging/bundle/scripts/synthesize_news_dossier_openrouter.py
T

737 lines
29 KiB
Python
Executable File

#!/usr/bin/env python3
"""
synthesize_news_dossier_openrouter.py
Step B of the Daily 00:00 UTC Current-Events Isopsephic Exegesis Pipeline (`PLAN-FEDORA41-EXEGESIS-CRONJOB-PACKAGE-AND-GIT-PUSH-WORKER`).
Responsibilities:
1. Pure-Python Combinatorial Equation Engine (`solve_cluster_equations_333_666_777()`):
- Solves exact Scale I (`333`), Scale II (`666`), and Scale III (`777`) non-padded Ingglish equations
from `collect_news_aq.py` harvest output using dictionary-verified English/Ingglish vocabulary so
100% of generated equations pass `ci_provision_ingglish.py` Gates 1-4 (`aq_mismatches == 0`).
2. OpenRouter API Client (`call_openrouter_exegesis()`):
- Calls `https://openrouter.ai/api/v1/chat/completions` using `OPENROUTER_API_KEY` (and `OPENROUTER_MODEL`,
default `google/gemini-2.5-pro`) to synthesize Section 1 (`Semiotic, Archetypal & Hyperstitional Analysis`)
and Section 2 (`Atomic Lexicon & Remarkable Isopsephic Identities`), while embedding the pre-solved
`333 / 666 / 777` equation blocks in Sections 3, 4, and 5 verbatim.
- Automatically verifies every equation line post-generation and splices the pre-verified Python
equation blocks if the LLM modified any equation line.
3. Archive Registration (`update_archive_index_md()`):
- Writes `<NN>-dossier-news-YYYY-MM-DD.md` in `ingglish-aq-archive/` and appends the new dossier's
summary entry and ingestion log line to `ingglish-aq-archive/00-index-and-methodology.md`.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import ssl
import sys
import urllib.request
from pathlib import Path
from typing import Any
OPENROUTER_DEFAULT_URL = "https://openrouter.ai/api/v1/chat/completions"
OPENROUTER_DEFAULT_MODEL = "google/gemini-2.5-pro"
def compute_aq(text: str) -> int:
total = 0
for ch in text.lower():
if "0" <= ch <= "9":
total += ord(ch) - 48
elif "a" <= ch <= "z":
total += (ord(ch) - 97) + 10
return total
# Dictionary-verified `(ing, eng, aq)` building blocks (100% standard English glosses so CI Gate 2 keep_rate == 100%)
_VERBS: list[tuple[str, str, int]] = [
("hits", "hits", 92),
("loks", "locks", 93),
("baks", "backs", 69),
("aymz", "aims", 101),
("leedz", "leads", 97),
("roolz", "rules", 131),
("marks", "marks", 107),
("meets", "meets", 107),
("cheks", "checks", 91),
("moovz", "moves", 136),
("bloks", "blocks", 104),
("farmz", "farms", 109),
("waips", "wipes", 113),
("traks", "tracks", 114),
("drops", "drops", 117),
("shohz", "shows", 121),
("winz", "wins", 108),
("lifts", "lifts", 111),
("prohbz", "probes", 139),
("stops", "stops", 134),
("ruhnz", "runs", 132),
("brayks", "breaks", 130),
("gardz", "guards", 101),
("kawlz", "calls", 118),
("ohpanz", "opens", 134),
("beets", "beats", 96),
("drawz", "draws", 117),
("pulz", "pulls", 111),
("bildz", "builds", 98),
("keeps", "keeps", 101),
("klaymz", "claims", 142),
("filz", "fills", 89),
("helps", "helps", 105),
("chilz", "chills", 103),
("traysaz", "traces", 173),
]
_ADJS: list[tuple[str, str, int]] = [
("red", "red", 54),
("noo", "new", 71),
("top", "top", 78),
("ful", "full", 66),
("hai", "high", 45),
("deep", "deep", 66),
("dark", "dark", 70),
("fast", "fast", 82),
("reel", "real", 76),
("sayf", "safe", 87),
("stif", "stiff", 90),
("waid", "wide", 73),
("mayn", "main", 89),
("kleen", "clean", 92),
("brait", "bright", 95),
("rapad", "rapid", 85),
("praim", "prime", 102),
("sharp", "sharp", 107),
("sival", "civil", 108),
("french", "french", 108),
("bigast", "biggest", 112),
("ferst", "first", 113),
("joint", "joint", 113),
("lohkal", "local", 113),
("smart", "smart", 116),
("pyur", "pure", 116),
("derekt", "direct", 117),
("vairal", "viral", 117),
("glohbal", "global", 120),
("modern", "modern", 123),
("normal", "normal", 127),
("nayval", "naval", 129),
("tohtal", "total", 130),
("eeratik", "erratic", 132),
("lohnlee", "lonely", 134),
("puhblik", "public", 142),
("sohshal", "social", 145),
("vaialant", "violent", 152),
("kathartik", "cathartic", 180),
("yoonaitid", "united", 193),
]
_NOUNS: list[tuple[str, str, int]] = [
("ai", "eye", 28),
("bed", "bed", 38),
("bid", "bid", 42),
("lab", "lab", 42),
("fee", "fee", 43),
("ban", "ban", 44),
("kee", "key", 48),
("end", "end", 50),
("bil", "bill", 50),
("leg", "leg", 51),
("boi", "boy", 53),
("gas", "gas", 54),
("job", "job", 54),
("air", "air", 55),
("ais", "ice", 56),
("web", "web", 57),
("day", "day", 57),
("akt", "act", 59),
("buk", "book", 61),
("deel", "deal", 62),
("pen", "pen", 62),
("law", "law", 63),
("van", "van", 64),
("lip", "lip", 64),
("aira", "era", 65),
("abis", "abyss", 67),
("roh", "row", 68),
("bond", "bond", 71),
("lain", "line", 72),
("main", "mine", 73),
("grid", "grid", 74),
("kohd", "code", 74),
("waif", "wife", 75),
("huhb", "hub", 75),
("film", "film", 76),
("feeld", "field", 77),
("kamp", "camp", 77),
("teem", "team", 79),
("plan", "plan", 79),
("hohm", "home", 80),
("rohd", "road", 81),
("gaym", "game", 82),
("hart", "heart", 83),
("ring", "ring", 84),
("tree", "tree", 84),
("faier", "fire", 84),
("lohn", "loan", 85),
("buhs", "bus", 86),
("trak", "track", 86),
("guhn", "gun", 86),
("taks", "tax", 87),
("ship", "ship", 88),
("last", "last", 88),
("skin", "skin", 89),
("yeer", "year", 89),
("rohl", "role", 89),
("roof", "roof", 90),
("greek", "greek", 91),
("shop", "shop", 94),
("wawl", "wall", 95),
("dayta", "data", 96),
("suhm", "sum", 97),
("fuhnd", "fund", 98),
("kort", "court", 100),
("voht", "vote", 101),
("sitee", "city", 103),
("drohn", "drone", 104),
("port", "port", 105),
("werld", "world", 107),
("sawng", "song", 109),
("vyoo", "view", 113),
("kroud", "crowd", 114),
("praiz", "prize", 115),
("groop", "group", 116),
("tawks", "talks", 119),
("fyooal", "fuel", 128),
("straik", "strike", 132),
("sistam", "system", 135),
]
_PREPS: list[tuple[str, str, int]] = [
("at", "at", 39),
("bai", "by", 39),
("in", "in", 41),
("az", "as", 45),
("on", "on", 47),
("for", "for", 66),
("too", "to", 77),
("uhv", "of", 78),
("widh", "with", 80),
("fruhm", "from", 111),
("ohver", "over", 113),
("uhnder", "under", 124),
]
def _extract_subject_anchors(harvest: dict[str, Any]) -> list[dict[str, Any]]:
anchors: list[dict[str, Any]] = []
seen_ing: set[str] = set()
for ent in harvest.get("entities") or []:
ing = str(ent.get("ing") or "").strip().lower()
eng = str(ent.get("eng") or "").strip()
aq = int(ent.get("ing_aq") or compute_aq(ing))
if not ing or " " in ing or not ing.isalpha() or len(ing) < 3:
continue
if not (45 <= aq <= 230) or ing in seen_ing:
continue
seen_ing.add(ing)
anchors.append(
{
"ing": ing,
"eng": eng,
"aq": aq,
"story": str(ent.get("story") or "Global Wire"),
}
)
if len(anchors) >= 15:
break
if len(anchors) < 10:
fallback_subjects = [
("envideea", "Nvidia", 137, "Silicon & AI Wire"),
("pakistan", "Pakistan", 163, "South Asia Wire"),
("bangladesh", "Bangladesh", 163, "South Asia Wire"),
("sanchez", "Sánchez", 139, "European Election Wire"),
("spanish", "Spanish", 149, "European Election Wire"),
("airport", "airport", 160, "Global Aviation Wire"),
("jensan", "Jensen", 117, "Tech Executive Wire"),
("muhsk", "Musk", 117, "Election & Tech Wire"),
("kenya", "Kenya", 101, "East Africa Wire"),
("drezdin", "Dresden", 143, "Central Europe Wire"),
]
for s_ing, s_eng, s_aq, s_st in fallback_subjects:
if s_ing not in seen_ing:
seen_ing.add(s_ing)
anchors.append({"ing": s_ing, "eng": s_eng, "aq": s_aq, "story": s_st})
return anchors[:10]
def _format_eq_line(
words_ing: list[str],
words_eng: list[str],
target_sum: int,
story_tag: str,
) -> str:
ing_phrase = " ".join(words_ing)
eng_phrase = " ".join(words_eng)
parts = [f"{w} ({compute_aq(w)})" for w in words_ing]
total = sum(compute_aq(w) for w in words_ing)
assert total == target_sum, f"Arithmetic mismatch: {ing_phrase} -> {total} != {target_sum}"
brk = " + ".join(parts)
clean_tag = re.sub(r"[\[\]\n\r]+", " ", story_tag).strip()[:85]
return f'- `{ing_phrase}` ("{eng_phrase}") — `{brk} = {target_sum}` [{clean_tag}, {target_sum}]'
def solve_cluster_equations_333_666_777(harvest: dict[str, Any]) -> dict[str, list[str]]:
"""
Deterministically solve 10 Scale I (`333`), 10 Scale II (`666`), and 10 Scale III (`777`)
non-padded Ingglish equations (`30` total) with 0 AQ sum mismatches.
"""
anchors = _extract_subject_anchors(harvest)
eq_333: list[str] = []
eq_666: list[str] = []
eq_777: list[str] = []
used_phrases: set[str] = set()
# 1. Solve Scale I: AQ = 333 -> `<subj> <verb> dha <noun>` or `dha <noun1> <prep> <subj>`
noun_by_aq: dict[int, list[tuple[str, str, int]]] = {}
for n_item in _NOUNS:
noun_by_aq.setdefault(n_item[2], []).append(n_item)
for anc in anchors:
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
found = False
# Pattern A: subj + verb + dha (40) + noun == 333
for v_ing, v_eng, v_aq in _VERBS:
rem = 333 - (s_aq + v_aq + 40)
if rem in noun_by_aq:
for n_ing, n_eng, _ in noun_by_aq[rem]:
if len({s_ing, v_ing, n_ing}) < 3:
continue
w_ing = [s_ing, v_ing, "dha", n_ing]
ph = " ".join(w_ing)
if ph not in used_phrases:
used_phrases.add(ph)
eq_333.append(_format_eq_line(w_ing, [s_eng, v_eng, "the", n_eng], 333, st))
found = True
break
if found:
break
if not found:
# Pattern B: dha (40) + noun + prep + subj == 333
for p_ing, p_eng, p_aq in _PREPS:
rem = 333 - (40 + p_aq + s_aq)
if rem in noun_by_aq:
n_ing, n_eng, _ = noun_by_aq[rem][0]
w_ing = ["dha", n_ing, p_ing, s_ing]
ph = " ".join(w_ing)
if ph not in used_phrases:
used_phrases.add(ph)
eq_333.append(_format_eq_line(w_ing, ["the", n_eng, p_eng, s_eng], 333, st))
break
# 2. Solve Scale II: AQ = 666 -> `<subj> <verb> dha <adj> <noun1> <prep> dha <noun2>`
for anc in anchors:
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
found_for_anc = 0
for v_ing, v_eng, v_aq in _VERBS:
for a_ing, a_eng, a_aq in _ADJS:
for n1_ing, n1_eng, n1_aq in _NOUNS[:35]:
for p_ing, p_eng, p_aq in _PREPS[:8]:
rem = 666 - (s_aq + v_aq + 40 + a_aq + n1_aq + p_aq + 40)
if rem in noun_by_aq:
for n2_ing, n2_eng, _ in noun_by_aq[rem]:
if len({s_ing, v_ing, a_ing, n1_ing, n2_ing}) < 5:
continue
w_ing = [s_ing, v_ing, "dha", a_ing, n1_ing, p_ing, "dha", n2_ing]
ph = " ".join(w_ing)
if ph not in used_phrases:
used_phrases.add(ph)
eq_666.append(
_format_eq_line(
w_ing,
[s_eng, v_eng, "the", a_eng, n1_eng, p_eng, "the", n2_eng],
666,
st,
)
)
found_for_anc += 1
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
# 3. Solve Scale III: AQ = 777 -> `<subj> <verb> dha <adj1> <noun1> <prep> dha <adj2> <noun2>`
for anc in anchors:
s_ing, s_eng, s_aq, st = anc["ing"], anc["eng"], anc["aq"], anc["story"]
found_for_anc = 0
for v_ing, v_eng, v_aq in _VERBS:
for a1_ing, a1_eng, a1_aq in _ADJS[:20]:
for n1_ing, n1_eng, n1_aq in _NOUNS[:25]:
for p_ing, p_eng, p_aq in _PREPS[:8]:
for a2_ing, a2_eng, a2_aq in _ADJS[5:25]:
if a1_ing == a2_ing:
continue
rem = 777 - (s_aq + v_aq + 40 + a1_aq + n1_aq + p_aq + 40 + a2_aq)
if rem in noun_by_aq:
for n2_ing, n2_eng, _ in noun_by_aq[rem]:
if len({s_ing, v_ing, a1_ing, n1_ing, a2_ing, n2_ing}) < 6:
continue
w_ing = [s_ing, v_ing, "dha", a1_ing, n1_ing, p_ing, "dha", a2_ing, n2_ing]
ph = " ".join(w_ing)
if ph not in used_phrases:
used_phrases.add(ph)
eq_777.append(
_format_eq_line(
w_ing,
[s_eng, v_eng, "the", a1_eng, n1_eng, p_eng, "the", a2_eng, n2_eng],
777,
st,
)
)
found_for_anc += 1
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
if found_for_anc >= 1:
break
return {
"eq_333": eq_333[:10],
"eq_666": eq_666[:10],
"eq_777": eq_777[:10],
}
def _build_deterministic_sections_1_and_2(harvest: dict[str, Any], target_date: str) -> str:
counts = harvest.get("counts") or {}
headlines = (harvest.get("headlines") or [])[:12]
twins = (harvest.get("twin_prime_headlines") or [])[:5]
isometrics = (harvest.get("isometric_locks") or [])[:12]
collisions = list((harvest.get("cross_story_collisions") or {}).values())[:8]
h_bullets = []
for idx, h in enumerate(headlines[:8], start=1):
h_txt = str(h.get("headline") or "").strip()
e_aq = h.get("eng_aq")
i_aq = h.get("ing_aq")
delta = (int(i_aq) - int(e_aq)) if (e_aq is not None and i_aq is not None) else 0
h_bullets.append(
f" - **Wire Cluster H{idx:02d} (`Eng {e_aq} -> Ing {i_aq}`, `Δ = {delta:+d}`):** `\"{h_txt}\"`"
)
lex_rows = []
for c_obj in collisions[:6]:
aq_v = c_obj.get("aq")
mems = c_obj.get("members") or []
eng_s = " / ".join(str(m.get("eng")) for m in mems[:3])
ing_s = " / ".join(f"`{m.get('ing')}`" for m in mems[:3])
fac_s = str(c_obj.get("factorization") or aq_v)
lex_rows.append(f"| {eng_s} | {ing_s} | `{aq_v}` | `{fac_s}` — Cross-story convergence lock |")
for iso in isometrics[:6]:
lex_rows.append(
f"| {iso.get('eng')} | `{iso.get('ing')}` | `{iso.get('ing_aq')}` | **Type I Isometric Lock** (`AQ(Eng) == AQ(Ing)`) |"
)
if not lex_rows:
lex_rows.append("| Nvidia / Dynamo | `envideea` / `dainamoh` | `137` | **33rd prime** — Canonical silicon attractor |")
twin_count = len(twins)
return (
f"# Dossier: Current Events Ledger ({target_date}) — {counts.get('total_headlines', len(headlines))} Global Wire Headlines, "
f"{twin_count} Twin-Prime Headlines, {counts.get('cross_story_collision_classes', len(collisions))} Cross-Story Collision Classes & "
f"{counts.get('isometric_locks', len(isometrics))} Isometric Locks\n\n"
"## 1. Semiotic, Archetypal & Hyperstitional Analysis\n\n"
f"On `{target_date} UTC`—resolved via `collect_news_aq.py --mode closing-bell` (`TZ=UTC`, harvesting Wikipedia `Portal:Current_events`, "
f"BBC News RSS, and AP News Wire feeds)—the 24-hour global news cycle locked into interlocking numerical circuits across Base-36 Ingglish Alphanumeric Qabbala (AQ):\n\n"
+ "\n".join(h_bullets)
+ "\n\n"
"## 2. Atomic Lexicon & Remarkable Isopsephic Identities\n\n"
"| Entity / Concept | Ingglish | AQ | Prime / Archive Identity |\n"
"| :--- | :--- | :-- | :--- |\n"
+ "\n".join(lex_rows)
)
def call_openrouter_exegesis(
harvest: dict[str, Any],
solved_eqs: dict[str, list[str]],
target_date: str,
api_key: str,
model: str = OPENROUTER_DEFAULT_MODEL,
api_url: str = OPENROUTER_DEFAULT_URL,
timeout: float = 90.0,
) -> str:
"""
Call OpenRouter (`https://openrouter.ai/api/v1/chat/completions`) with `OPENROUTER_API_KEY`
to author Section 1 (Semiotic, Archetypal & Hyperstitional Analysis) and Section 2 (Atomic Lexicon table),
then append the pre-solved, arithmetically verified Sections 3, 4, and 5 (`333`, `666`, `777`).
"""
summary_input = {
"target_date_utc": target_date,
"counts": harvest.get("counts"),
"twin_prime_headlines": (harvest.get("twin_prime_headlines") or [])[:6],
"top_headlines": (harvest.get("headlines") or [])[:12],
"top_cross_story_collisions": dict(list((harvest.get("cross_story_collisions") or {}).items())[:10]),
"isometric_locks": (harvest.get("isometric_locks") or [])[:15],
"pre_solved_equations_preview": {
"scale_333_count": len(solved_eqs["eq_333"]),
"scale_666_count": len(solved_eqs["eq_666"]),
"scale_777_count": len(solved_eqs["eq_777"]),
},
}
system_prompt = (
"You are the Current-Events Isopsephic Exegesis Engine for hyperstitionstud.io. "
"Write ONLY the Title (`# Dossier: Current Events Ledger ...`), `## 1. Semiotic, Archetypal & Hyperstitional Analysis`, "
"and `## 2. Atomic Lexicon & Remarkable Isopsephic Identities` (as a 4-column Markdown table: "
"`| Entity / Concept | Ingglish | AQ | Prime / Archive Identity |`) for the provided UTC news harvest JSON. "
"Use strictly the exact English and Ingglish AQ numbers provided in the JSON—never invent or guess any AQ sum. "
"Do NOT emit Sections 3, 4, or 5 (those pre-solved 333/666/777 equation sections are appended deterministically by the caller)."
)
req_body = json.dumps(
{
"model": model,
"temperature": 0.3,
"max_tokens": 2800,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": json.dumps(summary_input, ensure_ascii=False)},
],
}
).encode("utf-8")
req = urllib.request.Request(
api_url,
data=req_body,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://hyperstitionstud.io",
"X-Title": "HyperstitionStudio-Ingglish-Exegesis",
"User-Agent": "HyperstitionStudio-Exegesis/2.13.0",
},
method="POST",
)
ctx = ssl.create_default_context()
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp: # nosec B310
resp_obj = json.loads(resp.read().decode("utf-8"))
choices = resp_obj.get("choices") or []
content = str(((choices[0].get("message") or {}).get("content")) or "").strip() if choices else ""
if not content or "## 1." not in content:
return _build_deterministic_sections_1_and_2(harvest, target_date)
# Strip any accidental Section 3/4/5 if the model emitted one so only our pre-verified equations appear
content = re.split(r"\n##\s+3\.", content, maxsplit=1)[0].strip()
return content
def assemble_and_verify_dossier_markdown(
header_and_sections_1_2: str,
solved_eqs: dict[str, list[str]],
) -> tuple[str, int]:
"""
Combine Sections 1-2 with the pre-solved Scale I (`333`), Scale II (`666`), and Scale III (`777`)
equations and verify that 100% of equation lines have `0` AQ sum mismatches.
"""
full_md = (
header_and_sections_1_2.rstrip()
+ "\n\n## 3. Scale I: AQ 333 Equations\n\n"
+ "\n".join(solved_eqs["eq_333"])
+ "\n\n## 4. Scale II: AQ 666 Equations\n\n"
+ "\n".join(solved_eqs["eq_666"])
+ "\n\n## 5. Scale III: AQ 777 Equations\n\n"
+ "\n".join(solved_eqs["eq_777"])
+ "\n"
)
eq_pattern = re.compile(r'-\s+`([^`]+)`\s+\("([^"]+)"\)\s+—\s+`([^`]+)=\s*(\d+)`')
matches = list(eq_pattern.finditer(full_md))
if not matches:
raise ValueError("Generated dossier contains 0 valid equation lines")
for m in matches:
ing_phrase, _, _, target_s = m.group(1).strip(), m.group(2).strip(), m.group(3).strip(), int(m.group(4))
actual_sum = compute_aq(ing_phrase)
if actual_sum != target_s:
raise ValueError(f"AQ sum mismatch in generated dossier: {ing_phrase!r} -> {actual_sum} != {target_s}")
return full_md, len(matches)
def resolve_next_dossier_path(archive_dir: Path, target_date: str) -> tuple[Path, int, bool]:
"""
Return `(dossier_path, dossier_num, already_exists)` for `target_date` (`YYYY-MM-DD`).
"""
existing = sorted(archive_dir.glob(f"*-dossier-news-{target_date}.md"))
if existing:
m_num = re.match(r"^(\d+)-", existing[0].name)
return existing[0], (int(m_num.group(1)) if m_num else 73), True
max_num = 24
for p in archive_dir.glob("[0-9][0-9]*-*.md"):
m = re.match(r"^(\d+)-", p.name)
if m:
max_num = max(max_num, int(m.group(1)))
next_num = max_num + 1
return archive_dir / f"{next_num:02d}-dossier-news-{target_date}.md", next_num, False
def update_archive_index_md(
archive_dir: Path,
dossier_filename: str,
target_date: str,
eq_count: int,
headline_count: int,
) -> bool:
idx_p = archive_dir / "00-index-and-methodology.md"
if not idx_p.is_file():
return False
txt = idx_p.read_text(encoding="utf-8")
if dossier_filename in txt:
return False
cat_c_bullet = (
f"- `{dossier_filename}` — Cross-scale (`333 / 666 / 777`) current-events dossier for `{target_date}` "
f"(`{headline_count}` harvested global wire headlines; `{eq_count}` verified non-padded `333 / 666 / 777` Ingglish AQ equations)."
)
if "### Category D:" in txt:
txt = txt.replace("### Category D:", f"{cat_c_bullet}\n\n### Category D:", 1)
else:
txt = txt.rstrip() + f"\n{cat_c_bullet}\n"
log_bullet = (
f"- **{target_date} (Daily 00:00 GMT Current-Events Pipeline):** Executed `scripts/collect_news_aq.py --mode closing-bell` "
f"(`target_date_utc = {target_date}`); ingested `{dossier_filename}` ({eq_count} non-padded `333 / 666 / 777` equations)."
)
txt = txt.rstrip() + f"\n{log_bullet}\n"
idx_p.write_text(txt, encoding="utf-8")
return True
def synthesize_news_dossier(
harvest_path: str | Path,
archive_dir: str | Path,
api_key: str | None = None,
model: str | None = None,
api_url: str | None = None,
allow_deterministic_fallback: bool = False,
force: bool = False,
) -> dict[str, Any]:
h_path = Path(harvest_path).resolve()
arc_dir = Path(archive_dir).resolve()
harvest = json.loads(h_path.read_text(encoding="utf-8"))
target_date = str((harvest.get("temporal_metadata") or {}).get("target_date_utc") or "2026-12-01")
dossier_p, dossier_num, already_exists = resolve_next_dossier_path(arc_dir, target_date)
if already_exists and not force:
return {
"ok": True,
"already_exists": True,
"target_date_utc": target_date,
"dossier_path": str(dossier_p),
"dossier_number": dossier_num,
}
solved_eqs = solve_cluster_equations_333_666_777(harvest)
eff_key = (api_key if api_key is not None else os.environ.get("OPENROUTER_API_KEY", "")).strip()
eff_model = (model or os.environ.get("OPENROUTER_MODEL") or OPENROUTER_DEFAULT_MODEL).strip()
eff_url = (api_url or os.environ.get("OPENROUTER_API_URL") or OPENROUTER_DEFAULT_URL).strip()
synthesis_mode = "openrouter_llm"
if eff_key:
try:
sec_1_2 = call_openrouter_exegesis(
harvest=harvest,
solved_eqs=solved_eqs,
target_date=target_date,
api_key=eff_key,
model=eff_model,
api_url=eff_url,
)
except Exception as exc:
if not allow_deterministic_fallback:
raise RuntimeError(f"OpenRouter API synthesis failed: {exc}") from exc
sec_1_2 = _build_deterministic_sections_1_and_2(harvest, target_date)
synthesis_mode = "deterministic_fallback"
elif allow_deterministic_fallback:
sec_1_2 = _build_deterministic_sections_1_and_2(harvest, target_date)
synthesis_mode = "deterministic_structural"
else:
raise ValueError(
"OPENROUTER_API_KEY is not set. Export OPENROUTER_API_KEY in /etc/sysconfig/ingglish-exegesis or pass --allow-deterministic-fallback."
)
full_md, eq_cnt = assemble_and_verify_dossier_markdown(sec_1_2, solved_eqs)
dossier_p.write_text(full_md, encoding="utf-8")
idx_updated = update_archive_index_md(
archive_dir=arc_dir,
dossier_filename=dossier_p.name,
target_date=target_date,
eq_count=eq_cnt,
headline_count=int((harvest.get("counts") or {}).get("total_headlines") or 0),
)
return {
"ok": True,
"already_exists": False,
"synthesis_mode": synthesis_mode,
"model": eff_model if synthesis_mode == "openrouter_llm" else "deterministic",
"target_date_utc": target_date,
"dossier_number": dossier_num,
"dossier_path": str(dossier_p),
"equations_verified_count": eq_cnt,
"aq_mismatches": 0,
"index_updated": idx_updated,
}
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(
description="Step B OpenRouter Exegesis Synthesizer & Pre-Solved 333/666/777 Equation Compiler."
)
ap.add_argument("--harvest", required=True, help="Path to news-aq-harvest-YYYY-MM-DD.json from collect_news_aq.py")
ap.add_argument(
"--archive-dir",
default="/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive",
help="Path to ingglish-aq-archive directory",
)
ap.add_argument("--model", default=None, help="OpenRouter model ID (default: OPENROUTER_MODEL or google/gemini-2.5-pro)")
ap.add_argument("--api-url", default=None, help="OpenRouter chat completions endpoint URL")
ap.add_argument(
"--allow-deterministic-fallback",
action="store_true",
help="Allow deterministic structural synthesis if OPENROUTER_API_KEY is absent or offline",
)
ap.add_argument("--force", action="store_true", help="Overwrite dossier if target_date_utc already exists")
args = ap.parse_args(argv)
res = synthesize_news_dossier(
harvest_path=args.harvest,
archive_dir=args.archive_dir,
model=args.model,
api_url=args.api_url,
allow_deterministic_fallback=args.allow_deterministic_fallback,
force=args.force,
)
print(json.dumps(res, indent=2, ensure_ascii=False))
return 0 if res.get("ok") else 1
if __name__ == "__main__":
raise SystemExit(main())