#304 生时纠正用途扫描提供可核对的覆盖依据 #309

Merged
Claude merged 5 commits from codex/rect-purpose-coverage-20261117 into staging 2026-11-17 10:57:00 +08:00
9 changed files with 655 additions and 35 deletions
+4
View File
@@ -1,5 +1,9 @@
# 印度占星 Skill 更新日志
## 2026-11-17 · 生时范围用途扫描补充覆盖依据
- 离线扫描为 Arudha、Vimshottari 和 Narayana 回执记录经校验的覆盖依据(BUG-1938)。Skill 版本沿用。
## 2026-11-17 · 生时纠正自选优先保存最近的分钟
- 自选后优先采用离填写时间最近、与换座线至少相隔 60 秒的段内整分钟。占星 Skill 版本不变(BUG-1952)。
+11
View File
@@ -26094,6 +26094,17 @@
- 关联记录:BUG-1935、BUG-1922。
- 修复版本:`claude/admin-clarity-1936`(分支名沿用旧编号),待 staging 实测。
## BUG-1938 | 生时纠正用途扫描缺少 Arudha 和应期的宽范围覆盖依据
- 状态:fixed-pending-verify(离线后端,待独立验收)。
- 首次发现 / 最近更新:2026-11-16 / 2026-11-17。
- 触发与现象:多个用途同时要求 Arudha 或应期时,分钟抽样即使稳定也只算抽样覆盖。
- 根因:旧提供器把秒级逐点扫描当成覆盖前提。BUG-1932 的初版保守回执测试有秒级短范围应期和结构用途,缺少宽范围下按计算依赖验证覆盖的用例。
- 修复:Arudha 验证换座分段,Vimshottari 验证星宿内周期平移,Narayana 同时检查行星度数排序与周期平移。回执记录可复核的依据,发现不一致仍降级。
- 验证与防复发:原生引擎的三类逐秒对照与合成反例覆盖同秒换座、逆行过零、区段中点反常、日期反向、周期重排和跨星宿。见 [研究对照](research/rect-purpose-coverage-20261117.md)。
- 关联记录:#304、#297、BUG-1932、BUG-1953。
- 修复版本:`codex/rect-purpose-coverage-20261117`,待独立验收。
## BUG-1939 | 聊天扣点数改成后台设定后,页面仍按「1 点」判断余额,也不告诉用户每次扣多少
- 状态:fixed-pending-verify(待 staging 实测)。
@@ -0,0 +1,39 @@
# 生时纠正用途扫描的覆盖依据
## Arudha
`scripts/jaimini.py::calc_arudha_padas` 把上升的星座换成各宫起点。`calc_arudha_pada_for_house` 根据宫主星座数宫距,再按落点应用例外规则。因此 A1、A7、A10 和 UL 的星座只可能在上升或所用行星换座时变化。
扫描从原生星盘读取九曜黄经和速度,复用 D1 的上升换座搜索。行星顺行和逆行都按实际换座的两秒定位,逆行过 0° 时以星座真正改变的第一秒为界。同秒发生的多次换座合并。每个区段核对首尾和中点,有网格记录的区段也一起核对。随后只将前后两秒确有变化的点列为 Arudha 边界。高纬度、缺黄经、方向变化或区段内值不同,回执降为 `sampled_only`。
反例见 `test_arudha_rejects_internal_change_without_a_sign_cut`、`test_arudha_retrograde_wrap_and_simultaneous_cut` 和 `test_arudha_keeps_sampling_when_sign_inputs_are_uncertain`。
## Vimshottari
`scripts/rectification_purpose_gate/native.py::_vimshottari` 调用 `scripts/chart_dasha/birth_moment.py::mahadashas`。它从出生时刻扣除月亮在本宿已走的比例乘初运年数。`split_period` 再按固定比例切分。原生应期的平移量等于出生时刻的增量减去已走时长的增量。扫描要求同一宿内月亮前进且后一项足以抵消前一项,周期才向较早的日期移动。跨宿会重定初运,扫描先按真实跨宿秒分段。
每段检查月亮确实前进,各条周期的起止同向等量平移,且周期在预报窗口的进出与平移一致。相邻探针之间的平移必须短于最短周期,避免一个周期在两次探针之间出现又消失。签名变化时反复二分到秒,同一分钟有多个变化时逐个记录。很短的区间仍逐秒查。
反例见 `test_vimshottari_rejects_a_b_a_and_nonmonotone_dates` 和 `test_vimshottari_splits_at_nakshatra_and_verifies_each_segment`。
## Narayana
`scripts/rectification_purpose_gate/native.py::_narayana` 通过 `scripts/active_rectification_event_engine.py::_narayana_periods` 和 `_narayana_antardasha_table` 取得按年龄排列的周期。`scripts/narayana_rath.py::compare_signs` 和 `_same_sign_identity` 在强弱持平时比较星座内度数,计都从星座尾端量。因此即使星座固定,度数排序仍可能改变周期。只有星座相同、各行星的度数变化区间能确定排序、周期序列与年龄也一致时,这一段才按固定平移处理。
Narayana 与 Arudha 共用换座分段。检查相邻探针时用行星在该段的度数上下界排除可能的排名交叉。周期起止必须恰好随出生时刻同向平移,窗口内周期的进出要符合这个平移。度数区间有重叠、周期顺序变化或引擎未算出该层时,回执保留为 `sampled_only`。满足条件时按分钟网格和秒级二分记录不同签名的首秒。
反例见 `test_narayana_rejects_internal_period_reorder`、`test_narayana_rejects_degree_order_change_inside_one_sign` 和 `test_narayana_splits_at_an_ascendant_flip`。
## 原生引擎对照
沿用 #297 的三条合成夹具。表内「覆盖」「抽样」分别对应 `policy_covered`、`sampled_only`。
| 夹具 | 本次前 | 本次后 |
| --- | --- | --- |
| `stable_structure` | D1、D9、月亮宿均覆盖 | 三层均覆盖,仍可用于结构用途 |
| `crossing_d9` | D1、D9、月亮宿均覆盖,D9 有一条边界 | 三层及该边界一致,仍须缩小范围 |
| `vimshottari_date` | D1、D10、Vimshottari、Narayana 覆盖。A10、十宫及宫主、AmK、过运为抽样 | A10 转为覆盖,其余各层结果一致 |
另以 `vimshottari_date` 的范围起点为中心延展到前后各 30 分钟,设为事业、婚恋、财富的月粒度输入。A7、A10、UL、Vimshottari、Narayana 均由抽样变为有依据的覆盖。Vimshottari 的已知边界从 17 个增至 24 个。引擎计算 277 次,预算上限 4000。对同一范围另外做了 3601 次逐秒对照,五层边界均与 CLI 一致,本机耗时约 31 秒。缺生产器的层仍显示原有缺口,合并用途仍需缩小范围。
`test_native_coverage_matches_per_second_oracle` 对 Arudha 四层、Vimshottari 和 Narayana 分别做原生秒级对照,各取四分钟合成范围。每类至少有一条真实签名边界,两种搜索的边界逐秒一致。A1 在这项直接测试中验证,现有 CLI 用途政策不请求该层。
@@ -0,0 +1,20 @@
# #304 生时纠正用途扫描补覆盖依据
实现基于 `origin/staging` 的 `41357404f`,对应 BUG-1938。Arudha 枚举上升和九曜换座,Vimshottari 按月亮跨宿分段,Narayana 复用换座分段并检查度数排序。应期区段内核对周期平移与窗口成员变化。覆盖回执增加可选 `basis`,原有秒级精度和覆盖降级谓词沿用。
任务书把 Narayana 的段内周期视为星座的函数,实际引擎还比较星座内度数。度数排序无法确定的片段继续显示抽样。Vimshottari 的方向按原生日期的实际移动检查,即出生时刻向后、同一周期边界向较早时刻移动。
[覆盖依据和 #297 夹具对照](../research/rect-purpose-coverage-20261117.md)
## 验证
- 新增三类原生逐秒对照以及逆行过零、同秒换座、星座内变化、月亮跨宿、周期重排等反例。旧断言未改。
- 通过离线 CLI 复跑月粒度一小时合成样例。A7、A10、UL、Vimshottari、Narayana 五层均有 `basis`,计算 277 次(上限 4000)。另做 3601 次逐秒计算,五层的边界时刻一致。
- ESLint 0 错误,63 条既有告警。已检索服务端及前端入口对离线模块的导入,结果为空。
- Windows 开工预检确认 Gitea 可达,外部引擎适配器检查通过。首次运行触及超时上限。延长预检后碎片扫描通过,定向预检剩一项既有的 WorkBuddy 镜像路径断言失败。见预检台账 #279 记录。
- Windows 和 Linux 定向回归各通过 72 项与 26 个子测试。Linux 三类原生逐秒对照各用时约 0.09 秒、0.09 秒、0.67 秒。
- Linux `python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过。隐私标记检查通过(62 项)。
## 已知边界
A1 有提供器及原生逐秒对照。现有用途政策未把 A1 列入所需层,所以要求从同一 CLI 输入拿到 A1 回执的验收项仍缺。保持用途政策原样,其他缺生产器的层由 BUG-1953 接续。事业、财富和婚恋的可用范围仍受这些缺项约束。
@@ -0,0 +1,81 @@
# 生时纠正用途扫描:用算法性质给 Arudha 与应期出覆盖依据(2026-11-17,Claude)
Bug 编号:BUG-1938(#304 拆出的前一半)。关联 BUG-1932(#297)。后一半「缺生产器的层」另开 BUG-1953,等占星师回复,不在本单。
## 背景
#297 的扫描里,两类层在真实范围下永远到不了 `policy_covered`:
- Arudha(A1、A7、A10、UL):`_arudha_provider` 要求已检查点之间的最大间隔不超过 1 秒才算覆盖,30 分钟的范围做不到,只能给 `sampled_only`。
- 应期(Vimshottari、Narayana):`_timing_provider` 只有范围不超过 180 秒才逐秒检查,更宽的范围一律 `sampled_only`。
这两类层其实不需要逐秒检查,它们什么时候变可以从算法本身推出来。本单把这些性质写成代码和测试,让覆盖判定有依据。**只改覆盖判定的依据,不改任何层的计算结果,不放宽 `_receipt` 的规则。**
文件:`scripts/rectification_purpose_gate/providers.py`(主要)、`native.py`(只在需要暴露中间量时)。
## 一、Arudha
要证明并使用的性质:在一个范围内,如果上升星座不变、七颗行星(加上所用的交点)的星座都不变,那么 A1、A7、A10、UL 都不变。所以 Arudha 可能变化的时刻只在这些换座时刻上。
做法:
1. 先读 `scripts/jaimini.py::calc_arudha_padas`,确认它的输入只有上升星座和各行星星座。如果它还读了别的随时间变的量(度数、逆行、强弱比较等),把这些量也列进「可能变化的时刻」的来源;列不全就不要声称覆盖,在 PROGRESS 写明差在哪里。
2. 新的 Arudha 提供器:
- 上升换座时刻:用已有的 `find_lines(..., (1,), longitude_at=...)`,条件与 `_varga_provider` 相同(纬度不超过 60 度、网格上黄经单调前进)。
- 行星换座时刻:对每颗行星的黄经,按 `_sector_provider` 的办法在分钟网格上找跨 30 度整数倍的位置再二分到秒。逆行的行星黄经会倒退,跨界检测要两个方向都认。`sample` 的 `raw` 里目前只有上升和月亮的黄经;需要的行星黄经从 `native.py` 的 `_chart` 结果里加进 `raw`,不另算一遍。
- 在每个候选时刻的前一秒和这一秒各取一次 Arudha 值,值变了的才记为这一层的边界。
- 所有候选时刻都检查过、各段内首尾值相同,才给 `policy_covered`,`method_id` 写 `sign_change_enumeration`,`max_unchecked_gap_seconds` 写实际的网格间隔,并在回执的 `reason` 之外新增一个字段 `basis`,写明依据(例如 `arudha_depends_on_signs_only`)。`_receipt` 目前会把 `resolution > 1` 或 `error > 1` 的降成 `sampled_only`,这条不动;边界时刻本身仍然二分到 1 秒。
- 高纬度、黄经不单调、任一行星黄经取不到:退回现在的做法(`sampled_only`)。
3. 反例测试(必须有,不能只测通过的情况):
- 用确定性假函数造一个「星座都没变但 Arudha 值变了」的输入,新提供器必须**不给** `policy_covered`(靠段内首尾值核对或段中点抽查发现)。为此在每个无换座的段里至少再抽查一个中点。
- 行星逆行跨回上一个星座的情况能检出边界。
- 同一秒内上升和行星同时换座,只记一次边界。
## 二、Vimshottari
要证明并使用的性质:出生时刻往后移,月亮黄经单调增加,所有 Vimshottari 周期的起止日期随之**单调**向前移(月亮跨星宿边界的那一刻除外,那一刻整个序列跳变)。所以在一个月亮不跨星宿的段内,任何一条周期边界跨过「用户问的日期 / 月末 / 年末」的次数至多一次,分钟网格发现签名变化后二分到秒就是完整的。
做法:
1. 先读 `native.py::_vimshottari` 和它调用的引擎,确认上面的单调性在代码里成立(余额按月亮在星宿内的位置线性算出)。不成立就停下来在 PROGRESS 写明,不要硬套。
2. 新的应期提供器(Vimshottari):
- 月亮跨星宿的时刻用已有的 `_sector_provider` 逻辑求出,作为强制分段点。
- 每个段内:分钟网格上算 `period_signature`,相邻两点签名不同就二分到秒;再加一条单调性核对——段内各网格点上同一条周期边界的日期必须单调不减,发现倒退就不给覆盖。
- 通过则 `policy_covered`,`method_id` 写 `moon_monotone_minute_grid_bisection`,`basis` 写 `vimshottari_boundaries_monotone_in_moon_longitude`。
- 范围不超过 180 秒时保留现在的逐秒做法。
3. 反例测试:
- 假函数造一个段内签名 A→B→A(一分钟内变过去又变回来)的输入:单调性成立时这不可能发生,所以用「边界日期非单调」的假输入验证提供器会拒绝给覆盖。
- 月亮跨星宿的范围:分段点被检出,两段分别判定。
- 真实引擎一例:±30 分钟范围、按月粒度,逐秒暴力扫描得到的边界集合与新提供器给出的完全一致(暴力扫描只在这条测试里跑一次,范围可以缩到 ±5 分钟控制耗时,并标 `slow` 以外的现有标记方式;写明耗时)。
## 三、Narayana
要证明并使用的性质:Narayana 的周期顺序和年数只由上升星座和各行星星座决定;出生时刻在一个「星座都不变」的段内移动时,所有周期边界随出生时刻**整体平移同样的时长**(年龄不变,起点跟着出生时刻走)。所以段内签名变化同样至多发生在边界平移跨过问的日期时,分钟网格加二分足够;星座换座时刻是强制分段点。
做法:
1. 先读 `native.py::_narayana`、`_narayana_periods`、`_narayana_antardasha_table`,确认输入只有上升星座和行星星座(以及出生时刻作为起点)。有别的依赖按第一节第 1 条的办法处理。
2. 提供器结构同 Vimshottari,分段点用第一节求出的上升与行星换座时刻(两处共用,不重复计算)。`method_id` 写 `sign_segments_minute_grid_bisection`,`basis` 写 `narayana_periods_fixed_within_sign_segment`。
3. 反例测试:段内周期顺序变了的假输入必须不给覆盖;跨上升换座的范围被分成两段;真实引擎一例与逐秒暴力扫描对齐(同上,缩小范围)。
## 四、不做的事
- 不接宫主、Chara 征象星、金星/木星、过运、财富 Yoga、Ashtakavarga 的生产器(BUG-1953)。本单之后领域用途(事业、钱财、婚恋)仍然会因为这些层 `blocked` 而到不了 `scope_ready`,这是预期,写进 PROGRESS 的「已知边界」。
- 不改 `scope._policy` 的层表,不改 `assess_use`,不改 `scan._receipt`、`_assessment` 的判定规则。
- 不接任何生产入口(API、页面、聊天都不导入新代码)。
- 不改 `scripts/chart_choice/`、`frontend/`、`scripts/report_render/`、`references/real_case_calibration/`。
- 不改 `scripts/jaimini.py` 和大运引擎的计算。
## 五、交付
- 代码与测试:`tests/test_rectification_purpose_coverage.py`(新文件,放本单全部测试);`tests/test_rectification_purpose_scan.py`、`test_rectification_purpose_binding.py`、`test_active_rectification_candidates.py`、`test_rectification_purpose_gate.py` 照旧通过,不删改旧断言。旧断言里写死 Arudha 或应期为 `sampled_only` 的,确实因本单变成 `policy_covered` 时可以改,逐条在 PROGRESS 说明。
- `docs/research/rect-purpose-coverage-20261117.md`:三条性质各一节,写「代码依据(文件和函数)→ 性质 → 提供器怎么用它 → 反例测试名」,再给一张表:三例真实引擎输入(用 #297 夹具里的那三例)在本单前后各层的覆盖状态对照。这份文档会转给占星师审,用普通话写,不堆术语。
- `docs/BUG_HISTORY.md` 在 BUG-1938 一节记录(没有就新增;只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。`CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-purpose-coverage-20261117.md`。
## 验收
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
- 新测试文件全部通过,三类层各有至少一条反例测试和一条与逐秒暴力扫描对齐的真实引擎测试;
- 用命令行入口 `python -m scripts.rectification_purpose_gate --input <json>` 跑一个 ±30 分钟、按月粒度的合成输入:A1/A7/A10/UL、Vimshottari、Narayana 的回执为 `policy_covered` 并带 `basis`;整次扫描的计算次数不超过默认预算 4000;
- `cd frontend && npx eslint .` 0 错误(本单不应有前端改动);
- 没有任何生产入口导入 `scripts/rectification_purpose_gate`(验收时会 grep)。
@@ -148,6 +148,10 @@ def native_scope_compute(scope: dict):
name: float(item["lon"]) for name, item in chart["planets"].items()
if isinstance(item, dict) and isinstance(item.get("lon"), (int, float)) and isfinite(item["lon"])
}
speeds = {
name: float(item["speed"]) for name, item in chart["planets"].items()
if isinstance(item, dict) and isinstance(item.get("speed"), (int, float)) and isfinite(item["speed"])
}
moon = planets.get("Moon")
ref = "native:" + fingerprint({"profile": profile, "at": at.isoformat(), "ascendant": asc, "planets": planets})
arudhas = jaimini.calc_arudha_padas(int(asc // 30), planets)["padas"] if ARUDHAS.intersection(required) else {}
@@ -177,6 +181,7 @@ def native_scope_compute(scope: dict):
return {
**packet, "outputs": outputs,
"raw": {"ascendant_longitude": asc, "moon_longitude": moon, "planet_longitudes": planets,
"planet_speeds": speeds,
"chart_ref": ref, "native_adapter_version": NATIVE_METHOD_VERSION,
"calculation_contract": chart.get("calculation_contract", chart.get("contract"))},
}
+273 -35
View File
@@ -3,20 +3,24 @@
from __future__ import annotations
from datetime import timedelta
from functools import cache
from itertools import pairwise
from math import floor
from math import floor, isfinite
from scripts.active_rectification_candidates import MAX_WINDOW_MINUTES
from scripts.chart_choice.boundaries import ChartRequest, find_lines
from scripts.dasha_common import VIMSHOTTARI_YEARS
from .native import ANGLE_DIMENSIONS, ARUDHAS, division_of
from .scan import BoundaryMethodUnavailable
from .scope import SECOND, range_limits
from .timing import TIMING_OUTPUTS, period_signature
from .scope import SECOND, range_limits, stamp
from .timing import TIMING_OUTPUTS, output_periods, period_signature
MINUTE = timedelta(minutes=1)
CHUNK = timedelta(minutes=MAX_WINDOW_MINUTES - 1)
TIMING_EXACT_SECONDS = 180
GRAHAS = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu")
DATE_ROUNDING = timedelta(microseconds=2)
def _grid(start, end, step):
@@ -26,13 +30,14 @@ def _grid(start, end, step):
yield end
def _details(method, points, boundaries, *, bounded, reason=None):
def _details(method, points, boundaries, *, bounded, reason=None, basis=None):
max_gap = max(((right - left).total_seconds() for left, right in zip(points, points[1:])), default=0)
return {
"state": "policy_covered" if bounded else "sampled_only",
"method_id": method, "boundaries": boundaries, "resolution_seconds": 1,
"max_unchecked_gap_seconds": max_gap,
"boundary_error_seconds": 1 if boundaries else 0, "reason": reason,
**({"basis": basis} if bounded and basis else {}),
}
@@ -46,8 +51,12 @@ def _bisect_change(left, right, changes):
return right
def _longitude_delta(left, right) -> float:
return (right - left + 180) % 360 - 180
def _ascending_enough(left, right) -> bool:
return 0 <= (right - left + 180) % 360 - 180 < 2.0
return 0 <= _longitude_delta(left, right) < 2.0
def _longitude(row: dict, key: str) -> float:
@@ -148,47 +157,273 @@ def _discover_changes(points, value_at):
return cuts
def _arudha_provider(layer):
def _midpoint(left, right):
return left + SECOND * (int((right - left).total_seconds()) // 2)
def _with_midpoints(points):
return sorted(set(points) | {_midpoint(left, right) for left, right in pairwise(points)})
def _segment_probes(start, end, boundaries, grid):
edges = (start, *boundaries, end + SECOND)
for left, after in pairwise(edges):
right = after - SECOND
interior = {at for at in grid if left < at < right}
probes = set(_with_midpoints(sorted({left, right} | interior)))
probes.add(_midpoint(left, right))
yield sorted(probes)
def _planet_longitude(row, name):
value = (row.get("raw") or {}).get("planet_longitudes", {}).get(name)
if not isinstance(value, (int, float)) or not isfinite(value):
raise BoundaryMethodUnavailable("planet_longitude_unavailable")
return value % 360
def _one_direction(values):
deltas = [_longitude_delta(left, right) for left, right in pairwise(values)]
return (all(0 <= delta < 2 for delta in deltas) or
all(-2 < delta <= 0 for delta in deltas))
def _planet_direction(rows, name):
values = [_planet_longitude(row, name) for row in rows]
if not _one_direction(values):
return False
speeds = [(row.get("raw") or {}).get("planet_speeds", {}).get(name) for row in rows]
if not all(isinstance(speed, (int, float)) and isfinite(speed) for speed in speeds):
return False
if all(speed == 0 for speed in speeds):
return all(value == values[0] for value in values)
if not (all(speed > 0 for speed in speeds) or all(speed < 0 for speed in speeds)):
return False
return all(_longitude_delta(a, b) * speeds[0] > 0 for a, b in pairwise(values))
def _sign_layout_factory(profiles):
@cache
def layout(start, end, branch, sample):
profile = profiles[branch]
grid = list(_grid(start, end, MINUTE))
probes = _with_midpoints(grid)
if abs(profile["lat"]) > 60:
return grid, [], False
observed = {}
def row(at):
if at not in observed:
observed[at] = sample(at, branch)
return observed[at]
def asc(at):
return _longitude(row(at), "ascendant_longitude")
try:
rows = [row(at) for at in probes]
asc_values = [asc(at) for at in probes]
if not all(_ascending_enough(a, b) for a, b in pairwise(asc_values)):
return grid, [], False
if not all(_planet_direction(rows, name) for name in GRAHAS):
return grid, [], False
req = ChartRequest(start.date().isoformat(), profile["lat"], profile["lon"], 0,
profile["ayanamsa"], profile["node_mode"])
cuts = {line.at for left, right in pairwise(_grid(start, end, CHUNK))
for line in find_lines(req, left, right, (1,), longitude_at=asc)}
for name in GRAHAS:
def sign(at):
return int(_planet_longitude(row(at), name) // 30)
cuts.update(_discover_changes(probes, sign))
except BoundaryMethodUnavailable:
return grid, [], False
checked = [observed[at] for at in sorted(observed)]
bounded = all(_planet_direction(checked, name) for name in GRAHAS)
return grid, sorted(cuts), bounded
return layout
def _executed_output(sample, at, branch, layer):
output = sample(at, branch)["outputs"].get(layer)
return output if output and output["status"] == "executed" else None
def _arudha_provider(layer, sign_layout):
def provider(item, sample):
start, end = range_limits(item)
branch = item["branch_id"]
observed = set()
def value_at(at):
observed.add(at)
return sample(at, branch)["outputs"].get(layer, {}).get("value")
def value(at):
output = _executed_output(sample, at, branch, layer)
return output["value"] if output else None
points = _grid(start, end, MINUTE)
value_at(start)
cuts = _discover_changes(points, value_at)
checked = sorted(observed)
gap = max((right - left for left, right in pairwise(checked)), default=timedelta(0))
covered = gap <= SECOND and all(value_at(at) is not None for at in checked)
return _details("minute_grid_then_second_bisection", checked, cuts,
bounded=covered, reason=None if covered else "scan_incomplete")
grid, candidates, bounded = sign_layout(start, end, branch, sample)
if bounded:
segments = [set(map(value, points)) for points in _segment_probes(start, end, candidates, grid)]
bounded = all(len(values) == 1 and None not in values for values in segments)
if bounded:
cuts = [at for at in candidates if value(at - SECOND) != value(at)]
return _details("sign_change_enumeration", grid, cuts, bounded=True,
basis="arudha_depends_on_signs_only")
return _details("minute_grid_then_second_bisection", grid, _discover_changes(grid, value),
bounded=False, reason="scan_incomplete")
return provider
def _timing_provider(layer, forecast, granularity):
def _degree_order_fixed(rows):
# Narayana's strength and dual-lord rules compare unrounded degrees,
# with Ketu measured from the far end of its sign.
for before, after in pairwise(rows):
ranges = []
for name in GRAHAS:
a, b = (_planet_longitude(row, name) % 30 for row in (before, after))
if name == "Ketu":
a, b = 30 - a, 30 - b
ranges.append((min(a, b), max(a, b)))
if any(left[1] >= right[0] for left, right in pairwise(sorted(ranges))):
return False
return True
def _translated_periods(before, after, shift, forecast_limits):
lo, hi = forecast_limits
if not all(start < hi and end > lo and start < end
for periods in (before, after) for _, start, end in periods.values()):
return False
for key in before.keys() | after.keys():
if key not in before or key not in after:
# A period can be omitted only when the same translated interval
# lies outside the forecast window at the other probe.
_, start, end = (after if key in after else before)[key]
delta = -shift if key in after else shift
if start + delta < hi and end + delta > lo:
return False
continue
a, a_start, a_end = before[key]
b, b_start, b_end = after[key]
identity = ("lord", "level", "parent_period_id", "direction")
if (any(a.get(field) != b.get(field) for field in identity)
or abs(b_start - a_start - shift) > DATE_ROUNDING
or abs(b_end - a_end - shift) > DATE_ROUNDING):
return False
return True
def _timing_transitions(points, value):
cuts = []
for left, right in pairwise(points):
before, after = value(left), value(right)
while before != after:
edge = _bisect_change(left, right, lambda at: value(at) != before)
cuts.append(edge)
left, before = edge, value(edge)
return cuts
def _timing_provider(layer, forecast, granularity, sign_layout, moon_layout):
vim = layer == "Vimshottari"
forecast_limits = stamp(forecast["start"]), stamp(forecast["end"])
depth = {"year": 1, "month": 2, "day": 3}[granularity]
shortest_vim = timedelta(days=365.25 * 120 * (min(VIMSHOTTARI_YEARS.values()) / 120) ** depth)
def valid_pairs(points, periods, moon_longitude):
for left, right in pairwise(points):
a, b = periods(left), periods(right)
if vim:
common = sorted(a.keys() & b.keys())
if not common:
return False
shift = b[common[0]][1] - a[common[0]][1]
# A hidden period cannot enter and leave between two probes
# when the translation is shorter than the shortest period.
moon_delta = _longitude_delta(moon_longitude(left), moon_longitude(right))
if not (0 < moon_delta < 2 and -shortest_vim < shift <= timedelta(0)):
return False
else:
shift = right - left
if not _translated_periods(a, b, shift, forecast_limits):
return False
return True
def provider(item, sample):
start, end = range_limits(item)
branch = item["branch_id"]
exact = (end - start).total_seconds() <= TIMING_EXACT_SECONDS
signatures = {}
def value_at(at):
if at not in signatures:
output = sample(at, branch)["outputs"].get(layer)
signatures[at] = period_signature(output, forecast, granularity) if output and output["status"] == "executed" else None
return signatures[at]
@cache
def output(at):
return _executed_output(sample, at, branch, layer)
value_at(start)
cuts = _discover_changes(_grid(start, end, SECOND if exact else MINUTE), value_at)
complete = all(signatures.values())
return _details("native_period_windows_per_second" if exact else "native_period_windows_minute_sampling",
sorted(signatures), cuts, bounded=exact and complete,
reason="method_unresolved" if not complete else None if exact else "scan_incomplete")
@cache
def value(at):
row = output(at)
return period_signature(row, forecast, granularity) if row else None
@cache
def periods(at):
row = output(at)
return output_periods(row) if row else {}
if end - start <= SECOND * TIMING_EXACT_SECONDS:
grid = list(_grid(start, end, SECOND))
cuts = _discover_changes(grid, value)
complete = all(map(value, grid))
return _details("native_period_windows_per_second", grid, cuts, bounded=complete,
reason=None if complete else "method_unresolved")
if vim:
moon = moon_layout(item, sample)
grid = list(_grid(start, end, MINUTE))
forced = moon["boundaries"]
bounded = moon["state"] == "policy_covered"
else:
grid, forced, bounded = sign_layout(start, end, branch, sample)
cuts = []
reason = "scan_incomplete"
if bounded:
for points in _segment_probes(start, end, forced, grid):
if not all(map(value, points)):
reason = "method_unresolved"
bounded = False
break
if not vim and not _degree_order_fixed([sample(at, branch) for at in points]):
reason = "degree_order_unresolved"
bounded = False
break
checked = set(points)
def observe(at):
checked.add(at)
return value(at)
found = _timing_transitions(points, observe)
ordered = sorted(checked)
if not all(map(value, ordered)):
reason = "method_unresolved"
bounded = False
break
def moon_longitude(at):
return _longitude(sample(at, branch), "moon_longitude")
if not valid_pairs(ordered, periods, moon_longitude):
bounded = False
break
cuts.extend(found)
if not bounded:
fallback = _discover_changes(sorted(set(grid) | set(forced)), value)
return _details("native_period_windows_minute_sampling", grid, sorted(set(cuts + fallback)),
bounded=False, reason=reason)
cuts.extend(at for at in forced if value(at - SECOND) != value(at))
method = "moon_monotone_minute_grid_bisection" if vim else "sign_segments_minute_grid_bisection"
basis = ("vimshottari_boundaries_monotone_in_moon_longitude" if vim else
"narayana_periods_fixed_within_sign_segment")
return _details(method, grid, sorted(set(cuts)), bounded=True, basis=basis)
return provider
@@ -196,15 +431,18 @@ def _timing_provider(layer, forecast, granularity):
def native_boundary_providers(scope: dict) -> dict:
profiles = scope["profiles"]
purpose = scope["purpose_scope"]
sign_layout = _sign_layout_factory(profiles)
moon_layout = _sector_provider("moon_nakshatra", profiles)
providers = {}
for layer in scope["policy"]["required_layers"]:
division = division_of(layer)
if division is not None:
providers[layer] = _varga_provider(layer, division, profiles)
elif layer in ANGLE_DIMENSIONS:
providers[layer] = _sector_provider(layer, profiles)
providers[layer] = moon_layout if layer == "moon_nakshatra" else _sector_provider(layer, profiles)
elif layer in ARUDHAS:
providers[layer] = _arudha_provider(layer)
providers[layer] = _arudha_provider(layer, sign_layout)
elif layer in TIMING_OUTPUTS and purpose["forecast_window"] is not None:
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"])
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"],
sign_layout, moon_layout)
return providers
@@ -38,6 +38,7 @@ def _receipt(item: dict, layer: str, details: dict, bounds: list[datetime]) -> d
"resolution_seconds": resolution, "max_unchecked_gap_seconds": gap,
"boundary_error_seconds": error, "stop_tolerance_seconds": 1,
"reason": details.get("reason"),
**({"basis": details["basis"]} if state == "policy_covered" and details.get("basis") else {}),
"uncovered": [] if state == "policy_covered" else [{"start": start.isoformat(), "end": end.isoformat()}],
}
@@ -0,0 +1,221 @@
"""Boundary proof and per-second comparisons for the offline purpose scan."""
from datetime import datetime, timedelta, timezone
from functools import cache
from itertools import pairwise
import json
from pathlib import Path
import pytest
from scripts.rectification_purpose_gate.native import native_scope_compute
from scripts.rectification_purpose_gate.providers import GRAHAS, native_boundary_providers
from scripts.rectification_purpose_gate.scope import SECOND, build_scope_request, range_limits, stamp
from scripts.rectification_purpose_gate.timing import period_signature
START = datetime(2000, 1, 1, tzinfo=timezone.utc)
BRANCH = "synthetic"
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
ARUDHAS = ("A1", "A7", "A10", "UL")
def _scope(layers, midpoint=START, half=120, *, through=None):
original = json.loads(FIXTURE.read_text(encoding="utf-8"))["vimshottari_date"]["input"]
question = {**original["question"], "granularity": "month"}
if through:
question["forecast_end"] = through
ranges = [{"start": (midpoint - SECOND * half).isoformat(),
"end": (midpoint + SECOND * half).isoformat()}]
scope = build_scope_request(question, original["original_input"], ranges,
original["profiles"], original["evaluated_at"])
# Isolate the tested provider, including A1 which the current route does not request.
scope["policy"]["required_layers"] = list(layers)
return scope
def _value(value, **extra):
return {"status": "executed", "value": value, **extra}
def _period(start, end, key="md"):
return {"period_id": key, "start": start.isoformat(), "end": end.isoformat(),
"lord": key, "level": "MD", "parent_period_id": None}
def _synthetic(asc=lambda _: 15.0, planets=None, outputs=None):
def sample(at, _):
offset = int((at - START) / SECOND)
longitudes = {name: 30 * i + 1 + i * 1.6 for i, name in enumerate(GRAHAS)}
speeds = dict.fromkeys(GRAHAS, 0)
longitudes["Moon"] += offset * 0.0002
speeds["Moon"] = 17.28
if planets:
planets(offset, longitudes, speeds)
layer_values = {"moon_nakshatra": _value(int(longitudes["Moon"] / (360 / 27)))}
if outputs:
layer_values.update(outputs(offset))
return {"outputs": layer_values, "raw": {"ascendant_longitude": asc(offset),
"moon_longitude": longitudes["Moon"], "planet_longitudes": longitudes,
"planet_speeds": speeds}}
return sample
def _scan(scope, layer, sample):
return native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample)
def test_arudha_rejects_internal_change_without_a_sign_cut():
scope = _scope(["A1"], START + SECOND * 120, half=119)
sample = _synthetic(outputs=lambda t: {"A1": _value("B" if t == 120 else "A")})
result = _scan(scope, "A1", sample)
assert result["state"] == "sampled_only"
assert "basis" not in result
def _window_with(*layers):
return _scope(layers, START + SECOND * 120)
@pytest.mark.parametrize("with_ascendant", [False, True])
def test_arudha_retrograde_wrap_and_simultaneous_cut(with_ascendant):
def planets(t, longitudes, speeds):
# At t=30 Mercury is exactly on 0° and still in the same sign.
longitudes["Mercury"] = ((30 - t) * 0.00001) % 360
speeds["Mercury"] = -0.864
def asc(t):
return 30 + (t - 31) * 0.003 if with_ascendant else 15
sample = _synthetic(asc, planets, lambda t: {"A1": _value(t >= 31)})
result = _scan(_window_with("A1"), "A1", sample)
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
assert result["max_unchecked_gap_seconds"] == 60
@pytest.mark.parametrize("kind", ["missing", "station", "high-latitude"])
def test_arudha_keeps_sampling_when_sign_inputs_are_uncertain(kind):
def planets(t, longitudes, speeds):
if kind == "missing":
del longitudes["Mercury"]
if kind == "station":
longitudes["Mercury"] += abs(t - 30) * 0.00001
speeds["Mercury"] = -1 if t < 30 else 1
scope = _window_with("A1")
if kind == "high-latitude":
scope["profiles"][BRANCH]["lat"] = 65
sample = _synthetic(planets=planets, outputs=lambda _: {"A1": _value("A")})
assert _scan(scope, "A1", sample)["state"] == "sampled_only"
def test_vimshottari_rejects_a_b_a_and_nonmonotone_dates():
scope = _window_with("Vimshottari")
q = scope["purpose_scope"]["forecast_window"]
target = stamp(q["start"]) + timedelta(days=2)
q["target_boundaries"] = [target.isoformat()]
def outputs(t):
date = target + timedelta(days=1 if 25 <= t < 35 else -1)
return {"Vimshottari": _value("periods", periods=[_period(date, date + timedelta(days=15))])}
result = _scan(scope, "Vimshottari", _synthetic(outputs=outputs))
assert result["state"] == "sampled_only"
assert "basis" not in result
def test_vimshottari_splits_at_nakshatra_and_verifies_each_segment():
scope = _window_with("Vimshottari")
q = scope["purpose_scope"]["forecast_window"]
mid = stamp(q["start"]) + timedelta(days=2)
def planets(t, longitudes, speeds):
longitudes["Moon"] = 40 + (t - 31) * 0.0001
def outputs(t):
shift = timedelta(hours=1 if t >= 31 else 0, seconds=-t)
return {"Vimshottari": _value("periods", periods=[
_period(mid + shift, mid + shift + timedelta(days=15), "next" if t >= 31 else "first")])}
result = _scan(scope, "Vimshottari", _synthetic(planets=planets, outputs=outputs))
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
def test_narayana_rejects_internal_period_reorder():
q = _window_with("Narayana")["purpose_scope"]["forecast_window"]
date = stamp(q["start"]) + timedelta(days=2)
def outputs(t):
start = date + SECOND * t
key = "other" if 25 <= t < 35 else "md"
return {"Narayana": _value("periods", periods=[_period(start, start + timedelta(days=40), key)])}
result = _scan(_window_with("Narayana"), "Narayana", _synthetic(outputs=outputs))
assert result["state"] == "sampled_only"
assert "basis" not in result
def test_narayana_rejects_degree_order_change_inside_one_sign():
date = stamp(_window_with("Narayana")["purpose_scope"]["forecast_window"]["start"])
def planets(t, longitudes, speeds):
longitudes["Mercury"] = 90 + 1 + (31 - t) * 0.00001
speeds["Mercury"] = -0.864
def outputs(t):
return {"Narayana": _value("periods", periods=[
_period(date + SECOND * t, date + SECOND * t + timedelta(days=40))])}
result = _scan(_window_with("Narayana"), "Narayana", _synthetic(planets=planets, outputs=outputs))
assert (result["state"], result["reason"]) == ("sampled_only", "degree_order_unresolved")
def test_narayana_splits_at_an_ascendant_flip():
scope = _window_with("Narayana")
q = scope["purpose_scope"]["forecast_window"]
date = stamp(q["start"]) + timedelta(days=1)
def outputs(t):
start = date + SECOND * t
key = "other" if t >= 31 else "md"
return {"Narayana": _value("periods", periods=[_period(start, start + timedelta(days=40), key)])}
sample = _synthetic(lambda t: 30 + (t - 31) * 0.003, outputs=outputs)
result = _scan(scope, "Narayana", sample)
assert result["state"] == "policy_covered"
assert result["boundaries"] == [START + SECOND * 31]
@pytest.mark.parametrize("group", ["Arudha", "Vimshottari", "Narayana"])
def test_native_coverage_matches_per_second_oracle(group):
if group == "Arudha":
scope = _scope(ARUDHAS, START + timedelta(hours=1, minutes=37, seconds=25))
elif group == "Vimshottari":
scope = _scope([group])
else:
scope = _scope([group], through="2027-01-01T00:00:00Z")
q = scope["purpose_scope"]["forecast_window"]
midpoint_output = native_scope_compute(scope)(START, BRANCH)["outputs"][group]
assert midpoint_output["status"] == "executed"
q["target_boundaries"] = [next(row["start"] for row in midpoint_output["periods"]
if stamp(q["start"]) < stamp(row["start"]) < stamp(q["end"]))]
sample = cache(native_scope_compute(scope))
item = scope["plausible_ranges"][0]
start, end = range_limits(item)
forecast = scope["purpose_scope"]["forecast_window"]
saw_boundary = False
for layer, provider in native_boundary_providers(scope).items():
result = provider(item, sample)
assert result["state"] == "policy_covered"
values = []
times = [start + SECOND * i for i in range(int((end - start) / SECOND) + 1)]
for at in times:
row = sample(at, BRANCH)["outputs"][layer]
assert row["status"] == "executed"
values.append(row["value"] if group == "Arudha" else period_signature(row, forecast, "month"))
expected = [at for at, (left, right) in zip(times[1:], pairwise(values)) if left != right]
assert result["boundaries"] == expected
saw_boundary |= bool(expected)
assert saw_boundary