From d4b750250180bd34f5844ea96bfd7f4e1a92c58b Mon Sep 17 00:00:00 2001 From: Hermes Agent Date: Wed, 2 Dec 2026 21:12:31 +0000 Subject: [PATCH] feat(quant): implement Plan #72 pre-market-open daily brief & dual-calendar VPS cadence --- README.md | 4 +- .../hyperstition-closing-bell-harvest.service | 4 +- .../hyperstition-closing-bell-harvest.timer | 3 +- deploy/run-vps-data-production.sh | 20 ++++- src/hyperstitionstud_io/mcp/tools.py | 2 +- src/hyperstitionstud_io/quant/collector.py | 2 +- src/hyperstitionstud_io/quant/daily_brief.py | 85 +++++++++++++++++-- tests/test_core_suite.py | 61 +++++++++++++ 8 files changed, 165 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index fb95f32..845d159 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ > **Gitea Commit & Release Telemetry (`v2.17.1` • Namespace `urn:io:hyperstitionstud`)** > - **Repository Role & Public Route:** Shared PEP 420 Python core library (`hyperstitionstud_io.*`), MCP/REST server, `/quant/`, `/learn/`, `/engineering/`, `/math/`, & `/donate/` webroots → [`https://hyperstitionstud.io/`](https://hyperstitionstud.io/) -> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.17.1 release state across 13 tracked module/artifact surface(s) -> - **Touched Files / Surfaces:** `deploy/push-all-to-git-libre-audio.sh`, `deploy/run-vps-data-production.sh`, `deploy/sync-vps-repos.sh`, `src/hyperstitionstud_io/ci/deploy_scripts_sync.py`, `src/hyperstitionstud_io/ci/public_regression.py`, `src/hyperstitionstud_io/config/__init__.py`, `src/hyperstitionstud_io/mcp/tools.py`, `src/hyperstitionstud_io/publishing/archive_rotator.py` (+5 more) +> - **Latest Commit Scope (`hyperstitionstudio-core`):** Synchronized v2.17.1 release state across 7 tracked module/artifact surface(s) +> - **Touched Files / Surfaces:** `deploy/hyperstition-closing-bell-harvest.service`, `deploy/hyperstition-closing-bell-harvest.timer`, `deploy/run-vps-data-production.sh`, `src/hyperstitionstud_io/mcp/tools.py`, `src/hyperstitionstud_io/quant/collector.py`, `src/hyperstitionstud_io/quant/daily_brief.py`, `tests/test_core_suite.py` > - **Live Verified Ecosystem Metrics (`v2.17.1`):** `6` Repositories • `17` CLI Entrypoints • `20` MCP/REST Tools • `14` URN Resources • `63` Verified Web Routes • `388` KG Nodes / `1,282` Edges • `282` Glossary Entries • `4,943` Offline CMUdict Phonetics • `0` Synthetic Data diff --git a/deploy/hyperstition-closing-bell-harvest.service b/deploy/hyperstition-closing-bell-harvest.service index 543efa4..9ff6c16 100644 --- a/deploy/hyperstition-closing-bell-harvest.service +++ b/deploy/hyperstition-closing-bell-harvest.service @@ -1,5 +1,5 @@ [Unit] -Description=Hyperstition Studio US Closing-Bell Financial & FRED Macro Harvest (21:30 UTC Mon-Fri) +Description=Hyperstition Studio Pre-Market-Open (14:00 UTC) & US Closing-Bell (21:30 UTC) Financial & FRED Macro Harvest (Mon-Fri) After=network-online.target Wants=network-online.target @@ -9,4 +9,4 @@ WorkingDirectory=/srv/hyperstitionstud.io/repos Environment="REPOS_ROOT=/srv/hyperstitionstud.io/repos" Environment="LIVE_REPOS=/var/www/hyperstitionstud.io/repos" Environment="PYTHONPATH=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src" -ExecStart=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/deploy/run-vps-data-production.sh --window=us-closing-bell +ExecStart=/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/deploy/run-vps-data-production.sh --window=auto diff --git a/deploy/hyperstition-closing-bell-harvest.timer b/deploy/hyperstition-closing-bell-harvest.timer index 9c5a6c2..e5544f9 100644 --- a/deploy/hyperstition-closing-bell-harvest.timer +++ b/deploy/hyperstition-closing-bell-harvest.timer @@ -1,7 +1,8 @@ [Unit] -Description=Weekday 21:30 UTC (16:30 EST) Timer for Hyperstition Studio US Closing-Bell Harvest +Description=Weekday 14:00 UTC (09:00 EST) & 21:30 UTC (16:30 EST) Timer for Hyperstition Studio Pre-Market & Closing-Bell Harvest [Timer] +OnCalendar=Mon..Fri *-*-* 14:00:00 UTC OnCalendar=Mon..Fri *-*-* 21:30:00 UTC Persistent=true RandomizedDelaySec=15 diff --git a/deploy/run-vps-data-production.sh b/deploy/run-vps-data-production.sh index 093db9e..1b92b55 100755 --- a/deploy/run-vps-data-production.sh +++ b/deploy/run-vps-data-production.sh @@ -69,6 +69,24 @@ for arg in "$@"; do esac done +if [[ "${WINDOW_MODE}" == "auto" ]]; then + UTC_HOUR="$(date -u +%H)" + case "${UTC_HOUR}" in + 13|14|15) + WINDOW_MODE="us-pre-market-open" + ;; + 21|22|23) + WINDOW_MODE="us-closing-bell" + ;; + 00|01|02) + WINDOW_MODE="utc-rollover" + ;; + *) + WINDOW_MODE="us-closing-bell" + ;; + esac +fi + LOCK_FILE="${HYPERSTITION_HARVEST_LOCK:-/tmp/hyperstition-vps-harvest.lock}" if [[ -n "$(type -P flock || true)" ]]; then exec 9>"${LOCK_FILE}" @@ -102,7 +120,7 @@ if [[ "${PUSH_ONLY}" -eq 0 ]]; then fi fi run_checked "quant.timeseries" "${PYTHON_BIN}" -m hyperstitionstud_io.quant.timeseries - run_checked "hs-daily-brief" "${PYTHON_BIN}" -m hyperstitionstud_io.quant.daily_brief + run_checked "hs-daily-brief" "${PYTHON_BIN}" -m hyperstitionstud_io.quant.daily_brief --window "${WINDOW_MODE}" run_checked "build_encyclopedia_knowledge_graph.py" "${PYTHON_BIN}" "${REPOS_ROOT}/encyclopedia-knowledge-graph/scripts/build_encyclopedia_knowledge_graph.py" --verify-only echo "[2/5] Running Stage 3 transactional verification gates (hs-doctor, ReadOnlyIsolationGuard, test_core_suite)..." diff --git a/src/hyperstitionstud_io/mcp/tools.py b/src/hyperstitionstud_io/mcp/tools.py index 972ccdc..9ae0640 100644 --- a/src/hyperstitionstud_io/mcp/tools.py +++ b/src/hyperstitionstud_io/mcp/tools.py @@ -187,7 +187,7 @@ MCP_TOOLS_SCHEMA: list[dict[str, Any]] = [ "inputSchema": { "type": "object", "properties": { - "harvest_mode": {"type": "string", "enum": ["us-closing-bell", "utc-rollover"], "default": "us-closing-bell"}, + "harvest_mode": {"type": "string", "enum": ["us-pre-market-open", "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')."}, }, }, diff --git a/src/hyperstitionstud_io/quant/collector.py b/src/hyperstitionstud_io/quant/collector.py index 356f9fb..c2e34aa 100755 --- a/src/hyperstitionstud_io/quant/collector.py +++ b/src/hyperstitionstud_io/quant/collector.py @@ -1201,7 +1201,7 @@ def reconcile_telemetry_snapshot( 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("--mode", choices=["us-pre-market-open", "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("--live", action="store_true", help="Attempt live keyless HTTP fetch (Yahoo v8 / Stooq CSV / CoinGecko).") ap.add_argument("--append-history", action="store_true", help="Merge newly fetched real exchange bars into site/quant/real-market-history.json.") diff --git a/src/hyperstitionstud_io/quant/daily_brief.py b/src/hyperstitionstud_io/quant/daily_brief.py index 60a4c0d..b28d650 100644 --- a/src/hyperstitionstud_io/quant/daily_brief.py +++ b/src/hyperstitionstud_io/quant/daily_brief.py @@ -27,6 +27,28 @@ from hyperstitionstud_io.quant.macro import build_macro_indicators_bundle from hyperstitionstud_io.quant.timeseries import build_quant_timeseries_bundle +SESSION_WINDOWS = ("us-pre-market-open", "us-closing-bell", "utc-rollover") + + +def _resolve_session_window( + session_window: str | None = None, + now_utc: datetime.datetime | None = None, +) -> str: + if session_window and session_window != "auto": + if session_window not in SESSION_WINDOWS: + raise ValueError(f"Unsupported session_window {session_window!r}; expected one of {SESSION_WINDOWS} or 'auto'.") + return session_window + dt = now_utc or datetime.datetime.now(datetime.timezone.utc) + hour = dt.hour + if 13 <= hour <= 15: + return "us-pre-market-open" + if 21 <= hour <= 23: + return "us-closing-bell" + if 0 <= hour <= 2: + return "utc-rollover" + return "us-closing-bell" + + def _find_latest_available_bar(inst: dict[str, Any]) -> dict[str, Any] | None: bars = [b for b in (inst.get("bars") or []) if b.get("data_available") and b.get("close_usd") is not None] return bars[-1] if bars else None @@ -143,8 +165,10 @@ def _compute_bayesian_regime_update( def build_daily_portfolio_brief( allow_live_network: bool = False, write_files: bool = True, + session_window: str | None = None, ) -> dict[str, Any]: cfg = load_workspace_config() + resolved_window = _resolve_session_window(session_window) ts_bundle = build_quant_timeseries_bundle(write_files=False) macro_bundle = build_macro_indicators_bundle(allow_live_network=allow_live_network, write_files=False) @@ -288,6 +312,7 @@ def build_daily_portfolio_brief( "$id": "urn:io:hyperstitionstud:schema:v1:daily-portfolio-brief", "version": CURRENT_VERSION, "run_number": run_number, + "session_window": resolved_window, "generated_at_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "synthetic_data_eliminated": True, "agenda_1_executive_summary": { @@ -454,32 +479,62 @@ def build_daily_portfolio_brief( js_body = "// Auto-generated by hyperstitionstud_io.quant.daily_brief — DO NOT EDIT MANUALLY\nwindow.HYPERSTITION_DAILY_BRIEF = " + json.dumps(brief_payload, ensure_ascii=False) + ";\n" out_js_path.write_text(js_body, encoding="utf-8") - # Update append-only Bayesian state ledger outside read-only files (deduplicating same-day identical posteriors) + # Update append-only Bayesian state ledger outside read-only files + # Deduplicate entries matching BOTH calendar day (generated_at_utc[:10]) AND session_window raw_history = list(prior_state.get("run_history") or []) dedup_history: list[dict[str, Any]] = [] for entry in raw_history: if not isinstance(entry, dict): continue e_dt = str(entry.get("generated_at_utc") or "")[:10] + e_win = entry.get("session_window") e_post = entry.get("posterior_probabilities") - if dedup_history and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == e_dt and dedup_history[-1].get("posterior_probabilities") == e_post: + if e_win is not None: + match_idx = next( + ( + i + for i, prev in enumerate(dedup_history) + if str(prev.get("generated_at_utc") or "")[:10] == e_dt and prev.get("session_window") == e_win + ), + None, + ) + if match_idx is not None: + dedup_history[match_idx] = entry + else: + dedup_history.append(entry) + elif ( + dedup_history + and dedup_history[-1].get("session_window") is None + and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == e_dt + and dedup_history[-1].get("posterior_probabilities") == e_post + ): dedup_history[-1] = entry else: dedup_history.append(entry) cur_dt_10 = str(brief_payload["generated_at_utc"])[:10] cur_post = bayesian_block["posterior_probabilities"] - if dedup_history and str(dedup_history[-1].get("generated_at_utc") or "")[:10] == cur_dt_10 and dedup_history[-1].get("posterior_probabilities") == cur_post: - dedup_history[-1] = { - "run_number": int(dedup_history[-1].get("run_number") or len(dedup_history)), + cur_match_idx = next( + ( + i + for i, prev in enumerate(dedup_history) + if str(prev.get("generated_at_utc") or "")[:10] == cur_dt_10 and prev.get("session_window") == resolved_window + ), + None, + ) + if cur_match_idx is not None: + dedup_history[cur_match_idx] = { + "run_number": int(dedup_history[cur_match_idx].get("run_number") or (cur_match_idx + 1)), + "session_window": resolved_window, "generated_at_utc": brief_payload["generated_at_utc"], "posterior_probabilities": cur_post, - "question_id": str(dedup_history[-1].get("question_id") or current_question["question_id"]), + "question_id": str(dedup_history[cur_match_idx].get("question_id") or current_question["question_id"]), "cidv1": brief_payload["ipld_dag_json_cidv1"]["/"], } else: next_run_num = (int(dedup_history[-1].get("run_number") or len(dedup_history)) + 1) if dedup_history else 1 dedup_history.append({ "run_number": next_run_num, + "session_window": resolved_window, "generated_at_utc": brief_payload["generated_at_utc"], "posterior_probabilities": cur_post, "question_id": f"Q-RUN-{next_run_num:04d}", @@ -492,10 +547,11 @@ def build_daily_portfolio_brief( new_state = { "version": CURRENT_VERSION, "run_number": effective_run_number, + "session_window": resolved_window, "updated_at_utc": brief_payload["generated_at_utc"], "latest_posteriors": bayesian_block["posterior_probabilities"], "active_daily_question": current_question, - "run_history": dedup_history[-30:], + "run_history": dedup_history[-60:], } state_path.parent.mkdir(parents=True, exist_ok=True) state_path.write_text(json.dumps(new_state, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") @@ -506,14 +562,27 @@ def build_daily_portfolio_brief( def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="hs-daily-brief", description="Generate the 5-Agenda Zero-Synthetic-Data Daily Portfolio & Memetic Regime Update.") ap.add_argument("--live-macro", action="store_true", help="Fetch fresh FRED CSV series before computing the daily brief.") + ap.add_argument( + "--window", + "--session-window", + dest="session_window", + choices=["auto", "us-pre-market-open", "us-closing-bell", "utc-rollover"], + default="auto", + help="Session window tag (default: auto-detected from UTC hour).", + ) args = ap.parse_args(argv) - brief = build_daily_portfolio_brief(allow_live_network=args.live_macro, write_files=True) + brief = build_daily_portfolio_brief( + allow_live_network=args.live_macro, + write_files=True, + session_window=args.session_window, + ) print( json.dumps( { "ok": True, "version": brief["version"], "run_number": brief["run_number"], + "session_window": brief["session_window"], "posteriors": brief["agenda_1_executive_summary"]["bayesian_regime_inference"]["posterior_probabilities"], "question_id": brief["agenda_5_daily_key_macro_question_and_rigor"]["active_daily_question"]["question_id"], "cidv1": brief["ipld_dag_json_cidv1"]["/"], diff --git a/tests/test_core_suite.py b/tests/test_core_suite.py index 0e7b5db..7586496 100644 --- a/tests/test_core_suite.py +++ b/tests/test_core_suite.py @@ -950,6 +950,10 @@ def test_ipld_quant_and_mcp_server() -> None: vps_prod_sh = cfg_test.core_dir / "deploy" / "run-vps-data-production.sh" assert vps_prod_sh.is_file() and "/dev/null" not in vps_prod_sh.read_text(encoding="utf-8") + vps_prod_txt = vps_prod_sh.read_text(encoding="utf-8") + assert "--window=auto" in vps_prod_txt or '--window=*' in vps_prod_txt + assert "us-pre-market-open" in vps_prod_txt + assert '--window "${WINDOW_MODE}"' in vps_prod_txt for u_name in ( "hyperstition-closing-bell-harvest.service", "hyperstition-closing-bell-harvest.timer", @@ -958,6 +962,63 @@ def test_ipld_quant_and_mcp_server() -> None: ): assert (cfg_test.core_dir / "deploy" / u_name).is_file() + # Verify Plan #72: Dual-Calendar Pre-Market-Open Timer & Session-Window Brief Deduplication + cb_timer_txt = (cfg_test.core_dir / "deploy" / "hyperstition-closing-bell-harvest.timer").read_text(encoding="utf-8") + assert "OnCalendar=Mon..Fri *-*-* 14:00:00 UTC" in cb_timer_txt + assert "OnCalendar=Mon..Fri *-*-* 21:30:00 UTC" in cb_timer_txt + cb_svc_txt = (cfg_test.core_dir / "deploy" / "hyperstition-closing-bell-harvest.service").read_text(encoding="utf-8") + assert "--window=auto" in cb_svc_txt + + import datetime as _dt + from types import SimpleNamespace + from unittest.mock import patch as _mock_patch + from hyperstitionstud_io.quant.collector import build_financial_quant_harvest as _bfqh + from hyperstitionstud_io.quant.daily_brief import ( + _resolve_session_window, + build_daily_portfolio_brief, + ) + + assert _bfqh(harvest_mode="us-pre-market-open", live_fetch=False)["harvest_mode"] == "us-pre-market-open" + assert _resolve_session_window("auto", _dt.datetime(2026, 12, 2, 14, 0, tzinfo=_dt.timezone.utc)) == "us-pre-market-open" + assert _resolve_session_window("auto", _dt.datetime(2026, 12, 2, 21, 30, tzinfo=_dt.timezone.utc)) == "us-closing-bell" + assert _resolve_session_window("auto", _dt.datetime(2026, 12, 2, 0, 5, tzinfo=_dt.timezone.utc)) == "utc-rollover" + + tmp_brief_core = tmp_path / "brief_core_tmp" + (tmp_brief_core / "site" / "quant").mkdir(parents=True, exist_ok=True) + seed_hist = [ + { + "run_number": idx + 1, + "session_window": "us-closing-bell", + "generated_at_utc": "", + "posterior_probabilities": {"R1_BULL_RISK_ON": 0.25, "R2_PINNED_ISOMETRIC": 0.50, "R3_TAIL_DRAWDOWN_RISK_OFF": 0.25}, + "question_id": f"Q-RUN-{idx + 1:04d}", + "cidv1": f"baguqeeraseed{idx:04d}", + } + for idx in range(62) + ] + # Ensure unique dates in seed_hist so none collide with each other + base_seed_dt = _dt.date(2026, 9, 1) + for idx, item in enumerate(seed_hist): + item["generated_at_utc"] = (base_seed_dt + _dt.timedelta(days=idx)).strftime("%Y-%m-%dT21:30:00Z") + (tmp_brief_core / "site" / "quant" / "daily-brief-state.json").write_text( + json.dumps({"version": "2.18.0", "run_number": 62, "run_history": seed_hist}, indent=2), + encoding="utf-8", + ) + fake_cfg = SimpleNamespace(core_dir=tmp_brief_core, archive_dir=cfg_test.archive_dir, read_only_files=()) + with _mock_patch("hyperstitionstud_io.quant.daily_brief.load_workspace_config", return_value=fake_cfg): + b_am = build_daily_portfolio_brief(allow_live_network=False, write_files=True, session_window="us-pre-market-open") + assert b_am["session_window"] == "us-pre-market-open" + b_pm = build_daily_portfolio_brief(allow_live_network=False, write_files=True, session_window="us-closing-bell") + assert b_pm["session_window"] == "us-closing-bell" + b_am_dup = build_daily_portfolio_brief(allow_live_network=False, write_files=True, session_window="us-pre-market-open") + assert b_am_dup["session_window"] == "us-pre-market-open" + + brief_state_out = json.loads((tmp_brief_core / "site" / "quant" / "daily-brief-state.json").read_text(encoding="utf-8")) + assert len(brief_state_out["run_history"]) == 60 + today_10 = b_am["generated_at_utc"][:10] + today_entries = [x for x in brief_state_out["run_history"] if x["generated_at_utc"][:10] == today_10] + assert [x["session_window"] for x in today_entries] == ["us-pre-market-open", "us-closing-bell"] + # Verify /engineering/ (hs-eng-docs) & /math/ (hs-math-docs) Piecewise & Non-Sequential Revertability from hyperstitionstud_io.publishing.engineering_docs import build_engineering_site from hyperstitionstud_io.publishing.math_docs import build_math_site