Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4c94e336d | ||
|
|
cec54bc7a2 | ||
|
|
a44dfb51fd |
@@ -1,5 +1,9 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-11-17 · 生时用途扫描按断言组判断
|
||||
|
||||
- 离线用途政策 v2 按断言组核对所需层和时间变化,婚恋预测细分四类事件。Skill 版本沿用(BUG-1962)。
|
||||
|
||||
## 2026-11-17 · 用途扫描补齐分盘行星、宫主和其他计算层
|
||||
|
||||
- 离线扫描新增必要层的原生取数与边界回执。Skill 版本沿用(BUG-1953)。
|
||||
|
||||
@@ -26369,6 +26369,17 @@
|
||||
- 修复版本:`claude/shadbala-defects-1961`,未推送。
|
||||
- 更正说明(2026-11-17,随本条追加,不改动原条目):BUG-1581、1582、1584、1586 原文把状态写成 `resolved`,并说改动是「按占星师裁定」;提交 `78f98eba` 的说明写的是 rulings implemented as given。核对她 2026-11-04、2026-11-05 两次答复的原文和她 2026-11-07 交接表之后,这个说法过头了:七分盘尊位分值和特殊相照分段公式是她对「BPHS 口径」这个具名版本给的方向,并且她写的是「候选计算合同」;太阳 Ayana 计 A+A 是她的推荐,她明确说是版本选择、另一种读法也能成立;月亮 Paksha 取 P 是「所核印刷版本有正文依据」;她 11-05 写明没有批准这些改动直接进入校正评分,11-07 把整个 Shadbala 标为待裁定。这几条应读作「按候选合同实现,待占星师验收」。BUG-1585 排除罗睺、计都仍是本仓的实现选择(她 11-05 指出这不是 BPHS 规则),没有改。BUG-1583、BUG-1587 的方向她是明确给过的。
|
||||
|
||||
## BUG-1962 | 生时用途政策把断言放在一起,时间粒度同时截断大运层级
|
||||
|
||||
- 状态:fixed-pending-verify,待独立验收。
|
||||
- 首次发现 / 最近更新:2026-11-17 / 2026-11-17。
|
||||
- 触发与现象:一个依赖未决时,原政策限制整份用途。年粒度省掉小运与小小运,也缺少行运按本命点度数计算的精确命中。
|
||||
- 根因:路由所需层作为一张平表,资料覆盖与用途决定同组。时间粒度同时用于比较日期和选择计算深度。
|
||||
- 修复:用途政策 v2 按断言组判断,绑定婚恋事件类别,Vimshottari 固定计算到 PD,Narayana 到 AD,记录五类时间变化。精确行运命中沿用年度服务,出生范围内给采样回执。保留 v1 复验。
|
||||
- 验证与防复发:按组隔离、缺层与失败区分、事件绑定、五类时间变化与容差、真实行运命中漂移和 v1 夹具均有回归。见 [#320 进度](tasks/PROGRESS-rect-purpose-policy-v2-20261117.md)。
|
||||
- 关联记录:#320、#307、#304、#297、BUG-1953、BUG-1938、BUG-1932。
|
||||
- 修复版本:`codex/rect-purpose-policy-v2-20261117`。
|
||||
|
||||
## BUG-1963 | 聊天「解读依据」的行星力量一行写「达标 / 未达标」,读起来像及格线
|
||||
|
||||
- 状态:fixed-pending-verify(待 staging 实测)。
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# 生时用途政策 v2
|
||||
|
||||
产品约定,待占星师确认。每个组列的是支持这一类说法所需的证据。用同一范围内的所有证据检查某一组时,组内任何一层有缺口或实质变化,该组会给出具体限制。其他组独立判断。
|
||||
|
||||
## 断言组与依赖
|
||||
|
||||
| 用途 | 断言组 | 依赖 |
|
||||
| --- | --- | --- |
|
||||
| 性格与格局 | `structure_core` | D1、月亮星宿、宫主、九曜落座、功能性吉凶、星座相位 |
|
||||
| 性格与格局 | `structure_d9` | D9 上升和行星落座 |
|
||||
| 性格与格局 | `structure_yogas` | Raja Yoga、Dhana Yoga |
|
||||
| 性格与格局 | `structure_strength` | Shadbala、八分点 |
|
||||
| 事业 | `career_direction` | D1、D10 上升和行星、宫主与宫主落宫、功能性吉凶、星座相位、征象星、A10 |
|
||||
| 事业 | `career_d9_support` | D9 上升和行星落座 |
|
||||
| 事业 | `career_yogas` | Raja Yoga |
|
||||
| 事业 | `career_strength` | Shadbala、八分点 |
|
||||
| 事业 | `career_timing` | 两套运限、整宫行运、年度盘、行运对本命点度数的精确命中 |
|
||||
| 钱财 | `wealth_structure` | D1、D2、D11、D2 与 D11 的行星、宫主与宫主落宫、功能性吉凶、A10 |
|
||||
| 钱财 | `wealth_d9_support` | D9 上升和行星落座 |
|
||||
| 钱财 | `wealth_yogas` | Dhana Yoga |
|
||||
| 钱财 | `wealth_strength` | Shadbala、八分点 |
|
||||
| 钱财 | `wealth_timing` | 两套运限、整宫行运、年度盘、行运对本命点度数的精确命中 |
|
||||
| 婚恋 | `relationship_pattern` | D1、D9 上升和行星、宫主与宫主落宫、金星木星、功能性吉凶、星座相位、征象星、UL、A7 |
|
||||
| 婚恋 | `relationship_strength` | Shadbala、八分点 |
|
||||
| 婚恋 | `relationship_timing:<event_class>` | 两套运限、整宫行运、年度盘、行运对本命点度数的精确命中 |
|
||||
|
||||
预测组只用于日、月、年粒度的事业、钱财、婚恋问题。婚恋类别暂为心动(`attraction`)、相识(`first_contact`)、成对(`pairing`)、法律婚(`legal_marriage`)。四类暂共用一张依赖表,待占星师区分。不同类别有独立指纹。缺类别时婚恋预测组需要补输入,其他组仍可评估。
|
||||
|
||||
钱财证据卡在任务书列出的 A1、A7、A10 中使用 A10,因此固定取 A10。卡片另列 A2、A11 的依据。路由里的复合标签按明确等价关系对照,比如「10 宫及宫主」由宫主和宫主落宫承接。未被表覆盖的路由层明确输出为 `unmapped_route_layers`,有未映射层时整项用途最多为有条件。
|
||||
|
||||
## 状态
|
||||
|
||||
| 状态 | 判断 |
|
||||
| --- | --- |
|
||||
| `scope_ready`(够用) | 组内每层都完整覆盖,且所有合理出生时刻支持同一组证据。 |
|
||||
| `conditional`(有条件) | 所需层方法未决、只做了抽样,或尚缺生产器。 |
|
||||
| `needs_refinement`(需要缩小范围) | 组内已观察到实质变化,回执列出变化层和观测时刻。 |
|
||||
| `needs_input`(需要补充) | 婚恋预测尚未选事件类别。 |
|
||||
| `insufficient_evidence`(证据不足) | 计算失败或扫描预算造成所需层不完整。 |
|
||||
|
||||
原始事实及其覆盖范围逐候选保存。Shadbala 仍为方法待核。整宫行运和度数命中各有独立证据。后者复用年度服务的本命上升与九曜黄经、精确合相及精确相位。出生范围用分钟网格发现变化后将已发现的变化定位到秒,这只给抽样回执。
|
||||
|
||||
## 时间粒度
|
||||
|
||||
Vimshottari 总算到 PD,Narayana 总算到 AD。年、月、日比较下面五项。
|
||||
|
||||
1. 问到的预测窗里有没有相关周期。
|
||||
2. 相关周期的主星、层级、父周期和周期标识。按标识比较,不按数组顺序配对。
|
||||
3. 窗内周期的起止是否跨过该日、该月、该年的边界,或问题明确给出的时间界线。
|
||||
4. 同一层级同一主星在窗内出现几段,其中相隔几次。相接的时段没有空隙。
|
||||
5. 同一层级同一主星在窗内的总时长是否变化超过容差。先合并重叠时段,再计入总时长。日、月、年的容差暂为 1、7、30 天,待占星师确认。
|
||||
|
||||
周期对某个断言的支持或反对方向还需绑定断言的解读,留待后续实现。
|
||||
@@ -0,0 +1,40 @@
|
||||
# #320 用途政策 v2
|
||||
|
||||
- [任务书](TASK-rect-purpose-policy-v2-20261117.md)。以 `origin/staging` 的 `cb60dfe3c` 开工。
|
||||
- [政策约定、组表和证据边界](../research/rect-purpose-policy-v2-20261117.md)。月、日、年均计算相同的原生大运深度。精确行运命中复用年度服务,保留抽样限制和实际移动的日期。
|
||||
|
||||
## v1 复验
|
||||
|
||||
| 原输入 | 新输入 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 三份 v1 原生用例及两组历史扫描/绑定测试依赖当时默认版本 | 显式传 `precision_policy_version=purpose_policy_v1`,原结果断言和原生数据均保留 | 新输入默认 v2,历史用例明确选择其原政策。 |
|
||||
|
||||
## CLI 合成例
|
||||
|
||||
三个例子均使用公开测试夹具里的前后各 30 分钟范围,比较一个月内的结果。婚恋例选择「成对」。每个格子列出 `limited_by` 的层和原因,具体候选时刻留在 CLI JSON。
|
||||
|
||||
| 断言组 | 状态 | `limited_by` |
|
||||
| --- | --- | --- |
|
||||
| `career_direction` | 需要缩小范围 | D10、D10 行星都有出生时刻相关变化 |
|
||||
| `career_d9_support` | 需要缩小范围 | D9 上升变化 |
|
||||
| `career_yogas` | 够用 | 无 |
|
||||
| `career_strength` | 有条件 | Shadbala 方法待核 |
|
||||
| `career_timing` | 需要缩小范围 | 见下段共同时间限制 |
|
||||
| `wealth_structure` | 需要缩小范围 | D2、D11 上升及 D2 行星变化 |
|
||||
| `wealth_d9_support` | 需要缩小范围 | D9 上升变化 |
|
||||
| `wealth_yogas` | 够用 | 无 |
|
||||
| `wealth_strength` | 有条件 | Shadbala 方法待核 |
|
||||
| `wealth_timing` | 需要缩小范围 | 见下段共同时间限制 |
|
||||
| `relationship_pattern` | 需要缩小范围 | D9 上升变化,金木星尊贵涉及座内度数,只抽样 |
|
||||
| `relationship_strength` | 有条件 | Shadbala 方法待核 |
|
||||
| `relationship_timing:pairing` | 需要缩小范围 | 见下段共同时间限制 |
|
||||
|
||||
三组预测共有的限制为 Vimshottari 周期身份、跨目标日期或粒度界线及窗内总时长发生实质变化,年度盘和精确行运命中也观察到变化且只完成抽样。事业、钱财、婚恋分别计算 368、290、351 次,都在 4000 次预算内,整体都需缩小范围。
|
||||
|
||||
这三个例子里,事业和钱财各有一组 Yoga 证据在整个范围一致,可以单独使用。方向、财务结构和婚恋格局仍受分盘变化影响,需要更小的出生范围。力量组等待方法确认。三个预测组观察到的日期或窗口变化已经影响结论,精确命中和年度盘的取样也只能说明样本中的变化。
|
||||
|
||||
## 验证
|
||||
|
||||
- 隔离 Linux 容器的 Python 快速门(`--profile quick --skip-frontend-runtime`)通过。仓库隐私标记测试 62 项通过。
|
||||
- 新旧用途套件 148 项、26 个子测试通过。三份原有 v1 夹具按原断言复验。ESLint 零错误,63 条既有警告。
|
||||
- Windows 预检的 Python、适配器和 Gitea 可见性通过。碎片扫描和定向预检分别在 90 秒、45 秒超时。
|
||||
@@ -7,6 +7,7 @@
|
||||
- 被环境或依赖挡住的事项写进根目录 `BLOCKED.md`;Bug 事实写进 `docs/BUG_HISTORY.md`;两者不在这里重复。
|
||||
- 纯文档改动不触发 staging 门禁(见 `deploy/gated-paths.txt`)。
|
||||
|
||||
- [生时用途政策 v2(#320)](PROGRESS-rect-purpose-policy-v2-20261117.md) — 断言组、时间粒度和三份原生 CLI 对照。
|
||||
- [用途扫描缺失层(#307)](PROGRESS-rect-purpose-layers-20261117.md) — 原生计算、分钟网格和逐秒边界对照。
|
||||
- [报告出生输入标示(#313)](PROGRESS-rect-artifact-marking-20261117.md) — 详情、Markdown 导出、合盘写入复核及返还。
|
||||
- [旧聊天出生依据过期(#314)](PROGRESS-rect-stale-chat-evidence-20261117.md) — 历史上下文、摘要与聊天分隔。
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
# 生时纠正用途政策 v2:按断言分组,时间粒度按实质变化判定(2026-11-17,Claude)
|
||||
|
||||
Bug 编号:BUG-1962(#320)。关联 BUG-1932(#297)、BUG-1938(#304)、BUG-1953(#307)。
|
||||
|
||||
## 背景
|
||||
|
||||
#297 的用途政策 `purpose_policy_v1`(`scripts/rectification_purpose_gate/scope.py::_policy`)把问题路由的 `required_layers` 原样当作所需层,整个用途只有一个结论:所需层里有一层算不了或会变,整个用途就不是「够用」。#307 已经补齐了大部分层的生产器。
|
||||
|
||||
占星师 11-17 的裁定:
|
||||
|
||||
1. 所需层以 `references/technique_registry.json` 和 `scripts/consultation_plan_contract.py` 为起点,补上实际参与断言的层;只列进清单不算执行。
|
||||
2. **每条拟输出的断言绑定它依赖的层**。某层算不了或会变时,只限制依赖它的断言,其余照常;不能把缺的层删出表后宣称「用途稳定」。
|
||||
3. 婚恋要把心动、相识、成对、法律婚分开。
|
||||
4. 时间粒度:大运边界跨过用户关心的日/月/年只是实质变化之一;还要看窗口有无、支持或反对的方向、父级周期身份、窗口宽度与多段空隙。**不要按「年只看 MD、月只看 AD、日只看 PD」规定层级**——现在的 `vimshottari_depth = {year:1, month:2, day:3}` 正是这种规定,要改。
|
||||
|
||||
本单出 `purpose_policy_v2`。**这张表是产品约定,要送占星师审**;v1 保留可读(旧扫描结果能按 v1 复验),新扫描默认用 v2。
|
||||
|
||||
## 一、断言组
|
||||
|
||||
政策从「一个用途一组层」改成「一个用途若干断言组,每组一组层」。v2 的表(层名用 #297/#304/#307 已有的名字):
|
||||
|
||||
| 用途 | 断言组 | 依赖的层 |
|
||||
|---|---|---|
|
||||
| 性格/格局(structure) | `structure_core` | D1、`moon_nakshatra`、`house_lords`、`planet_signs`、`functional_roles`、`aspects` |
|
||||
| | `structure_d9` | D9、`planet_vargas:D9` |
|
||||
| | `structure_yogas` | `raj_yogas`、`wealth_yogas` |
|
||||
| | `structure_strength` | `strength_shadbala`、`ashtakavarga` |
|
||||
| 事业(career) | `career_direction` | D1、D10、`planet_vargas:D10`、`house_lords`、`lord_placements`、`functional_roles`、`aspects`、`chara_karakas`、A10 |
|
||||
| | `career_d9_support` | D9、`planet_vargas:D9` |
|
||||
| | `career_yogas` | `raj_yogas` |
|
||||
| | `career_strength` | `strength_shadbala`、`ashtakavarga` |
|
||||
| | `career_timing`(仅预测粒度) | Vimshottari、Narayana、`transit_relations`、`annual_chart` |
|
||||
| 钱财(wealth) | `wealth_structure` | D1、D2、D11、`planet_vargas:D2`、`planet_vargas:D11`、`house_lords`、`lord_placements`、`functional_roles`、A1、A7、A10 中按现有路由用到的 Arudha(读 `consultation_plan_contract` 和钱财证据卡确认用了哪几个,不确定就全列) |
|
||||
| | `wealth_d9_support` | D9、`planet_vargas:D9` |
|
||||
| | `wealth_yogas` | `wealth_yogas` |
|
||||
| | `wealth_strength` | `strength_shadbala`、`ashtakavarga` |
|
||||
| | `wealth_timing`(仅预测粒度) | Vimshottari、Narayana、`transit_relations`、`annual_chart` |
|
||||
| 婚恋(marriage) | `relationship_pattern` | D1、D9、`planet_vargas:D9`、`house_lords`、`lord_placements`、`venus_jupiter`、`functional_roles`、`aspects`、`chara_karakas`、UL、A7 |
|
||||
| | `relationship_strength` | `strength_shadbala`、`ashtakavarga` |
|
||||
| | `relationship_timing:<event_class>`(仅预测粒度) | Vimshottari、Narayana、`transit_relations`、`annual_chart` |
|
||||
|
||||
要求:
|
||||
|
||||
- 表放在 `scope.py` 一处(常量),每组带一个 `group_id`、所属用途、层列表、是否只在预测粒度出现。
|
||||
- 「问题路由的 `required_layers` 里有、但 v2 表里没有映射到任何组的层」,单独列为 `unmapped_route_layers` 输出,不能静默丢掉;有这种层时该用途整体最多 `conditional`。
|
||||
- 钱财里引用 D10/A10 的情况:本单不做自动判断,按表固定。
|
||||
- 婚恋的 `event_class`:问题输入新增可选字段 `event_class`,取值 `attraction`(心动)、`first_contact`(相识)、`pairing`(成对)、`legal_marriage`(法律婚)。婚恋 + 预测粒度没有给 `event_class` 时,`relationship_timing` 组状态为 `needs_input`,不猜;`event_class` 进用途指纹(`BINDING_KEYS` 相关的绑定),不同类别的结果不能互相复用。四个类别本单用同一组层,表里写明「待占星师区分」。
|
||||
- 结构类问题不强加大运、年度层;一旦问「这几年怎样」就是预测粒度,带上 timing 组(现有规则保留)。
|
||||
|
||||
## 二、按组评估
|
||||
|
||||
`scan.py::_assessment` 和 `assess_use` 的结果里加 `claim_groups`:每组一行,字段 `group_id`、`status`(沿用现有 `scope_ready` / `conditional` / `needs_refinement` / `insufficient_evidence` / `needs_input`)、`layers`(每层的覆盖状态与是否变化)、`limited_by`(导致非 `scope_ready` 的层和原因)。
|
||||
|
||||
组状态规则:
|
||||
|
||||
- 组内每层 `policy_covered` 且范围内不变 → `scope_ready`。
|
||||
- 有层在范围内会变(`birth_time_sensitive`)→ `needs_refinement`,`limited_by` 写哪层、在哪些时刻变。
|
||||
- 有层 `method_unresolved`(例如 `strength_shadbala`)、`sampled_only` 或缺生产器 → 该组 `conditional`,`limited_by` 写原因;**不影响其他组**。
|
||||
- 有层 `incomplete`(计算失败、预算用完)→ `insufficient_evidence`。
|
||||
|
||||
用途整体状态 = 各组中最差的那个,但输出必须同时给出各组状态,调用方(#298)按组使用:可以用 `scope_ready` 的组照常下结论,其余组按各自状态处理。原来的整体字段(`status`、`can_use_interval` 等)保留以兼容,含义写进 README:整体 `scope_ready` 当且仅当所有组都是。
|
||||
|
||||
占星师 11-09 规范里的 `stable_claims` / `conditional_claims`(`_claim_ids`)保持现有含义,另在每个 claim 上加 `group_id`。
|
||||
|
||||
## 三、时间粒度
|
||||
|
||||
1. **大运层级不再按粒度截断**:`vimshottari_depth` 一律 3(到 PD),`narayana_depth` 一律 2。粒度只决定「什么样的变化算实质变化」,不决定算到哪一级。
|
||||
2. **实质变化**:`timing.py::period_signature` 目前按粒度桶和目标边界比较。改为比较下面这些,任何一项在范围内不同即为实质变化(逐项写进 `limited_by` 的原因):
|
||||
- 预测窗内**有没有**相关周期(窗口有无);
|
||||
- 相关周期的**身份**:主星、层级、父级周期 id(比较同身份周期,不按数组下标对齐);
|
||||
- 周期边界是否跨过用户问的日期 / 所在月末 / 所在年末(按粒度,现有规则保留);
|
||||
- 预测窗内相关周期的**段数和空隙**(同一主星在窗内出现几段、中间断开几次);
|
||||
- 窗内相关周期的**总时长**变化超过一个容差:容差写成政策常量(日粒度 1 天、月粒度 7 天、年粒度 30 天),并在 README 标明「产品暂定,待占星师定」。
|
||||
「支持或反对的方向」依赖断言对周期的解读,本单没有这一层数据,在 README 写明「未实现,等断言绑定」,**不要**用主星吉凶自己推。
|
||||
3. 原始的逐候选结果全部保留在输出里,便于复核。
|
||||
|
||||
## 四、行运层的一处缺口
|
||||
|
||||
#307 的 `transit_relations` 只投影了「慢行星相对本命上升、月亮的整宫关系」。年度服务(`annual_service.package._natal_chart`、`NATAL_POINTS`)另外按本命上升和九曜的**度数**算精确合相、精确相位;本命上升每 4 分钟走 1 度,这类日期在 ±30 分钟内会移动好几天。
|
||||
|
||||
本单补一层 `transit_natal_contacts`:预测窗内行运对本命各点(上升与九曜)的精确合相、相位日期,按年度服务现有的口径取值。没有解析边界的话 `sampled_only`,网格发现 + 二分。放进三个用途的 timing 组。
|
||||
|
||||
## 五、不做的事
|
||||
|
||||
- 不改任何层的计算和 #304/#307 的覆盖判定;不放宽 `_receipt`。
|
||||
- 不接生产入口(#298 才接)。
|
||||
- 不计算 Shadbala。
|
||||
- 不改 `scripts/chart_choice/`、`frontend/`、`scripts/report_render/`、`references/`。
|
||||
- 不推断「支持/反对」方向。
|
||||
|
||||
## 六、测试
|
||||
|
||||
`tests/test_rectification_purpose_policy_v2.py`(新):
|
||||
|
||||
1. 表的完整性:每个用途的路由层都映射到组或进 `unmapped_route_layers`;组 id 唯一;预测组只在预测粒度出现。
|
||||
2. 按组评估:用确定性假函数造「D10 会变、其余都稳」→ `career_direction` 为 `needs_refinement`,`career_d9_support` 为 `scope_ready`,整体为 `needs_refinement`;「只有 Shadbala 待定」→ 只有 `*_strength` 组 `conditional`,其余 `scope_ready`。
|
||||
3. 婚恋:无 `event_class` → timing 组 `needs_input`、其余组照常;四个类别指纹不同。
|
||||
4. 时间粒度五项,每项一条「只有这一项不同」的用例,结果为实质变化;另一条「各项都同、只是边界在容差内平移」为不变。同主星不同父级周期不被当作同一周期。
|
||||
5. `vimshottari_depth` 恒为 3:年粒度下 AD 切换落在预测窗内且影响窗口时被检出。
|
||||
6. `transit_natal_contacts`:一条真实引擎用例,上升度数变化使精确相位日期移动并被检出;一条反例。
|
||||
7. v1 兼容:用 v1 产生的旧夹具复验结果不变(`tests/fixtures/rectification_purpose_scan_20261116.json`)。
|
||||
8. 既有五个用途扫描测试文件照旧通过,不删断言;确需调整的逐条在 PROGRESS 说明。
|
||||
|
||||
命令行核对:±30 分钟、月粒度、事业/钱财/婚恋各一个合成输入,把每组状态和 `limited_by` 写进 PROGRESS,并用人话写一段「这三个例子里哪些组能用、哪些不能、为什么」,供转给占星师。
|
||||
|
||||
## 七、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1962(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
|
||||
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-purpose-policy-v2-20261117.md`。
|
||||
- `docs/research/rect-purpose-policy-v2-20261117.md`(新):v2 表、组状态规则、时间粒度五项、暂定容差、未实现项,用普通话写,会转给占星师审。
|
||||
|
||||
## 验收
|
||||
|
||||
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
|
||||
- 新旧用途扫描测试全部通过;
|
||||
- `cd frontend && npx eslint .` 0 错误(本单不应有前端改动);
|
||||
- 没有任何生产入口导入 `scripts/rectification_purpose_gate`;diff 不含第五节列出的路径。
|
||||
@@ -0,0 +1,9 @@
|
||||
# 离线生时用途评估
|
||||
|
||||
在仓库根目录运行 `python -m scripts.rectification_purpose_gate --input <文件>`。输入格式和既有夹具见 [用途扫描说明](../../docs/research/rect-purpose-scan-20261116.md)。新输入默认使用 `purpose_policy_v2`。复验旧结果时,在 JSON 的 `question` 中设定 `"precision_policy_version": "purpose_policy_v1"`。
|
||||
|
||||
v2 的 `purpose_assessment.claim_groups` 和 `decision.claim_groups` 返回同一组决定。每组列出依赖层的覆盖、是否变化和 `limited_by`。`scope_ready` 的组可独立使用。整体 `status` 取最严限制,顺序为 `scope_ready`、`conditional`、`needs_refinement`、`needs_input`、`insufficient_evidence`。所有组都够用且路由层都已映射时,`can_use_interval` 才为真。未支持的用途列在 `missing_domains`,路由遗漏列在 `unmapped_route_layers`。缺少全部断言组时为 `insufficient_evidence`。
|
||||
|
||||
`stable_claim_ids` 仍标识全范围都有同一证据的事实,`conditional_claim_ids` 仍标识只在部分证据中得到支持的事实。每条 v2 事实有单独的 `group_id`,消费方需要按所属组使用事实。原始逐候选数据保留在 `candidates`,`can_modify_birth_record` 与 `representative_is_birth_truth` 固定为 false。
|
||||
|
||||
事业、钱财和婚恋的预测组使用 Vimshottari MD/AD/PD 与 Narayana MD/AD。时间粒度判断预测窗口的有无、周期身份、日期分界、段数及间隙、窗内总时长变化。暂定的总时长容差为日 1 天、月 7 天、年 30 天,待占星师确认。周期解读对断言的支持或反对方向等到断言绑定后实现。组表及覆盖边界见 [政策 v2 说明](../../docs/research/rect-purpose-policy-v2-20261117.md)。
|
||||
@@ -19,6 +19,8 @@ from __future__ import annotations
|
||||
from typing import Any, Dict, Final, List, Mapping, Sequence, Tuple
|
||||
|
||||
PURPOSE_USE_SCHEMA: Final[str] = 'jyotish.purpose_use_decision.v1'
|
||||
LEGACY_POLICY_VERSION = 'purpose_policy_v1'
|
||||
POLICY_VERSION = 'purpose_policy_v2'
|
||||
|
||||
BINDING_KEYS: Final[Tuple[str, ...]] = (
|
||||
'input_revision', 'candidate_set_fingerprint', 'purpose_fingerprint',
|
||||
@@ -37,6 +39,11 @@ STATUS_CONDITIONAL: Final[str] = 'conditional'
|
||||
STATUS_NEEDS_REFINEMENT: Final[str] = 'needs_refinement'
|
||||
STATUS_INSUFFICIENT_EVIDENCE: Final[str] = 'insufficient_evidence'
|
||||
STATUS_STALE: Final[str] = 'stale'
|
||||
STATUS_NEEDS_INPUT: Final[str] = 'needs_input'
|
||||
GROUP_STATUS_ORDER = (
|
||||
STATUS_SCOPE_READY, STATUS_CONDITIONAL, STATUS_NEEDS_REFINEMENT,
|
||||
STATUS_NEEDS_INPUT, STATUS_INSUFFICIENT_EVIDENCE,
|
||||
)
|
||||
|
||||
|
||||
def _binding_is_complete(binding: Any) -> bool:
|
||||
@@ -94,6 +101,38 @@ def _result(status: str, stable: Sequence[str], conditional: Sequence[str], reas
|
||||
}
|
||||
|
||||
|
||||
def _group_result(assessment: dict, stable, conditional) -> dict:
|
||||
groups = assessment.get("claim_groups")
|
||||
unmapped = assessment.get("unmapped_route_layers")
|
||||
missing = assessment.get("missing_domains")
|
||||
if not isinstance(groups, list) or not isinstance(unmapped, list) or not isinstance(missing, list):
|
||||
raise ValueError("v2 requires explicit claim groups and route coverage")
|
||||
ids = set()
|
||||
statuses = []
|
||||
for group in groups:
|
||||
if not isinstance(group, dict):
|
||||
raise ValueError("invalid claim group")
|
||||
group_id, status = group.get("group_id"), group.get("status")
|
||||
if (not isinstance(group_id, str) or not group_id or group_id in ids
|
||||
or status not in GROUP_STATUS_ORDER or not isinstance(group.get("layers"), list)
|
||||
or not isinstance(group.get("limited_by"), list)):
|
||||
raise ValueError("invalid claim group")
|
||||
ids.add(group_id)
|
||||
statuses.append(status)
|
||||
if unmapped or missing:
|
||||
statuses.append(STATUS_CONDITIONAL if groups else STATUS_INSUFFICIENT_EVIDENCE)
|
||||
status = max(statuses, key=GROUP_STATUS_ORDER.index, default=STATUS_INSUFFICIENT_EVIDENCE)
|
||||
reason = {
|
||||
STATUS_SCOPE_READY: "adequate_for_frozen_purpose",
|
||||
STATUS_CONDITIONAL: "only_listed_claim_groups_are_available",
|
||||
STATUS_NEEDS_REFINEMENT: "material_output_change",
|
||||
STATUS_NEEDS_INPUT: "purpose_input_required",
|
||||
STATUS_INSUFFICIENT_EVIDENCE: "incomplete_claim_group_evidence",
|
||||
}[status]
|
||||
return {**_result(status, stable, conditional, reason),
|
||||
"claim_groups": groups, "unmapped_route_layers": unmapped, "missing_domains": missing}
|
||||
|
||||
|
||||
def assess_use(assessment: dict, expected_binding: dict) -> dict:
|
||||
"""Return permissions for the evaluated scope, not birth-time confidence.
|
||||
|
||||
@@ -113,6 +152,8 @@ def assess_use(assessment: dict, expected_binding: dict) -> dict:
|
||||
coverage = assessment['layer_coverage']
|
||||
stable = assessment['stable_claim_ids']
|
||||
conditional = assessment['conditional_claim_ids']
|
||||
if binding['precision_policy_version'].startswith(f'{POLICY_VERSION}:'):
|
||||
return _group_result(assessment, stable, conditional)
|
||||
|
||||
if assessment['material_change']:
|
||||
return _result(STATUS_NEEDS_REFINEMENT, stable, conditional, 'material_output_change')
|
||||
|
||||
@@ -67,15 +67,18 @@ def _yogas(detector, planet_rows, house_lords):
|
||||
]}
|
||||
|
||||
|
||||
def _transit_sky(forecast, ayanamsa, node_mode):
|
||||
start, end = forecast
|
||||
# Only the portions of the annual transit producer that are common to every natal chart.
|
||||
# Its exact conjunction and aspect queries need natal longitudes and are separate outputs.
|
||||
ctx = annual._Context({
|
||||
def _transit_context(start, ayanamsa, node_mode):
|
||||
return annual._Context({
|
||||
"birth": {"year": start.year, "month": start.month, "day": start.day,
|
||||
"hour": start.hour, "minute": start.minute, "tz": 0},
|
||||
"observation_date": start.date(), "ayanamsa": ayanamsa, "node_mode": node_mode,
|
||||
})
|
||||
|
||||
|
||||
def _transit_sky(forecast, ayanamsa, node_mode):
|
||||
start, end = forecast
|
||||
# Only the portions of the annual transit producer that are common to every natal chart.
|
||||
ctx = _transit_context(start, ayanamsa, node_mode)
|
||||
snapshot = annual._slow_transits(ctx, {
|
||||
"status": "computed", "lagna_sign_idx": 0, "moon_sign_idx": 0, "longitudes": {},
|
||||
}, start, end)
|
||||
@@ -88,6 +91,30 @@ def _transit_sky(forecast, ayanamsa, node_mode):
|
||||
]
|
||||
|
||||
|
||||
def _transit_natal_contacts(forecast, profile, asc, planets):
|
||||
longitudes = {"Lagna": asc, **{name: planets[name] for name in annual.NATAL_POINTS[1:]}}
|
||||
start, end = forecast
|
||||
context = _transit_context(start, profile["ayanamsa"], profile["node_mode"])
|
||||
with domain_calculation_service.swiss_ephemeris_lock():
|
||||
snapshot = annual._slow_transits(context, {
|
||||
"status": "computed", "lagna_sign_idx": boundaries.varga_sign(asc, 1),
|
||||
"moon_sign_idx": boundaries.varga_sign(planets["Moon"], 1), "longitudes": longitudes,
|
||||
}, start, end)
|
||||
|
||||
def contacts(field):
|
||||
return [
|
||||
{"body": row["body"], "natal_point": row["natal_point"], "contact": row["contact"],
|
||||
**({"aspect_nth": row["aspect_nth"]} if "aspect_nth" in row else {}),
|
||||
"crossings": [
|
||||
{"at": crossing["instant"]["utc"], "retrograde": crossing["retrograde"]}
|
||||
for crossing in row["crossings"]
|
||||
]}
|
||||
for row in snapshot[field]
|
||||
]
|
||||
|
||||
return {"conjunctions": contacts("natal_point_contacts"), "aspects": contacts("exact_aspect_contacts")}
|
||||
|
||||
|
||||
def _annual_charts(at, profile, asc_index, forecast):
|
||||
start, end = forecast
|
||||
birth_year = profile_clock(at, profile).year
|
||||
@@ -121,7 +148,7 @@ def _annual_charts(at, profile, asc_index, forecast):
|
||||
|
||||
|
||||
def native_layer_values(required, forecast):
|
||||
layers = LAYER_NAMES.intersection(required)
|
||||
layers = (LAYER_NAMES | {"transit_natal_contacts"}).intersection(required)
|
||||
|
||||
@cache
|
||||
def sky(ayanamsa, node_mode):
|
||||
@@ -189,6 +216,12 @@ def native_layer_values(required, forecast):
|
||||
for body, instant, sign in sky(profile["ayanamsa"], profile["node_mode"])
|
||||
]} if forecast and "Moon" in planets else None
|
||||
method, dependencies = "native_whole_sign_slow_transits", ["lagna_sign", "moon_sign", "forecast_window"]
|
||||
elif layer == "transit_natal_contacts":
|
||||
value = _transit_natal_contacts(forecast, profile, asc, planets) if forecast and has_grahas else None
|
||||
method, dependencies = (
|
||||
"native_exact_slow_transit_contacts",
|
||||
["ascendant_longitude", "planet_longitudes", "forecast_window", "ayanamsa", "node_mode"],
|
||||
)
|
||||
elif layer == "annual_chart":
|
||||
value = _annual_charts(at, profile, asc_index, forecast) if forecast else None
|
||||
method, dependencies = (
|
||||
|
||||
@@ -14,7 +14,7 @@ from scripts.dasha_common import VIMSHOTTARI_YEARS
|
||||
from .layer_values import GRAHAS, PLANET_VARGAS, SIGN_LAYERS
|
||||
from .native import ANGLE_DIMENSIONS, ARUDHAS, division_of
|
||||
from .scan import BoundaryMethodUnavailable
|
||||
from .scope import SECOND, range_limits, stamp
|
||||
from .scope import LEGACY_POLICY_VERSION, SECOND, range_limits, stamp
|
||||
from .timing import TIMING_OUTPUTS, output_periods, period_signature
|
||||
|
||||
MINUTE = timedelta(minutes=1)
|
||||
@@ -474,10 +474,9 @@ def _timing_transitions(points, value):
|
||||
return cuts
|
||||
|
||||
|
||||
def _timing_provider(layer, forecast, granularity, sign_layout, moon_layout):
|
||||
def _timing_provider(layer, forecast, granularity, sign_layout, moon_layout, *, depth, policy_version):
|
||||
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):
|
||||
@@ -510,7 +509,7 @@ def _timing_provider(layer, forecast, granularity, sign_layout, moon_layout):
|
||||
@cache
|
||||
def value(at):
|
||||
row = output(at)
|
||||
return period_signature(row, forecast, granularity) if row else None
|
||||
return period_signature(row, forecast, granularity, policy_version=policy_version) if row else None
|
||||
|
||||
@cache
|
||||
def periods(at):
|
||||
@@ -610,9 +609,14 @@ def native_boundary_providers(scope: dict) -> dict:
|
||||
providers[layer] = _partition_provider(layer, lagna_moon_layout, "transit_relations_from_natal_lagna_moon")
|
||||
elif layer == "annual_chart" and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _sampled_layer(layer, "solar_return_ascendant_between_samples_unproven")
|
||||
elif layer == "transit_natal_contacts" and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _sampled_layer(layer, "exact_contact_between_samples_unproven")
|
||||
elif layer == "strength_shadbala":
|
||||
providers[layer] = _shadbala_pending
|
||||
elif layer in TIMING_OUTPUTS and purpose["forecast_window"] is not None:
|
||||
providers[layer] = _timing_provider(layer, purpose["forecast_window"], purpose["granularity"],
|
||||
sign_layout, moon_layout)
|
||||
providers[layer] = _timing_provider(
|
||||
layer, purpose["forecast_window"], purpose["granularity"], sign_layout, moon_layout,
|
||||
depth=scope["policy"]["vimshottari_depth"],
|
||||
policy_version=scope["policy"].get("id", LEGACY_POLICY_VERSION),
|
||||
)
|
||||
return providers
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from math import isfinite
|
||||
|
||||
from . import LEGACY_POLICY_VERSION, POLICY_VERSION
|
||||
from .scope import SECOND, collect_scope_outputs, fingerprint, range_limits, stamp, usable
|
||||
from .timing import TIMING_OUTPUTS, period_envelopes, period_signature
|
||||
from .timing import TIMING_OUTPUTS, period_change_witnesses, period_envelopes, period_observation, period_signature
|
||||
|
||||
COVERAGE = {"policy_covered", "sampled_only", "incomplete"}
|
||||
|
||||
@@ -117,13 +119,20 @@ def _layer_value(layer: str, output: dict, forecast: dict | None, granularity: s
|
||||
return period_signature(output, forecast, granularity) or None
|
||||
|
||||
|
||||
def _classify_layer(layer, candidates, required, covered, forecast, granularity):
|
||||
def _classify_layer(layer, candidates, required, covered, forecast, granularity, policy_version):
|
||||
groups = {}
|
||||
observations = []
|
||||
timed_v2 = policy_version == POLICY_VERSION and layer in TIMING_OUTPUTS and forecast is not None
|
||||
for row in candidates:
|
||||
output = row["outputs"].get(layer)
|
||||
if output is None or not usable(output):
|
||||
continue
|
||||
value = _layer_value(layer, output, forecast, granularity)
|
||||
if timed_v2:
|
||||
observation = period_observation(output, forecast, granularity)
|
||||
observations.append((row["candidate_at"], observation))
|
||||
value = observation[0]
|
||||
else:
|
||||
value = _layer_value(layer, output, forecast, granularity)
|
||||
if value is not None:
|
||||
groups.setdefault(fingerprint(value), []).append((row, output, value))
|
||||
|
||||
@@ -132,9 +141,12 @@ def _classify_layer(layer, candidates, required, covered, forecast, granularity)
|
||||
relevant = layer in required
|
||||
differences = []
|
||||
claims = []
|
||||
if len(groups) > 1:
|
||||
witnesses = period_change_witnesses(observations, granularity) if timed_v2 else {}
|
||||
material = bool(witnesses) if timed_v2 else len(groups) > 1
|
||||
if material:
|
||||
differences.append({
|
||||
"layer": layer, "relevant": relevant, "reason": "birth_time_sensitive",
|
||||
**({"witnesses": witnesses} if timed_v2 else {}),
|
||||
"by_value": [
|
||||
{"value": rows[0][2], "candidate_ids": [row["candidate_id"] for row, _, _ in rows],
|
||||
"branch_ids": sorted({row["branch_id"] for row, _, _ in rows})}
|
||||
@@ -147,7 +159,7 @@ def _classify_layer(layer, candidates, required, covered, forecast, granularity)
|
||||
}
|
||||
if relevant:
|
||||
for key, rows in groups.items():
|
||||
is_stable = len(groups) == 1 and fully_supported
|
||||
is_stable = not material and fully_supported
|
||||
claims.append({
|
||||
"claim_id": f"{layer}:{key[:16]}", "layer": layer, "value": rows[0][2],
|
||||
"support": "all_candidates" if is_stable else "observed_candidates_only",
|
||||
@@ -161,18 +173,78 @@ def _classify_layer(layer, candidates, required, covered, forecast, granularity)
|
||||
return coverage, differences, claims, reasons
|
||||
|
||||
|
||||
def _claim_group_results(policy, coverage, receipts, differences, limitations, claims):
|
||||
rows_by_layer = defaultdict(list)
|
||||
reasons_by_layer = defaultdict(set)
|
||||
groups_by_layer = defaultdict(list)
|
||||
changes_by_layer = {row["layer"]: row for row in differences}
|
||||
for row in receipts:
|
||||
rows_by_layer[row["layer"]].append(row)
|
||||
for row in limitations:
|
||||
reasons_by_layer[row["layer"]].add(row["reason"])
|
||||
|
||||
results = []
|
||||
for group in policy["claim_groups"]:
|
||||
group_id = group["group_id"]
|
||||
layers, limited_by = [], []
|
||||
if group["needs_input"]:
|
||||
limited_by.append({"reason": "event_class_required", "layer": None})
|
||||
incomplete = changed = conditional = False
|
||||
for layer in group["layers"]:
|
||||
groups_by_layer[layer].append(group_id)
|
||||
related = rows_by_layer[layer]
|
||||
reasons = reasons_by_layer[layer]
|
||||
state = ("incomplete" if any(r["state"] == "incomplete" for r in related) else
|
||||
"policy_covered" if related and all(r["state"] == "policy_covered" for r in related)
|
||||
else "sampled_only")
|
||||
change = changes_by_layer.get(layer)
|
||||
layers.append({"layer": layer, "coverage": state, "execution_coverage": coverage[layer],
|
||||
"changed": change is not None})
|
||||
if change:
|
||||
changed = True
|
||||
times = sorted({at for row in related for at in row["boundary_times"]})
|
||||
observed_at = sorted({key.rsplit("@", 1)[-1] for value in change["by_value"]
|
||||
for key in value["candidate_ids"][:1]})
|
||||
limited_by.append({"layer": layer, "reason": change["reason"],
|
||||
"boundary_times": times, "observed_at": observed_at})
|
||||
for kind, witnesses in sorted(change.get("witnesses", {}).items()):
|
||||
limited_by.append({"layer": layer, "reason": kind, "observed_at": witnesses})
|
||||
failures = any(r["state"] == "incomplete" and r["reason"] != "method_unresolved"
|
||||
for r in related) or "calculation_failure" in reasons
|
||||
insufficient = state != "policy_covered" or coverage[layer] != "executed_complete"
|
||||
if failures or insufficient:
|
||||
incomplete |= failures
|
||||
conditional |= insufficient
|
||||
for reason in sorted(reasons or {state if state != "policy_covered" else "method_unresolved"}):
|
||||
limited_by.append({"layer": layer, "reason": reason})
|
||||
status = ("needs_input" if group["needs_input"] else
|
||||
"insufficient_evidence" if incomplete else
|
||||
"needs_refinement" if changed else "conditional" if conditional else "scope_ready")
|
||||
results.append({"group_id": group_id, "domain": group["domain"], "status": status,
|
||||
"layers": layers, "limited_by": limited_by})
|
||||
grouped_claims = [
|
||||
{**claim, "group_id": group_id, "claim_id": f"{group_id}:{claim['claim_id']}"}
|
||||
for claim in claims for group_id in groups_by_layer[claim["layer"]]
|
||||
]
|
||||
return results, grouped_claims
|
||||
|
||||
|
||||
def _assessment(collected: dict, scope: dict, receipts: list[dict], failures: set,
|
||||
sample_count: int, budget: int) -> dict:
|
||||
required, candidates = collected["required_layers"], collected["candidates"]
|
||||
layer_names = set(required) | {key for row in candidates for key in row["outputs"]}
|
||||
forecast = scope["purpose_scope"]["forecast_window"]
|
||||
granularity = scope["purpose_scope"]["granularity"]
|
||||
policy = scope["policy"]
|
||||
policy_version = policy.get("id", LEGACY_POLICY_VERSION)
|
||||
differences, claims, envelopes, limitations = [], [], {}, []
|
||||
coverage = {}
|
||||
for layer in sorted(layer_names):
|
||||
related = [row for row in receipts if row["layer"] == layer]
|
||||
bounded = not failures and bool(related) and all(row["state"] == "policy_covered" for row in related)
|
||||
state, changes, facts, reasons = _classify_layer(layer, candidates, required, bounded, forecast, granularity)
|
||||
state, changes, facts, reasons = _classify_layer(
|
||||
layer, candidates, required, bounded, forecast, granularity, policy_version,
|
||||
)
|
||||
differences.extend(changes)
|
||||
claims.extend(facts)
|
||||
reasons.update(row["reason"] for row in related if row["reason"])
|
||||
@@ -192,8 +264,13 @@ def _assessment(collected: dict, scope: dict, receipts: list[dict], failures: se
|
||||
branch_state = ("unresolved_material" if len(branch_ids) > 1 and material else
|
||||
"resolved" if len(branch_ids) == 1 and scan_state != "incomplete" else
|
||||
"bounded_equivalent" if scan_state == "policy_covered" and all_layers else "not_evaluated")
|
||||
group_fields = {}
|
||||
if policy_version == POLICY_VERSION:
|
||||
groups, claims = _claim_group_results(policy, coverage, receipts, differences, limitations, claims)
|
||||
group_fields = {"claim_groups": groups, "unmapped_route_layers": policy["unmapped_route_layers"],
|
||||
"missing_domains": policy["missing_domains"]}
|
||||
return {
|
||||
**collected, "layer_coverage": coverage, "domain_complete": domain_complete,
|
||||
**collected, **group_fields, "layer_coverage": coverage, "domain_complete": domain_complete,
|
||||
"scan_state": scan_state, "branch_state": branch_state,
|
||||
"per_layer_scan_receipts": receipts, "output_envelopes": envelopes,
|
||||
"material_change": material,
|
||||
|
||||
@@ -11,9 +11,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from scripts.consultation_plan_contract import PLAN_VERSION, plan_route_contract
|
||||
|
||||
from . import BINDING_KEYS
|
||||
|
||||
POLICY_VERSION = "purpose_policy_v1"
|
||||
from . import BINDING_KEYS, LEGACY_POLICY_VERSION, POLICY_VERSION
|
||||
GRANULARITIES = ("structure", "year", "month", "day")
|
||||
DOMAIN_ALIASES = {
|
||||
"career": "career", "事业": "career",
|
||||
@@ -25,6 +23,44 @@ SECOND = timedelta(seconds=1)
|
||||
TIMING_LAYERS = frozenset({"Dasha", "Vimshottari", "Narayana", "Transit"})
|
||||
KNOWN_STATES = frozenset({"executed", "blocked", "not_applicable", "error"})
|
||||
MISSING_POLICY_LAYER = "purpose_policy"
|
||||
EVENT_CLASSES = frozenset({"attraction", "first_contact", "pairing", "legal_marriage"})
|
||||
WINDOW_DURATION_TOLERANCE_DAYS = {"day": 1, "month": 7, "year": 30}
|
||||
TIMING_GROUP_LAYERS = ("Vimshottari", "Narayana", "transit_relations", "annual_chart", "transit_natal_contacts")
|
||||
|
||||
# (group ID, domain, layers, prediction only). All relationship event classes
|
||||
# share the same dependencies until their separate evidence is approved.
|
||||
CLAIM_GROUPS = (
|
||||
("structure_core", "structure", ("D1", "moon_nakshatra", "house_lords", "planet_signs", "functional_roles", "aspects"), False),
|
||||
("structure_d9", "structure", ("D9", "planet_vargas:D9"), False),
|
||||
("structure_yogas", "structure", ("raj_yogas", "wealth_yogas"), False),
|
||||
("structure_strength", "structure", ("strength_shadbala", "ashtakavarga"), False),
|
||||
("career_direction", "career", ("D1", "D10", "planet_vargas:D10", "house_lords", "lord_placements",
|
||||
"functional_roles", "aspects", "chara_karakas", "A10"), False),
|
||||
("career_d9_support", "career", ("D9", "planet_vargas:D9"), False),
|
||||
("career_yogas", "career", ("raj_yogas",), False),
|
||||
("career_strength", "career", ("strength_shadbala", "ashtakavarga"), False),
|
||||
("career_timing", "career", TIMING_GROUP_LAYERS, True),
|
||||
# The wealth evidence card uses A10 among the three padas listed in the brief.
|
||||
("wealth_structure", "wealth", ("D1", "D2", "D11", "planet_vargas:D2", "planet_vargas:D11",
|
||||
"house_lords", "lord_placements", "functional_roles", "A10"), False),
|
||||
("wealth_d9_support", "wealth", ("D9", "planet_vargas:D9"), False),
|
||||
("wealth_yogas", "wealth", ("wealth_yogas",), False),
|
||||
("wealth_strength", "wealth", ("strength_shadbala", "ashtakavarga"), False),
|
||||
("wealth_timing", "wealth", TIMING_GROUP_LAYERS, True),
|
||||
("relationship_pattern", "marriage", ("D1", "D9", "planet_vargas:D9", "house_lords", "lord_placements",
|
||||
"venus_jupiter", "functional_roles", "aspects", "chara_karakas", "UL", "A7"), False),
|
||||
("relationship_strength", "marriage", ("strength_shadbala", "ashtakavarga"), False),
|
||||
("relationship_timing", "marriage", TIMING_GROUP_LAYERS, True),
|
||||
)
|
||||
ROUTE_LAYER_EQUIVALENTS = {
|
||||
"10th house/lord": ("house_lords", "lord_placements"),
|
||||
"7th house/lord": ("house_lords", "lord_placements"),
|
||||
"2nd/11th/9th/5th houses": ("house_lords", "lord_placements"),
|
||||
"AmK": ("chara_karakas",), "DK": ("chara_karakas",),
|
||||
"Venus/Jupiter": ("venus_jupiter",), "Wealth Yogas": ("wealth_yogas",),
|
||||
"Ashtakavarga": ("ashtakavarga",), "Dasha": ("Vimshottari", "Narayana"),
|
||||
"Transit": ("transit_relations", "transit_natal_contacts"),
|
||||
}
|
||||
|
||||
|
||||
def fingerprint(value) -> str:
|
||||
@@ -147,7 +183,7 @@ def profile_clock(at: datetime, profile: dict) -> datetime:
|
||||
return stamp(at).astimezone(zone)
|
||||
|
||||
|
||||
def _policy(domains: list[str], granularity: str, version: str) -> dict:
|
||||
def _legacy_policy(domains: list[str], granularity: str, version: str) -> dict:
|
||||
# 产品约定,待占星师审核。Use the existing server route's machine-readable
|
||||
# layers for domain scopes. "structure" is the explicit basic-chart scope.
|
||||
forecast = granularity != "structure"
|
||||
@@ -164,13 +200,13 @@ def _policy(domains: list[str], granularity: str, version: str) -> dict:
|
||||
for layer in route.required_layers:
|
||||
if layer not in TIMING_LAYERS or forecast:
|
||||
layers.extend(("Vimshottari", "Narayana") if layer == "Dasha" else (layer,))
|
||||
if missing or version != POLICY_VERSION:
|
||||
if missing or version != LEGACY_POLICY_VERSION:
|
||||
layers.append(MISSING_POLICY_LAYER)
|
||||
if version != POLICY_VERSION:
|
||||
if version != LEGACY_POLICY_VERSION:
|
||||
layers = [MISSING_POLICY_LAYER]
|
||||
depth = {"structure": 0, "year": 1, "month": 2, "day": 3}[granularity]
|
||||
return {
|
||||
"id": POLICY_VERSION, "version": version, "route_version": PLAN_VERSION,
|
||||
"id": LEGACY_POLICY_VERSION, "version": version, "route_version": PLAN_VERSION,
|
||||
"required_layers": list(dict.fromkeys(layers)), "missing_domains": missing,
|
||||
"vimshottari_depth": depth, "narayana_depth": min(depth, 2),
|
||||
"decision_predicates": ["structure_identity"] + (["window_presence", f"{granularity}_bucket", "target_boundaries"] if forecast else []),
|
||||
@@ -178,6 +214,50 @@ def _policy(domains: list[str], granularity: str, version: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _policy(domains: list[str], granularity: str, version: str, event_class: str | None) -> dict:
|
||||
if version != POLICY_VERSION:
|
||||
return _legacy_policy(domains, granularity, version)
|
||||
|
||||
forecast = granularity != "structure"
|
||||
groups = []
|
||||
for group_id, domain, layers, timing_only in CLAIM_GROUPS:
|
||||
if domain not in domains or (timing_only and not forecast):
|
||||
continue
|
||||
if group_id == "relationship_timing" and event_class:
|
||||
group_id = f"{group_id}:{event_class}"
|
||||
groups.append({
|
||||
"group_id": group_id, "domain": domain, "layers": list(layers), "timing_only": timing_only,
|
||||
"needs_input": group_id == "relationship_timing",
|
||||
})
|
||||
unmapped = []
|
||||
for domain in domains:
|
||||
route = plan_route_contract(domain)
|
||||
if route is None:
|
||||
continue
|
||||
mapped = {layer for group in groups if group["domain"] == domain for layer in group["layers"]}
|
||||
unmapped.extend(
|
||||
layer for layer in route.required_layers
|
||||
if (forecast or layer not in TIMING_LAYERS)
|
||||
and not set(ROUTE_LAYER_EQUIVALENTS.get(layer, (layer,))) <= mapped
|
||||
)
|
||||
missing = [domain for domain in domains if not any(group["domain"] == domain for group in groups)]
|
||||
required = list(dict.fromkeys(layer for group in groups for layer in group["layers"]))
|
||||
if missing:
|
||||
required.append(MISSING_POLICY_LAYER)
|
||||
return {
|
||||
"id": POLICY_VERSION, "version": version, "route_version": PLAN_VERSION,
|
||||
"required_layers": required, "missing_domains": missing,
|
||||
"claim_groups": groups, "unmapped_route_layers": list(dict.fromkeys(unmapped)),
|
||||
"vimshottari_depth": 3, "narayana_depth": 2,
|
||||
"window_duration_tolerance_days": WINDOW_DURATION_TOLERANCE_DAYS.get(granularity),
|
||||
"decision_predicates": ["structure_identity"] + ([
|
||||
"window_presence", "period_identity", f"{granularity}_bucket", "target_boundaries",
|
||||
"window_segments_and_gaps", "window_total_duration",
|
||||
] if forecast else []),
|
||||
"birth_resolution_seconds": 1,
|
||||
}
|
||||
|
||||
|
||||
def _forecast(question: dict, granularity: str) -> dict | None:
|
||||
if granularity == "structure":
|
||||
return None
|
||||
@@ -214,16 +294,18 @@ def build_scope_request(question: dict, original_input: dict, remaining_ranges:
|
||||
if event_class is not None:
|
||||
event_class = _text(event_class, "event_class")
|
||||
version = _text(question.get("precision_policy_version", POLICY_VERSION), "precision_policy_version")
|
||||
if version == POLICY_VERSION and event_class is not None and event_class not in EVENT_CLASSES:
|
||||
raise ValueError("unsupported_event_class")
|
||||
branches = _profiles(profiles)
|
||||
ranges = _ranges(remaining_ranges, branches)
|
||||
forecast = _forecast(question, granularity)
|
||||
evaluated = stamp(evaluated_at).isoformat()
|
||||
policy = _policy(domains, granularity, version)
|
||||
policy = _policy(domains, granularity, version, event_class)
|
||||
purpose = {
|
||||
"question": " ".join(text.split()), "domains": domains, "event_class": event_class,
|
||||
"granularity": granularity, "required_techniques": policy["required_layers"],
|
||||
"required_outputs": policy["required_layers"], "decision_predicates": policy["decision_predicates"],
|
||||
"precision_policy_id": POLICY_VERSION, "evaluated_at": evaluated, "forecast_window": forecast,
|
||||
"precision_policy_id": policy["id"], "evaluated_at": evaluated, "forecast_window": forecast,
|
||||
}
|
||||
fingerprints = {
|
||||
"input_revision": _text(original_input.get("input_revision"), "input_revision"),
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import timedelta, timezone
|
||||
|
||||
from .scope import stamp, usable
|
||||
from .scope import LEGACY_POLICY_VERSION, POLICY_VERSION, WINDOW_DURATION_TOLERANCE_DAYS, stamp, usable
|
||||
|
||||
TIMING_OUTPUTS = frozenset({"Vimshottari", "Narayana"})
|
||||
|
||||
@@ -28,8 +29,10 @@ def _bucket(at, granularity, offset):
|
||||
return (local.year, local.month, local.day)[:{"year": 1, "month": 2, "day": 3}[granularity]]
|
||||
|
||||
|
||||
def period_signature(output: dict, forecast: dict, granularity: str) -> tuple:
|
||||
"""Keep identity, endpoint precision, explicit target crossings and direction."""
|
||||
def period_signature(output: dict, forecast: dict, granularity: str, *, policy_version=LEGACY_POLICY_VERSION):
|
||||
"""Compare discrete features. V2 duration tolerance is applied across all observations."""
|
||||
if policy_version == POLICY_VERSION:
|
||||
return period_observation(output, forecast, granularity)[0]
|
||||
offset = timezone(timedelta(seconds=forecast["comparison_offset_seconds"]))
|
||||
boundaries = [stamp(forecast["start"]), *map(stamp, forecast["target_boundaries"]), stamp(forecast["end"])]
|
||||
return tuple(
|
||||
@@ -46,7 +49,7 @@ def _window(start, end) -> dict:
|
||||
return {"start": start.isoformat(), "end": end.isoformat(), "closed_start": True, "closed_end": False}
|
||||
|
||||
|
||||
def _union(windows: list[tuple]) -> list[dict]:
|
||||
def _merged_windows(windows: list[tuple]) -> list[tuple]:
|
||||
merged = []
|
||||
for start, end in sorted(windows):
|
||||
if start == end:
|
||||
@@ -55,7 +58,69 @@ def _union(windows: list[tuple]) -> list[dict]:
|
||||
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
|
||||
else:
|
||||
merged.append((start, end))
|
||||
return [_window(start, end) for start, end in merged]
|
||||
return merged
|
||||
|
||||
|
||||
def _union(windows: list[tuple]) -> list[dict]:
|
||||
return [_window(start, end) for start, end in _merged_windows(windows)]
|
||||
|
||||
|
||||
def period_observation(output: dict, forecast: dict, granularity: str) -> tuple[dict, dict]:
|
||||
lo, hi = stamp(forecast["start"]), stamp(forecast["end"])
|
||||
offset = timezone(timedelta(seconds=forecast["comparison_offset_seconds"]))
|
||||
targets = (lo, *map(stamp, forecast["target_boundaries"]), hi)
|
||||
identity, boundaries = [], []
|
||||
by_lord = defaultdict(list)
|
||||
for key, (row, start, end) in sorted(output_periods(output).items()):
|
||||
left, right = max(start, lo), min(end, hi)
|
||||
if left >= right:
|
||||
continue
|
||||
lord, level = row["lord"], row.get("level")
|
||||
identity.append((key, lord, level, row.get("parent_period_id")))
|
||||
boundaries.append((
|
||||
key, (_bucket(left, granularity, offset), _bucket(right, granularity, offset),
|
||||
tuple((left <= target, right <= target) for target in targets)),
|
||||
))
|
||||
by_lord[(str(level or ""), str(lord))].append((left, right))
|
||||
|
||||
segments, durations = [], {}
|
||||
for key, windows in sorted(by_lord.items()):
|
||||
merged = _merged_windows(windows)
|
||||
segments.append((key, (len(windows), len(merged) - 1)))
|
||||
durations[key] = sum((end - start for start, end in merged), timedelta())
|
||||
return {
|
||||
"window_presence": bool(identity), "period_identity": identity,
|
||||
"target_boundary_crossing": boundaries, "window_segments_and_gaps": segments,
|
||||
}, durations
|
||||
|
||||
|
||||
def period_change_witnesses(observations, granularity: str) -> dict[str, list[str]]:
|
||||
"""Return observed birth times for each differing axis, without bucketing durations."""
|
||||
tolerance = timedelta(days=WINDOW_DURATION_TOLERANCE_DAYS[granularity])
|
||||
seen = {}
|
||||
limits = {}
|
||||
witnesses = {}
|
||||
for at, (shape, durations) in observations:
|
||||
def compare(axis, key, value):
|
||||
other, other_at = seen.setdefault((axis, key), (value, at))
|
||||
if value != other and axis not in witnesses:
|
||||
witnesses[axis] = sorted({other_at, at})
|
||||
|
||||
compare("window_presence", None, shape["window_presence"])
|
||||
if not shape["window_presence"]:
|
||||
continue
|
||||
compare("period_identity", None, shape["period_identity"])
|
||||
for axis in ("target_boundary_crossing", "window_segments_and_gaps"):
|
||||
for key, value in shape[axis]:
|
||||
compare(axis, key, value)
|
||||
for key, duration in durations.items():
|
||||
low, high = limits.get(key, ((duration, at), (duration, at)))
|
||||
low = min(low, (duration, at))
|
||||
high = max(high, (duration, at))
|
||||
limits[key] = (low, high)
|
||||
if high[0] - low[0] > tolerance and "window_total_duration" not in witnesses:
|
||||
witnesses["window_total_duration"] = sorted({low[1], high[1]})
|
||||
return witnesses
|
||||
|
||||
|
||||
def period_envelopes(candidates: list[dict], layer: str, policy_covered: bool) -> list[dict]:
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
},
|
||||
"evaluated_at": "2026-11-16T00:00:00Z",
|
||||
"question": {
|
||||
"precision_policy_version": "purpose_policy_v1",
|
||||
"question": "Synthetic structural calculation",
|
||||
"domains": [
|
||||
"structure"
|
||||
@@ -304,6 +305,7 @@
|
||||
},
|
||||
"evaluated_at": "2026-11-16T00:00:00Z",
|
||||
"question": {
|
||||
"precision_policy_version": "purpose_policy_v1",
|
||||
"question": "Synthetic structural calculation",
|
||||
"domains": [
|
||||
"structure"
|
||||
@@ -837,6 +839,7 @@
|
||||
},
|
||||
"evaluated_at": "2026-11-16T00:00:00Z",
|
||||
"question": {
|
||||
"precision_policy_version": "purpose_policy_v1",
|
||||
"question": "Synthetic day-boundary comparison",
|
||||
"domains": [
|
||||
"career"
|
||||
|
||||
@@ -11,6 +11,7 @@ from scripts.rectification_purpose_gate.scope import build_scope_request, collec
|
||||
EVALUATED = "2026-11-16T00:00:00Z"
|
||||
QUESTION = {
|
||||
"question": "Synthetic timing scope", "domains": ["事业"], "granularity": "month",
|
||||
"precision_policy_version": "purpose_policy_v1",
|
||||
"forecast_start": "2026-09-01T00:00:00+08:00", "forecast_end": "2026-12-01T00:00:00+08:00",
|
||||
}
|
||||
PROFILE = {"lat": 57.0, "lon": 0, "tz": 0, "ayanamsa": "raman", "node_mode": "mean"}
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Versioned claim-group and timing behavior for the offline purpose policy."""
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import cache
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from scripts.rectification_purpose_gate import POLICY_VERSION, assess_use
|
||||
from scripts.rectification_purpose_gate import scope as scope_module
|
||||
from scripts.rectification_purpose_gate.native import native_scope_compute
|
||||
from scripts.rectification_purpose_gate.providers import native_boundary_providers
|
||||
from scripts.rectification_purpose_gate.scan import scan_scope
|
||||
from scripts.rectification_purpose_gate.scope import EVENT_CLASSES, SECOND, build_scope_request, range_limits, stamp
|
||||
from scripts.rectification_purpose_gate.timing import period_change_witnesses, period_observation
|
||||
|
||||
START = datetime(2000, 1, 1, tzinfo=timezone.utc)
|
||||
BRANCH = "test"
|
||||
PROFILE = {"lat": 57.0, "lon": 0, "tz": 0, "ayanamsa": "raman", "node_mode": "mean"}
|
||||
WINDOW = {"forecast_start": "2026-01-01T00:00:00Z", "forecast_end": "2027-01-01T00:00:00Z"}
|
||||
FIXTURE = Path(__file__).with_name("fixtures") / "rectification_purpose_scan_20261116.json"
|
||||
|
||||
|
||||
def _scope(domain="career", granularity="structure", *, ranges=None, **overrides):
|
||||
return build_scope_request(
|
||||
{"question": "Synthetic scope", "domains": [domain], "granularity": granularity, **WINDOW, **overrides},
|
||||
{"input_revision": "synthetic"},
|
||||
ranges or [{"start": START.isoformat(), "end": (START + 60 * SECOND).isoformat()}],
|
||||
{"engine_version": "synthetic", "branches": {BRANCH: PROFILE}},
|
||||
"2026-01-01T00:00:00Z",
|
||||
)
|
||||
|
||||
|
||||
def _period(period_id, start, end, *, level="AD", lord="Jupiter", parent="md"):
|
||||
return {"period_id": period_id, "lord": lord, "parent_period_id": parent, "level": level,
|
||||
"start": start + "T00:00:00Z", "end": end + "T00:00:00Z"}
|
||||
|
||||
|
||||
def _value(value="stable", periods=None):
|
||||
return {"status": "executed", "value": value, "method_id": "synthetic", "result_ref": "synthetic",
|
||||
**({"periods": periods} if periods is not None else {})}
|
||||
|
||||
|
||||
def _evaluate(scope, output_at=None, overrides=None):
|
||||
layers = scope["policy"]["required_layers"]
|
||||
|
||||
def compute(at, branch):
|
||||
outputs = {layer: _value() for layer in layers}
|
||||
for layer in ("Vimshottari", "Narayana"):
|
||||
if layer in outputs:
|
||||
outputs[layer] = _value("native_periods", [_period("md/ad", "2026-01-10", "2026-02-10")])
|
||||
if output_at is not None:
|
||||
outputs.update(output_at(at))
|
||||
return {"candidate_at": at, "branch_id": branch, "profile": scope["profiles"][branch], "outputs": outputs}
|
||||
|
||||
def covered(item, sample):
|
||||
left, right = range_limits(item)
|
||||
midpoint = left + SECOND * (int((right - left) / SECOND) // 2)
|
||||
sample(midpoint, item["branch_id"])
|
||||
return {"state": "policy_covered", "method_id": "synthetic_known_boundaries",
|
||||
"boundaries": [midpoint] if left < midpoint else [], "resolution_seconds": 1,
|
||||
"max_unchecked_gap_seconds": 0, "boundary_error_seconds": 0}
|
||||
|
||||
assessment = scan_scope(scope, compute, {**dict.fromkeys(layers, covered), **(overrides or {})})
|
||||
return assessment, assess_use(assessment, scope["binding"])
|
||||
|
||||
|
||||
def _statuses(result):
|
||||
return {row["group_id"]: row["status"] for row in result["claim_groups"]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain", ["career", "wealth", "marriage", "structure"])
|
||||
@pytest.mark.parametrize("granularity", ["structure", "day", "month", "year"])
|
||||
def test_groups_cover_route_names_or_list_them_explicitly(domain, granularity):
|
||||
policy = _scope(domain, granularity)["policy"]
|
||||
assert policy["id"] == POLICY_VERSION
|
||||
groups = policy["claim_groups"]
|
||||
assert all(group["domain"] == domain for group in groups)
|
||||
assert len({group["group_id"] for group in groups}) == len(groups)
|
||||
assert set(policy["required_layers"]) == {layer for group in groups for layer in group["layers"]}
|
||||
assert not policy["unmapped_route_layers"]
|
||||
assert policy["vimshottari_depth"] == 3 and policy["narayana_depth"] == 2
|
||||
assert all(not group["timing_only"] for group in groups) == (granularity == "structure" or domain == "structure")
|
||||
|
||||
|
||||
def test_unknown_route_dependency_blocks_only_overall_readiness(monkeypatch):
|
||||
original = scope_module.plan_route_contract
|
||||
|
||||
def route(domain):
|
||||
contract = original(domain)
|
||||
return replace(contract, required_layers=(*contract.required_layers, "unmapped_future_layer"))
|
||||
|
||||
monkeypatch.setattr(scope_module, "plan_route_contract", route)
|
||||
_, decision = _evaluate(_scope())
|
||||
assert decision["unmapped_route_layers"] == ["unmapped_future_layer"]
|
||||
assert set(_statuses(decision).values()) == {"scope_ready"}
|
||||
assert decision["status"] == "conditional"
|
||||
assert not decision["can_use_interval"]
|
||||
|
||||
|
||||
def test_d10_boundary_limits_career_direction_but_keeps_d9_ready():
|
||||
scope = _scope()
|
||||
assessment, decision = _evaluate(scope, lambda at: {"D10": _value("old" if at < START + 30 * SECOND else "new")})
|
||||
statuses = _statuses(decision)
|
||||
assert statuses["career_direction"] == "needs_refinement"
|
||||
assert statuses["career_d9_support"] == "scope_ready"
|
||||
assert decision["status"] == "needs_refinement" and not decision["can_use_interval"]
|
||||
group = next(row for row in decision["claim_groups"] if row["group_id"] == "career_direction")
|
||||
assert {"layer": "D10", "reason": "birth_time_sensitive", "boundary_times": [(START + 30 * SECOND).isoformat()],
|
||||
"observed_at": [START.isoformat(), (START + 30 * SECOND).isoformat()]} in group["limited_by"]
|
||||
assert any(claim["group_id"] == "career_d9_support" and claim["claim_id"] in decision["stable_claim_ids"]
|
||||
for claim in assessment["claims"])
|
||||
assert len({claim["claim_id"] for claim in assessment["claims"]}) == len(assessment["claims"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain,strength_group", [
|
||||
("career", "career_strength"), ("wealth", "wealth_strength"), ("marriage", "relationship_strength"),
|
||||
("structure", "structure_strength"),
|
||||
])
|
||||
def test_method_unresolved_shadbala_only_limits_its_strength_group(domain, strength_group):
|
||||
scope = _scope(domain)
|
||||
shadbala = native_boundary_providers(scope)["strength_shadbala"]
|
||||
_, decision = _evaluate(scope, lambda _: {
|
||||
"strength_shadbala": {"status": "blocked", "reason": "method_unresolved"},
|
||||
}, {"strength_shadbala": shadbala})
|
||||
statuses = _statuses(decision)
|
||||
assert statuses.pop(strength_group) == "conditional"
|
||||
assert set(statuses.values()) == {"scope_ready"}
|
||||
assert decision["status"] == "conditional"
|
||||
|
||||
|
||||
def test_engine_failure_stays_in_affected_claim_group():
|
||||
_, decision = _evaluate(_scope(), lambda _: {"D10": {"status": "error", "reason": "calculation_failure"}})
|
||||
assert _statuses(decision)["career_direction"] == "insufficient_evidence"
|
||||
assert _statuses(decision)["career_d9_support"] == "scope_ready"
|
||||
assert decision["status"] == "insufficient_evidence"
|
||||
|
||||
|
||||
def test_relationship_timing_requires_one_of_four_distinct_bound_event_classes():
|
||||
missing = _scope("marriage", "month")
|
||||
_, decision = _evaluate(missing)
|
||||
states = _statuses(decision)
|
||||
assert states.pop("relationship_timing") == "needs_input"
|
||||
assert set(states.values()) == {"scope_ready"}
|
||||
assert decision["status"] == "needs_input"
|
||||
scopes = [_scope("marriage", "month", event_class=kind) for kind in sorted(EVENT_CLASSES)]
|
||||
assert len({scope["binding"]["purpose_fingerprint"] for scope in scopes}) == 4
|
||||
assessment, ready = _evaluate(scopes[0])
|
||||
assert ready["status"] == "scope_ready" and ready["can_use_interval"]
|
||||
assert f"relationship_timing:{scopes[0]['purpose_scope']['event_class']}" in _statuses(ready)
|
||||
assert assess_use(assessment, scopes[-1]["binding"])["status"] == "stale"
|
||||
with pytest.raises(ValueError, match="unsupported_event_class"):
|
||||
_scope("marriage", "year", event_class="unspecified")
|
||||
|
||||
|
||||
def _changes(before, after, *, granularity="month", target_boundaries=()):
|
||||
forecast = {"start": WINDOW["forecast_start"], "end": WINDOW["forecast_end"],
|
||||
"target_boundaries": list(target_boundaries), "comparison_offset_seconds": 0}
|
||||
observations = [(at, period_observation(_value("native_periods", periods), forecast, granularity))
|
||||
for at, periods in zip(("a", "b"), (before, after))]
|
||||
return set(period_change_witnesses(observations, granularity))
|
||||
|
||||
|
||||
def test_window_presence_is_material_even_if_one_candidate_has_no_period():
|
||||
assert _changes([], [_period("one", "2026-01-05", "2026-01-20")]) == {"window_presence"}
|
||||
|
||||
|
||||
def test_same_lord_with_a_different_parent_is_a_different_identity():
|
||||
period = _period("one", "2026-01-05", "2026-01-20")
|
||||
assert _changes([period], [{**period, "parent_period_id": "other"}]) == {"period_identity"}
|
||||
|
||||
|
||||
def test_crossing_a_target_date_is_material_with_identical_month_and_duration():
|
||||
before = _period("one", "2026-01-08", "2026-01-10")
|
||||
after = _period("one", "2026-01-09", "2026-01-11")
|
||||
assert _changes([before], [after], target_boundaries=["2026-01-08T18:00:00Z"]) == {"target_boundary_crossing"}
|
||||
|
||||
|
||||
def test_separate_segments_are_material_with_same_ids_months_and_total_duration():
|
||||
a = _period("one", "2026-01-08", "2026-01-10")
|
||||
b = _period("two", "2026-01-10", "2026-01-12")
|
||||
gap = _period("two", "2026-01-11", "2026-01-13")
|
||||
assert _changes([a, b], [gap, a]) == {"window_segments_and_gaps"}
|
||||
|
||||
|
||||
def test_window_duration_only_changes_outside_the_policy_tolerance():
|
||||
before = _period("one", "2026-01-05", "2026-01-10")
|
||||
limit = _period("one", "2026-01-05", "2026-01-17")
|
||||
longer = _period("one", "2026-01-05", "2026-01-18")
|
||||
assert _changes([before], [longer]) == {"window_total_duration"}
|
||||
assert _changes([before], [limit]) == set()
|
||||
assert _changes([before], [_period("one", "2026-01-08", "2026-01-13")]) == set()
|
||||
|
||||
|
||||
def test_edges_outside_the_forecast_do_not_change_the_observed_window():
|
||||
before = _period("one", "2025-11-05", "2026-01-15")
|
||||
after = _period("one", "2025-12-05", "2026-01-15")
|
||||
assert _changes([before], [after]) == set()
|
||||
|
||||
|
||||
def test_duration_extrema_compares_entire_candidate_set_not_only_adjacent_pairs():
|
||||
forecast = {"start": WINDOW["forecast_start"], "end": WINDOW["forecast_end"],
|
||||
"target_boundaries": [], "comparison_offset_seconds": 0}
|
||||
dates = ["2026-01-10", "2026-01-14", "2026-01-18"]
|
||||
observations = [
|
||||
(end, period_observation(_value("native_periods", [_period("one", "2026-01-05", end)]), forecast, "month"))
|
||||
for end in dates
|
||||
]
|
||||
assert period_change_witnesses(observations, "month") == {"window_total_duration": [dates[0], dates[-1]]}
|
||||
|
||||
|
||||
def test_year_scope_keeps_pd_and_surfaces_ad_switch_near_requested_boundary():
|
||||
scope = _scope("career", "year", target_boundaries=["2026-05-15T00:00:00Z"])
|
||||
_, decision = _evaluate(scope, lambda at: {
|
||||
"Vimshottari": _value("native_periods", [
|
||||
_period("one", "2026-05-01", "2026-05-14" if at == START else "2026-05-16"),
|
||||
_period("two", "2026-05-14" if at == START else "2026-05-16", "2026-06-01"),
|
||||
]),
|
||||
})
|
||||
group = next(row for row in decision["claim_groups"] if row["group_id"] == "career_timing")
|
||||
assert group["status"] == "needs_refinement"
|
||||
assert {"target_boundary_crossing", "birth_time_sensitive"} <= {row["reason"] for row in group["limited_by"]}
|
||||
compute = native_scope_compute(scope)
|
||||
rows = compute(START, BRANCH)["outputs"]["Vimshottari"]["periods"]
|
||||
assert scope["policy"]["vimshottari_depth"] == 3
|
||||
assert {"MD", "AD", "PD"} <= {row["level"] for row in rows}
|
||||
|
||||
|
||||
def test_native_exact_lagna_contact_moves_and_provider_never_claims_coverage():
|
||||
end = START + 120 * SECOND
|
||||
scope = _scope("career", "month", ranges=[{"start": START.isoformat(), "end": end.isoformat()}])
|
||||
scope["policy"]["required_layers"] = ["transit_natal_contacts"]
|
||||
layer = "transit_natal_contacts"
|
||||
compute = cache(native_scope_compute(scope))
|
||||
item = scope["plausible_ranges"][0]
|
||||
|
||||
def periods(at):
|
||||
value = compute(at, BRANCH)["outputs"][layer]["value"]
|
||||
return {(row["body"], row["aspect_nth"]): [c["at"] for c in row["crossings"]]
|
||||
for row in value["aspects"] if row["natal_point"] == "Lagna"}
|
||||
|
||||
before, after = periods(START), periods(end)
|
||||
assert any(before[key] != after[key] for key in before.keys() & after.keys())
|
||||
details = native_boundary_providers(scope)[layer](item, compute)
|
||||
assert details["state"] == "sampled_only" and details["boundaries"]
|
||||
for at in details["boundaries"]:
|
||||
assert compute(at - SECOND, BRANCH)["outputs"][layer]["value"] != compute(at, BRANCH)["outputs"][layer]["value"]
|
||||
|
||||
|
||||
def test_identical_transit_samples_still_leave_unknown_changes():
|
||||
layer = "transit_natal_contacts"
|
||||
scope = _scope("career", "month")
|
||||
calls = []
|
||||
|
||||
def sample(at, branch):
|
||||
calls.append(at)
|
||||
return {"outputs": {layer: _value({"aspects": [], "conjunctions": []})}}
|
||||
|
||||
details = native_boundary_providers(scope)[layer](scope["plausible_ranges"][0], sample)
|
||||
assert calls
|
||||
assert details["state"] == "sampled_only" and "basis" not in details and not details["boundaries"]
|
||||
|
||||
|
||||
def test_existing_fixtures_declare_v1_and_preserve_the_old_scope_binding():
|
||||
fixtures = json.loads(FIXTURE.read_text(encoding="utf-8"))
|
||||
for fixture in fixtures.values():
|
||||
packet = fixture["input"]
|
||||
question = packet["question"]
|
||||
scope = build_scope_request(question, packet["original_input"], packet["remaining_ranges"],
|
||||
packet["profiles"], packet["evaluated_at"])
|
||||
assert scope["policy"]["id"] == "purpose_policy_v1"
|
||||
assert "claim_groups" not in scope["policy"]
|
||||
assert scope["policy"]["vimshottari_depth"] == (0 if question["granularity"] == "structure" else 3)
|
||||
@@ -28,7 +28,7 @@ def _scope(*, ranges=None, timing=False, profiles=None, **question):
|
||||
else:
|
||||
options = {"domains": ["structure"], "granularity": "structure"}
|
||||
return build_scope_request(
|
||||
{"question": "Synthetic scope", **options, **question},
|
||||
{"question": "Synthetic scope", "precision_policy_version": "purpose_policy_v1", **options, **question},
|
||||
{"input_revision": "synthetic"},
|
||||
[{"start": _at(0), "end": _at(60)}] if ranges is None else ranges,
|
||||
{"engine_version": "synthetic-native", "branches": {"s": PROFILE} if profiles is None else profiles},
|
||||
|
||||
Reference in New Issue
Block a user