"""Offline purpose-layer projections, real edge scans, and conservative counterexamples.""" from datetime import datetime, timedelta, timezone from functools import cache from itertools import pairwise import json from pathlib import Path import sys import pytest from scripts.rectification_purpose_gate import __main__ as cli from scripts.rectification_purpose_gate.layer_values import GRAHAS, LAYER_NAMES from scripts.rectification_purpose_gate.native import native_scope_compute from scripts.rectification_purpose_gate.providers import CHUNK, native_boundary_providers from scripts.rectification_purpose_gate.scan import scan_scope from scripts.rectification_purpose_gate.scope import SECOND, build_scope_request, range_limits, stamp from scripts.rectification_purpose_gate.timing import period_envelopes START = datetime(2000, 1, 1, tzinfo=timezone.utc) BRANCH = "synthetic" FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json" SAMPLED = {"venus_jupiter", "annual_chart"} ASC_EDGE = "2000-01-01T01:37:25+00:00" SKY_EDGE = "2000-01-02T06:12:39+00:00" EDGES = { "house_lords": ASC_EDGE, "lord_placements": ASC_EDGE, "planet_signs": SKY_EDGE, "planet_vargas:D2": "2000-01-01T00:13:32+00:00", "planet_vargas:D9": "2000-01-01T03:32:03+00:00", "planet_vargas:D10": "2000-01-01T00:13:32+00:00", "planet_vargas:D11": "2000-01-01T02:55:56+00:00", "functional_roles": "2000-01-21T04:40:27+00:00", "venus_jupiter": ASC_EDGE, "aspects": SKY_EDGE, "chara_karakas": "2000-01-01T05:33:59+00:00", "ashtakavarga": ASC_EDGE, "wealth_yogas": ASC_EDGE, "raj_yogas": ASC_EDGE, "transit_relations": ASC_EDGE, "annual_chart": "2000-01-01T00:23:22+00:00", } def _packet(start, end, *, lon=None): packet = json.loads(FIXTURE.read_text(encoding="utf-8"))["vimshottari_date"]["input"] packet["question"].update( granularity="month", forecast_start="2026-01-01T00:00:00+00:00", forecast_end="2027-01-01T00:00:00+00:00", target_boundaries=[], ) packet["remaining_ranges"] = [{"start": start.isoformat(), "end": end.isoformat()}] if lon is not None: packet["profiles"]["branches"][BRANCH]["lon"] = lon return packet def _scope(packet, layers): scope = build_scope_request(packet["question"], packet["original_input"], packet["remaining_ranges"], packet["profiles"], packet["evaluated_at"]) # Isolate these producers without changing the question routing policy. scope["policy"]["required_layers"] = sorted(layers) return scope def _second_edges(sample, item, layer): start, end = range_limits(item) branch = item["branch_id"] points = [start + SECOND * count for count in range(int((end - start) / SECOND) + 1)] values = [sample(at, branch)["outputs"][layer]["value"] for at in points] assert all(value is not None for value in values) return [at for at, (before, after) in zip(points[1:], pairwise(values)) if before != after] @pytest.mark.parametrize("layer,edge", EDGES.items()) def test_real_edges_match_every_second(layer, edge): at = stamp(edge) packet = _packet(at - 120 * SECOND, at + 120 * SECOND, lon=-45 if layer == "functional_roles" else None) scope = _scope(packet, [layer]) sample = cache(native_scope_compute(scope)) item = scope["plausible_ranges"][0] details = native_boundary_providers(scope)[layer](item, sample) assert details["state"] == ("sampled_only" if layer in SAMPLED else "policy_covered"), details assert details["boundaries"] == _second_edges(sample, item, layer) assert at in details["boundaries"] before, after = sample(at - SECOND, BRANCH), sample(at, BRANCH) left, right = [row["outputs"][layer]["value"] for row in (before, after)] if layer in {"planet_vargas:D9", "planet_vargas:D10"}: assert left["Moon"] != right["Moon"] if layer == "functional_roles": raw = [row["raw"] for row in (before, after)] assert int(raw[0]["ascendant_longitude"] // 30) == int(raw[1]["ascendant_longitude"] // 30) phase = [int(((r["planet_longitudes"]["Moon"] - r["planet_longitudes"]["Sun"]) % 360) // 180) for r in raw] assert phase == [0, 1] assert "Moon" in left["malefics"] and "Moon" in right["neutrals"] if layer == "chara_karakas": assert any(left[role] != right[role] and "Moon" in (left[role], right[role]) for role in ("Darakaraka", "Amatyakaraka")) if layer == "annual_chart": assert [row["ascendant_sign"] for row in left["charts"]] != [row["ascendant_sign"] for row in right["charts"]] def _mock_value(value, layer): return {"status": "executed", "value": value, "method_id": "synthetic", "result_ref": f"test:{layer}"} def _fake(layer, value, *, geometry=None, ascendant=lambda _: 15): def sample(at, branch): tick = int((at - START) / SECOND) lons = {name: index * 30 + 1 + index * 1.6 for index, name in enumerate(GRAHAS)} speeds = dict.fromkeys(GRAHAS, 0.0) lons["Moon"] += tick * 0.0002 speeds["Moon"] = 17.28 if geometry: geometry(tick, lons, speeds) asc = ascendant(tick) return {"candidate_at": at.isoformat(), "branch_id": branch, "profile": {}, "outputs": {layer: _mock_value(value(tick, lons, asc), layer)}, "raw": {"ascendant_longitude": asc, "moon_longitude": lons["Moon"], "planet_longitudes": lons, "planet_speeds": speeds}} return cache(sample) @pytest.mark.parametrize("layer", sorted(LAYER_NAMES - {"strength_shadbala"})) def test_change_without_a_matching_geometric_cut_never_gets_coverage(layer): scope = _scope(_packet(START, START + 120 * SECOND), [layer]) sample = _fake(layer, lambda tick, *_: {"value": "before" if tick < 30 else "after"}) receipt = native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample) assert receipt["state"] == "sampled_only" assert "basis" not in receipt assert receipt["boundaries"] == [START + 30 * SECOND] def test_karaka_finds_and_separates_two_rank_changes_between_minute_samples(): layer = "chara_karakas" scope = _scope(_packet(START, START + 60 * SECOND), [layer]) def geometry(tick, lons, speeds): lons.update(Moon=33.9 + tick / 240, Sun=4.0, Mars=64.06) speeds["Moon"] = 360 sample = _fake(layer, lambda tick, lons, asc: sorted(GRAHAS[:7], key=lambda name: lons[name] % 30, reverse=True), geometry=geometry) item = scope["plausible_ranges"][0] details = native_boundary_providers(scope)[layer](item, sample) assert details["state"] == "policy_covered" assert details["boundaries"] == _second_edges(sample, item, layer) assert len(details["boundaries"]) == 2 assert all(START < edge < START + 60 * SECOND for edge in details["boundaries"]) def test_retrograde_planet_varga_detects_wrap_in_reverse_direction(): layer = "planet_vargas:D9" scope = _scope(_packet(START, START + 60 * SECOND), [layer]) def geometry(tick, lons, speeds): lons["Rahu"] = (0.025 - tick / 1000) % 360 speeds["Rahu"] = -86.4 sample = _fake(layer, lambda tick, lons, asc: {"Rahu": int(lons["Rahu"] // 30)}, geometry=geometry) item = scope["plausible_ranges"][0] details = native_boundary_providers(scope)[layer](item, sample) assert details["state"] == "policy_covered" assert details["boundaries"] == _second_edges(sample, item, layer) == [START + 26 * SECOND] def test_shadbala_is_explicitly_unavailable_without_invoking_strength_calculation(monkeypatch): import shadbala def unexpected_strength(*args, **kwargs): pytest.fail("The offline purpose scan must never compute Shadbala") monkeypatch.setattr(shadbala, "calc_shadbala", unexpected_strength) layer = "strength_shadbala" scope = _scope(_packet(START, START + 60 * SECOND), [layer]) compute = native_scope_compute(scope) output = compute(START, BRANCH)["outputs"][layer] assert (output["status"], output["value"], output["method_id"]) == ("blocked", None, "shadbala_pending_review") assessment = scan_scope(scope, compute, native_boundary_providers(scope)) receipt = assessment["per_layer_scan_receipts"][0] assert (receipt["state"], receipt["reason"], receipt["method_id"], receipt["boundary_times"]) == ( "incomplete", "method_unresolved", "shadbala_pending_review", [], ) def test_scan_deduplicates_boundary_on_the_240_minute_chunk_seam(): layer = "D1" scope = _scope(_packet(START, START + timedelta(minutes=240)), [layer]) seam = int(CHUNK / SECOND) sample = _fake(layer, lambda tick, lons, asc: int(asc // 30), ascendant=lambda tick: 30 + (tick - seam) / 6000) item = scope["plausible_ranges"][0] details = native_boundary_providers(scope)[layer](item, sample) assert details["boundaries"] == [START + CHUNK] assert details["state"] == "policy_covered" def test_midnight_range_keeps_the_exact_boundary(): layer = "D1" scope = _scope(_packet(START - 4 * SECOND, START + 4 * SECOND), [layer]) sample = _fake(layer, lambda tick, lons, asc: int(asc // 30), ascendant=lambda tick: 30 + tick / 6000) item = scope["plausible_ranges"][0] assert native_boundary_providers(scope)[layer](item, sample)["boundaries"] == [START] def test_disjoint_ranges_do_not_compose_a_bridge_or_duplicate_boundaries(): layer = "D1" packet = _packet(START - 4 * SECOND, START + 4 * SECOND) packet["remaining_ranges"].append({"start": (START + 14 * SECOND).isoformat(), "end": (START + 28 * SECOND).isoformat()}) scope = _scope(packet, [layer]) sample = _fake(layer, lambda tick, lons, asc: int(asc // 30), ascendant=lambda tick: 30 + tick / 6000 if tick < 14 else 60 + (tick - 20) / 6000) bound_profile = scope["profiles"][BRANCH] def bound_sample(at, branch): return {**sample(at, branch), "profile": bound_profile} result = scan_scope(scope, bound_sample, native_boundary_providers(scope)) receipts = result["per_layer_scan_receipts"] assert [r["boundary_times"] for r in receipts] == [[START.isoformat()], [(START + 20 * SECOND).isoformat()]] assert all(r["state"] == "policy_covered" for r in receipts) assert all(not START + 4 * SECOND < stamp(row["candidate_at"]) < START + 14 * SECOND for row in result["candidates"]) def test_ayanamsa_and_node_branches_compare_independently(): layer = "planet_signs" at = stamp(SKY_EDGE) packet = _packet(at - 120 * SECOND, at + 120 * SECOND) branches = packet["profiles"]["branches"] branches["alternate"] = {**branches[BRANCH], "ayanamsa": "raman", "node_mode": "true"} bounds = packet["remaining_ranges"][0] packet["remaining_ranges"] = [{**bounds, "branch_id": branch} for branch in branches] scope = _scope(packet, [layer]) sample = cache(native_scope_compute(scope)) provider = native_boundary_providers(scope)[layer] for item in scope["plausible_ranges"]: details = provider(item, sample) assert details["boundaries"] == _second_edges(sample, item, layer) assert sample(at, BRANCH)["raw"]["planet_longitudes"]["Rahu"] != sample(at, "alternate")["raw"]["planet_longitudes"]["Rahu"] def test_incomplete_timing_returns_sample_ranges_rather_than_a_full_envelope(): layer = "Vimshottari" row = {"period_id": "md", "start": START.isoformat(), "end": (START + 60 * SECOND).isoformat()} output = {**_mock_value("native_periods", layer), "periods": [row]} candidates = [{"candidate_id": "test", "branch_id": BRANCH, "outputs": {layer: output}}] partial, = period_envelopes(candidates, layer, False) assert partial["scope"] == "sampled_points_range" and partial["common_window"] is None complete, = period_envelopes(candidates, layer, True) assert complete["scope"] == "full_interval_envelope" and complete["common_window"] is not None def test_offline_cli_input_runs_all_layers_within_the_candidate_budget(tmp_path, monkeypatch, capsys): packet_path = tmp_path / "synthetic.json" packet_path.write_text(json.dumps(_packet(START - 1800 * SECOND, START + 1800 * SECOND)), encoding="utf-8") def with_layers(*args): scope = build_scope_request(*args) scope["policy"]["required_layers"] = sorted(LAYER_NAMES) return scope monkeypatch.setattr(cli, "build_scope_request", with_layers) monkeypatch.setattr(sys, "argv", ["rectification_purpose_gate", "--input", str(packet_path)]) assert cli.main() == 0 result = json.loads(capsys.readouterr().out)["purpose_assessment"] assert result["budget"]["candidates_computed"] <= result["budget"]["candidate_limit"] == 4000 assert not result["budget"]["exhausted"] receipts = {r["layer"]: r for r in result["per_layer_scan_receipts"]} assert receipts.keys() == LAYER_NAMES assert {layer for layer, r in receipts.items() if r["state"] == "sampled_only"} == SAMPLED assert receipts["strength_shadbala"]["state"] == "incomplete" assert all(r["basis"] for layer, r in receipts.items() if layer not in SAMPLED | {"strength_shadbala"})