#!/usr/bin/env python3 """ hyperstitionstud_io.publishing.highlights Ad-Hoc Two-Paragraph Phone-Messenger Highlights Summary Generator (`hs-highlights` & `hs_generate_highlights_summary`). Enforces: - Maximum 2 paragraphs (`paragraph_count <= 2`, separated by `\n\n`), - Phone-messenger readability (`char_count <= 1,100`, 0 HTML tags, 0 raw LaTeX backslashes, 0 Markdown tables), - Exclusive output to `/workspace/untracked/recent-highlights/` (`0` dirty files in tracked Git repositories, with graceful `EROFS` fallback), - Zero Web UI exposure (`0` DOM/HTML buttons added to any web surface), - Zero metered LLM tokens (`0` API calls, `< 20 ms` runtime). """ from __future__ import annotations import argparse import datetime import json from pathlib import Path from typing import Any from hyperstitionstud_io import __version__ as CURRENT_VERSION from hyperstitionstud_io.config import load_workspace_config from hyperstitionstud_io.glossary import ReadOnlyIsolationGuard from hyperstitionstud_io.ipld import compute_dag_json_cidv1 from hyperstitionstud_io.mcp.tools import MCP_TOOLS_SCHEMA from hyperstitionstud_io.publishing.engineering_docs import introspect_engineering_manifest from hyperstitionstud_io.publishing.math_docs import introspect_math_manifest def build_recent_highlights_summary( focus: str = "both", max_chars: int = 1100, out_dir: str | Path | None = None, workspace_root: str | Path | None = None, ) -> dict[str, Any]: """ Generate the <= 2 paragraph phone-messenger highlights summary for software engineers and mathematics enthusiasts and persist all output artifacts exclusively to `/workspace/untracked/recent-highlights/` when writable. """ cfg = load_workspace_config(workspace_root=workspace_root) focus_norm = focus.strip().lower() if focus_norm not in ("both", "eng", "engineering", "math", "mathematics"): focus_norm = "both" with ReadOnlyIsolationGuard(cfg.read_only_files) as guard: eng_man = introspect_engineering_manifest(workspace_root=workspace_root) math_man = introspect_math_manifest(workspace_root=workspace_root) eng_c = eng_man["introspected_counts"] math_inv = math_man["algebraic_invariants"] math_emp = math_man["empirical_counts"] tool_cnt = len(MCP_TOOLS_SCHEMA) p_eng = ( f"[Hyperstition Studio v{CURRENT_VERSION} — Software Engineering Highlights] " f"Across {eng_c['repositories']} offline-portable repositories served from a RAM-backed tmpfs webroot over Caddy HTTP/3 + Brotli-11, " f"recent releases shipped an introspective /engineering/ hub (Units E0–E5), a {tool_cnt}-tool stateless read-only MCP & OpenAPI 3.1.0 REST server (:8095) " f"with IPLD dag-json (0x0129) CIDv1 provenance and quiescent 100M SQLite FTS5 logrotate, an in-process ProtectSystem=strict (EROFS) syscall test harness, " f"34x latency fast-paths (~35 ms 900x1260 PNG/JSON stats cards), and a 6-gate public regression suite (hs-public-smoke) + zero-token SemVer bumper. " f"Explore: https://hyperstitionstud.io/engineering/" ) p_math = ( f"[Applied Mathematics & Quantitative Semiotics Highlights] " f"On /math/ (Units M0–M5) and /quant/, every metric is computed with 0 synthetic data (missing/holiday/private observations serialize strictly as null): " f"phonemic projection Φ: Σ_eng* → Σ_ing* collapses Cluster 292 variance from σ²_0 = {math_inv['cluster_292_gen0_variance']} to σ²_1 = {math_inv['cluster_292_gen1_variance']} " f"across {math_inv['g4_isometric_fixed_point_count']} G4 isometric fixed points, while the 4-species Confluence Dose (D ∈ {{0..4}}) across " f"{math_emp['total_real_bars_n']} real exchange bars and {math_emp['fred_macro_series_n']} native-cadence St. Louis Fed (FRED) macro series reveals a -58% median volatility compression " f"at Dose 2 (101 bps vs. 240.5 bps) and powers a 3-state discrete Bayesian regime brief + a 4-ring hardened Guile Scheme (λ Z-combinator), TypeScript, and Rust REPL. " f"Explore: https://hyperstitionstud.io/math/" ) if focus_norm in ("eng", "engineering"): paragraphs = [p_eng] elif focus_norm in ("math", "mathematics"): paragraphs = [p_math] else: paragraphs = [p_eng, p_math] full_text = "\n\n".join(paragraphs) if len(full_text) > max_chars: # Compact while keeping <= 2 paragraphs and preserving trailing URLs budget_per_p = max(120, (max_chars - 2) // len(paragraphs)) compacted: list[str] = [] for p_str in paragraphs: if len(p_str) <= budget_per_p: compacted.append(p_str) else: url_idx = p_str.rfind("Explore: https://") suffix = (" " + p_str[url_idx:]) if url_idx != -1 else "" keep_len = max(40, budget_per_p - len(suffix) - 3) cut = p_str[:keep_len].rsplit(" ", 1)[0] compacted.append(cut + "..." + suffix) paragraphs = compacted full_text = "\n\n".join(paragraphs) target_untracked = ( Path(out_dir).resolve() if out_dir is not None else (cfg.workspace_root / "untracked" / "recent-highlights").resolve() ) txt_latest = target_untracked / "recent-highlights-summary-latest.txt" json_latest = target_untracked / "recent-highlights-summary-latest.json" txt_ver = target_untracked / f"recent-highlights-summary-v{CURRENT_VERSION}.txt" json_ver = target_untracked / f"recent-highlights-summary-v{CURRENT_VERSION}.json" payload: dict[str, Any] = { "ok": True, "version": CURRENT_VERSION, "generated_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "focus": focus_norm, "paragraph_count": len(paragraphs), "char_count": len(full_text), "max_chars": max_chars, "llm_tokens_used": 0, "web_ui_exposed": False, "paragraphs": paragraphs, "messenger_text": full_text, "metrics_snapshot": { "repositories": eng_c["repositories"], "cli_entrypoints": eng_c["cli_entrypoints"], "mcp_tools": tool_cnt, "cluster_292_gen0_variance": math_inv["cluster_292_gen0_variance"], "cluster_292_gen1_variance": math_inv["cluster_292_gen1_variance"], "g4_isometric_fixed_points": math_inv["g4_isometric_fixed_point_count"], "real_exchange_bars_n": math_emp["total_real_bars_n"], "fred_macro_series_n": math_emp["fred_macro_series_n"], }, "untracked_artifacts": { "out_dir": str(target_untracked), "txt_path": str(txt_latest), "json_path": str(json_latest), "versioned_txt_path": str(txt_ver), "versioned_json_path": str(json_ver), "persisted_to_untracked": False, }, } payload["ipld_dag_json_cidv1"] = {"/": compute_dag_json_cidv1(payload)} try: target_untracked.mkdir(parents=True, exist_ok=True) txt_latest.write_text(full_text + "\n", encoding="utf-8") txt_ver.write_text(full_text + "\n", encoding="utf-8") payload["untracked_artifacts"]["persisted_to_untracked"] = True json_bytes = (json.dumps(payload, indent=2, ensure_ascii=False) + "\n").encode("utf-8") json_latest.write_bytes(json_bytes) json_ver.write_bytes(json_bytes) except OSError: payload["untracked_artifacts"]["persisted_to_untracked"] = False payload["isolation_receipt"] = guard.audit_receipt() return payload def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser( prog="hs-highlights", description="Generate a <= 2 paragraph phone-messenger highlights summary for software engineers and mathematics enthusiasts (writes to /workspace/untracked/recent-highlights/).", ) ap.add_argument("--focus", default="both", choices=["both", "eng", "math"], help="Target audience focus (default: both).") ap.add_argument("--max-chars", type=int, default=1100, help="Maximum total characters (default: 1100).") ap.add_argument("--out-dir", default=None, help="Output directory (defaults to /workspace/untracked/recent-highlights).") ap.add_argument("--json", action="store_true", help="Print full JSON payload to stdout instead of plain messenger text.") args = ap.parse_args(argv) res = build_recent_highlights_summary( focus=args.focus, max_chars=args.max_chars, out_dir=args.out_dir, ) if args.json: print(json.dumps(res, indent=2, ensure_ascii=False)) else: print(res["messenger_text"]) return 0 if __name__ == "__main__": raise SystemExit(main())