Compare commits

..
Author SHA1 Message Date
jesse-uxandGrok (agent loop) 73899bdf65 feat(consult): show the fixed verification-limit line on the page (#187, BUG-1834)
只说显示,不动回答正文、存储文字、回执与提示词:

- consult-answer-basis.ts:一处定义 CONSULT_VERIFICATION_LIMIT_LINE,
  新增 withVerificationLimitLine(插在最后一张审计表末行之后、幂等)
- 简明解读「解读依据」展开列表末行加这一句:无状态标签、不计入 N 项、
  空列表不渲染、流式不出现
- 深度解读:非流式且没有 basisRows 时,在可见文字的表尾加同一句
- references/product_runtime_contract.md 只在「F」6c 行末追加一句同意记录
  (git diff 只有那一行)
- 既有断言按任务书改一处(三栏注释):先断言这句恰好 1 次,再去掉它做原断言

Tests: 新增 consult-limitation-line-1834.test.tsx(12 条);receipt 4、
answer-mode-ui 14、candidate-status 12、report-no-web-wording 4 全过;
tsc 0 错,eslint 0 error;合同相关 pytest 31 条全过。

Co-Authored-By: Grok (agent loop)
2026-11-09 16:04:10 +08:00
ClaudeandClaude Opus 5.5 057da78d8a docs(task): brief for limitation-line (#187, 2026-11-09)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 15:38:00 +08:00
ClaudeandClaude Opus 5.5 004cf9d88f docs(accept): BUG-1817 acceptance-fix note
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m39s
Independent Staging Quality Gate / validate-python (push) Successful in 7m6s
Independent Staging Quality Gate / publish (push) Successful in 3m24s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 14:45:07 +08:00
ClaudeandClaude Opus 5.5 6c774a4f28 fix(accept): #181 uses the astrologer's round-7 §5 P0.2 yoga status mapping
One shared table in yoga-status-words.ts (YOGA_STATUS_MAPPING / yogaStatus)
that the 解读依据 line uses now and #182's model wording must import:
candidate / support_only_candidate, computed, formed_under_source,
conditions_not_met, blocked / not_available_yet. Only formation.status can
say 成立 or 必要条件未满足; a hits-only name is 当前无法确认 with the gap named.
The grey line never clips a status text. Tests: one per table row plus the
hits-only case (13 in the file).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 14:44:57 +08:00
ClaudeandClaude Opus 5.5 35c87349e3 fix(accept): #174 ingress to_sign/direction and per-time outside-window flags
- to_sign was taken from the JD instead of a longitude, and direction read a
  direct 0° Aries ingress as retrograde; both now come from the step's
  longitudes.
- shadow_entry / shadow_exit / both stations carry outside_requested_window
  as the brief requires; the window end uses the end day's UTC offset.
- 3 regression tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 14:42:27 +08:00
Claude 7505c841b2 Merge remote-tracking branch 'origin/codex/basis-candidate-status-20261109' into codex/accept-grok-batch2-1109
# Conflicts:
#	docs/BUG_HISTORY.md
2026-11-09 14:41:30 +08:00
Claude c19baf033b Merge remote-tracking branch 'origin/codex/ondemand-transit-window-20261109' into codex/accept-grok-batch2-1109 2026-11-09 14:41:25 +08:00
jesse-uxandGrok (agent loop) 09a67aad5a fix(consult): 解读依据的格局行按卡上状态说话,不再写成成立 (#181, BUG-1824)
- 新增 yoga-status-words.ts:conditions_not_met → 不成立;candidate → 候选;
  computed → 未确认;其他 → 未标状态;结构观察不进这一行
- yogaLine 逐个名字到 card.base.natal.yogas_detail.rows 取状态词并按状态分组
  (候选:A、B;未确认:C),没有可列的写「本题没有检测到相关格局」
- 「格局」兜底文案改为「盘上检测到的格局已列出各自状态」(三栏注释)
- 数据卡、回执 schema、行状态判定、页面组件都不动

Tests: 新增 consult-basis-candidate-status-1824.test.ts(8 条);
consult-technique-evidence-1793 / consult-answer-basis-receipt-20261108 /
consult-answer-mode-ui-20261108 继续通过;tsc 0 错,lint 0 error。

Co-Authored-By: Grok (agent loop)
2026-11-09 14:33:47 +08:00
jesse-uxandGrok (agent loop) 78c34c09ab feat(ondemand): transit window — ingress, stations, retrograde loops, target longitude (#174, BUG-1817)
按 #173 的合同加第二个按需工具,只做后端:

- scripts/ondemand_calc/transit_window.py:四类事件(ingress / station /
  retrograde_loop / target_longitude),黄经与日速度来自
  _calc_sidereal_planets_for_jd(先配星历路径),口径由调用方显式传
- 事件二分到 ≤1 分钟;逆行往返给两个停滞、retrograde_span、影子期进出,
  区间外每侧最多 400 天并标 outside_requested_window
- 节点不报停滞:partial + node_station_not_supported 的 gap
- 位置口径 mean 阻塞;缺项返回 blocked 信封并点名,不编任何日期
- registry 加两行注册

Tests: tests/test_ondemand_transit_window_20261109.py 17 条;连同 transit_date、
contract、api growth 共 47 条全过。2026 水星逆行停滞与直接 SwissEph 速度二分
相差 1.41 分钟。

Co-Authored-By: Grok (agent loop)
2026-11-09 14:18:39 +08:00
ClaudeandClaude Opus 5.5 21b1fe1aae docs(task): brief for basis-candidate-status (2026-11-09)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 14:03:27 +08:00
ClaudeandClaude Opus 5.5 636b24f081 docs(task): brief for ondemand-transit-window (2026-11-09)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-09 14:03:27 +08:00
27 changed files with 1846 additions and 891 deletions
+41 -13
View File
@@ -24519,17 +24519,45 @@
- 关联记录:占星师 2026-11-07 Q9、2026-11-08 第五轮第 9 条;FIX-ondemand-transit-date-1(产品拍板 C 方案)
- 修复版本:分支 codex/ondemand-transit-date-20261109
## BUG-1827 | 校时可比性:她的层名写法与产品层名不一致;贡献粒度、拆不开的 MD/AD、缺失字段都没暴露
## BUG-1817 | 没有「一段时间内的行运变化」:换座、停滞、逆行往返、目标经度都算不出来
- 状态:fixed-pending-verify(分支 codex/rect-layer-alias-20261109)
- 首次发现 / 最近更新:2026-11-09(占星师第七轮回复 P1)/ 2026-11-09(修复)
- 影响面:scripts/active_rectification_event_engine.py(_candidate_row 末尾追加 contributions)、scripts/active_rectification_events.py(层名对照、MD/AD 一致排除、missing_mandatory_layers、三个计数)。
- 现象:同一份合成例,她原文写法(missing_layers = [Narayana_AD])得到 not_reducible,产品测试写法(Narayana_MD_AD)得到 common_coverage;回执里 missing_mandatory_layers 是 null 而 reasons 里又有这个字符串;计分只有分值与层总分,看不出每项贡献依赖哪些层、是否拆得开。
- 触发条件:任何校时候选比较。
- 根因:判定层只认产品层名,没有输入适配,也不知道「她原文的 Narayana_AD = 整件事不计分」与「产品的 Narayana_AD = 只缺小运那一项」是两件不同的事;计分证据没有逐项贡献,MD 与 AD 的合并分拆不开时又按 0 处理;缺失信息只在 reasons 里有一个字符串。
- 修复:新增 ASTROLOGER_EVENT_LAYER_ALIASES(只在「该候选整件事缺失」且无其他门控层、且它有的每件事层集合与共同覆盖一致时套用,记 layer_aliases_applied);引擎行追加 contributions(event_id / layer / dependency / profile / points / decomposable / missing_reason,整件不计分的事也记一项);任一候选的 dasha_varga_core 贡献 decomposable 为假时,对所有候选一致排除该单元并写 excluded_contributions;新增顶层 missing_mandatory_layers([{candidate_time, layer, event_ids}],按时间与层排序,永不 null,旧形状行标 legacy_row_without_contributions);reasons 里的 missing_mandatory_layers 当且仅当列表非空;新增 top_candidate_count / top_segment_count / unique_time 三个计数。
- 验证:frontend 无涉及;tests/test_rectification_layer_alias_bug1827.py 17 条(含真实引擎行:贡献非空分值之和等于 score、layer_points 与 contributions 一一对应、依赖含 Vimshottari_MD_AD_PD / Narayana_MD / Narayana_AD),连同 1801 / active_events / 1802 / technique_contract 合计 52 条全过;can_apply、confidence、top_score、winning_segment 未变(旧测试逐条通过)。
- 防复发:上述测试;对照表只有 Narayana_AD 一条,新增条目需拍板;拆不开的合分不再按 0 计。
- 关联记录:BUG-1801、BUG-1759、BUG-1785、占星师 2026-11-09 第七轮 P1
- 验收退回(2026-11-09,FIX-rect-layer-alias-3):排除后未按共同覆盖比较——单元拿掉了,但候选 missing_layers 里的 Narayana_AD 仍被算成 unexplained,于是又走 not_reducible,而且那个分支不输出 excluded_contributions。已改为:某个差异层若被所有带它的候选的「不可拆 MD/AD 项」覆盖(且没有别的缺失层)就视为已解释;not_reducible 分支也输出 excluded_contributions。
- 修复版本:分支 codex/rect-layer-alias-20261109
- 状态:fixed-pending-verify(分支 codex/ondemand-transit-window-20261109)
- 首次发现 / 最近更新:2026-11-07(占星师 Q9)/ 2026-11-09(后端修复)
- 影响面:新增 scripts/ondemand_calc/transit_window.py;scripts/ondemand_calc/registry.py 加两行注册。
- 现象:只能问「某一天行运如何」,问「接下来多久换座 / 什么时候停滞 / 这次逆行什么时候往返 / 什么时候到某个度数」都得自己猜日期。
- 根因:按需计算骨架里只有单日期工具;现成的 ephemeris_events 按 UT 正午逐日采样且不认 node_mode、没有罗睺计都;transit_trigger.find_exact_transit_date 只返回第一次到达、岁差写死;cmd_transit 的 --retrograde-calendar / --find-conjunction 依赖不存在的 transit_search.py。
- 修复:新增 transit_window 工具(ingress / station / retrograde_loop / target_longitude),黄经与日速度来自 jyotish_engine._calc_sidereal_planets_for_jd,口径由调用方显式传;事件二分到 ≤1 分钟;逆行往返给两个停滞、retrograde_span、影子期进出,允许区间外 400 天搜索并标 outside_requested_window;目标经度按方向列出每一次到达;节点不报停滞(partial + gap);失败只留缺口不编日期。
- 验证:tests/test_ondemand_transit_window_20261109.py(17 条)与 transit_date / contract / api growth 合计 47 条全过;2026 水星逆行两个停滞与直接 SwissEph 速度二分的差为 1.41 分钟。
- 防复发:上述测试;合同 docstring 的注册步骤已含本工具。
- 验收修正(Claude 2026-11-09,codex/accept-grok-batch2-1109):换座的 to_sign 原来把 JD 当黄经取星座(每次换座的新星座都是错的),direction 把 0° 白羊处的顺行换座判成 retrograde,两处都改为按粗扫步的黄经计算;逆行往返里两个停滞与影子期进出各自标 outside_requested_window;区间终点按终点那天的 UTC 偏移换算。补 3 条回归测试(共 20 条)。
- 关联记录:占星师 2026-11-07 Q9、2026-11-08 第五轮第 9 条;#173(共用骨架)
- 修复版本:分支 codex/ondemand-transit-window-20261109
## BUG-1824 | 「解读依据」把候选格局显示成「成立」
- 状态:fixed-pending-verify(分支 codex/basis-candidate-status-20261109)
- 首次发现 / 最近更新:2026-11-09(第七轮验收包,页面阶段)/ 2026-11-09(修复)
- 影响面:frontend/src/lib/consultation-technique-evidence.ts 的 yogaLine;frontend/src/lib/consult-answer-basis.ts 的「格局」兜底文案;新增 frontend/src/lib/yoga-status-words.ts。
- 现象:简明解读的「解读依据」里,「格局」一行写「成立:Sunaphaa Yoga、Vosi Yoga」,而卡上这些格局的状态是 candidate / computed,卡上的规则写明 none is confirmed。
- 触发条件:任何带数据卡的简明解读回答。
- 根因:yogaLine 只读领域段的 yogas.hits(检测器匹配到的规则名,BUG-1157),一律写成「成立:」;真正的状态在 card.base.natal.yogas_detail.rows[] 的 status / formation.status 里,从来没被这一行读过。
- 修复:新增 yoga-status-words.ts(conditions_not_met → 不成立;candidate → 候选;computed → 未确认;其他 → 未标状态;结构观察不进这一行);yogaLine 改为按名字到 yogas_detail.rows 取状态词并按状态分组(候选:A、B;未确认:C),没有可列的写「本题没有检测到相关格局」;兜底文案由「盘上成立和落空的格局已核对」改为「盘上检测到的格局已列出各自状态」。行状态(已算 / 有条件)与数据卡事实记录不动。
- 验证:frontend/tests/consult-basis-candidate-status-1824.test.ts(8 条:三种状态词、formed_under_source 不写成成立、结构观察不出现、未标状态、灰字与兜底都不含「成立:」和「已确认」、计算状态与解读状态分开、空 hits 文案、词表本身不提供「成立」);consult-technique-evidence-1793(2)、consult-answer-basis-receipt-20261108(4)、consult-answer-mode-ui-20261108(14)继续通过。
- 防复发:上述测试;词表单独成文件,后续 #182 复用同一套词。
- 验收修正(Claude 2026-11-09,codex/accept-grok-batch2-1109):占星师第七轮回复 §5 P0.2 给出了确切映射,初版词表(候选 / 未确认 / 不成立 / 未标状态,formed_under_source 显示为候选)与之不同,验收时替换为原表:candidate / support_only_candidate → 命中候选规则,尚未完整确认;computed(未完成来源条件治理)→ 检测器检出,待核实;formed_under_source → 按所选来源的形成条件成立;强度和结果另评;conditions_not_met → 所选来源的必要条件未满足;blocked / not_available_yet / 卡上无状态行 / 状态值不在表内 → 当前无法确认,缺:<缺项>。只有 formation.status(完整条件检查)能给出「成立」或「必要条件未满足」;只在 hits 里出现的名字一律落到「当前无法确认」。灰字按「名字:状态文字」分组、组间用「。」,放不下的整项写「另 N 项未列」,状态文字不被 80 字截断。新增 5 行映射各一条与「只在 hits 里的格局不显示成立」一条回归测试(共 13 条)。#182(模型侧措辞)必须 import 同一个 yoga-status-words.ts 的 YOGA_STATUS_MAPPING / yogaStatus。
- 关联记录:BUG-1793、BUG-1157、#182
- 修复版本:分支 codex/basis-candidate-status-20261109
## BUG-1834 | 用户该知道的限制只藏在后台:页面上看不到「本次未做外部核验」
- 状态:fixed-pending-verify(分支 codex/limitation-line-20261109)
- 首次发现 / 最近更新:2026-11-09(占星师第七轮回复)/ 2026-11-09(显示层修复)
- 影响面:frontend/src/lib/consult-answer-basis.ts(常量与 withVerificationLimitLine)、components/consult-answer-basis.tsx(列表末行)、components/chat-message-content.tsx(深度解读表尾)、references/product_runtime_contract.md 的「F」6c 行末备注。
- 现象:产品 2026-11-08(BUG-1794)把外部验证四行只留在后台回执,普通用户看不到任何「本次未完成外部资料与案例核验」的提示,容易把候选窗口当成已确认结论。
- 触发条件:任何简明解读的「解读依据」展开、任何带审计表的深度解读。
- 根因:限制信息只有后台记录这一条出路,页面没有「把已知边界显示给用户」的位置。
- 修复:一处定义常量 CONSULT_VERIFICATION_LIMIT_LINE,页面上两处引用——简明解读列表在技法行之后多一行(无状态、不计入 N 项、空列表仍不渲染、流式不出现);深度解读在最后一张审计表的最后一行之后空一行插入同一句(只在非流式且没有 basisRows 时生效、已有该句不重复加、没有审计表不加)。回答正文、存储文字、回执、提示词都不变;四行外部验证不恢复。合同「F」6c 行末追加一句记录这次同意。
- 验证:frontend/tests/consult-limitation-line-1834.test.tsx(12 条:常量与句号、列表末行位置与不重复、无状态标签、空列表为空、流式不加、行数据不含该句、深解读表尾位置与去重、无表格不加、简明只在列表出现一次、存储文字不变、接线条件);既有 consult-answer-basis-receipt(4)、consult-answer-mode-ui(14)、consult-basis-candidate-status(12)、report-no-web-wording(4)全过;tsc 0 错;eslint 0 error;合同相关 pytest 31 条全过。
- 防复发:上述测试;这句话只有一份定义,改文字只改常量;报告类无联网措辞规则(BUG-1810)继续有效。
- 关联记录:BUG-1794(四行外部验证只留后台)、BUG-1810(报告不写联网措辞)、#181、占星师 2026-11-09 第七轮回复
- 修复版本:分支 codex/limitation-line-20261109
-28
View File
@@ -1,28 +0,0 @@
# #184 范围补充:占星师第七轮回复 P1(2026-11-09)
本文件补充 `TASK-rect-layer-alias-20261109.md`。两者冲突时以本文件为准。占星师原文见她的《第七轮验收与 R2 裁定回复》§5 P1。
## 她的要求
1. **按真实计分粒度比较**,不能靠改缺失层的名称让合成例通过。原文:“禁止用改缺失名称的测试代替真实部分缺失路径。”
- 每一项计分贡献都要带上这些信息:`event_id`、`technique`/`layer`、`dependency`、`profile`、`points`、缺失原因。复用现有的计分证据,不另起一套。
- 如果大运和小运的合并分暂时拆不开,就对所有候选一致地排除这一项合并贡献,并写明理由。不能把缺这一项的候选当 0 分,而让有这一项的候选继续计分。
2. **区分三个计数**:`top_candidate_count`、`top_segment_count`、`unique_time`。
- 例子:共同分数 8:8,候选区间 12:00–12:01,`comparable_tied=false`。这可能是一个连续领先的区间,但不是唯一的分钟。
- 代表分钟不能冒充唯一解。
3. **`missing_mandatory_layers` 必须以真实字段暴露出来。** 现在回执里这个字段是 `null`,但 reason 里又写了 missing_mandatory_layers,两边对不上。要回传实际的字段路径和缺失列表,`null` 不能被读成“没有缺失”。
## 本单因此改为
- 原任务书里的层名对照(`Narayana_AD → Narayana_MD_AD`)**只能作为输入适配**:只在她的原文层名进入产品时做一次映射,并在回执里记下映射前后的名称。验收不能依赖它让合成例通过。
- 主要工作是上面第 1–3 条,改动范围限于 `scripts/active_rectification_events.py` 和相关回执。
- 反例测试至少包括:
- 真实路径上只缺小运(AD),大运(MD)有值;
- 大运和小运的合并贡献拆不开;
- 有负分的贡献;
- 8:8 连续区间:`top_segment_count = 1`,`unique_time = false`;
- `missing_mandatory_layers` 是非空列表,并且字段路径可以读到。
- 不改旧的 `can_apply` 含义,不改历史评分阈值。
- 不得自行写“产品决定”或“裁定”;任务书没写到的取舍一律选需拍板。
BUG-1827。自测命令与原任务书相同。
-75
View File
@@ -1,75 +0,0 @@
# #184 验收退回 + 回答两个问题(2026-11-09,Claude)
本文件补充 `TASK-rect-layer-alias-20261109.md` 和 `FIX-rect-layer-alias-1.md`,冲突时以本文件为准。验收的是 `8a844f3c`。
## 验收结果
- 通过的部分(保留,不要改):`top_candidate_count` / `top_segment_count` / `unique_time` 三个计数和 5 条测试;既有 1801 / 1802 / active_events / technique_contract 40 条全过;只加字段,不改判定。
- 未完成:P1 第 1 条(逐项贡献 + MD/AD 合分一致排除)、第 3 条(`missing_mandatory_layers` 真实字段)、原任务书的层名对照(输入适配 + `layer_aliases_applied`)。Claude 跑了验收包 `rect_her_synthetic.py`:三个合成例与 staging 结果完全相同,她原文写法仍是 `not_reducible`,`missing_mandatory_layers` 仍取到 `null`。
## 回答你的两个问题
### ① 不拆单
三条都在本单完成。原任务书“不许改 `active_rectification_event_engine.py`”是 Claude 写给层名对照用的,与 FIX-1 冲突,**本文件放开为:只许在产生候选行的函数末尾追加字段**(`missing_layers`、`layer_points`、`evidence`、`score` 的值与顺序一律不变;不改任何计分、门槛、层名)。
### ② `missing_mandatory_layers` 的形状
`adjudicate_candidate_rows` 的结果加顶层字段:
```
"missing_mandatory_layers": [
{"candidate_time": "12:01", "layer": "Narayana_AD", "event_ids": ["e5"]},
...
]
```
- 按 `(candidate_time, layer)` 排序;`event_ids` 排序;没有缺失时是 `[]`,任何情况下都不是 `null`(空候选也是 `[]`)。
- `event_ids` 来自下面的逐项贡献;行上没有贡献明细时(旧形状行)写 `null`,并在该项加 `"event_ids_source": "legacy_row_without_contributions"`。
- `reasons` 含 `"missing_mandatory_layers"` 当且仅当该列表非空(写测试)。
- 原 `missing_layers` 字段不变。
## 要做的
### 1. 逐项贡献(引擎行,追加字段 `contributions`)
每个候选行加 `contributions: list[dict]`,每件事、每层一项,复用 `layer_points` 已有的层名(`dasha_varga_core` / `controlled_transit` / `Ashtakavarga` / `Shadbala`):
```
{"event_id": "e5", "layer": "dasha_varga_core",
"dependency": ["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD", "D10"], # 这项分数实际依赖的层
"profile": {...}, # 只搬运引擎上下文里已有的 profile(功能吉凶 profile、Narayana 各步 profile);没有就 null,不新算
"points": 2.0, # 与 layer_points 同值
"decomposable": false, # 这项里 MD 与 AD 的分数拆不开时为 false
"missing_reason": "Narayana_AD_unresolved"} # 没有缺失时为 null
```
- 整件不计分的事(缺门控层而 `continue` 的那几处)也记一项:`layer` 写门控层名(如 `Narayana_MD_AD`、`D9`),`points: null`,`missing_reason: "event_not_scored:<层名>"`。
- 不变式测试:每行非空 `points` 之和与该行 `score` 相等(四位小数);`layer_points` 与 `contributions` 一一对应。
### 2. MD/AD 合分一致排除(`active_rectification_events.py`)
- 只要有任一候选在事件 e 上的 `dasha_varga_core` 贡献 `decomposable == false`,就把 `(e, dasha_varga_core)` 从**所有**候选的比较单元里一起拿掉(缺的不当 0,全的也不计),再按剩下的共同覆盖比较。
- `coverage_comparison` 加 `excluded_contributions: [{"event_id", "layer", "reason": "md_ad_not_decomposable"}]`;没有排除时不出现。
- 没有 `contributions` 的旧形状行保持现状(`not_reducible`)。
- 既有 1801 用例若因此改变结果,逐条写“原值 / 新值 / 原因”三栏注释,原因写 `占星师第七轮 P1:拆不开的 MD/AD 合分对所有候选一致排除(BUG-1827)`;不得删断言。
### 3. 层名对照
照原任务书第 1–3 节做(只在她原文写法进入时映射一次,记 `layer_aliases_applied`),并照 FIX-1 的反例清单写测试。验收不靠它:反例必须走真实形状(带 `contributions` 的行)。
### 4. 不变的东西(写测试)
- `can_apply` 的含义与取值:对 1801 / 1802 / active_events 的全部既有用例,`can_apply`、`confidence`、`top_score`、`winning_segment` 与改前逐个相同。
- 不改历史评分阈值、`EVENT_GATING_LAYERS` 成员、`COMPARABILITY_POLICY` 名字。
## 验收时 Claude 会做
- 跑验收包 `rect_her_synthetic.py`,看她原文写法是否得到 `common_coverage` + `excluded_contributions`,`missing_mandatory_layers` 是否为非空列表。
- 量封存 20 / 偏移 900 / live v5 的变化(只量不重新封存)。
## 不要碰
原任务书“不要碰”清单除上面放开的一处外继续有效。不得自行写“产品决定/裁定”;任务书没写到的取舍一律选需拍板。
BUG-1827:本分支还没有这一条,在 `docs/BUG_HISTORY.md` 末尾追加(只在末尾追加)。
-41
View File
@@ -1,41 +0,0 @@
# #184 验收退回(第 2 次):真实“只缺小运”路径仍是 not_reducible(2026-11-09,Claude)
本文件补充 `TASK-rect-layer-alias-20261109.md`、`FIX-rect-layer-alias-1.md`、`FIX-rect-layer-alias-2.md`,冲突时以本文件为准。验收的是 `446420d7`。
## 已核对通过(保留,不要改)
- 引擎行 `contributions`:七个字段齐全,非空 `points` 之和等于 `score`,`layer_points` 与 `contributions` 一一对应;只追加字段。
- `missing_mandatory_layers: [{candidate_time, layer, event_ids}]`:排序、`[]` 永不 `null`、旧形状行 `event_ids: null` + `event_ids_source`;`reasons` 条件正确。
- `top_candidate_count` / `top_segment_count` / `unique_time`;层名对照只在整件缺失时套用,并记 `layer_aliases_applied`。
- `can_apply` / `confidence` / `top_score` / `winning_segment` 在既有用例上不变;52 条测试通过。
## 问题:FIX-2 第 2 条没有生效
FIX-2 第 2 条要求:拆不开的 `(e, dasha_varga_core)` 对所有候选一起拿掉,**再按剩下的共同覆盖比较**。现在代码确实把单元拿掉了,但 `assess_leader_comparability` 之后仍把该候选 `missing_layers` 里的 `Narayana_AD` 算作 `unexplained`,于是直接走 `not_reducible` 分支;这个分支还**不输出** `excluded_contributions`。
Claude 实测(真实形状行:两个候选都有 e1–e5 的 `layer_points` 与 `contributions`,12:01 的 e5 `dasha_varga_core` 为 `decomposable: false`、`missing_reason: "Narayana_AD_unresolved"`、`missing_layers: ["Narayana_AD"]`):
| 字段 | 现在 | 应该 |
| --- | --- | --- |
| `coverage_comparison.comparison` | `not_reducible` | `common_coverage` |
| `unreducible_layers` | `["Narayana_AD"]` | 不出现 |
| `excluded_contributions` | 不出现 | `[{"event_id": "e5", "layer": "dasha_varga_core", "reason": "md_ad_not_decomposable"}]` |
| `comparable_leader` | `null` | 按剩余共同覆盖算出(可以是 `comparable_tied`) |
也就是说她要的“真实部分缺失路径给出可比结果,或带理由的明确排除”,现在两样都没有。
## 要做的
1. 在 `assess_leader_comparability` 里:某个差异层 `L`,如果每个带 `L` 的候选,其 `contributions` 中所有 `missing_reason == f"{L}_unresolved"` 的项都已被 `excluded_contributions` 覆盖(同一 `event_id` 的 `dasha_varga_core`),并且该候选没有别的未解释缺失,则 `L` 视为已由排除解释,不进 `unexplained`。没有 `contributions` 的旧形状行不适用,仍按原逻辑(旧行仍 `not_reducible`)。
2. `excluded_contributions` 在 `not_reducible` 分支里也要输出(只要非空)。
3. 测试(写进 `tests/test_rectification_layer_alias_bug1827.py`,不弱化已有断言;若已有断言“产品 Narayana_AD 仍 not_reducible”与本条冲突,只对**带 contributions 的真实形状行**改期望,并写三栏注释,原因 `占星师第七轮 P1:拆不开的 MD/AD 合分对所有候选一致排除后按共同覆盖比较(BUG-1827,FIX-3)`):
- 上表的真实形状例:`common_coverage`、`excluded_contributions` 如上、`common_scores` 不含 e5 的 `dasha_varga_core`;
- 同一例里 e5 另有一层也缺失且不可拆分 → 仍 `not_reducible`,且输出 `excluded_contributions`;
- 旧形状行(无 `contributions`、`missing_layers: ["Narayana_AD"]`、事件都在)→ 仍 `not_reducible`,不出现 `excluded_contributions`;
- 带负分贡献的真实形状例(FIX-1 反例清单):排除后共同覆盖得分按剩余单元计算,负分照计;
- `can_apply`、`confidence` 在上述各例与改前相同(用测试锁住)。
4. PROGRESS 补“第 2 次打回”一节;BUG-1827 补一行“验收退回:排除后未按共同覆盖比较”(只改这一条)。
## 不要碰
前三份任务书的“不要碰”清单继续有效;`active_rectification_event_engine.py` 本轮不再改。不得自行写“产品决定/裁定”;任务书没写到的取舍一律选需拍板。
@@ -0,0 +1,45 @@
# PROGRESS · 「解读依据」候选格局不再写成「成立」(#181,BUG-1824,2026-11-09)
- 分支:`codex/basis-candidate-status-20261109`(基线 `afac4ea9`)
- 任务书:`docs/tasks/TASK-basis-candidate-status-20261109.md`
- Bug:`docs/BUG_HISTORY.md` 末尾追加 BUG-1824
## 改了什么
| 文件 | 内容 |
| --- | --- |
| `frontend/src/lib/yoga-status-words.ts`(新) | `YOGA_STATUS_WORDS` 与 `yogaStatusWord(row)`:`formation.status = conditions_not_met` → 不成立;`status = candidate` → 候选;`status = computed` → 未确认;其他 → 未标状态。另导出 `isStructuralObservation(row)` |
| `frontend/src/lib/consultation-technique-evidence.ts` | 只改 `yogaLine` 与一行 import:仍取领域段 `yogas.hits` 的前 3 个名字,逐个到 `card.base.natal.yogas_detail.rows` 按 `name` 找状态词;结构观察跳过;按状态词分组(组按首次出现排、组内保持原顺序);找不到行 → 未标状态;没有可列的 → 「本题没有检测到相关格局」 |
| `frontend/src/lib/consult-answer-basis.ts` | 「格局」的兜底文案改为「盘上检测到的格局已列出各自状态」,改动处写三栏注释(原因:BUG-1824:候选不得显示为成立) |
没动:数据卡(`yogas.hits` / `yogas_detail` 事实记录一字未改)、回执 schema、`display_status` 取值、页面组件、答题提示词、`references/**`、`scripts/**`。
## 状态词表
| 卡上的值 | 显示 |
| --- | --- |
| `formation.status = "conditions_not_met"` | 不成立 |
| `status = "candidate"` | 候选 |
| `status = "computed"` | 未确认 |
| 其他 / 缺失 | 未标状态 |
`formed_under_source` 不单独显示为「成立」——卡上规则是 `none is confirmed`,按 `status` 显示。
词表里没有「成立」「已确认」这两个词(「不成立」是否定式,是任务书要求的)。
## 自测
| 命令 | 结果 |
| --- | --- |
| `node ... --test tests/consult-basis-candidate-status-1824.test.ts` | 8 过 / 0 败 |
| `tests/consult-technique-evidence-1793.test.ts` | 2 过 / 0 败 |
| `tests/consult-answer-basis-receipt-20261108.test.tsx` | 4 过 / 0 败 |
| `tests/consult-answer-mode-ui-20261108.test.tsx` | 14 过 / 0 败 |
| `tsc --noEmit -p frontend` | 0 错 |
| `npm run lint` | 0 error |
新测试覆盖任务书的 7 条:三种状态词各对各;`formed_under_source` 显示候选、不写成立;结构观察不出现;卡上没有对应行的名字 → 未标状态;灰字与兜底都不含「成立:」「已确认」;`consultAnswerBasisRows` 走一遍时「格局」行 `status === "done"` 且 `result` 是分组灰字(计算状态与解读状态分开);空 `hits` → 「本题没有检测到相关格局」。既有断言没有改动,所以没有三栏注释。
## 说明
- 「格局」行要显示成 `已算`,测试里的审计行用 `interpretation_status: "supporting"`(引擎把 yoga 行标为 observation/supporting 时 `display_status` 才是 firm)。这是既有判定,本单没有改。
- 页面组件 `consult-answer-basis.tsx` 不用改:它只渲染 `result` 与状态标签。
@@ -0,0 +1,56 @@
# PROGRESS · 「解读依据」末行与审计表末尾的固定未核验说明(#187,BUG-1834,2026-11-09)
- 分支:`codex/limitation-line-20261109`(基线 `004cf9d8`,#181 已在其上)
- 任务书:`docs/tasks/TASK-limitation-line-20261109.md`
- Bug:`docs/BUG_HISTORY.md` 末尾追加 BUG-1834
## 做了什么
| 文件 | 改动 |
| --- | --- |
| `frontend/src/lib/consult-answer-basis.ts` | 新增常量 `CONSULT_VERIFICATION_LIMIT_LINE`(文字与句号一字不改)与纯函数 `withVerificationLimitLine(text)` |
| `frontend/src/components/consult-answer-basis.tsx` | 列表里技法行之后多一个 `<li>`:只有这句话、没有状态标签、不计入摘要的 N 项 |
| `frontend/src/components/chat-message-content.tsx` | 可见文字在 `withoutExternalVerificationRows` 之后再走 `withVerificationLimitLine`,条件是「非流式」且「没有传 `basisRows`」 |
| `references/product_runtime_contract.md` | 只在「F」6c 那一行**行末**追加产品负责人 2026-11-09 同意的那一句,其余一字未改 |
| `frontend/tests/consult-limitation-line-1834.test.tsx`(新) | 12 条 |
没有改提示词、`yoga-status-words.ts`、`EXTERNAL_VERIFICATION_ROW_RE`、回执、`scripts/**`、报告链路。
## 渲染片段(合成回答)
简明解读的列表(节选,末尾两行):
```html
<li class="consult-answer-basis-row">…<span class="consult-answer-basis-name">格局</span><span class="consult-answer-basis-result">本题没有检测到相关格局</span></span><span class="consult-answer-basis-status is-done">已算</span></li>
<li class="consult-answer-basis-row"><span class="consult-answer-basis-text"><span class="consult-answer-basis-result">本次未完成外部资料与案例核验,候选窗口尚未据此确认。</span></span></li>
```
深度解读的可见文字(节选,表格末行之后):
```
| Yogas | exec | observation | 候选 |
本次未完成外部资料与案例核验,候选窗口尚未据此确认。
表格之后的收尾一段。
```
## 自测
| 命令 | 结果 |
| --- | --- |
| `node --test tests/consult-limitation-line-1834.test.tsx` | 12 过 / 0 败 |
| `tests/consult-answer-basis-receipt-20261108.test.tsx` | 4 过 |
| `tests/consult-answer-mode-ui-20261108.test.tsx` | 14 过 |
| `tests/consult-basis-candidate-status-1824.test.ts` | 12 过 |
| `tests/report-no-web-wording-20261109.test.ts` | 4 过 |
| `tsc --noEmit -p frontend` | 0 错 |
| `npx eslint`(四个改动文件) | 0 error |
| `pytest tests/test_upstream_skill_parity.py tests/test_astrologer_rulings_round5_20261108.py` | 31 过 / 0 败 |
## 偏离与说明
1. **既有断言改了一处**(任务书点名的那个):`consult-answer-basis-receipt-20261108.test.tsx` 里 `assert.doesNotMatch(markup, EXTERNAL_COPY)` 会因为这句话里的「外部资料」失败。改成先断言这句话恰好 1 次、再把它从 markup 里去掉后做原来的 `doesNotMatch`,写了「原值 / 新值 / 原因」三栏。`EXTERNAL_COPY` 正则本身没动。
2. **没有新增 CSS 规则**:这一行复用 `.consult-answer-basis-result` 的灰字样式,所以 `globals.css` 未改(任务书里 CSS 是「可选」)。
3. **深度解读的渲染断言只到渲染前那一步**:测试环境没有 markdown 渲染器,`ChatMessageContent` 的表格在 `renderToStaticMarkup` 下出不来(既有 UI 测试也是这个限制)。所以表格末尾那条用 `withoutExternalVerificationRows` + `withVerificationLimitLine` 的组合验位置与去重,`ChatMessageContent` 的接线用源码断言确认条件(`!streaming && !basisRows?.length`)。
4. 没有遇到需要拍板的取舍。
@@ -0,0 +1,45 @@
# PROGRESS · 按需计算(二)一段时间内的行运变化(#174,BUG-1817,2026-11-09)
- 分支:`codex/ondemand-transit-window-20261109`(基线 `afac4ea9`)
- 任务书:`docs/tasks/TASK-ondemand-transit-window-20261109.md`
- Bug:`docs/BUG_HISTORY.md` 新增 BUG-1817
## 做了什么
| 文件 | 内容 |
| --- | --- |
| `scripts/ondemand_calc/transit_window.py`(新) | `TOOL = 'transit_window'`,`run(body)`。四类事件:换座 `ingress`、停滞 `station`、逆行往返 `retrograde_loop`、到达目标经度 `target_longitude` |
| `scripts/ondemand_calc/registry.py` | 加了 `from . import transit_window` 与 `TOOLS['transit_window']` 两行(其余未动) |
| `tests/test_ondemand_transit_window_20261109.py`(新) | 17 条:本单专有 5 条 + 通用 12 条 |
| `docs/BUG_HISTORY.md` | 末尾追加 BUG-1817 |
口径与数值都照任务书:黄经与日速度全部来自 `jyotish_engine._calc_sidereal_planets_for_jd`(调用前先 `_configure_ephemeris_path()`),岁差/交点/位置口径由调用方传;`position_mode=mean` 返回 `blocked` + `position_mode_unsupported`;缺参数返回 `blocked` 信封并点名缺项(HTTP 仍是 200,按合同)。没有改合同、没有改 API 服务器、没有建前端目录。
## 实测(验收第 1 条的对照)
2026 年水星逆行(区间 2026-01-01 至 2026-03-31,lahiri / mean):
| 项 | 本工具 | 直接用 SwissEph 速度二分 | 差 |
| --- | --- | --- | ---: |
| 逆行停滞 | 2026-02-26T06:49Z | 2026-02-26T06:49Z | **1.41 分钟** |
| 顺行停滞 | 2026-03-20T19:32Z | 2026-03-20T19:32Z | **1.41 分钟** |
逆行段:`retrograde_span = [314.265716, 328.340901]`,影子期 `shadow_entry 2026-02-11T22:11Z` 早于逆行停滞、`shadow_exit 2026-04-09T11:44Z` 晚于顺行停滞,符合要求。
目标经度 320°(区间放宽到 2026-04-30 才够三次):2026-02-15T16:04Z 直行、2026-03-10T02:26Z 逆行、2026-04-01T14:43Z 直行。
收敛:每个事件二分到 ≤ 1/1440 天(1 分钟);粗扫月亮 6 小时、其余 1 天;逆行往返每侧最多 400 天,写在 `raw.precision`。
## 自测
| 命令 | 结果 |
| --- | --- |
| `pytest tests/test_ondemand_transit_window_20261109.py tests/test_ondemand_transit_date_20261109.py tests/test_ondemand_calc_contract_20261109.py tests/test_api_server_growth_contract.py` | **47 过 / 0 败**(本单 17 条) |
覆盖本单专有 5 条:停滞对照 ≤ 2 分钟;目标经度三次方向 direct/retrograde/direct;影子期先后;lahiri 与 raman 换座时刻不同且回显;罗睺 mean 与 true 换座时刻不同;伦敦跨夏令时那天的偏移为 0/1。通用 12 条:缺项点名(start_date / end_date / 地点 / 时区 / 岁差 / events)、超 366 天与倒序日期、未知事件与未知行星、`position_mode=mean` 阻塞、`profile_source` 标记、指纹稳定与敏感、引擎失败不给日期、节点不报停滞(`partial` + gap)、`natal_point` 缺失阻塞、注册表分派。
## 偏离与取舍
- **目标经度测试的区间**:任务书示例区间 1–3 月只够两次到齐(第二次逆行的第三次要等 4 月顺行恢复),所以那条测试把 `end_date` 放到 2026-04-30,并在测试里注明原因。没有改实现。
- **换座判定的实现**:按「星座编号变化 + 二分找第一次变化」实现,顺行与逆行(退回原星座)都成立;跨过 30° 边界的就是换座,不需要另外判断方向。
- **`ayanamsa_degrees_at_start`**:由引擎同一次调用返回的 ayanamsa 值,6 位小数。
- 遇到 `events` 里同时要 `station` 和 `retrograde_loop` 的节点星:`gaps` 记两条 `node_station_not_supported:<星>`(一次请求一条),状态 `partial`——任务书要求「不计算并写 gap」,按星记足够定位。
@@ -1,24 +0,0 @@
# PROGRESS · 校时可比性(#184,BUG-1827)
## 第 2 次打回(FIX-rect-layer-alias-3,2026-11-09)
**问题**:FIX-2 第 2 条只做了一半。单元是拿掉了,但候选 `missing_layers` 里的 `Narayana_AD` 仍被算成
`unexplained`,于是又落到 `not_reducible`;而那个分支**不输出** `excluded_contributions`。
**改法**:新增 `_explained_by_exclusion()`——某个差异层 L,若每个带 L 的候选都有贡献明细、其
`missing_reason == f"{L}_unresolved"` 的项全部落在 `excluded_contributions` 里、且没有别的缺失层,
就视为已由排除解释,不进 `unexplained`;`not_reducible` 分支也输出 `excluded_contributions`(非空时)。
旧形状行(没有 `contributions`)不适用,仍是原逻辑。
**新增 4 条测试**(真实形状行:`layer_points` + `contributions` 一一对应):
| 用例 | 期望 |
| --- | --- |
| 只缺小运、e5 的 MD/AD 拆不开 | `common_coverage` + `excluded_contributions`,共同覆盖里没有 e5 那一层,两侧按剩余单元计分(5.0 : 5.0,`comparable_tied`) |
| 同例另加一个缺失层(D9) | 仍 `not_reducible`,但 `excluded_contributions` 照常输出 |
| 旧形状行 | 不出现 `excluded_contributions` |
| 带负分的贡献 | 负分照计:e1 2.5 + e2 −0.5 = 2.0,没有被当成 0 |
`can_apply` / `confidence` / `top_score` / `winning_segment` 在既有用例上不变;本文件 20 条 + 既有
1801 / active_events / 1802 / technique_contract 合计 **56 条全过**。
@@ -0,0 +1,106 @@
# TASK:「解读依据」把候选格局显示成“成立”(#181,BUG-1824,2026-11-09)
- Gitea:#181
- 分支:`codex/basis-candidate-status-20261109`(基于 staging `afac4ea92f293a4d2bc81f62563487d26f92e4d2`)
- Bug 编号:BUG-1824(开工时核对 `docs/BUG_HISTORY.md` 的最大编号;1809–1830 已为这一批预留)
- 负责验收:Claude(jyotisha-2a)
- 范围:只改「解读依据」里「格局」这一行的灰字和兜底文案。
不得自行写“产品决定/裁定”;任务书没写的取舍一律选需拍板。
## 现象(第七轮验收包,页面阶段)
简明解读下的「解读依据」里,「格局」一行显示「成立:Sunaphaa Yoga、Vosi Yoga」「成立:Dharidhra Yoga…」。数据卡上这些格局的状态都是 `candidate`(或 `computed`),卡上的规则写明 `none is confirmed`。列表把“计算已执行”说成了“解读成立”。
## 根因(afac4ea9 实测,行号以符号为准)
- `frontend/src/lib/consultation-technique-evidence.ts` 的 `yogaLine(card)` 只读领域段的 `yogas.hits`(名字列表),一律写成 `成立:<名字>`;没有名字时写 `本题没有成立的格局`。
- `hits` 是“检测器在本盘匹配到的规则名”(`consultation-evidence-card.ts` 约 :2401,BUG-1157),不是“成立”。
- 每个格局真正的状态在同一张卡的 `card.base.natal.yogas_detail.rows[]` 里(`consultation-evidence-card.ts` 约 :2007–2028 从引擎层 `yoga_conditions` 原样拷贝):
- `status`:`candidate` | `computed` | `structural_observation`(引擎 `scripts/consultation_native_layers.py` 的 `status_rule`);
- `formation.status`:`formed_under_source` | `candidate` | `conditions_not_met`(`formation_rule`);
- `claim_kind`:`structural_observation` 时不是命名格局。
- `frontend/src/lib/consult-answer-basis.ts` 的 `BASIS_ENTRIES` 里「格局」的兜底文案是 `盘上成立和落空的格局已核对`,同样说过头。
- 行状态(`已算` / `有条件`)来自 `display_status` / 两轴状态,是**计算**状态;这部分是对的,不改。
## 要做的
### 1. 新建状态词表 `frontend/src/lib/yoga-status-words.ts`
一个导出的常量和一个函数,供本单使用(#182 以后也会复用,所以单独成文件):
| 卡上的值 | 列表显示 |
| --- | --- |
| `formation.status = "conditions_not_met"` | 不成立 |
| `status = "candidate"` | 候选 |
| `status = "computed"` | 未确认 |
| 其他 / 缺失 | 未标状态 |
- 判定顺序:先看 `formation.status === "conditions_not_met"`,否则看 `status`。
- `formed_under_source` **不**单独显示为“成立”:卡上规则是 `none is confirmed`,照 `status` 显示(候选 / 未确认)。
- 函数签名建议:`yogaStatusWord(row: Record<string, unknown>): "不成立" | "候选" | "未确认" | "未标状态"`。
- 词表里**不得**出现“成立”“已确认”这类词。
### 2. 改 `yogaLine(card)`(`consultation-technique-evidence.ts`)
- 仍取领域段 `yogas.hits` 的名字(顺序不变,最多 3 个)。
- 每个名字到 `card.base.natal.yogas_detail.rows` 里按 `name` 找对应行,用 `yogaStatusWord` 得到状态词。
- `claim_kind === "structural_observation"` 或 `status === "structural_observation"` 的名字不进这一行(与 `annual-report-sections.ts` 把结构观察单列、不进「格局」的做法一致)。
- 找不到对应行的名字显示“未标状态”。
- 按状态词分组,组内保持原顺序,组按第一次出现的顺序排:`候选:A、B;未确认:C`。
- 没有可列的名字时写 `本题没有检测到相关格局`。
- `LINES` 表、其他技法的灰字、`techniqueDisplayStatus`、`withTechniqueEvidence` 的结构都不改。
### 3. 改兜底文案(`consult-answer-basis.ts`)
`BASIS_ENTRIES` 里「格局」的 `result` 由 `盘上成立和落空的格局已核对` 改为 `盘上检测到的格局已列出各自状态`。改动处写“原值 / 新值 / 原因”三栏注释,原因写 `BUG-1824:候选不得显示为成立`。文件头注释里对应描述同步改一句。其余条目不改。
### 4. 测试 `frontend/tests/consult-basis-candidate-status-1824.test.ts`
用合成卡(不写真人资料),至少覆盖:
1. 卡上状态分别为 `candidate`、`computed`、`formation.status = conditions_not_met` 的三个格局,`yogaLine` 产出 `候选:…;未确认:…;不成立:…`,三个词各对各;
2. `formed_under_source` + `status = candidate` 显示“候选”;
3. 结构观察不出现在这一行;
4. 卡上没有对应行的名字显示“未标状态”;
5. 生成的灰字和兜底文案里都不含“成立:”这个子串,也不含“已确认”;
6. 经 `consultAnswerBasisRows` 走一遍:「格局」行的 `status` 仍是 `done`(已算),`result` 是第 1 条的灰字——计算状态和解读状态分开;
7. 空 `hits` 时灰字为 `本题没有检测到相关格局`。
既有测试 `frontend/tests/consult-technique-evidence-1793.test.ts`、`consult-answer-basis-receipt-20261108.test.tsx`、`consult-answer-mode-ui-20261108.test.tsx` 必须照样通过;若其中有断言写了旧文案,改时写三栏注释,不得删断言。
### 5. 记录
- `docs/BUG_HISTORY.md` 末尾追加 BUG-1824(状态、现象、触发条件、根因、修复、验证、防复发、关联 BUG-1793 / BUG-1157 / #182)。只在末尾追加,不用 sed 改整个文件。
- `docs/tasks/PROGRESS-basis-candidate-status-20261109.md`。
## 允许改的文件(只有这些)
- 新建:`frontend/src/lib/yoga-status-words.ts`、`frontend/tests/consult-basis-candidate-status-1824.test.ts`、`docs/tasks/PROGRESS-basis-candidate-status-20261109.md`
- 修改:`frontend/src/lib/consultation-technique-evidence.ts`(只改 `yogaLine` 和必要的 import)、`frontend/src/lib/consult-answer-basis.ts`(只改「格局」兜底文案与头注释一句)、`docs/BUG_HISTORY.md`(末尾追加)
- 页面组件 `frontend/src/components/consult-answer-basis.tsx` 预计不用改;若确实要改,停下选“需拍板”。
## 不要碰
- `references/**`(占星师方法文件),一字不改;包括 `references/product_runtime_contract.md`。
- `frontend/src/lib/consult-preset-prompts.ts`、`frontend/src/lib/consultation-methodology.ts`、`frontend/src/mastra/product-voice.ts`:不改答题规则。
- `frontend/src/lib/consultation-evidence-card.ts`:数据卡的事实记录一字不改(`yogas.hits`、`yogas_detail` 的字段和内容都不动;“把状态词写进卡和产品规则”归 #182)。该文件也是 #170 / #172 的范围。
- `frontend/src/lib/consultation-answer-fact-guard.ts`:拦截检查归 #182 / #183。
- `frontend/src/lib/consultation-agent-events.ts`(回执 schema,`display_status` 的取值不改)、`frontend/src/app/api/consult/route.ts`。
- `frontend/src/mastra/consultation-tools.ts`(#171)、`frontend/src/mastra/consultation-workflow.ts` 与 `frontend/src/lib/consultation-route-service.ts`(#185)。
- `scripts/**` 全部,特别是冻结文件:`scripts/jyotish_api_server.py`、`scripts/jyotish_engine.py`、`scripts/domain_calculation_service.py`、`scripts/dasha_analyzer.py`、`scripts/narayana_dasha.py`、`scripts/shadbala.py`、`scripts/ashtakavarga.py`、`scripts/jaimini.py`、`scripts/varga.py`、`scripts/functional_benefics.py`、`scripts/divisional_charts_extended.py`;以及 `scripts/consultation_native_layers.py`(引擎的状态值不改)。
- 既有断言不得弱化。
## 自测命令(Windows / PowerShell)
- `frontend\node_modules\.bin\tsc --noEmit -p frontend`
- 在 `frontend` 下运行 `npm run lint`
- 在 `frontend` 下运行 `node node_modules/tsx/dist/cli.mjs --test tests/consult-basis-candidate-status-1824.test.ts tests/consult-technique-evidence-1793.test.ts tests/consult-answer-basis-receipt-20261108.test.tsx tests/consult-answer-mode-ui-20261108.test.tsx`
前端全量测试、Python 快速门和 eslint 由 Claude 在验收时跑。
## 何时停下来选“需拍板”
- 卡上出现上表以外的状态值,且不能归入“未标状态”时。
- 要改数据卡、回执 schema、答题规则或页面组件才能做到时。
- 任务书没写到的任何文案或取舍。
+123
View File
@@ -0,0 +1,123 @@
# TASK:「解读依据」展开后的最后一行与深度解读审计表末尾,显示一句固定的未核验说明(#187,BUG-1834,2026-11-09)
- Gitea:#187
- 分支:`codex/limitation-line-20261109`(基于 staging `004cf9d88fdc17c949b7d5a5fe7febae585485c0`,#181 已在其上)
- Bug 编号:BUG-1834(开工时核对 `docs/BUG_HISTORY.md` 的最大编号;1829–1860 已预留)
- 负责验收:Claude(jyotisha-7e)
- 范围:**只改前端显示**,外加合同里指定的一句备注。回执、后台记录、提示词都不动。
不得自行写“产品决定/裁定”;任务书没写的取舍一律选需拍板。
## 背景
- 产品 2026-11-08(BUG-1794):回答里不写联网检索、外部资料、MEVG、真实案例校准;审计表的四行外部验证只留在后台回执(`references/product_runtime_contract.md`「F」6c)。
- 占星师 2026-11-09 第七轮回复:用户需要知道的限制不能只藏在后台,要求在「解读依据」或别的可见处写:「本次未完成外部资料与案例核验,候选窗口尚未据此确认」。
- 产品负责人 2026-11-09 同意的折中(就是本单的全部范围):
- 简明解读:「解读依据(N 项)」**展开后**,列表最后一行固定写:「本次未完成外部资料与案例核验,候选窗口尚未据此确认。」
- 深度解读:页面上显示的审计表**末尾**放同一句,只这一句。
- **不恢复**四行 MEVG / 外部验证行;后台回执照旧;这句话**不进回答正文**(模型不写,存下来的回答文字不变,只在显示时加)。
## 现状(004cf9d8 实测,行号以符号为准)
- 简明解读的列表:`frontend/src/components/consult-answer-basis.tsx` 的 `ConsultAnswerBasis`(`<details>` 里的 `<ul className="consult-answer-basis-list">`,摘要写 `{rows.length} 项`)。
- 列表数据:`frontend/src/lib/consult-answer-basis.ts` 的 `consultAnswerBasisRows`(只列可识别的技法,外部验证行一律不进,`isBackstageAuditRow` / `EXTERNAL_VERIFICATION_ROW_RE`)。
- 深度解读的审计表:`frontend/src/components/chat-message-content.tsx` 先 `withoutExternalVerificationRows(storedText)` 去掉外部验证行,表格随正文 Markdown 显示;`basisRows` 只在 `answerMode === "plain"` 时传入(`chat-message-row.tsx`)。
- #181(已在 staging)新建了单一状态词表 `frontend/src/lib/yoga-status-words.ts`(`YOGA_STATUS_MAPPING`),「解读依据」的格局灰字从它取。**本单照这种“一处定义、两处引用”的写法,但不改这个文件。**
## 要做的
### 1. 一处定义这句话
在 `frontend/src/lib/consult-answer-basis.ts` 导出常量:
```ts
export const CONSULT_VERIFICATION_LIMIT_LINE = "本次未完成外部资料与案例核验,候选窗口尚未据此确认。";
```
文字一字不改(含句号)。页面上出现这句话的地方都从这个常量取,不在别处另写字面量(测试里可以写字面量做对照)。
### 2. 简明解读:列表最后一行
- `ConsultAnswerBasis` 在技法行之后加**一行**,只有这句话,不带右侧状态(不显示 已算 / 有条件),用现有的灰字样式(`.consult-answer-basis-result` 那一套颜色与字号);若需要区分,最多加一个修饰类名,CSS 只在 `frontend/src/app/globals.css` 现有 `.consult-answer-basis-*` 规则旁加一条。
- 只在展开后可见(放在同一个 `<ul>` 里、`<details>` 之内),摘要行不变。
- 摘要里的 **N 仍是技法行数**(`rows.length`),这一行不计入 N。
- `rows.length === 0` 时整个列表照旧不渲染,这句话也不出现;流式输出中(列表本来就不显示)也不出现。
- `consultAnswerBasisRows` 的返回值不变:这句话**不是**一条 `ConsultAnswerBasisRow`,不进数据,只在组件里渲染。
### 3. 深度解读:审计表末尾
- 在 `consult-answer-basis.ts` 新增一个纯函数(例如 `withVerificationLimitLine(text: string): string`),在 `chat-message-content.tsx` 里接在 `withoutExternalVerificationRows(storedText)` 之后调用,**只在**以下条件同时成立时生效:
- 没有传 `basisRows`(即不是简明解读的列表场景);
- 不在流式输出中(`streaming === false`);
- 文字里有审计表(表头被 `AUDIT_TABLE_HEADER_RE` 或 `consultation-technique-audit.ts` 的两轴表头识别;复用已有的正则,不新写第三套)。
- 效果:在**最后一张**审计表的最后一行之后,空一行,插入这句话作为独立一段;一个回答只加一次。
- 文字里已经有这句话时不再重复加。
- 没有审计表的回答(包括闲聊、简明解读正文)不加。
- 存储的 `message.text`、回执的 `techniqueAuditTable` 都不变。
### 4. 合同备注(`references/` 里唯一允许改的一处)
`references/product_runtime_contract.md`「## F. 可能违反占星师 2026-11-07 写作底线的现有产品规则……」一节的 **6c 条**(以「6c. (BUG-1794,产品决定,偏离她的方法裁定)」开头的那一行)**行末**追加一句,原文如下:
> 产品负责人 2026-11-09 同意(BUG-1834):只在简明解读「解读依据」展开列表的最后一行、以及深度解读审计表末尾,由页面显示一句固定说明「本次未完成外部资料与案例核验,候选窗口尚未据此确认。」;回答正文仍不写,四行外部验证不恢复,后台记录不变。
- 只改这一行,不改别的行,不动任何 `<!-- product-block:... -->` 块(6c 在所有 product-block 之外,不会送进模型,因此提示词不变)。
### 5. 其他文件
- 新测试 `frontend/tests/consult-limitation-line-1834.test.tsx`。
- `docs/tasks/PROGRESS-limitation-line-20261109.md`。
- `docs/BUG_HISTORY.md` 末尾追加 BUG-1834(只在末尾追加)。
改动文件清单(除此之外不改):`frontend/src/lib/consult-answer-basis.ts`、`frontend/src/components/consult-answer-basis.tsx`、`frontend/src/components/chat-message-content.tsx`、`frontend/src/app/globals.css`(可选,最多一条规则)、`references/product_runtime_contract.md`(只上述一句)、`frontend/tests/consult-answer-basis-receipt-20261108.test.tsx`(只改下文点名的断言)、新测试、PROGRESS、`docs/BUG_HISTORY.md`。
## 验收(写进新测试)
1. 简明解读:`renderToStaticMarkup(<ConsultAnswerBasis rows={...} />)` 里这句话恰好出现 1 次,位于 `<ul>` 内、在所有技法行之后;摘要仍写 `{rows.length} 项`;这一行没有 `consult-answer-basis-status` 元素。
2. `rows=[]` 时输出仍为空字符串;`ChatMessageContent` 流式时没有这句话。
3. `consultAnswerBasisRows(...)` 的结果里没有这句话(行数、行内容与改前一致)。
4. 深度解读:带两轴审计表(含外部验证行)的回答经 `ChatMessageContent` 渲染后:四行外部验证仍不出现;这句话恰好 1 次,且在表格最后一行之后、表格后原有文字之前;`withVerificationLimitLine` 对已含此句的文字不重复添加。
5. 没有审计表的深度回答、传了 `basisRows` 的简明回答正文里,都不由第 3 节加这句话(简明解读只在列表里出现一次)。
6. 存储文字不变:调用前后的 `message.text` 相同;`withoutExternalVerificationRows` 的原有测试照过。
7. 合同:`references/product_runtime_contract.md` 含上文那句原文;`git diff` 显示只有 6c 那一行变化;`frontend/src/lib/product-runtime-contract.ts` 读出的各 product-block 文本与改前逐字相同(测试里对每个块名比对不含这句话即可)。
8. 报告类不变:`frontend/tests/report-no-web-wording-20261109.test.ts` 照过(个人报告、年报、合盘都不出现这句话)。
### 既有断言的调整(只许这一处)
`frontend/tests/consult-answer-basis-receipt-20261108.test.tsx` 约 :104 的 `assert.doesNotMatch(markup, EXTERNAL_COPY)` 会因这句话里的「外部资料」失败。改为:先断言 markup 里这句话恰好 1 次,再把这句话从 markup 里去掉后对剩余部分做原来的 `doesNotMatch`。写“原值 / 新值 / 原因”三栏注释,原因写:`产品负责人 2026-11-09 同意(BUG-1834):展开的解读依据末行显示固定未核验说明,其余不变`。`EXTERNAL_COPY` 正则本身不改,其他断言不改、不弱化。
## 不要碰
- `references/**`:除上文第 4 节那一句外一字不改(包括 `product_runtime_contract.md` 的其他任何行和所有 product-block)。
- `frontend/src/lib/consult-preset-prompts.ts`、`frontend/src/lib/consultation-methodology.ts`、`frontend/src/mastra/product-voice.ts`、`frontend/src/lib/product-runtime-contract.ts`:提示词与答题规则不改;模型不会被要求写这句话。
- `frontend/src/lib/yoga-status-words.ts`、`frontend/src/lib/consultation-technique-evidence.ts`(#181 / #182 的状态词表与证据行;`EXTERNAL_VERIFICATION_ROW_RE` 不改)。
- 回执与后台:`frontend/src/app/api/consult/route.ts`、`frontend/src/lib/consultation-agent-events.ts`、`scripts/**` 全部。
- 冻结文件只许 import 调用,不许改:`scripts/jyotish_api_server.py`、`scripts/jyotish_engine.py`、`scripts/domain_calculation_service.py`、`scripts/dasha_analyzer.py`、`scripts/narayana_dasha.py`、`scripts/shadbala.py`、`scripts/ashtakavarga.py`、`scripts/jaimini.py`、`scripts/varga.py`、`scripts/functional_benefics.py`、`scripts/divisional_charts_extended.py`。
- 报告:`frontend/src/lib/personal-report-reading.ts`、`frontend/src/lib/annual-report-generate.ts`、`frontend/src/lib/synastry-full-technical.ts`(#167 / BUG-1810 的无联网措辞规则继续有效)。
- 其他未完成单子占用的文件与分支:
- #170 卡片压缩:`frontend/src/lib/consultation-evidence-card.ts`、`frontend/src/lib/consult-model-view-compact.ts`、`frontend/src/lib/consult-model-codes.json`;
- #171 lookup:`frontend/src/mastra/consultation-tools.ts`;
- #184 生时纠正事件:`scripts/active_rectification_events.py`、`scripts/active_rectification_event_engine.py`;
- #185 显式口径:`frontend/src/mastra/consultation-workflow.ts`、`frontend/src/lib/consultation-route-service.ts`、`frontend/src/lib/calculation-modes.ts`;
- #186 用途门:`scripts/rectification_purpose_gate.py`;
- 分支 `codex/r2-option-d-1109`(Narayana 分支 / 证据卡,`scripts/narayana_rath.py`),不合并、不 rebase 到它。它也改了 `product_runtime_contract.md` 的「A」块;本单只动「F」6c 那一行,不得顺手改「A」块。
## 自测命令(Windows / PowerShell)
- `frontend\node_modules\.bin\tsc --noEmit -p frontend`
- 在 `frontend` 下:`npx eslint src/lib/consult-answer-basis.ts src/components/consult-answer-basis.tsx src/components/chat-message-content.tsx tests/consult-limitation-line-1834.test.tsx`
- 在 `frontend` 下:`node node_modules/tsx/dist/cli.mjs --test tests/consult-limitation-line-1834.test.tsx tests/consult-answer-basis-receipt-20261108.test.tsx tests/consult-answer-mode-ui-20261108.test.tsx tests/consult-basis-candidate-status-1824.test.ts tests/report-no-web-wording-20261109.test.ts`
- `.venv\Scripts\python -m pytest tests/test_upstream_skill_parity.py tests/test_astrologer_rulings_round5_20261108.py -q`(合同文件被这两组测试读取,确认一句备注不破坏它们)
前端全量测试、Python 快速门和全量 eslint 由 Claude 在验收时跑。
## 进度记录
`docs/tasks/PROGRESS-limitation-line-20261109.md`:做了什么、跑了哪些命令、通过/失败数、偏离与原因;附上简明解读列表与深度解读表尾的渲染片段各一段(用测试里的合成回答,不用真人资料)。
## 何时停下来选“需拍板”
- 深度解读的审计表在页面上并不以表格显示(例如被拆走或折叠),“表末尾”无处可放时。
- 这句话被某个既有过滤器(`EXTERNAL_VERIFICATION_ROW_RE`、报告无联网检查等)拦掉,必须改过滤器才能显示时。
- 需要改上文点名之外的既有断言时。
- 任务书没写到的任何取舍(例如要不要换样式、加图标或改文字)。
@@ -0,0 +1,157 @@
# TASK:按需计算——一段时间内的行运变化:换座、停滞、逆行往返、到达目标经度(#174,BUG-1817,2026-11-09)
- Gitea:#174
- 分支:`codex/ondemand-transit-window-20261109`(基于 staging `afac4ea92f293a4d2bc81f62563487d26f92e4d2`)
- Bug 编号:BUG-1817(开工时核对 `docs/BUG_HISTORY.md` 的最大编号;1809–1830 已为这一批预留)
- 负责验收:Claude(jyotisha-2a)
- 范围:**只做后端**。新增一个工具文件,在注册表里加一行。不做前端接入,不建 `frontend/src/mastra/ondemand-tools/`。
不得自行写“产品决定/裁定”;任务书没写的取舍一律选需拍板。
## 背景
占星师 2026-11-07 Q9:“一段时间内换位、逆行、精确经过:`transit --months`、`--retrograde-calendar`、`--find-conjunction`、`--target-longitude`。”
2026-11-08 第五轮第 9 条:“行运窗口:支持换座、停滞、逆行往返和目标经度。”
#173 已在 staging 建好共用模块 `scripts/ondemand_calc/`。**开工前先读完**:
- `scripts/ondemand_calc/contract.py` 顶部 docstring(信封字段、错误规则、加工具的三步);
- `scripts/ondemand_calc/registry.py`;
- `scripts/ondemand_calc/transit_date.py`(第一个工具,本单照它的写法);
- `docs/tasks/PROGRESS-ondemand-transit-date-20261109.md`「给 #174–#178 的注册步骤」;
- `tests/test_ondemand_transit_date_20261109.py`(测试写法、星历路径配置)。
## 现状(afac4ea9 实测,行号以符号为准)
- 调用入口已经存在:`scripts/jyotish_api_server.py` 的 `/api/ondemand_calc` 薄路由 → `ondemand_calc.registry.ondemand_calc_api(body)` → `TOOLS[body["tool"]](body)`。**本单不需要、也不许改 API 服务器。**
- 缺参数时合同的做法是**返回 `calculation_status = "blocked"` 的信封**(`contract.blocked_envelope`),HTTP 仍是 200,`gaps` 点名缺项。原任务书里“缺一项就 400”作废,以合同为准。
- `contract.validate_common(body)` 只认单个 `date` 字段;本工具是区间,处理方法见下文“输入”。
- `contract.resolve_profile`:岁差必填;`node_mode` / `position_mode` 缺省时用产品默认值 `mean` / `apparent`,并写 `profile_source = "product_default_explicit"`(显式传了写 `caller_supplied`)。**本单照用,不改。** 节点 / 位置口径何时从本命请求显式带过来,归 #185。
- `position_mode = "mean"` 必须返回 `blocked`,`gaps` 写 `{"field": "position_mode", "reason": "position_mode_unsupported"}`,照 `transit_date.run` 的写法。
- 计算用引擎函数 `jyotish_engine._calc_sidereal_planets_for_jd(jd, node_mode=..., include_ketu=True, ayanamsa_name=...)`,调用前先 `engine._configure_ephemeris_path()`,和 `transit_date.py` 完全一样。这样数值与指定日期行运一致,岁差和交点口径都真正生效。
- **不要用**以下现成函数做最终时刻(可以在测试里当对照):
- `scripts/ephemeris_events.py` 的 `build_ephemeris_events`:按 UT 正午逐日采样,`node_mode` 只接收不使用,没有罗睺 / 计都;
- `scripts/transit_trigger.py` 的 `find_exact_transit_date`:只返回第一次到达,默认岁差是 lahiri;
- `scripts/jyotish_engine.py` 的 `cmd_transit`、`--retrograde-calendar`、`--find-conjunction`:依赖的 `scripts/transit_search.py` 不存在。
## 要做的
### 文件
1. 新建 `scripts/ondemand_calc/transit_window.py`,`TOOL = 'transit_window'`,实现 `run(body: dict) -> dict`。
2. 在 `scripts/ondemand_calc/registry.py`:
- 顶部 `from . import transit_date` 旁边加一行 `from . import transit_window`;
- `TOOLS` 里加一行 `'transit_window': transit_window.run,`,上方写一行注释列出必填参数(照 `transit_date` 那行注释的格式)。
- registry.py 其他内容不改。
3. 新测试 `tests/test_ondemand_transit_window_20261109.py`。
4. `docs/tasks/PROGRESS-ondemand-transit-window-20261109.md`。
5. `docs/BUG_HISTORY.md` 末尾追加 BUG-1817(只在文件末尾追加,不改其他条目)。
除上面 5 个文件外不改任何文件。
### 输入(`body`)
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `tool` | 是 | `"transit_window"` |
| `start_date`、`end_date` | 是 | `YYYY-MM-DD`,当地日期;`end_date >= start_date`;跨度 ≤ 366 天(本文件内常量 `MAX_WINDOW_DAYS = 366`,**不改** `contract.MAX_RANGE_DAYS`) |
| `lat`、`lon`、`tz` 或 `timezone_id` | 是 | 与 `transit_date` 相同(可放在 `place` 里) |
| `ayanamsa` | 是 | 与 `transit_date` 相同 |
| `node_mode`、`position_mode` | 否 | 交给 `resolve_profile`,缺省用产品默认值并如实标记 |
| `planets` | 否 | 九曜子集;不给时为九曜全集 |
| `events` | 是 | `ingress` / `station` / `retrograde_loop` / `target_longitude` 的非空子集 |
| `target` | `events` 含 `target_longitude` 时必填 | `{"planet": "...", "longitude": 0–360}` 或 `{"planet": "...", "natal_point": "<星名或 Ascendant>"}` |
| `natal` | 用 `natal_point` 时必填 | `{"points": {"Moon": 123.456, ...}}`,恒星黄经,由调用方给出;本工具**不自己排本命盘** |
校验顺序与写法:
- 先自己校验 `start_date` / `end_date`(缺失、格式、先后、跨度),出错抛 `OnDemandInputError(..., field='start_date' 或 'end_date')`;
- 再用 `contract.validate_common({**body, 'date': body['start_date']})` 校验地点和时区,用 `contract.resolve_profile` 取口径(`profile.tz` 因此是起始日的偏移);
- 所有 `OnDemandInputError` 都转成 `contract.blocked_envelope(tool=TOOL, body=body, error=error)`;
- `requested` 必须是调用方原样的 `body`(不得把上面临时加的 `date` 写进 `requested` 或指纹)。
### 计算
- 每个事件的时刻用二分法精确到 **≤ 1 分钟**(区间宽度 ≤ 1/1440 天)。
- 粗扫步长:月亮 ≤ 6 小时,其余 ≤ 1 天;在 `raw.precision` 里写明步长和收敛阈值。
- 当地时间:给了 `timezone_id` 时,**按事件当天**用 `contract.offset_hours(day, None, timezone_id)` 换算(夏令时生效);只给 `tz` 时用固定偏移。
- **换座(ingress)**:恒星黄经跨过 30° 整数倍的时刻;逆行导致的退回原星座也是一次换座,标 `direction: "retrograde"`。罗睺 / 计都按 `profile.node_mode`(mean 或 true)计算,不得忽略。
- **停滞(station)**:日速度(引擎返回的 `speed`)变号的时刻,标 `station_type: "retrograde"`(顺转逆)或 `"direct"`(逆转顺)。只对 Mercury、Venus、Mars、Jupiter、Saturn 计算;太阳、月亮没有停滞。罗睺 / 计都请求 `station` 或 `retrograde_loop` 时,不计算,在 `gaps` 写 `{"field": "planets", "reason": "node_station_not_supported:<星名>"}`,状态 `partial`(其他请求正常时)。
- **逆行往返(retrograde_loop)**:每一段逆行给出:
- `station_retrograde`、`station_direct` 两个停滞时刻及当时黄经;
- `retrograde_span`:`[station_direct 黄经, station_retrograde 黄经]`;
- `shadow_entry`:逆行前首次到达 `station_direct` 黄经的时刻;`shadow_exit`:顺行恢复后最后一次离开 `station_retrograde` 黄经的时刻。
- 只要两个停滞中有一个落在请求区间内就列出这一段;为找齐停滞和影子期,可以向区间外搜索,但每侧最多 400 天;落在请求区间外的时刻标 `outside_requested_window: true`。400 天内找不到的那一项为 `null`,并在 `gaps` 写 `loop_incomplete:<星名>:<字段>`。
- **到达目标经度(target_longitude)**:列出区间内**每一次**精确到达(逆行可能造成三次),每次标 `direction: "direct"` 或 `"retrograde"`。`natal_point` 在 `natal.points` 里找不到时 `blocked`,`gaps` 写 `{"field": "target.natal_point", "reason": "natal_point_missing:<名>"}`,不得用行运位置或别的点顶替。
### 输出
用 `contract.build_envelope`,信封字段与合同一致,不加顶层字段,`profile` 不加字段。`raw` 形状:
```
{
"start_date": "...", "end_date": "...",
"ayanamsa_degrees_at_start": <float>,
"precision": {"coarse_step_hours": {...}, "convergence_minutes": 1, "search_margin_days": 400},
"events": [
{"type": "ingress" | "station" | "target_longitude", "planet": "...",
"utc": "YYYY-MM-DDTHH:MMZ", "local": "YYYY-MM-DDTHH:MM", "utc_offset_hours": <float>,
"jd_ut": <float>, "longitude": <float, 6 位>, "sign": "...", "degree_in_sign": <float>,
...该类型自己的字段(from_sign / to_sign / direction / station_type / target_longitude)}
],
"retrograde_loops": [ {...见上...} ]
}
```
- `events` 按 `jd_ut` 升序。
- 计算失败(引擎抛错、星历不可用)时:`blocked`,`raw == {}`,`gaps` 写 `engine_failed:<异常类名>` 或 `ephemeris_unavailable`;信封中除 `requested` 外不得出现任何日期或时刻字符串(`computed_at_utc` 除外,与 `transit_date` 一致)。
- 部分行星失败、其余成功:`partial`,成功的照列,失败的在 `gaps` 点名。
## 本单专有验收(写进新测试)
1. 2026 年水星的一次逆行(公开星历):
- 两个停滞时刻与直接用 SwissEph 求速度过零的时刻相差 ≤ 2 分钟(测试里自己用 `swe.calc_ut` + `FLG_SIDEREAL | FLG_SPEED` 二分作对照);
- 以逆行段中间的某个黄经为目标,三次到达都列出,方向依次为 direct / retrograde / direct;
- `shadow_entry` 早于 `station_retrograde`,`shadow_exit` 晚于 `station_direct`。
2. lahiri 与 raman 下,同一次换座的时刻不同,且各自 `profile.ayanamsa` 如实回显。
3. 罗睺 / 计都在 `node_mode = mean` 与 `true` 下,同一次换座的时刻不同。
4. 用 `timezone_id = "Europe/London"` 跨夏令时切换日(2026-03-29)的区间:切换前后事件的 `utc_offset_hours` 分别为 0 和 1。
5. 与 `transit_date` 的一致性:在某个换座时刻,用 `transit_date` 算同一时刻(同口径),该行星黄经与 30° 边界相差 ≤ 0.01°。
## 通用验收(写进新测试)
1. 缺 `start_date` / `end_date` / 地点 / 时区 / 岁差 / `events` 中任一项,返回 `blocked` 且 `gaps[0].field` 点名缺项;跨度 > 366 天、`end_date < start_date` 同样 `blocked`。
2. `position_mode = "mean"` 返回 `blocked` + `position_mode_unsupported`。
3. 省略 `node_mode` / `position_mode` 时 `profile.profile_source == "product_default_explicit"`;都显式传时为 `caller_supplied`。
4. 同一输入的 `input_fingerprint` 稳定;任一参数(日期、地点、岁差、交点、planets、events、target)改变后 fingerprint 改变。
5. 引擎抛错(monkeypatch `_calc_sidereal_planets_for_jd`)时返回 `blocked`、`raw == {}`,除 `requested` 与 `computed_at_utc` 外信封里没有日期字符串。
6. `ondemand_calc_api({"tool": "transit_window", ...})` 能分派到本工具;`transit_date` 原有测试不受影响。
7. 测试只用公开日期和合成坐标(不写任何真人出生资料)。
## 不要碰
- `references/**`(占星师方法文件),一字不改;包括 `references/product_runtime_contract.md`。
- `frontend/**` 全部,特别是 `frontend/src/lib/consult-preset-prompts.ts`、`frontend/src/lib/consultation-methodology.ts`;本单不建 `frontend/src/mastra/ondemand-tools/`。
- `scripts/ondemand_calc/contract.py`、`scripts/ondemand_calc/transit_date.py`、`scripts/ondemand_calc/muhurta_search.py`、`scripts/ondemand_calc/__init__.py`;`registry.py` 只许加上文那两行。合同不够用就停下选“需拍板”,不得改合同。
- 冻结文件只许 import 调用,不许改:`scripts/jyotish_api_server.py`、`scripts/jyotish_engine.py`、`scripts/domain_calculation_service.py`、`scripts/dasha_analyzer.py`、`scripts/narayana_dasha.py`、`scripts/shadbala.py`、`scripts/ashtakavarga.py`、`scripts/jaimini.py`、`scripts/varga.py`、`scripts/functional_benefics.py`、`scripts/divisional_charts_extended.py`。
- `scripts/ephemeris_events.py`、`scripts/transit_trigger.py`:不改现有行为;不补 `scripts/transit_search.py`。
- 其他未完成单子占用的文件:`frontend/src/mastra/consultation-tools.ts`(#171)、`frontend/src/lib/consultation-evidence-card.ts`(#170 / #172)、`frontend/src/mastra/consultation-workflow.ts` 与 `frontend/src/lib/consultation-route-service.ts`(#185)。
- 其他按需工具(#175–#178)的文件名:`solar_return.py`、`varga.py`(在 ondemand_calc 内)、`dasha_date.py`、`prashna.py`,不要预建。
- 既有测试的断言不得弱化;若必须改,写“原值 / 新值 / 原因”三栏注释,原因写 `占星师 Q9 / 第五轮 9:按需计算显式传口径`。
## 自测命令(Windows / PowerShell)
- `.venv\Scripts\python -m pytest tests/test_ondemand_transit_window_20261109.py tests/test_ondemand_transit_date_20261109.py tests/test_ondemand_calc_contract_20261109.py tests/test_api_server_growth_contract.py -q`
Python 快速门、前端全量测试和 eslint 由 Claude 在验收时跑。
## 进度记录
`docs/tasks/PROGRESS-ondemand-transit-window-20261109.md`:做了什么、跑了哪些命令、通过/失败数、偏离与原因;附上验收第 1 条的实测时刻差(分钟)。
## 何时停下来选“需拍板”
- `contract.py` 的信封或校验表达不了本工具的输入输出,必须改合同时。
- 要做到显式口径,就必须改冻结文件时。
- 某颗星的停滞在 2026 年的测试区间内二分不能收敛到 ≤ 2 分钟(速度长期接近 0),需要决定精度口径时。
- 任务书没写到的任何取舍。
@@ -1,107 +0,0 @@
# TASK:校时可比性——占星师原文层名 Narayana_AD 与产品层名对齐(#184,BUG-1827,2026-11-09)
- Gitea:#184
- 分支:`codex/rect-layer-alias-20261109`(基于 staging `afac4ea92f293a4d2bc81f62563487d26f92e4d2`)
- Bug 编号:BUG-1827(开工时核对 `docs/BUG_HISTORY.md` 的最大编号;1809–1830 已为这一批预留)
- 负责验收:Claude(jyotisha-2a)
- 范围:只改校时可比性判定 `assess_leader_comparability` 读层名的那一步。打分、事件引擎、置信度门槛都不改。
不得自行写“产品决定/裁定”;任务书没写的取舍一律选需拍板。
## 现象(第七轮验收包 `rectification/her_synthetic_12_00_vs_12_01.json`)
占星师的匿名合成例(验收清单 §10):两个候选 12:00 / 12:01,总分 10 / 8,12:01 有一件事(e5)因为缺 Narayana 小运而**整件不计分**;5 件事、3 个领域。
| 写法 | 12:01 的 `missing_layers` | `coverage_comparison.comparison` | `comparable_leader` |
| --- | --- | --- | --- |
| 照她原文 | `["Narayana_AD"]` | `not_reducible`,`unreducible_layers = ["Narayana_AD"]` | `null` |
| 照产品测试(`tests/test_rectification_comparability_bug1801.py`) | `["Narayana_MD_AD"]` | `common_coverage`,`common_scores` 8 : 8 | 12:00–12:01(2 分钟) |
同一个例子,两边结果不同,只因为层名不一样。
## 根因(afac4ea9 实测,行号以符号为准)
- `scripts/active_rectification_events.py` 的 `EVENT_GATING_LAYERS`(约 :296)只认产品层名 `Narayana_MD_AD`:缺它时整件事不计分,可比性判定把这件事从所有候选里一起拿掉,再按共同覆盖比较。
- `assess_leader_comparability`(约 :317)把不在 `EVENT_GATING_LAYERS`、也不能按层拆分的差异层算作 `unexplained` → `not_reducible`。
- **注意产品自己也用 `Narayana_AD` 这个名字,但意思不同**:`scripts/active_rectification_event_engine.py` 约 :760–764(占星师第六轮 R2)在“大运已定、只缺小运”时记 `Narayana_AD`,**这件事照常计分**(只缺小运那一项,分数折在 `dasha_varga_core` 里拆不开)。这时 `not_reducible` 是对的,不能改。
- 她原文的 `Narayana_AD` = 这件事整件不计分 = 产品的 `Narayana_MD_AD`。
- 产品的 `Narayana_AD` = 这件事计分、只缺小运那一项。
- 所以**不能**无条件把 `Narayana_AD` 换成 `Narayana_MD_AD`,否则产品自己的“只缺小运”会被当成整件缺失,变成“未知当相等”(她 R2 明确禁止)。
## 要做的
### 1. 对照表(`scripts/active_rectification_events.py`,紧挨 `EVENT_GATING_LAYERS`)
```python
# 占星师原文层名 → 产品层名(只在“该候选整件事缺失”时适用,见 _explained_by_alias)。
ASTROLOGER_EVENT_LAYER_ALIASES: Final[dict[str, str]] = {
"Narayana_AD": "Narayana_MD_AD",
}
```
表里只放 `Narayana_AD` 这一条。别的层名(如 Vimshottari 各级)占星师没有给出原文写法,不要猜着加;需要时选“需拍板”。
### 2. 条件判定(同文件,新私有函数,供 `assess_leader_comparability` 调用)
对每个“差异层” `L`(现有代码里的 `differing`):
- 若 `L` 在 `EVENT_GATING_LAYERS` 或可拆分层里:照旧算已解释。
- 若 `L` 在 `ASTROLOGER_EVENT_LAYER_ALIASES` 里,**且**对每个带 `L` 的候选都满足:
1. 该候选至少有一件事整件缺失(它的覆盖单元里缺少别的候选有的某个 `event_id` 的全部单元);
2. 该候选**每一件**出现在它自己覆盖单元里的事,单元集合与共同覆盖一致(没有“事件在、但少了某层”的情况);
3. 该候选的 `missing_layers` 里没有其他 `EVENT_GATING_LAYERS` 成员(否则说不清缺失的那件事是哪一层造成的);
则 `L` 视为对照表里的产品层名,算已解释。
- 只要有一个带 `L` 的候选不满足以上三条,`L` 照旧算 `unexplained`,结果仍是 `not_reducible`。
### 3. 输出记录
`coverage_comparison` 在用到对照表时多一个字段 `layer_aliases_applied: {"Narayana_AD": "Narayana_MD_AD"}`;没用到时不出现这个字段。其他字段、顺序、取值都不变。
### 4. 测试 `tests/test_rectification_layer_alias_bug1827.py`
只用合成匿名行(照 `tests/test_rectification_comparability_bug1801.py` 的 `_row` 写法):
1. 她原文写法(12:01 缺 e5,`missing_layers = ["Narayana_AD"]`)与产品测试写法(`["Narayana_MD_AD"]`)跑 `adjudicate_candidate_rows`:`top_score`、`second_score`、`winning_segment`、`provisional_leader`、`comparable_leader`、`leader_status`、`confidence`、`can_apply`、`reasons`,以及 `coverage_comparison` 中除 `layer_aliases_applied` 以外的全部字段,**两边完全相等**;原文写法的 `layer_aliases_applied == {"Narayana_AD": "Narayana_MD_AD"}`,产品写法没有该字段。
2. 产品自己的“只缺小运”:两个候选都有 e1–e5,12:01 带 `layer_points`、`missing_layers = ["Narayana_AD"]`、e5 的单元与 12:00 相同但分数不同 → 仍是 `not_reducible`,`unreducible_layers == ["Narayana_AD"]`,`comparable_leader is None`,没有 `layer_aliases_applied`。
3. 同一候选既缺整件事又有 `Narayana_MD_AD` 以外的另一个门控层(如 `D9`)同时带 `Narayana_AD` → 不套用对照表,`not_reducible`。
4. `tests/test_rectification_comparability_bug1801.py` 的全部用例不改、照样通过。
另跑一遍验收包脚本作对照(只读,不改它):
`PYTHONHASHSEED=0 python -I /workspace/eval-upstream-1107/acceptance_round7/scripts/rect_her_synthetic.py <本分支工作树> <输出.json>` 在 Windows 上没有这个路径,**不要求** Grok 跑;Claude 验收时跑。
### 5. 记录
- `docs/BUG_HISTORY.md` 末尾追加 BUG-1827(关联 BUG-1801、BUG-1759、BUG-1785;写明两种 `Narayana_AD` 含义的区别)。只在末尾追加。
- `docs/tasks/PROGRESS-rect-layer-alias-20261109.md`。
## 允许改的文件(只有这些)
- `scripts/active_rectification_events.py`:只加对照表常量、一个私有判定函数、`assess_leader_comparability` 里调用它和写 `layer_aliases_applied` 的几行。改动处写“原值 / 新值 / 原因”三栏注释,原因写 `占星师验收清单 §10:原文层名 Narayana_AD 与产品 Narayana_MD_AD 对齐(BUG-1827)`。
- 新建 `tests/test_rectification_layer_alias_bug1827.py`、`docs/tasks/PROGRESS-rect-layer-alias-20261109.md`
- `docs/BUG_HISTORY.md`(末尾追加)
## 不要碰
- `references/**`(占星师方法文件),一字不改;包括 `references/product_runtime_contract.md`。
- `frontend/**` 全部,特别是 `frontend/src/lib/consult-preset-prompts.ts`。
- `scripts/active_rectification_event_engine.py`:产品记 `Narayana_AD` / `Narayana_MD_AD` 的地方一字不改(层名的产生方不改,只改判定方怎么读)。
- `scripts/chart_choice/**`、`scripts/research/precision_gate_lib.py`:不改。
- `EVENT_GATING_LAYERS` 的成员、`_coverage_units`、`adjudicate_candidate_rows` 的打分与置信度门槛、`COMPARABILITY_POLICY` 名字:不改。
- 冻结文件只许 import 调用,不许改:`scripts/jyotish_api_server.py`、`scripts/jyotish_engine.py`、`scripts/domain_calculation_service.py`、`scripts/dasha_analyzer.py`、`scripts/narayana_dasha.py`、`scripts/shadbala.py`、`scripts/ashtakavarga.py`、`scripts/jaimini.py`、`scripts/varga.py`、`scripts/functional_benefics.py`、`scripts/divisional_charts_extended.py`。
- 其他未完成单子的文件:`scripts/ondemand_calc/**`(#174–#178)、`frontend/src/mastra/consultation-tools.ts`(#171)、`frontend/src/lib/consultation-evidence-card.ts`(#170 / #172)、`frontend/src/mastra/consultation-workflow.ts` 与 `frontend/src/lib/consultation-route-service.ts`(#185)。
- R2 扩大范围(`seed_only_v0` 低档平局当相等)在等占星师选 A–D,本单不碰。
- 既有断言不得弱化。
## 自测命令(Windows / PowerShell)
- `.venv\Scripts\python -m pytest tests/test_rectification_layer_alias_bug1827.py tests/test_rectification_comparability_bug1801.py tests/test_active_rectification_events.py tests/test_rectification_api_can_apply_guard_bug1802.py tests/test_rectification_technique_contract.py -q`
Python 快速门、前端全量测试和 eslint 由 Claude 在验收时跑。
## 何时停下来选“需拍板”
- 上面三条条件不足以区分两种 `Narayana_AD`,必须改事件引擎或层名产生方时。
- 需要加 `Narayana_AD` 以外的对照条目时。
- 任何改动会让既有校时用例(BUG-1801 / 1802 / 1785 / 1759)结果变化时。
- 任务书没写到的任何取舍。
@@ -4,7 +4,11 @@ import { memo, useEffect, useState, type ReactNode } from "react";
import { prefetchOnIdle } from "@/components/chat-chunk-prefetch";
import { ConsultAnswerBasis } from "@/components/consult-answer-basis";
import { withoutExternalVerificationRows, type ConsultAnswerBasisRow } from "@/lib/consult-answer-basis";
import {
withVerificationLimitLine,
withoutExternalVerificationRows,
type ConsultAnswerBasisRow,
} from "@/lib/consult-answer-basis";
import { plainParagraphs } from "@/components/chat-message-paragraphs";
import { splitSpokenAndReport } from "@/lib/chat-answer-split";
import { loadChatMarkdown, loadedChatMarkdown, type MarkdownRenderer } from "@/lib/chat-markdown-loader";
@@ -105,7 +109,10 @@ export function ChatMessageContent({
const renderMarkdown = useMarkdownRenderer();
// The stored answer keeps every audit row; the page leaves out the external
// verification ones (联网, the verification gate, real cases; owner 2026-11-08).
const text = withoutExternalVerificationRows(storedText);
// BUG-1834:深度解读的审计表末尾补一句固定说明;简明解读走下面的「解读依据」列表,
// 流式输出中不加,存储的文字不变(只在显示时加)。
const visibleText = withoutExternalVerificationRows(storedText);
const text = !streaming && !basisRows?.length ? withVerificationLimitLine(visibleText) : visibleText;
const split = splitSpokenAnswerAndTechniqueAudit(text);
const rows = resolveTechniqueAuditRows(split, auditRows);
const layers = splitSpokenAndReport(split.spoken);
@@ -5,6 +5,7 @@ import { ChevronRight } from "lucide-react";
import {
CONSULT_ANSWER_BASIS_STATUS_LABELS,
CONSULT_ANSWER_BASIS_TITLE,
CONSULT_VERIFICATION_LIMIT_LINE,
type ConsultAnswerBasisRow,
} from "@/lib/consult-answer-basis";
@@ -35,6 +36,12 @@ export function ConsultAnswerBasis({ rows }: { readonly rows: readonly ConsultAn
</span>
</li>
))}
{/* BUG-1834:展开后的最后一行固定写出未核验说明;不带状态,也不计入上面的 N 项。 */}
<li className="consult-answer-basis-row">
<span className="consult-answer-basis-text">
<span className="consult-answer-basis-result">{CONSULT_VERIFICATION_LIMIT_LINE}</span>
</span>
</li>
</ul>
</details>
</section>
+40 -1
View File
@@ -22,6 +22,13 @@ import { FUNCTIONAL_PROFILE_LABELS, DEFAULT_FUNCTIONAL_PROFILE, type FunctionalP
export const CONSULT_ANSWER_BASIS_TITLE = "解读依据";
/**
* 产品负责人 2026-11-09 同意(BUG-1834):用户要知道的限制不能只藏在后台,
* 所以「解读依据」展开后的最后一行、深度解读审计表末尾,由页面显示这一句。
* 只在这里定义一次;回答正文、存下来的文字、回执都不写它。
*/
export const CONSULT_VERIFICATION_LIMIT_LINE = "本次未完成外部资料与案例核验,候选窗口尚未据此确认。";
export type ConsultAnswerBasisStatus = "done" | "conditional";
export const CONSULT_ANSWER_BASIS_STATUS_LABELS: Readonly<Record<ConsultAnswerBasisStatus, string>> = {
@@ -55,7 +62,10 @@ const BASIS_ENTRIES: readonly BasisEntry[] = [
name: "功能吉凶",
result: (profile) => `按 ${FUNCTIONAL_PROFILE_LABELS[profile]} 判断每颗星在这张盘里起的作用`,
},
{ match: /^Yogas?\b|^格局/i, name: "格局", result: () => "盘上成立和落空的格局已核对" },
// 原值:`盘上成立和落空的格局已核对`
// 新值:`盘上检测到的格局已列出各自状态`
// 原因:BUG-1824:候选不得显示为成立(卡上规则是 none is confirmed)
{ match: /^Yogas?\b|^格局/i, name: "格局", result: () => "盘上检测到的格局已列出各自状态" },
{ match: /^Shadbala\b/i, name: "行星力量", result: () => "每颗星的强弱已算" },
{ match: /^Ashtakavarga$/i, name: "宫位点数", result: () => "每个宫得到的点数已算" },
{ match: /^Arudha\b/i, name: "Arudha 点位", result: () => "事业、婚姻相关的点位落在哪里" },
@@ -130,3 +140,32 @@ export function withoutExternalVerificationRows(text: string): string {
}
return out.join("\n");
}
/**
* 在**最后一张**审计表的最后一行之后,空一行插入那句固定说明(BUG-1834)。
* 只用于深度解读的显示:文字里没有审计表、或者已经有这句话时,原样返回。
*/
export function withVerificationLimitLine(text: string): string {
if (!text || text.includes(CONSULT_VERIFICATION_LIMIT_LINE)) return text;
const lines = text.split("\n");
let lastTableLine = -1;
let inTable = false;
for (let index = 0; index < lines.length; index += 1) {
const trimmed = lines[index]!.trim();
if (AUDIT_TABLE_HEADER_RE.test(trimmed)) {
inTable = true;
continue;
}
if (!inTable) continue;
if (trimmed.startsWith("|")) {
lastTableLine = index;
continue;
}
inTable = false;
}
if (lastTableLine < 0) return text;
const head = lines.slice(0, lastTableLine + 1);
const tail = lines.slice(lastTableLine + 1);
return [...head, "", CONSULT_VERIFICATION_LIMIT_LINE, ...tail].join("\n");
}
@@ -11,6 +11,7 @@
*/
import type { TechniqueAuditRow } from "./consultation-agent-events.ts";
import type { EvidenceCard } from "./consultation-evidence-card.ts";
import { isStructuralObservation, yogaStatus } from "./yoga-status-words.ts";
type Rec = Record<string, unknown>;
const rec = (value: unknown): Rec => (value && typeof value === "object" && !Array.isArray(value) ? value as Rec : {});
@@ -136,11 +137,45 @@ function savLine(card: EvidenceCard) {
});
}
// 原值:`成立:${hits}` / `本题没有成立的格局`
// 新值:按卡上 yogas_detail 的状态,用占星师第七轮 §5 P0.2 的映射表(yoga-status-words.ts)分组写
// 「名字、名字:状态文字」,组间用「。」;没有可列的写「本题没有检测到相关格局」
// 原因:BUG-1824:候选不得显示为成立;hits 列表不能推断成立,状态文字不得被截断
function yogaLine(card: EvidenceCard) {
const detail = rec(rec(rec(card.base).natal).yogas_detail);
const rows = Array.isArray(detail.rows) ? detail.rows.map(rec) : [];
const byName = new Map<string, Rec>();
for (const row of rows) {
const name = str(row.name);
if (name && !byName.has(name)) byName.set(name, row);
}
const notEvaluated = new Set(
(Array.isArray(detail.not_evaluated) ? detail.not_evaluated.map(rec) : []).map((row) => str(row.name)).filter(Boolean),
);
return firstOf(card, (section) => {
if (!("yogas" in section)) return undefined;
const hits = list(rec(section.yogas).hits);
return hits.length ? `成立:${hits.slice(0, 3).join("、")}` : "本题没有成立的格局";
const hits = list(rec(section.yogas).hits).slice(0, 3);
const groups = new Map<string, string[]>();
for (const name of hits) {
const row = byName.get(name);
if (row && isStructuralObservation(row)) continue;
const { text } = yogaStatus(row, { notEvaluated: notEvaluated.has(name) });
const bucket = groups.get(text) ?? [];
bucket.push(name);
groups.set(text, bucket);
}
if (!groups.size) return "本题没有检测到相关格局";
// 逐个名字往里放,放不下就写“另 N 项未列”,绝不把状态文字截半(截半会只剩“……成立”)。
const entries = [...groups].flatMap(([text, names]) => names.map((name) => [text, name] as const));
const render = (shown: number) => {
const kept = new Map<string, string[]>();
for (const [text, name] of entries.slice(0, shown)) kept.set(text, [...(kept.get(text) ?? []), name]);
const body = [...kept].map(([text, names]) => `${names.join("、")}:${text}`).join("。");
return shown < entries.length ? `${body}。另 ${entries.length - shown} 项未列` : body;
};
let shown = 1;
while (shown < entries.length && render(shown + 1).length <= MAX) shown += 1;
return render(shown);
});
}
+76
View File
@@ -0,0 +1,76 @@
/**
* BUG-1824 / 占星师第七轮回复 §5 P0.2(2026-11-09):Yoga 状态的唯一映射表。
* 「解读依据」页面(#181)和答题模型的状态措辞(#182)必须 import 同一张表,
* 不能一个把 candidate 升成“成立”、另一个把 computed 降成“非成立”。
*
* | 原始证据 | 推荐文字 |
* |---|---|
* | candidate / support_only_candidate | 命中候选规则,尚未完整确认 |
* | computed,未完成来源条件治理 | 检测器检出,待核实 |
* | formed_under_source | 按所选来源的形成条件成立;强度和结果另评 |
* | conditions_not_met | 所选来源的必要条件未满足 |
* | blocked / not_available_yet | 当前无法确认,列明缺项 |
*
* 规则(同一处原文):用 hits 列表不能推断“成立”;没有完整条件检查不能写“落空 / 非成立”。
* 所以:只有 `formation.status` 这一完整条件检查的结果能给出“成立”或“必要条件未满足”;
* 卡上找不到状态行、或状态值不在表内时,一律落到 blocked(当前无法确认),并写明缺什么。
*
* 验收时(Claude 2026-11-09)按占星师原表替换了 #181 初版词表
* (初版:候选 / 未确认 / 不成立 / 未标状态,formed_under_source 显示为候选)。
*/
export type YogaStatusKey = "candidate" | "computed" | "formed_under_source" | "conditions_not_met" | "blocked";
/** 占星师原表,文字逐字照抄;`evidence` 是卡上可能出现的原始值。 */
export const YOGA_STATUS_MAPPING: Readonly<Record<YogaStatusKey, { readonly evidence: readonly string[]; readonly text: string }>> = {
candidate: { evidence: ["candidate", "support_only_candidate"], text: "命中候选规则,尚未完整确认" },
computed: { evidence: ["computed"], text: "检测器检出,待核实" },
formed_under_source: { evidence: ["formed_under_source"], text: "按所选来源的形成条件成立;强度和结果另评" },
conditions_not_met: { evidence: ["conditions_not_met"], text: "所选来源的必要条件未满足" },
blocked: { evidence: ["blocked", "not_available_yet"], text: "当前无法确认,列明缺项" },
};
/** blocked 行实际显示的文字:把“列明缺项”换成具体缺项。 */
export const YOGA_BLOCKED_PREFIX = "当前无法确认,缺:";
export const YOGA_GAP_NO_ROW = "卡上没有这条格局的状态记录";
export const YOGA_GAP_NOT_EVALUATED = "引擎未能评估这条规则";
type Rec = Record<string, unknown>;
const rec = (value: unknown): Rec => (value && typeof value === "object" && !Array.isArray(value) ? value as Rec : {});
const text = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : undefined);
export type YogaStatus = { key: YogaStatusKey; text: string };
function blocked(gap: string): YogaStatus {
return { key: "blocked", text: `${YOGA_BLOCKED_PREFIX}${gap}` };
}
/**
* 一个格局行(`card.base.natal.yogas_detail.rows[]`)的状态。`row` 缺失 = 只在 hits 里出现、卡上没有状态行。
* `notEvaluated` 为 true 表示该名字在 `yogas_detail.not_evaluated` 里。
*/
export function yogaStatus(row: Rec | undefined, options: { notEvaluated?: boolean } = {}): YogaStatus {
if (!row) return blocked(options.notEvaluated ? YOGA_GAP_NOT_EVALUATED : YOGA_GAP_NO_ROW);
const formation = text(rec(row.formation).status);
// 只有完整条件检查的结果才能说“成立”或“必要条件未满足”。
if (formation === "formed_under_source") return { key: "formed_under_source", text: YOGA_STATUS_MAPPING.formed_under_source.text };
if (formation === "conditions_not_met") return { key: "conditions_not_met", text: YOGA_STATUS_MAPPING.conditions_not_met.text };
const status = text(row.status);
const claim = text(row.claim_status);
for (const key of ["candidate", "computed", "blocked"] as const) {
if (status && YOGA_STATUS_MAPPING[key].evidence.includes(status)) {
return key === "blocked" ? blocked(`状态为 ${status}`) : { key, text: YOGA_STATUS_MAPPING[key].text };
}
}
if ((claim && YOGA_STATUS_MAPPING.candidate.evidence.includes(claim)) || formation === "candidate") {
return { key: "candidate", text: YOGA_STATUS_MAPPING.candidate.text };
}
if (options.notEvaluated) return blocked(YOGA_GAP_NOT_EVALUATED);
return blocked(status ? `状态值 ${status} 不在映射表内` : "卡上这条格局没有状态值");
}
/** 卡上这一行是不是“结构观察”(不是命名格局),不进「格局」这一行。 */
export function isStructuralObservation(row: Rec): boolean {
return row.claim_kind === "structural_observation" || row.status === "structural_observation";
}
@@ -9,6 +9,7 @@ import test from "node:test";
import { renderToStaticMarkup } from "react-dom/server";
import { ConsultAnswerBasis } from "../src/components/consult-answer-basis.tsx";
import { CONSULT_VERIFICATION_LIMIT_LINE } from "../src/lib/consult-answer-basis.ts";
import { consultAnswerBasisRows, EXTERNAL_VERIFICATION_ROW_RE } from "../src/lib/consult-answer-basis.ts";
import type { TechniqueAuditRow } from "../src/lib/consultation-agent-events.ts";
import { buildEvidenceCard } from "../src/lib/consultation-evidence-card.ts";
@@ -101,6 +102,10 @@ test("rendered list: result_line in the grey line, 有条件 in the accent", ()
const markup = renderToStaticMarkup(<ConsultAnswerBasis rows={consultAnswerBasisRows(receiptRows("steve_jobs"))} />);
assert.match(markup, /<span class="consult-answer-basis-result">水瓶主运、巨蟹子运,只作条件性窗口<\/span><\/span><span class="consult-answer-basis-status is-conditional">有条件<\/span>/);
assert.match(markup, /consult-answer-basis-status is-done">已算</);
assert.doesNotMatch(markup, EXTERNAL_COPY);
// 原值:assert.doesNotMatch(markup, EXTERNAL_COPY)
// 新值:先断言固定说明恰好 1 次,把它从 markup 里去掉后再对剩余部分做原来的 doesNotMatch
// 原因:产品负责人 2026-11-09 同意(BUG-1834):展开的解读依据末行显示固定未核验说明,其余不变
assert.equal(markup.split(CONSULT_VERIFICATION_LIMIT_LINE).length - 1, 1);
assert.doesNotMatch(markup.replace(CONSULT_VERIFICATION_LIMIT_LINE, ""), EXTERNAL_COPY);
assert.match(styles, /\.consult-answer-basis-status\.is-conditional \{ color: var\(--color-action\); \}/);
});
@@ -0,0 +1,162 @@
/**
* BUG-1824:「解读依据」的「格局」一行不得把候选格局写成「成立」。
* 合成卡,不含任何真人资料。
*
* 验收(Claude 2026-11-09):状态文字改用占星师第七轮回复 §5 P0.2 的映射表。
* 原值 / 新值 / 原因(适用于下面每条被改写的期望值):
* 原值:候选 / 未确认 / 不成立 / 未标状态,formed_under_source 显示为「候选」
* 新值:命中候选规则,尚未完整确认 / 检测器检出,待核实 / 按所选来源的形成条件成立;强度和结果另评 /
* 所选来源的必要条件未满足 / 当前无法确认,缺:…
* 原因:占星师第七轮 §5 P0.2:模型和页面必须使用同一状态映射(#182 import 同一模块)
*/
import assert from "node:assert/strict";
import test from "node:test";
import type { TechniqueAuditRow } from "../src/lib/consultation-agent-events.ts";
import { consultAnswerBasisRows } from "../src/lib/consult-answer-basis.ts";
import type { EvidenceCard } from "../src/lib/consultation-evidence-card.ts";
import { withTechniqueEvidence } from "../src/lib/consultation-technique-evidence.ts";
import {
YOGA_BLOCKED_PREFIX, YOGA_GAP_NO_ROW, YOGA_GAP_NOT_EVALUATED, YOGA_STATUS_MAPPING, yogaStatus,
} from "../src/lib/yoga-status-words.ts";
type Row = Record<string, unknown>;
const CANDIDATE = "命中候选规则,尚未完整确认";
const COMPUTED = "检测器检出,待核实";
const FORMED = "按所选来源的形成条件成立;强度和结果另评";
const NOT_MET = "所选来源的必要条件未满足";
function cardWith(rows: Row[], hits: string[], extra: Row = {}): EvidenceCard {
return {
domains: ["career"],
domain_sections: { career: { yogas: { hits } } },
base: { natal: { yogas_detail: { rows, ...extra } } },
} as unknown as EvidenceCard;
}
function yogaResult(card: EvidenceCard): string | undefined {
const audit: TechniqueAuditRow[] = [{
technique: "Yogas",
calculation_status: "executed",
interpretation_status: "observation_only",
} as unknown as TechniqueAuditRow];
const enriched = withTechniqueEvidence(audit, card) ?? [];
const rows = consultAnswerBasisRows(enriched);
return rows.find((row) => row.name === "格局")?.result;
}
test("the mapping table is the astrologer's round-7 §5 P0.2 table, word for word", () => {
assert.deepEqual(
Object.fromEntries(Object.entries(YOGA_STATUS_MAPPING).map(([key, row]) => [key, [row.evidence, row.text]])),
{
candidate: [["candidate", "support_only_candidate"], CANDIDATE],
computed: [["computed"], COMPUTED],
formed_under_source: [["formed_under_source"], FORMED],
conditions_not_met: [["conditions_not_met"], NOT_MET],
blocked: [["blocked", "not_available_yet"], "当前无法确认,列明缺项"],
},
);
});
test("row 1: candidate and support_only_candidate read 命中候选规则,尚未完整确认", () => {
assert.equal(yogaResult(cardWith([{ name: "Sunaphaa Yoga", status: "candidate" }], ["Sunaphaa Yoga"])), `Sunaphaa Yoga:${CANDIDATE}`);
assert.equal(yogaStatus({ name: "X", status: "support_only_candidate" }).text, CANDIDATE);
assert.equal(yogaStatus({ name: "X", claim_status: "support_only_candidate" }).text, CANDIDATE);
});
test("row 2: computed without a completed condition check reads 检测器检出,待核实", () => {
assert.equal(yogaResult(cardWith([{ name: "Vosi Yoga", status: "computed" }], ["Vosi Yoga"])), `Vosi Yoga:${COMPUTED}`);
assert.equal(yogaStatus({ name: "X", status: "computed", formation: { status: "candidate" } }).text, COMPUTED);
});
test("row 3: formed_under_source reads the source-bound 成立 with strength and outcome left open", () => {
const line = yogaResult(cardWith([
{ name: "Amala Yoga", status: "candidate", formation: { status: "formed_under_source" } },
], ["Amala Yoga"]));
assert.equal(line, `Amala Yoga:${FORMED}`);
});
test("row 4: conditions_not_met reads 所选来源的必要条件未满足, never 落空 / 非成立 / 不成立", () => {
const line = yogaResult(cardWith([
{ name: "Dharidhra Yoga", status: "candidate", formation: { status: "conditions_not_met" } },
], ["Dharidhra Yoga"])) ?? "";
assert.equal(line, `Dharidhra Yoga:${NOT_MET}`);
assert.doesNotMatch(line, /落空|非成立|不成立/u);
});
test("row 5: blocked / not_available_yet reads 当前无法确认 and names what is missing", () => {
for (const status of ["blocked", "not_available_yet"]) {
const result = yogaStatus({ name: "X", status });
assert.equal(result.key, "blocked");
assert.equal(result.text, `${YOGA_BLOCKED_PREFIX}状态为 ${status}`);
}
const line = yogaResult(cardWith([], ["Lakshmi Yoga"], { not_evaluated: [{ name: "Lakshmi Yoga", evaluation_status: "evaluation_failed" }] }));
assert.equal(line, `Lakshmi Yoga:${YOGA_BLOCKED_PREFIX}${YOGA_GAP_NOT_EVALUATED}`);
});
test("a yoga that appears only in the hits list never renders 成立", () => {
const line = yogaResult(cardWith([], ["Gaja Kesari Yoga", "Budha-Aditya Yoga"])) ?? "";
assert.equal(line, `Gaja Kesari Yoga、Budha-Aditya Yoga:${YOGA_BLOCKED_PREFIX}${YOGA_GAP_NO_ROW}`);
assert.doesNotMatch(line, /成立/u);
// 状态值不在表内、或没有状态值的行同样落到 blocked,不猜。
assert.equal(yogaStatus({ name: "X", status: "confirmed" }).key, "blocked");
assert.equal(yogaStatus({ name: "X" }).key, "blocked");
});
test("mixed statuses group in first-seen order and the status text is never clipped", () => {
const line = yogaResult(cardWith([
{ name: "Sunaphaa Yoga", status: "candidate" },
{ name: "Vosi Yoga", status: "computed" },
{ name: "Gaja Kesari Yoga", status: "candidate", formation: { status: "formed_under_source" } },
], ["Sunaphaa Yoga", "Vosi Yoga", "Gaja Kesari Yoga"])) ?? "";
assert.ok(line.length <= 80, line);
assert.doesNotMatch(line, /…/u);
assert.ok(line.startsWith(`Sunaphaa Yoga:${CANDIDATE}。Vosi Yoga:${COMPUTED}`), line);
// 放不下的整项挪到“另 N 项未列”,而不是把 FORMED 截成“……成立”。
if (!line.includes(FORMED)) assert.match(line, /另 1 项未列$/u);
assert.doesNotMatch(line.replace(FORMED, ""), /成立/u);
});
test("structural observations stay out of the 格局 row", () => {
const card = cardWith([
{ name: "Neecha Bhanga witness", status: "structural_observation" },
{ name: "Sunaphaa Yoga", status: "candidate" },
], ["Neecha Bhanga witness", "Sunaphaa Yoga"]);
assert.equal(yogaResult(card), `Sunaphaa Yoga:${CANDIDATE}`);
});
test("neither the grey line nor the fallback copy claims 成立: or 已确认", () => {
const card = cardWith([
{ name: "Sunaphaa Yoga", status: "candidate" },
{ name: "Vosi Yoga", status: "computed" },
], ["Sunaphaa Yoga", "Vosi Yoga"]);
const line = yogaResult(card) ?? "";
const fallback = consultAnswerBasisRows([{
technique: "Yogas",
calculation_status: "executed",
} as unknown as TechniqueAuditRow]).find((row) => row.name === "格局")?.result ?? "";
for (const text of [line, fallback]) {
assert.doesNotMatch(text, /成立:/u);
assert.doesNotMatch(text, /已确认/u);
}
assert.equal(fallback, "盘上检测到的格局已列出各自状态");
});
test("the 格局 row keeps its calculation status while the grey line carries the reading status", () => {
const card = cardWith([{ name: "Sunaphaa Yoga", status: "candidate" }], ["Sunaphaa Yoga"]);
const enriched = withTechniqueEvidence([{
technique: "Yogas",
calculation_status: "executed",
interpretation_status: "supporting",
} as unknown as TechniqueAuditRow], card) ?? [];
const row = consultAnswerBasisRows(enriched).find((item) => item.name === "格局");
assert.ok(row);
assert.equal(row.status, "done");
assert.equal(row.result, `Sunaphaa Yoga:${CANDIDATE}`);
});
test("no hits at all says nothing was detected, not that nothing formed", () => {
const card = cardWith([{ name: "Sunaphaa Yoga", status: "candidate" }], []);
assert.equal(yogaResult(card), "本题没有检测到相关格局");
});
@@ -0,0 +1,129 @@
/**
* BUG-1834:「解读依据」展开后的最后一行、以及深度解读审计表末尾,显示一句固定的未核验说明。
* 合成回答,不含任何个人资料。
*/
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { renderToStaticMarkup } from "react-dom/server";
import { ChatMessageContent } from "../src/components/chat-message-content.tsx";
import { ConsultAnswerBasis } from "../src/components/consult-answer-basis.tsx";
import {
CONSULT_VERIFICATION_LIMIT_LINE,
consultAnswerBasisRows,
withVerificationLimitLine,
withoutExternalVerificationRows,
} from "../src/lib/consult-answer-basis.ts";
import type { TechniqueAuditRow } from "../src/lib/consultation-agent-events.ts";
const LITERAL = "本次未完成外部资料与案例核验,候选窗口尚未据此确认。";
const ROWS = consultAnswerBasisRows([
{ technique: "Formal Vargas", calculation_status: "executed", interpretation_status: "primary" },
{ technique: "Vimshottari", calculation_status: "executed", interpretation_status: "primary" },
] as unknown as TechniqueAuditRow[]);
const AUDIT_ANSWER = [
"## 结论与行动建议",
"",
"这一段的正文不写未核验说明。",
"",
"## Technique Audit Table",
"",
"| 技法 | 计算状态 | 解读状态 | 结论 |",
"| --- | --- | --- | --- |",
"| Formal Vargas | exec | primary | 已算 |",
"| Yogas | exec | observation | 候选 |",
"| MEVG / Global Web Evidence | blocked | — | 后台保留 |",
"",
"表格之后的收尾一段。",
].join("\n");
function renderPlain(text: string, basisRows?: typeof ROWS) {
return renderToStaticMarkup(<ChatMessageContent text={text} basisRows={basisRows} />);
}
test("the constant is the agreed sentence, punctuation included", () => {
assert.equal(CONSULT_VERIFICATION_LIMIT_LINE, LITERAL);
});
test("the plain-answer list shows the line once, after every technique row, inside the list", () => {
const markup = renderToStaticMarkup(<ConsultAnswerBasis rows={ROWS} />);
assert.equal(markup.split(LITERAL).length - 1, 1);
const listStart = markup.indexOf("<ul class=\"consult-answer-basis-list\">");
const listEnd = markup.indexOf("</ul>", listStart);
const at = markup.indexOf(LITERAL);
assert.ok(at > listStart && at < listEnd, "the line sits inside the list");
const lastTechniqueRow = markup.lastIndexOf("consult-answer-basis-name");
assert.ok(at > lastTechniqueRow, "the line comes after the technique rows");
assert.match(markup, new RegExp(`${ROWS.length} 项`));
});
test("the line carries no status label", () => {
const markup = renderToStaticMarkup(<ConsultAnswerBasis rows={ROWS} />);
const lineIndex = markup.indexOf(LITERAL);
const after = markup.slice(lineIndex, lineIndex + 400);
assert.doesNotMatch(after, /consult-answer-basis-status/);
});
test("an empty list renders nothing at all", () => {
assert.equal(renderToStaticMarkup(<ConsultAnswerBasis rows={[]} />), "");
});
test("a streaming answer does not get the line", () => {
const markup = renderToStaticMarkup(<ChatMessageContent text={AUDIT_ANSWER} streaming />);
assert.doesNotMatch(markup, new RegExp(LITERAL));
});
test("the basis rows themselves never carry the line", () => {
assert.equal(ROWS.some((row) => row.result.includes(LITERAL) || row.name.includes(LITERAL)), false);
assert.equal(consultAnswerBasisRows(undefined).length, 0);
});
test("a deep answer gets the line once, at the end of the last audit table", () => {
// 渲染层在没有 markdown 渲染器的测试环境里出不来表格,所以这里验的是渲染前那一步:
// 先去掉外部验证行,再在最后一张表格的末尾插入这句说明。
const visible = withVerificationLimitLine(withoutExternalVerificationRows(AUDIT_ANSWER));
assert.equal(visible.split(LITERAL).length - 1, 1);
const lineAt = visible.indexOf(LITERAL);
const lastRowAt = visible.lastIndexOf("| 候选 |");
const tailAt = visible.indexOf("表格之后的收尾一段");
assert.ok(lineAt > lastRowAt, "after the last table row");
assert.ok(tailAt > lineAt, "before the prose that follows the table");
assert.doesNotMatch(visible, /MEVG|Global Web Evidence/);
});
test("the settled deep answer wiring applies the line only without basis rows", () => {
// 与既有 UI 测试一致:渲染器不在测试环境时,用源码断言确认接线条件。
const source = readFileSync(new URL("../src/components/chat-message-content.tsx", import.meta.url), "utf8");
// 只在「已定稿」且「不是简明解读列表」时把说明加进可见文字。
assert.ok(source.includes("!streaming && !basisRows?.length ? withVerificationLimitLine(visibleText) : visibleText"));
});
test("withVerificationLimitLine is idempotent and skips text without a table", () => {
const once = withVerificationLimitLine(AUDIT_ANSWER);
assert.equal(withVerificationLimitLine(once), once);
assert.equal(withVerificationLimitLine("只有一段话,没有表格。"), "只有一段话,没有表格。");
});
test("a plain answer renders the line only in the list, never twice", () => {
const withBasis = renderToStaticMarkup(
<ChatMessageContent text="简明解读的正文。" basisRows={ROWS} />,
);
assert.equal(withBasis.split(LITERAL).length - 1, 1);
assert.ok(withBasis.includes("consult-answer-basis-list"));
});
test("a deep answer without an audit table gets no line", () => {
const markup = renderPlain("## 结论\n\n只有正文,没有审计表。");
assert.doesNotMatch(markup, new RegExp(LITERAL));
});
test("the stored text is not modified", () => {
const stored = AUDIT_ANSWER;
const before = String(stored);
renderPlain(stored);
assert.equal(stored, before, "rendering never rewrites the stored answer");
assert.notEqual(withVerificationLimitLine(stored), stored, "the line is added to the visible text only");
});
+1 -1
View File
@@ -218,7 +218,7 @@ evidence_card.backstage records, for the backend only, that global web evidence
6. 「E」块 S-09:原值综合判断表的受冲条数「只计数,不下结论、不报给用户」;`pressure` 句原写「条数和这串依据不念给用户」。**已改(BUG-1756)**:她裁定保留后台字段,但用户需要理解冲突时必须展示实际来源;条数仍不念。**再改(BUG-1758)**:卡上各宫不再带 `signal_count` / `signals`,改为按事实去重的来源账(输入、作用、涉及的宫);S-09 与 `pressure` 句不再提条数(引擎 `affliction_evidence.signal_count` 字段保留)。
6a. (BUG-1773,新增产品规则,不是修改她的方法)「E」块 S-13:落实她 2026-11-08 验收说明「同源规则不算独立证据票数」到跨层:卡上 `independence` 给每个盘面事实一个 fact_id,列出复用它的层;回答按不同 fact_id 计独立支持,共用一个事实时写成一个来源并点名各层,不写「多层 / 多体系一致」。
6b. (BUG-1789–BUG-1792,落实占星师 2026-11-08 第六轮 R3 / R4,不是修改她的方法)「A」块新增白话层名、错配拒句重写、自参照分支三条;卡上 `independence` 增加 `derived`(派生事实 → 依赖)与 `self_reference`,`jaimini.karakamsha` 增加 `karakamsha_lord_natal_house` 与读法一句。白话可以用通俗名称,证据入口仍保留精确层、实体与参照(她第五轮裁定 6:白话可以减少术语,不能减少信息)。
6c. (BUG-1794,产品决定,偏离她的方法裁定)第 1、2 条与「A」块 A-05、外部验证四行、「D」块:产品 2026-11-08 决定(BUG-1794),偏离占星师「缺口不能隐藏」的裁定(第五轮裁定 6 / 8、她的 Q5 之一与 Q6):产品选择不向用户展示;后台保留记录(回执里的技法审计行 MEVG / Global Web Evidence、Real Case Calibration 照旧)。回答(两种模式)不再写联网、外部资料、MEVG、真实案例校准的句子或审计表行;不写「已验证」「已校准」的禁令保留。
6c. (BUG-1794,产品决定,偏离她的方法裁定)第 1、2 条与「A」块 A-05、外部验证四行、「D」块:产品 2026-11-08 决定(BUG-1794),偏离占星师「缺口不能隐藏」的裁定(第五轮裁定 6 / 8、她的 Q5 之一与 Q6):产品选择不向用户展示;后台保留记录(回执里的技法审计行 MEVG / Global Web Evidence、Real Case Calibration 照旧)。回答(两种模式)不再写联网、外部资料、MEVG、真实案例校准的句子或审计表行;不写「已验证」「已校准」的禁令保留。产品负责人 2026-11-09 同意(BUG-1834):只在简明解读「解读依据」展开列表的最后一行、以及深度解读审计表末尾,由页面显示一句固定说明「本次未完成外部资料与案例核验,候选窗口尚未据此确认。」;回答正文仍不写,四行外部验证不恢复,后台记录不变。
7. 证据卡与专业模式语气:`EVIDENCE_CARD_BACKSTAGE_LINE`「置信度封顶」与审计表「结论降一级」——是降级而非删除,未发现冲突,列出备查。
8. (BUG-1733 已改)专业模式 VISIBLE VOICE 的「## 结论」一节原写「三到五行:冻结的时间范围(起止)、有条件的走势……」,PERIOD_FIRST_RULE 原写「先冻结时间范围,写明起止日期」,首轮提示原写「开头一节是简短的结论(时间范围和有条件的走势)」——盲测中多数回答首段是「时间范围冻结为……」,违反她 Q5 的呈现顺序(先答、再解释、再证据)。改为:第一句直接回答用户问的那件事,时间范围与参数紧随其后(不删);冻结时间范围仍是工作的第一步。
@@ -723,26 +723,6 @@ def _candidate_row(
evidence: list[CandidateEvidence] = []
missing_layers: list[str] = []
layer_points: dict[str, dict[str, float]] = {}
# 占星师 2026-11-09 第七轮 P1 第 1 条:逐项贡献(只用引擎已有的值,不新算分)。
contributions: list[dict[str, Any]] = []
contribution_profile: dict[str, Any] = {}
if context.get("functional_profile") is not None:
contribution_profile["functional_profile"] = context.get("functional_profile")
if context.get("narayana_step_profiles") is not None:
contribution_profile["narayana_step_profiles"] = context.get("narayana_step_profiles")
profile_payload = contribution_profile or None
def add_contribution(event_id: str, layer: str, dependency: list[str], points: Any,
decomposable: bool, missing_reason: str | None) -> None:
contributions.append({
"event_id": event_id,
"layer": layer,
"dependency": dependency,
"profile": profile_payload,
"points": points if points is None else round(float(points), 4),
"decomposable": decomposable,
"missing_reason": missing_reason,
})
for event in independent_events(request["events"])[0]:
event_at = _event_datetime(event)
@@ -750,9 +730,6 @@ def _candidate_row(
domain_vargas = [varga_charts[prefix] for prefix in prefixes]
if any(chart is None for chart in domain_vargas):
missing_layers.extend(prefixes)
blocked_prefix = next(prefix for prefix, chart in zip(prefixes, domain_vargas) if chart is None)
add_contribution(event["id"], blocked_prefix, list(prefixes), None, False,
f"event_not_scored:{blocked_prefix}")
continue
try:
vimshottari = _active_vimshottari(
@@ -763,9 +740,6 @@ def _candidate_row(
)
except (KeyError, TypeError, ValueError):
missing_layers.append("Vimshottari_MD_AD_PD")
add_contribution(event["id"], "Vimshottari_MD_AD_PD",
["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD", *prefixes], None, False,
"event_not_scored:Vimshottari_MD_AD_PD")
continue
try:
narayana = _active_narayana(
@@ -778,16 +752,10 @@ def _candidate_row(
)
except (KeyError, TypeError, ValueError):
missing_layers.append("Narayana_MD_AD")
add_contribution(event["id"], "Narayana_MD_AD",
["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD", *prefixes], None, False,
"event_not_scored:Narayana_MD_AD")
continue
if narayana[0] is None:
# BUG-1759: a blocked source-version step lands here (mandatory layer missing), never the old algorithm.
missing_layers.append("Narayana_MD_AD")
add_contribution(event["id"], "Narayana_MD_AD",
["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD", *prefixes], None, False,
"event_not_scored:Narayana_MD_AD")
continue
if narayana[1] is None:
# 原值:小运定不出时整条 Narayana 当缺失层,这个事件不计分(连已定的大运一起丢掉)。
@@ -840,20 +808,6 @@ def _candidate_row(
if shadbala_rules:
evidence[-1]["rule_ids"].extend(shadbala_rules)
evidence[-1]["points"] = round(evidence[-1]["points"] + shadbala_points * precision_weight(event["precision"]), 4)
# 占星师 2026-11-09 第七轮 P1 第 1 条:每层各记一项;MD 与 AD 拆不开时 decomposable=False。
ad_missing = narayana[1] is None
layer_dependency = {
"dasha_varga_core": ["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD", *prefixes],
"controlled_transit": ["transit_chart"],
"Ashtakavarga": ["Ashtakavarga"],
"Shadbala": ["Shadbala"],
}
for layer, points in event_layers.items():
add_contribution(
event["id"], layer, layer_dependency.get(layer, [layer]), points,
not (layer == "dasha_varga_core" and ad_missing),
"Narayana_AD_unresolved" if layer == "dasha_varga_core" and ad_missing else None,
)
return {
"time": candidate_at.strftime("%H:%M"),
@@ -864,8 +818,6 @@ def _candidate_row(
+ [layer for layer in context["feature"]["blocked_layers"] if layer not in OBSERVATION_ONLY_LAYERS]
)),
"layer_points": layer_points,
# 追加字段(不改上面任何字段的值与顺序)。
"contributions": contributions,
}
+4 -184
View File
@@ -299,47 +299,6 @@ EVENT_GATING_LAYERS: Final[frozenset[str]] = frozenset({
})
# 占星师原文层名 → 产品层名(只在「该候选整件事缺失」时适用,见 _explained_by_alias)。
ASTROLOGER_EVENT_LAYER_ALIASES: Final[dict[str, str]] = {
"Narayana_AD": "Narayana_MD_AD",
}
def _layers_by_event(unit: dict[tuple[str, str], float]) -> dict[str, set[str]]:
grouped: dict[str, set[str]] = {}
for (event_id, layer) in unit:
grouped.setdefault(event_id, set()).add(layer)
return grouped
def _explained_by_alias(layer: str, rows: Sequence[CandidateScoreRow], units: Sequence[dict[tuple[str, str], float]]) -> bool:
"""占星师原文层名能不能当作产品层名来解释这一处差异(BUG-1827)。
只有同时满足三条才算:该候选至少有一件事整件缺失;它自己覆盖单元里每一件事的层集合
与共同覆盖一致(没有「事件在、但少了某层」);它的缺失层里没有别的门控层。
"""
if layer not in ASTROLOGER_EVENT_LAYER_ALIASES:
return False
holders = [index for index, row in enumerate(rows) if layer in row["missing_layers"]]
if not holders:
return False
common = set.intersection(*[set(unit) for unit in units]) if units else set()
common_by_event = _layers_by_event(common)
all_events = {event for unit in units for (event, _) in unit}
for index in holders:
own_by_event = _layers_by_event(units[index])
# ① 至少有一件事整件缺失(别的候选有、它没有)。
if set(own_by_event) == all_events:
return False
# ② 它有的每一件事,层集合都必须与共同覆盖一致。
if any(common_by_event.get(event) != layers for event, layers in own_by_event.items()):
return False
# ③ 缺失层里不能再有别的门控层。
if any(item in EVENT_GATING_LAYERS and item != layer for item in rows[index]["missing_layers"]):
return False
return True
def _coverage_units(row: CandidateScoreRow) -> dict[tuple[str, str], float]:
"""(event, layer) -> points for every evidence unit this candidate actually computed.
@@ -355,99 +314,6 @@ def _coverage_units(row: CandidateScoreRow) -> dict[tuple[str, str], float]:
return {(str(item["event_id"]), "event_total"): float(item["points"]) for item in row["evidence"]}
def _excluded_dasha_contributions(rows: Sequence[CandidateScoreRow]) -> list[dict[str, str]]:
"""拆不开的 MD/AD 合分:只要有一个候选的该项 decomposable 为假,就对所有候选一起排除。"""
excluded: dict[str, dict[str, str]] = {}
for row in rows:
for contribution in row.get("contributions") or []:
if not isinstance(contribution, dict):
continue
if contribution.get("layer") != "dasha_varga_core":
continue
if contribution.get("decomposable") is not False:
continue
event_id = str(contribution.get("event_id") or "")
if event_id:
excluded[event_id] = {
"event_id": event_id,
"layer": "dasha_varga_core",
"reason": "md_ad_not_decomposable",
}
return [excluded[event_id] for event_id in sorted(excluded)]
def _explained_by_exclusion(layer: str, rows: Sequence[CandidateScoreRow],
excluded: Sequence[dict[str, str]]) -> bool:
"""差异层 L 是否已由「一致排除」解释(FIX-3)。
每个带 L 的候选都必须有贡献明细、其 ``missing_reason == f"{L}_unresolved"`` 的项
全部落在 ``excluded_contributions`` 里,并且该候选没有别的缺失层。
没有 contributions 的旧形状行不适用。
"""
covered = {(item["event_id"], item["layer"]) for item in excluded}
holders = [row for row in rows if layer in row["missing_layers"]]
if not holders:
return False
for row in holders:
contributions = row.get("contributions")
if not isinstance(contributions, list) or not contributions:
return False
unresolved = [
item for item in contributions
if isinstance(item, dict) and item.get("missing_reason") == f"{layer}_unresolved"
]
if not unresolved:
return False
for item in unresolved:
if (str(item.get("event_id") or ""), "dasha_varga_core") not in covered:
return False
if [other for other in row["missing_layers"] if other != layer]:
return False
return True
def missing_mandatory_layers(rows: Sequence[CandidateScoreRow]) -> list[dict[str, Any]]:
"""逐条列出「哪个候选、缺哪一层、影响哪几件事」(占星师第七轮 P1 第 3 条)。
没有缺失时返回 ``[]``(任何情况下都不是 ``null``);旧形状行没有贡献明细,
``event_ids`` 写 ``null`` 并标 ``event_ids_source``,不假装知道影响了哪几件事。
"""
entries: list[dict[str, Any]] = []
for row in rows:
contributions = row.get("contributions")
by_layer: dict[str, list[str]] = {}
has_contributions = isinstance(contributions, list) and bool(contributions)
for contribution in contributions or []:
if not isinstance(contribution, dict):
continue
reason = contribution.get("missing_reason")
layer = contribution.get("layer")
if not isinstance(reason, str) or not isinstance(layer, str):
continue
if reason.startswith("event_not_scored:"):
layer = reason.split(":", 1)[1]
elif reason.endswith("_unresolved"):
# dasha_varga_core 里「只缺小运」:缺失的层名在原因里(Narayana_AD_unresolved)。
layer = reason[: -len("_unresolved")]
else:
continue
event_id = str(contribution.get("event_id") or "")
if event_id:
by_layer.setdefault(layer, []).append(event_id)
for layer in row["missing_layers"]:
entry: dict[str, Any] = {"candidate_time": row["time"], "layer": layer}
if layer in by_layer:
entry["event_ids"] = sorted(set(by_layer[layer]))
elif has_contributions:
entry["event_ids"] = []
else:
entry["event_ids"] = None
entry["event_ids_source"] = "legacy_row_without_contributions"
entries.append(entry)
entries.sort(key=lambda item: (item["candidate_time"], item["layer"]))
return entries
def assess_leader_comparability(
rows: Sequence[CandidateScoreRow],
provisional_leader: WinningSegment | None,
@@ -475,48 +341,18 @@ def assess_leader_comparability(
"max": max((len(keys) for keys in unit_keys), default=0),
},
}
separable = {layer for keys in unit_keys for _, layer in keys} - {"event_total"}
differing = set.union(*row_layers) - set.intersection(*row_layers)
# 占星师第七轮 P1 第 1 条:拆不开的 MD/AD 合分对所有候选一致排除,缺的不当 0、全的也不计。
excluded_contributions = _excluded_dasha_contributions(rows)
if excluded_contributions:
dropped = {(item["event_id"], item["layer"]) for item in excluded_contributions}
units = [{key: value for key, value in unit.items() if key not in dropped} for unit in units]
unit_keys = [set(unit) for unit in units]
common = set.intersection(*unit_keys) if unit_keys else set()
base["common_unit_count"] = len(common)
base["candidate_unit_counts"] = {
"min": min((len(keys) for keys in unit_keys), default=0),
"max": max((len(keys) for keys in unit_keys), default=0),
}
equal = all(keys == unit_keys[0] for keys in unit_keys) and all(layers == row_layers[0] for layers in row_layers)
explained_aliases = {
layer: ASTROLOGER_EVENT_LAYER_ALIASES[layer]
for layer in differing
if layer not in EVENT_GATING_LAYERS and layer not in separable
and _explained_by_alias(layer, rows, units)
}
explained_by_exclusion = {
layer for layer in differing
if layer not in EVENT_GATING_LAYERS and layer not in separable
and _explained_by_exclusion(layer, rows, excluded_contributions)
}
unexplained = sorted(
layer for layer in differing
if layer not in EVENT_GATING_LAYERS and layer not in separable
and layer not in explained_aliases and layer not in explained_by_exclusion
)
if equal:
return {
**base,
"status": "comparable",
"comparison": "raw_totals",
"candidates_with_extra_coverage": 0,
**({"excluded_contributions": excluded_contributions} if excluded_contributions else {}),
**({"layer_aliases_applied": explained_aliases} if explained_aliases else {}),
"comparable_leader": provisional_leader,
"leader_changed": False,
}
separable = {layer for keys in unit_keys for _, layer in keys} - {"event_total"}
differing = set.union(*row_layers) - set.intersection(*row_layers)
unexplained = sorted(layer for layer in differing if layer not in EVENT_GATING_LAYERS and layer not in separable)
extra = sum(1 for keys in unit_keys if keys != common)
if unexplained:
return {
@@ -524,7 +360,6 @@ def assess_leader_comparability(
"status": "provisional_unequal_coverage",
"comparison": "not_reducible",
"unreducible_layers": unexplained,
**({"excluded_contributions": excluded_contributions} if excluded_contributions else {}),
"candidates_with_extra_coverage": extra,
"comparable_leader": None,
"leader_changed": None,
@@ -545,8 +380,6 @@ def assess_leader_comparability(
**base,
"status": "provisional_unequal_coverage",
"comparison": "common_coverage",
**({"layer_aliases_applied": explained_aliases} if explained_aliases else {}),
**({"excluded_contributions": excluded_contributions} if excluded_contributions else {}),
"candidates_with_extra_coverage": extra,
"common_top_score": common_top,
"common_scores": [{"time": row["time"], "score": row["score"]} for row in common_rows],
@@ -593,10 +426,6 @@ def adjudicate_candidate_rows(
"leave_one_event_out": leave_one_event_out or {"status": "not_evaluated", "runs": []},
},
"missing_layers": [],
"missing_mandatory_layers": [],
"top_candidate_count": 0,
"top_segment_count": 0,
"unique_time": False,
"leader_status": "no_leader",
"provisional_leader": None,
"comparable_leader": None,
@@ -609,7 +438,6 @@ def adjudicate_candidate_rows(
margin = round((top_score - second_score) / max(abs(top_score), 1.0) * 100, 2)
segments = _top_segments(rows, top_score)
missing_layers = sorted({layer for row in rows for layer in row["missing_layers"]})
missing_entries = missing_mandatory_layers(rows)
reasons: list[str] = []
if len(segments) != 1:
@@ -618,8 +446,7 @@ def adjudicate_candidate_rows(
reasons.append("insufficient_events")
if domain_count < 2:
reasons.append("insufficient_domains")
# 占星师第七轮 P1 第 3 条:这个 reason 当且仅当列表非空。
if missing_entries:
if missing_layers:
reasons.append("missing_mandatory_layers")
segment = _winning_segment(segments[0]) if len(segments) == 1 else None
@@ -683,16 +510,10 @@ def adjudicate_candidate_rows(
"score": score,
"tied_minute_count": len(score_rows),
})
# 占星师 2026-11-09 第七轮 P1 第 2 条:三个计数分开,代表分钟不能冒充唯一解。
top_candidate_count = sum(1 for row in rows if row["score"] == top_score)
top_segment_count = len(segments)
return {
"result_id": str(uuid5(NAMESPACE_URL, f"{ALGORITHM_VERSION}:{request_fingerprint}")),
"confidence": confidence,
"can_apply": can_apply,
"top_candidate_count": top_candidate_count,
"top_segment_count": top_segment_count,
"unique_time": top_candidate_count == 1,
"winning_segment": segment,
"event_count": event_count,
"domain_count": domain_count,
@@ -709,7 +530,6 @@ def adjudicate_candidate_rows(
"leave_one_event_out": leave_one_event_out or {"status": "not_evaluated", "runs": []},
},
"missing_layers": missing_layers,
"missing_mandatory_layers": missing_entries,
# winning_segment stays the raw-total leader; it is only "comparable" when coverage is equal.
"leader_status": (
"no_single_leader" if segment is None
+4 -1
View File
@@ -7,7 +7,7 @@ from __future__ import annotations
from typing import Any, Callable, Dict
from . import transit_date
from . import transit_date, transit_window
from .contract import OnDemandInputError, blocked_envelope
# 工具名 → run(body) -> envelope
@@ -15,6 +15,9 @@ TOOLS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
# 指定日期的行运:必填 date、地点(lat/lon)、时区(tz 或 timezone_id)、ayanamsa;
# node_mode / position_mode 缺省用产品默认值(mean / apparent)。
'transit_date': transit_date.run,
# 一段时间的行运变化:必填 start_date、end_date、地点、时区、ayanamsa、events;
# planets / target / natal 按事件类型选填。
'transit_window': transit_window.run,
}
__all__ = ['TOOLS', 'OnDemandInputError', 'ondemand_calc_api']
+506
View File
@@ -0,0 +1,506 @@
"""按需计算:一段时间内的行运变化(#174,BUG-1817)。
占星师 2026-11-07 Q9 / 2026-11-08 第五轮第 9 条:行运窗口要支持**换座、停滞、逆行往返、目标经度**。
数值一律来自引擎的恒星黄经(`jyotish_engine._calc_sidereal_planets_for_jd`),岁差、交点、
位置口径由调用方显式给出;本工具不排本命盘,`natal_point` 要调用方把恒星黄经传进来。
时刻用二分收敛到 ≤ 1 分钟。换座、停滞、目标经度的判定都只看恒星黄经与日速度,不另起算法。
"""
from __future__ import annotations
import sys
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from . import contract
from .contract import OnDemandInputError
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
TOOL = 'transit_window'
MAX_WINDOW_DAYS = 366
SEARCH_MARGIN_DAYS = 400
CONVERGENCE_MINUTES = 1
CONVERGENCE_DAYS = CONVERGENCE_MINUTES / 1440.0
PLANETS = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu')
STATION_PLANETS = ('Mercury', 'Venus', 'Mars', 'Jupiter', 'Saturn')
EVENT_TYPES = ('ingress', 'station', 'retrograde_loop', 'target_longitude')
COARSE_STEP_HOURS = {'Moon': 6.0, 'default': 24.0}
def _engine():
try:
from scripts import jyotish_engine as engine
except ModuleNotFoundError: # pragma: no cover - 直接跑 scripts/
import jyotish_engine as engine # type: ignore[no-redef]
return engine
def _jd_from_datetime(moment: datetime) -> float:
import swisseph as swe
return swe.julday(
moment.year, moment.month, moment.day,
moment.hour + moment.minute / 60.0 + moment.second / 3600.0,
)
def _local_midnight_jd(day: datetime, tz: float) -> float:
"""当地 00:00 对应的 JD(UT)。"""
return _jd_from_datetime(datetime(day.year, day.month, day.day) - timedelta(hours=tz))
class _Sky:
"""一个区间内按需取恒星黄经与日速度,调用方给的口径固定不变。"""
def __init__(self, engine: Any, profile: Dict[str, Any], planets: Sequence[str]) -> None:
self.engine = engine
self.profile = profile
self.planets = tuple(planets)
if hasattr(engine, '_configure_ephemeris_path'):
engine._configure_ephemeris_path() # noqa: SLF001
self._cache: Dict[float, Dict[str, Dict[str, float]]] = {}
def at(self, jd: float) -> Dict[str, Dict[str, float]]:
key = round(jd, 8)
if key in self._cache:
return self._cache[key]
data, _ayanamsa = self.engine._calc_sidereal_planets_for_jd( # noqa: SLF001
jd,
node_mode=self.profile['node_mode'],
include_ketu=True,
ayanamsa_name=self.profile['ayanamsa'],
)
snapshot: Dict[str, Dict[str, float]] = {}
for name in self.planets:
row = data.get(name)
if not row:
continue
snapshot[name] = {
'lon': float(row.get('degree_raw', row.get('degree', 0.0))),
'speed': float(row.get('speed') or 0.0),
'sign': str(row.get('sign') or ''),
}
self._cache[key] = snapshot
return snapshot
def ayanamsa(self, jd: float) -> float:
data, ayanamsa = self.engine._calc_sidereal_planets_for_jd( # noqa: SLF001
jd,
node_mode=self.profile['node_mode'],
include_ketu=True,
ayanamsa_name=self.profile['ayanamsa'],
)
del data
return float(ayanamsa or 0.0)
def lon(self, planet: str, jd: float) -> Optional[float]:
row = self.at(jd).get(planet)
return None if row is None else row['lon']
def _bisect(predicate: Callable[[float], bool], low: float, high: float,
tolerance: float = CONVERGENCE_DAYS) -> float:
"""在 [low, high] 上找 predicate 从 False 变 True 的位置。"""
lo, hi = low, high
while hi - lo > tolerance:
middle = (lo + hi) / 2.0
if predicate(middle):
hi = middle
else:
lo = middle
return (lo + hi) / 2.0
def _signed_delta(value: float, reference: float) -> float:
"""value - reference,按 0–360 取最短方向(正为顺行方向)。"""
return ((value - reference + 180.0) % 360.0) - 180.0
def _crossed(before: float, after: float, boundary: float) -> bool:
"""从 before 到 after(正向时间)是否跨过 boundary(模 360)。顺行逆行都算。"""
if before == after:
return False
delta = _signed_delta(after, before)
if delta == 0.0:
return False
if delta > 0.0:
return 0.0 < (boundary - before) % 360.0 <= delta
return 0.0 < (before - boundary) % 360.0 <= -delta
def _sign_boundaries(before: float, after: float) -> List[float]:
"""一步之内跨过的所有 30° 整数倍,按行进方向排序。"""
out: List[float] = []
forward = (after - before) % 360.0
if forward == 0.0:
return out
step = 30.0 if forward < 180.0 else -30.0
boundary = ((before // 30.0) + (1 if step > 0 else 0)) * 30.0
travelled = 0.0
guard = 0
while travelled < forward - 1e-9 and guard < 24:
guard += 1
if step > 0:
distance = (boundary - before) % 360.0
if distance > forward:
break
out.append(boundary % 360.0)
travelled = distance
boundary += 30.0
else:
distance = (before - boundary) % 360.0
if distance > (before - after) % 360.0:
break
out.append(boundary % 360.0)
travelled = distance
boundary -= 30.0
return out
def _sign_name(engine: Any, longitude: float) -> str:
signs = getattr(engine, 'SIGNS', None) or []
if not signs:
return ''
return str(signs[int(longitude % 360.0 / 30.0) % 12])
def _utc_stamp(jd: float) -> str:
import swisseph as swe
year, month, day, hour = swe.revjul(jd)
minutes = int(round(hour * 60.0))
return f'{year:04d}-{month:02d}-{day:02d}T{(minutes // 60) % 24:02d}:{minutes % 60:02d}Z'
def _local_parts(jd: float, tz: float) -> Tuple[str, int, int]:
"""当地日期与时分。"""
import swisseph as swe
year, month, day, hour = swe.revjul(jd + tz / 24.0)
minutes = int(round(hour * 60.0))
return f'{year:04d}-{month:02d}-{day:02d}', (minutes // 60) % 24, minutes % 60
def _offset_for_jd(jd: float, tz_fixed: Optional[float], timezone_id: Optional[str]) -> float:
if not timezone_id:
return float(tz_fixed or 0.0)
import swisseph as swe
year, month, day, _hour = swe.revjul(jd + (tz_fixed or 0.0) / 24.0)
return contract.offset_hours(datetime(year, month, day), None, timezone_id)
def _event(engine: Any, sky: _Sky, planet: str, jd: float, kind: str,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> Dict[str, Any]:
row = sky.at(jd).get(planet) or {}
longitude = float(row.get('lon') or 0.0)
offset = _offset_for_jd(jd, tz_fixed, timezone_id)
date_text, hour, minute = _local_parts(jd, offset)
return {
'type': kind,
'planet': planet,
'utc': _utc_stamp(jd),
'local': f'{date_text}T{hour:02d}:{minute:02d}',
'utc_offset_hours': round(offset, 4),
'jd_ut': round(jd, 8),
'longitude': round(longitude, 6),
'sign': _sign_name(engine, longitude),
'degree_in_sign': round(longitude % 30.0, 4),
}
def _sign_index(longitude: float) -> int:
return int(longitude % 360.0 / 30.0) % 12
def _ingress_events(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before = sky.lon(planet, jd)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after = sky.lon(planet, nxt)
if before is None or after is None:
before, jd = after, nxt
continue
if _sign_index(before) != _sign_index(after):
start_sign = _sign_index(before)
at = _bisect(lambda x: _sign_index(sky.lon(planet, x) or before) != start_sign, jd, nxt)
event = _event(engine, sky, planet, at, 'ingress', tz_fixed, timezone_id)
event['from_sign'] = _sign_name(engine, before)
# 验收修正(Claude 2026-11-09):原来 to_sign 用 JD 当黄经取星座、direction 在 0° 白羊处判反;
# 改为按粗扫步末端的黄经取星座,方向按最短角差的正负。
event['to_sign'] = _sign_name(engine, after)
event['direction'] = 'direct' if _signed_delta(after, before) > 0.0 else 'retrograde'
events.append(event)
before, jd = after, nxt
return events
def _station_events(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS['default'] / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before_row = sky.at(jd).get(planet)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after_row = sky.at(nxt).get(planet)
if not before_row or not after_row:
before_row, jd = after_row, nxt
continue
before_speed = before_row['speed']
after_speed = after_row['speed']
if before_speed == 0.0 or (before_speed < 0) != (after_speed < 0):
at = _bisect(lambda x: (sky.at(x).get(planet, {}).get('speed', 0.0) < 0) != (before_speed < 0), jd, nxt)
event = _event(engine, sky, planet, at, 'station', tz_fixed, timezone_id)
event['station_type'] = 'retrograde' if before_speed >= 0 else 'direct'
event['speed'] = round(float(sky.at(at).get(planet, {}).get('speed', 0.0)), 6)
events.append(event)
before_row, jd = after_row, nxt
return events
def _target_events(engine: Any, sky: _Sky, planet: str, target: float, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str]) -> List[Dict[str, Any]]:
step = COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) / 24.0
events: List[Dict[str, Any]] = []
jd = start_jd
before = sky.lon(planet, jd)
while jd < end_jd:
nxt = min(jd + step, end_jd)
after = sky.lon(planet, nxt)
if before is None or after is None:
before, jd = after, nxt
continue
if before != after and _crossed(before, after, target):
at = _bisect(lambda x: _crossed(before, sky.lon(planet, x) or before, target), jd, nxt)
event = _event(engine, sky, planet, at, 'target_longitude', tz_fixed, timezone_id)
event['target_longitude'] = round(float(target), 6)
event['direction'] = 'direct' if (after - before) % 360.0 < 180.0 else 'retrograde'
events.append(event)
before, jd = after, nxt
return events
def _retrograde_loops(engine: Any, sky: _Sky, planet: str, start_jd: float, end_jd: float,
tz_fixed: Optional[float], timezone_id: Optional[str],
gaps: List[Dict[str, str]]) -> List[Dict[str, Any]]:
margin = SEARCH_MARGIN_DAYS
stations = _station_events(engine, sky, planet, start_jd - margin, end_jd + margin, tz_fixed, timezone_id)
loops: List[Dict[str, Any]] = []
for index, station in enumerate(stations):
if station.get('station_type') != 'retrograde':
continue
if index + 1 >= len(stations):
continue
direct = stations[index + 1]
if direct.get('station_type') != 'direct':
continue
retro_lon = float(station['longitude'])
direct_lon = float(direct['longitude'])
entry = _find_crossing(engine, sky, planet, direct_lon, station['jd_ut'] - margin * 1.0,
station['jd_ut'], tz_fixed, timezone_id, backwards=True)
exit_ = _find_crossing(engine, sky, planet, retro_lon, direct['jd_ut'],
direct['jd_ut'] + margin * 1.0, tz_fixed, timezone_id, backwards=False)
inside = (start_jd <= station['jd_ut'] <= end_jd) or (start_jd <= direct['jd_ut'] <= end_jd)
if not inside:
continue
for key, value in (('shadow_entry', entry), ('shadow_exit', exit_)):
if value is None:
gaps.append({'field': 'retrograde_loop', 'reason': f'loop_incomplete:{planet}:{key}'})
loops.append({
'planet': planet,
'station_retrograde': station,
'station_direct': direct,
'retrograde_span': [round(direct_lon, 6), round(retro_lon, 6)],
'shadow_entry': entry,
'shadow_exit': exit_,
'outside_requested_window': not (start_jd <= station['jd_ut'] <= end_jd),
})
return loops
def _find_crossing(engine: Any, sky: _Sky, planet: str, longitude: float, low: float, high: float,
tz_fixed: Optional[float], timezone_id: Optional[str],
*, backwards: bool) -> Optional[Dict[str, Any]]:
"""在 [low, high] 内找最后一次(backwards)或第一次(向前)到达 longitude 的时刻。"""
if high <= low:
return None
step = COARSE_STEP_HOURS['default'] / 24.0
found: Optional[float] = None
jd = low
before = sky.lon(planet, jd)
while jd < high:
nxt = min(jd + step, high)
after = sky.lon(planet, nxt)
if before is not None and after is not None and before != after and _crossed(before, after, longitude):
at = _bisect(lambda x: _crossed(before, sky.lon(planet, x) or before, longitude), jd, nxt)
# 向后找「最后一次」到达:从早到晚扫,保留最后一个;向前找「第一次」:命中即停。
found = at
if not backwards:
break
before, jd = after, nxt
if found is None:
return None
return _event(engine, sky, planet, found, 'shadow_crossing', tz_fixed, timezone_id)
def _validate(body: Dict[str, Any]) -> Dict[str, Any]:
if not isinstance(body, dict):
raise OnDemandInputError('body must be an object')
start = contract.parse_date(body.get('start_date'), 'start_date') if body.get('start_date') else None
if start is None:
raise OnDemandInputError('missing required field: start_date', 'start_date')
end = contract.parse_date(body.get('end_date'), 'end_date') if body.get('end_date') else None
if end is None:
raise OnDemandInputError('missing required field: end_date', 'end_date')
if end < start:
raise OnDemandInputError('end_date must be on or after start_date', 'end_date')
if (end - start).days + 1 > MAX_WINDOW_DAYS:
raise OnDemandInputError(f'window must be at most {MAX_WINDOW_DAYS} days', 'end_date')
events = body.get('events')
if not isinstance(events, list) or not events:
raise OnDemandInputError('missing required field: events', 'events')
unknown = [item for item in events if item not in EVENT_TYPES]
if unknown:
raise OnDemandInputError(f'unknown event type: {unknown[0]}', 'events')
planets = body.get('planets')
if planets is None:
planets = list(PLANETS)
if not isinstance(planets, list) or not planets:
raise OnDemandInputError('planets must be a non-empty list', 'planets')
bad = [item for item in planets if item not in PLANETS]
if bad:
raise OnDemandInputError(f'unknown planet: {bad[0]}', 'planets')
target = body.get('target')
if 'target_longitude' in events:
if not isinstance(target, dict):
raise OnDemandInputError('missing required field: target', 'target')
if str(target.get('planet')) not in PLANETS:
raise OnDemandInputError('target.planet must be one of the nine planets', 'target')
has_longitude = target.get('longitude') is not None
has_point = target.get('natal_point') is not None
if not has_longitude and not has_point:
raise OnDemandInputError('target needs longitude or natal_point', 'target')
if has_longitude:
try:
value = float(target['longitude'])
except (TypeError, ValueError) as error:
raise OnDemandInputError('target.longitude must be a number', 'target') from error
if not 0.0 <= value < 360.0:
raise OnDemandInputError('target.longitude must be 0–360', 'target')
if has_point and not isinstance(body.get('natal'), dict):
raise OnDemandInputError('target.natal_point needs natal.points', 'natal')
return {
'start': start,
'end': end,
'planets': list(dict.fromkeys(planets)),
'events': list(dict.fromkeys(events)),
'target': target,
}
def _resolve_target(body: Dict[str, Any], inputs: Dict[str, Any]) -> Tuple[Optional[float], Optional[Dict[str, str]]]:
target = inputs.get('target') or {}
if 'target_longitude' not in inputs['events']:
return None, None
if target.get('longitude') is not None:
return float(target['longitude']), None
name = str(target.get('natal_point'))
points = (body.get('natal') or {}).get('points') if isinstance(body.get('natal'), dict) else None
if not isinstance(points, dict) or name not in points:
return None, {'field': 'target.natal_point', 'reason': f'natal_point_missing:{name}'}
return float(points[name]), None
def run(body: Dict[str, Any]) -> Dict[str, Any]:
try:
inputs = _validate(body)
common = contract.validate_common({**body, 'date': body['start_date']})
profile = contract.resolve_profile({**body, 'date': body['start_date']}, common)
target_longitude, target_gap = _resolve_target(body, inputs)
except OnDemandInputError as error:
return contract.blocked_envelope(tool=TOOL, body=body, error=error)
requested = dict(body)
if target_gap is not None:
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[target_gap],
)
if profile['position_mode'] not in contract.SUPPORTED_POSITION_MODES:
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'position_mode', 'reason': 'position_mode_unsupported'}],
)
tz_fixed = profile['tz'] if not profile.get('timezone_id') else None
timezone_id = profile.get('timezone_id')
try:
engine = _engine()
sky = _Sky(engine, profile, inputs['planets'])
except Exception as error: # noqa: BLE001 - 星历不可用也只留缺口
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
)
start_jd = _local_midnight_jd(inputs['start'], profile['tz'])
end_day = inputs['end'] + timedelta(days=1)
# 验收修正(Claude 2026-11-09):区间终点按终点那天的偏移换算(原来用起始日偏移,跨夏令时差 1 小时)。
end_offset = contract.offset_hours(end_day, None, timezone_id) if timezone_id else profile['tz']
end_jd = _local_midnight_jd(end_day, end_offset)
gaps: List[Dict[str, str]] = []
events: List[Dict[str, Any]] = []
loops: List[Dict[str, Any]] = []
try:
for planet in inputs['planets']:
if 'ingress' in inputs['events']:
events.extend(_ingress_events(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id))
if 'station' in inputs['events'] or 'retrograde_loop' in inputs['events']:
if planet in ('Rahu', 'Ketu'):
if 'station' in inputs['events'] or 'retrograde_loop' in inputs['events']:
gaps.append({'field': 'planets', 'reason': f'node_station_not_supported:{planet}'})
elif planet in STATION_PLANETS:
if 'station' in inputs['events']:
events.extend(_station_events(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id))
if 'retrograde_loop' in inputs['events']:
loops.extend(_retrograde_loops(engine, sky, planet, start_jd, end_jd, tz_fixed, timezone_id, gaps))
if 'target_longitude' in inputs['events'] and target_longitude is not None and planet == str((inputs['target'] or {}).get('planet')):
events.extend(_target_events(engine, sky, planet, target_longitude, start_jd, end_jd, tz_fixed, timezone_id))
except Exception as error: # noqa: BLE001 - 失败只留缺口,不编任何日期
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status='blocked', raw={},
gaps=[{'field': 'calculation', 'reason': f'engine_failed:{type(error).__name__}'}],
)
events.sort(key=lambda item: item['jd_ut'])
for loop in loops:
for key in ('station_retrograde', 'station_direct'):
stamp = loop.get(key) or {}
loop[f'{key}_outside_window'] = not (start_jd <= float(stamp.get('jd_ut', 0.0)) <= end_jd)
# 验收修正(Claude 2026-11-09):任务书要求落在请求区间外的每个时刻自己标 outside_requested_window。
for key in ('station_retrograde', 'station_direct', 'shadow_entry', 'shadow_exit'):
stamp = loop.get(key)
if isinstance(stamp, dict):
stamp['outside_requested_window'] = not (start_jd <= float(stamp['jd_ut']) <= end_jd)
raw = {
'start_date': inputs['start'].strftime('%Y-%m-%d'),
'end_date': inputs['end'].strftime('%Y-%m-%d'),
'ayanamsa_degrees_at_start': round(sky.ayanamsa(start_jd), 6),
'precision': {
'coarse_step_hours': {planet: COARSE_STEP_HOURS.get(planet, COARSE_STEP_HOURS['default']) for planet in inputs['planets']},
'convergence_minutes': CONVERGENCE_MINUTES,
'search_margin_days': SEARCH_MARGIN_DAYS,
},
'events': events,
'retrograde_loops': loops,
}
status = 'partial' if gaps else 'executed'
return contract.build_envelope(
tool=TOOL, requested=requested, profile=profile, status=status, raw=raw, gaps=gaps,
)
@@ -0,0 +1,292 @@
"""按需计算(二):一段时间内的行运变化(#174,BUG-1817)。
换座 / 停滞 / 逆行往返 / 目标经度,时刻二分到 ≤1 分钟,口径显式。
只用公开日期与合成坐标,不含任何个人资料。
"""
from __future__ import annotations
import sys
from datetime import datetime
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
for path in (str(ROOT), str(ROOT / 'scripts')):
if path not in sys.path:
sys.path.insert(0, path)
from scripts.ondemand_calc import ondemand_calc_api # noqa: E402
from scripts.ondemand_calc import transit_window # noqa: E402
BASE = {
'tool': 'transit_window',
'start_date': '2026-01-01',
'end_date': '2026-03-31',
'lat': 0.0,
'lon': 0.0,
'tz': 0.0,
'ayanamsa': 'lahiri',
'node_mode': 'mean',
'planets': ['Mercury'],
'events': ['ingress', 'station', 'retrograde_loop'],
}
def _body(**overrides):
body = dict(BASE)
body.update(overrides)
return body
def _jd(iso: str) -> float:
import swisseph as swe
moment = datetime.strptime(iso, '%Y-%m-%dT%H:%MZ')
return swe.julday(moment.year, moment.month, moment.day, moment.hour + moment.minute / 60.0)
def _reference_stations(planet: str, ayanamsa: str, start_iso: str, end_iso: str):
"""独立对照:直接用 SwissEph 的恒星黄经速度二分过零点。"""
import swisseph as swe
from ayanamsa_utils import apply_ayanamsa, sidereal_flags
apply_ayanamsa(ayanamsa)
flags = sidereal_flags(swe, ayanamsa) | getattr(swe, 'FLG_SPEED', 256)
planet_id = {'Mercury': swe.MERCURY, 'Venus': swe.VENUS, 'Mars': swe.MARS}[planet]
def speed(jd: float) -> float:
values, _ = swe.calc_ut(jd, planet_id, flags)
return values[3]
stations = []
jd = _jd(start_iso)
end = _jd(end_iso)
step = 0.5
before = speed(jd)
while jd < end:
nxt = min(jd + step, end)
after = speed(nxt)
if (before < 0) != (after < 0):
lo, hi = jd, nxt
while hi - lo > 1.0 / 1440.0:
middle = (lo + hi) / 2.0
if (speed(middle) < 0) == (before < 0):
lo = middle
else:
hi = middle
stations.append((lo + hi) / 2.0)
before, jd = after, nxt
return stations
def test_mercury_retrograde_stations_match_a_direct_swisseph_bisection() -> None:
envelope = ondemand_calc_api(_body())
assert envelope['calculation_status'] == 'executed'
stations = [event for event in envelope['raw']['events'] if event['type'] == 'station']
assert len(stations) == 2, stations
reference = _reference_stations('Mercury', 'lahiri', '2026-02-01T00:00Z', '2026-04-15T00:00Z')
assert len(reference) == 2
for event, expected in zip(stations, reference):
delta_minutes = abs(event['jd_ut'] - expected) * 24 * 60
assert delta_minutes <= 2.0, (event['utc'], delta_minutes)
def test_target_longitude_lists_all_three_passes_with_directions() -> None:
# 三次到齐要看到 4 月:第二次逆行、第三次要等顺行恢复(2026-04-01)。
envelope = ondemand_calc_api(_body(
end_date='2026-04-30',
events=['target_longitude'],
target={'planet': 'Mercury', 'longitude': 320.0},
))
events = [event for event in envelope['raw']['events'] if event['type'] == 'target_longitude']
assert len(events) == 3, events
assert [event['direction'] for event in events] == ['direct', 'retrograde', 'direct']
assert all(abs(event['longitude'] - 320.0) <= 0.01 for event in events)
def test_retrograde_loop_shadow_ordering_and_span() -> None:
envelope = ondemand_calc_api(_body())
loops = envelope['raw']['retrograde_loops']
assert len(loops) == 1
loop = loops[0]
assert loop['shadow_entry']['jd_ut'] < loop['station_retrograde']['jd_ut']
assert loop['shadow_exit']['jd_ut'] > loop['station_direct']['jd_ut']
low, high = loop['retrograde_span']
assert low < high
def test_ingress_times_differ_between_ayanamsas_and_echo_the_profile() -> None:
lahiri = ondemand_calc_api(_body(events=['ingress']))
raman = ondemand_calc_api(_body(events=['ingress'], ayanamsa='raman'))
assert lahiri['profile']['ayanamsa'] == 'lahiri'
assert raman['profile']['ayanamsa'] == 'raman'
lahiri_times = [event['utc'] for event in lahiri['raw']['events'] if event['type'] == 'ingress']
raman_times = [event['utc'] for event in raman['raw']['events'] if event['type'] == 'ingress']
assert lahiri_times and raman_times
assert lahiri_times[0] != raman_times[0]
def test_nodes_follow_the_node_mode() -> None:
# 罗睺约 19°/年,三个月里不会换座,所以用一整年。
year = {'start_date': '2026-01-01', 'end_date': '2026-12-31'}
mean = ondemand_calc_api(_body(planets=['Rahu'], events=['ingress'], node_mode='mean', **year))
true = ondemand_calc_api(_body(planets=['Rahu'], events=['ingress'], node_mode='true', **year))
mean_times = [event['utc'] for event in mean['raw']['events']]
true_times = [event['utc'] for event in true['raw']['events']]
assert mean_times and true_times
assert mean_times[0] != true_times[0]
def test_timezone_id_offset_follows_daylight_saving_inside_the_window() -> None:
envelope = ondemand_calc_api({
'tool': 'transit_window',
'start_date': '2026-03-27',
'end_date': '2026-03-30',
'lat': 51.5074,
'lon': -0.1278,
'timezone_id': 'Europe/London',
'ayanamsa': 'lahiri',
'planets': ['Sun'],
'events': ['ingress'],
})
assert envelope['calculation_status'] in {'executed', 'partial'}
offsets = {event['utc_offset_hours'] for event in envelope['raw']['events']}
assert offsets <= {0.0, 1.0}
assert envelope['raw']['precision']['convergence_minutes'] == 1
def test_longitude_at_an_ingress_agrees_with_the_single_date_tool() -> None:
window = ondemand_calc_api(_body(events=['ingress']))
ingress = next(event for event in window['raw']['events'] if event['type'] == 'ingress')
single = ondemand_calc_api({
'tool': 'transit_date',
'date': ingress['utc'][:10],
'time': ingress['utc'][11:16],
'lat': 0.0, 'lon': 0.0, 'tz': 0.0,
'ayanamsa': 'lahiri', 'node_mode': 'mean',
})
row = next(item for item in single['raw']['planets'] if item['planet'] == ingress['planet'])
boundary = round(row['longitude'] / 30.0) * 30.0
assert abs(row['longitude'] - boundary) <= 0.01
def test_missing_inputs_are_blocked_and_named() -> None:
cases = [
({'start_date': None}, 'start_date'),
({'end_date': None}, 'end_date'),
({'lat': None}, 'lat'),
({'tz': None}, 'tz'),
({'ayanamsa': None}, 'ayanamsa'),
({'events': None}, 'events'),
]
for change, field in cases:
envelope = ondemand_calc_api(_body(**change))
assert envelope['calculation_status'] == 'blocked', change
assert envelope['raw'] == {}
assert envelope['gaps'][0]['field'] == field, change
def test_window_limits_and_unknown_values_are_blocked() -> None:
too_long = ondemand_calc_api(_body(start_date='2026-01-01', end_date='2027-03-01'))
assert too_long['calculation_status'] == 'blocked'
assert too_long['gaps'][0]['field'] == 'end_date'
reversed_ = ondemand_calc_api(_body(start_date='2026-03-01', end_date='2026-01-01'))
assert reversed_['calculation_status'] == 'blocked'
unknown_event = ondemand_calc_api(_body(events=['not_an_event']))
assert unknown_event['calculation_status'] == 'blocked'
assert unknown_event['gaps'][0]['field'] == 'events'
unknown_planet = ondemand_calc_api(_body(planets=['NotAPlanet']))
assert unknown_planet['calculation_status'] == 'blocked'
assert unknown_planet['gaps'][0]['field'] == 'planets'
def test_mean_position_mode_is_blocked_with_the_named_gap() -> None:
envelope = ondemand_calc_api(_body(position_mode='mean'))
assert envelope['calculation_status'] == 'blocked'
assert envelope['gaps'] == [{'field': 'position_mode', 'reason': 'position_mode_unsupported'}]
def test_profile_source_marks_product_defaults() -> None:
default = ondemand_calc_api(_body())
assert default['profile']['profile_source'] == 'product_default_explicit'
explicit = ondemand_calc_api(_body(node_mode='mean', position_mode='apparent'))
assert explicit['profile']['profile_source'] == 'caller_supplied'
def test_fingerprint_is_stable_and_sensitive() -> None:
first = ondemand_calc_api(_body())
assert ondemand_calc_api(_body())['input_fingerprint'] == first['input_fingerprint']
seen = {first['input_fingerprint']}
for change in (
{'start_date': '2026-01-02'}, {'end_date': '2026-03-30'}, {'lat': 10.0}, {'ayanamsa': 'raman'},
{'node_mode': 'true'}, {'planets': ['Venus']}, {'events': ['ingress']},
):
envelope = ondemand_calc_api(_body(**change))
assert envelope['input_fingerprint'] not in seen, change
seen.add(envelope['input_fingerprint'])
def test_engine_failure_is_blocked_without_an_invented_date(monkeypatch) -> None:
def boom(*args, **kwargs):
raise RuntimeError('ephemeris broken')
monkeypatch.setattr(transit_window, '_Sky', lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError('broken')))
envelope = ondemand_calc_api(_body())
assert envelope['calculation_status'] == 'blocked'
assert envelope['raw'] == {}
assert envelope['gaps'][0]['field'] == 'calculation'
assert '2026-01-01' not in repr(envelope['raw'])
def test_nodes_do_not_get_station_events() -> None:
envelope = ondemand_calc_api(_body(planets=['Rahu'], events=['station']))
assert envelope['calculation_status'] == 'partial'
assert envelope['raw']['events'] == []
assert any('node_station_not_supported' in gap['reason'] for gap in envelope['gaps'])
def test_missing_natal_point_is_blocked_and_named() -> None:
envelope = ondemand_calc_api(_body(
events=['target_longitude'],
target={'planet': 'Mercury', 'natal_point': 'Moon'},
natal={'points': {'Sun': 10.0}},
))
assert envelope['calculation_status'] == 'blocked'
assert envelope['gaps'][0] == {'field': 'target.natal_point', 'reason': 'natal_point_missing:Moon'}
def test_registry_dispatches_to_the_new_tool() -> None:
envelope = ondemand_calc_api(_body(planets=['Sun'], events=['ingress'], start_date='2026-01-01', end_date='2026-01-05'))
assert envelope['tool'] == 'transit_window'
assert envelope['schema'] == 'jyotish.ondemand_calc.v1'
# 验收补测(Claude 2026-11-09):换座的 to_sign / direction,以及区间外时刻的逐项标记。
def test_ingress_names_the_new_sign_and_direction_across_zero_aries() -> None:
result = transit_window.run(_body(start_date='2026-04-01', end_date='2026-04-30', planets=['Sun'], events=['ingress']))
assert result['calculation_status'] == 'executed'
[event] = result['raw']['events']
assert (event['from_sign'], event['to_sign'], event['direction']) == ('Pisces', 'Aries', 'direct')
def test_retrograde_ingress_back_into_the_previous_sign_is_named() -> None:
result = transit_window.run(_body(start_date='2026-01-01', end_date='2026-12-31', events=['ingress']))
events = result['raw']['events']
assert events, result
signs = list(__import__('jyotish_engine').SIGNS)
for event in events:
step = 1 if event['direction'] == 'direct' else -1
assert signs.index(event['to_sign']) == (signs.index(event['from_sign']) + step) % 12, event
assert any(event['direction'] == 'retrograde' for event in events)
def test_each_time_outside_the_window_is_marked() -> None:
result = transit_window.run(_body(start_date='2026-01-01', end_date='2026-06-30', events=['retrograde_loop']))
loops = result['raw']['retrograde_loops']
assert len(loops) == 2
june = loops[1]
assert june['station_retrograde']['outside_requested_window'] is False
assert june['station_direct']['outside_requested_window'] is True
assert june['shadow_exit']['outside_requested_window'] is True
assert loops[0]['shadow_entry']['outside_requested_window'] is False
@@ -1,363 +0,0 @@
"""BUG-1827 · 占星师第七轮 P1 第 2 条:把「候选分钟数 / 连续区间数 / 是否唯一时刻」分开。
她的例子:共同分数 8:8、候选区间 12:00–12:01、``comparable_tied=false``——这是一个**连续领先的
区间**,不是唯一的分钟。代表分钟不能冒充唯一解,所以结果里三个计数分开写。
本文件先只覆盖这三个计数(P1 第 1、3 条要动计分粒度与缺失字段形状,等任务书拆分后再补)。
合成匿名行,不含任何个人资料。
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
for path in (str(ROOT), str(ROOT / 'scripts')):
if path not in sys.path:
sys.path.insert(0, path)
from scripts.active_rectification_events import adjudicate_candidate_rows # noqa: E402
from scripts.active_rectification_event_engine import compute_event_candidate_rows # noqa: E402
from tests.neutral_subject import NEUTRAL_BIRTH_PAYLOAD # noqa: E402
DOMAINS = ["career", "relationship", "finance", "career", "relationship"]
def _row(time: str, points: dict[str, float], missing: list[str] | None = None) -> dict:
return {
"time": time,
"score": round(sum(points.values()), 4),
"evidence": [
{"event_id": event_id, "domain": DOMAINS[int(event_id[1:]) - 1], "candidate_time": time,
"rule_ids": ["synthetic"], "points": value}
for event_id, value in points.items()
],
"missing_layers": missing or [],
}
def _adjudicate(rows: list[dict]) -> dict:
return adjudicate_candidate_rows(
rows, event_count=5, domain_count=3, request_fingerprint="synthetic-bug1827",
leave_one_event_out={"status": "pass", "runs": []},
)
FIVE = {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}
def test_a_two_minute_lead_is_one_segment_but_not_one_unique_time() -> None:
rows = [_row("12:00", FIVE), _row("12:01", FIVE), _row("12:02", {"e1": 2, "e2": 2})]
result = _adjudicate(rows)
# 12:00 与 12:01 同分且相邻:两个候选分钟,但只有一个连续区间。
assert result["top_candidate_count"] == 2
assert result["top_segment_count"] == 1
assert result["unique_time"] is False
def test_a_single_leader_is_one_candidate_and_one_segment() -> None:
rows = [_row("12:00", FIVE), _row("12:01", {"e1": 2, "e2": 2, "e3": 2})]
result = _adjudicate(rows)
assert result["top_candidate_count"] == 1
assert result["top_segment_count"] == 1
assert result["unique_time"] is True
def test_equal_scores_on_two_separate_minutes_are_two_segments() -> None:
rows = [_row("12:00", FIVE), _row("12:05", FIVE), _row("12:10", {"e1": 2})]
result = _adjudicate(rows)
assert result["top_candidate_count"] == 2
assert result["top_segment_count"] == 2
assert result["unique_time"] is False
assert "tied_leader" in result["reasons"]
def test_the_representative_time_never_claims_to_be_the_only_minute() -> None:
rows = [_row("12:00", FIVE), _row("12:01", FIVE)]
result = _adjudicate(rows)
# 两分钟连续领先:winning_segment 是一段(宽 2 分钟),不是一个唯一时刻。
segment = result["winning_segment"]
assert segment["width_minutes"] == 2
assert segment["start_time"] == "12:00" and segment["end_time"] == "12:01"
assert result["unique_time"] is False
assert result["top_candidate_count"] == 2
def test_counts_are_zero_when_there_are_no_candidates() -> None:
result = adjudicate_candidate_rows(
[], event_count=5, domain_count=3, request_fingerprint="synthetic-bug1827-empty",
)
assert result["top_candidate_count"] == 0
assert result["top_segment_count"] == 0
assert result["unique_time"] is False
# --- P1 第 1 条:逐项贡献 ---
def _scored_row(time: str, points: dict[str, float], contributions: list[dict]) -> dict:
row = _row(time, points)
row["contributions"] = contributions
return row
def _contribution(event_id: str, layer: str, points, decomposable=True, reason=None) -> dict:
return {
"event_id": event_id, "layer": layer,
"dependency": ["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD"],
"profile": {"functional_profile": "pvr_table30_v1"},
"points": points, "decomposable": decomposable, "missing_reason": reason,
}
def test_contribution_points_add_up_to_the_row_score() -> None:
rows = [_scored_row("12:00", {"e1": 2, "e2": 2}, [
_contribution("e1", "dasha_varga_core", 1.5),
_contribution("e1", "controlled_transit", 0.5),
_contribution("e2", "dasha_varga_core", 2.0),
])]
result = _adjudicate(rows)
assert result["top_score"] == 4.0
total = round(sum(item["points"] for item in rows[0]["contributions"]), 4)
assert total == rows[0]["score"] == 4.0
def test_an_event_that_is_not_scored_is_recorded_as_a_contribution() -> None:
rows = [_scored_row("12:00", {"e1": 2}, [
_contribution("e1", "dasha_varga_core", 2.0),
_contribution("e2", "Narayana_MD_AD", None, decomposable=False,
reason="event_not_scored:Narayana_MD_AD"),
])]
# 整件不计分的那件事在贡献里留了痕:points 为 null、原因点名门控层。
blocked = [item for item in rows[0]["contributions"]
if item["layer"] == "Narayana_MD_AD" and item["points"] is None]
assert blocked
assert blocked[0]["missing_reason"] == "event_not_scored:Narayana_MD_AD"
assert blocked[0]["decomposable"] is False
# 它不是行上的 missing_layers,所以缺失清单里不会凭空多出一层。
assert _adjudicate(rows)["missing_mandatory_layers"] == []
# --- P1 第 1 条:拆不开的 MD/AD 合分对所有候选一致排除 ---
def test_indivisible_dasha_contributions_are_excluded_for_every_candidate() -> None:
left = _row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2})
right = _row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_AD"])
left["contributions"] = [_contribution("e5", "dasha_varga_core", 2.0, decomposable=True)]
right["contributions"] = [_contribution("e5", "dasha_varga_core", 2.0, decomposable=False,
reason="Narayana_AD_unresolved")]
result = _adjudicate([left, right])
comparison = result["coverage_comparison"]
assert comparison["excluded_contributions"] == [
{"event_id": "e5", "layer": "dasha_varga_core", "reason": "md_ad_not_decomposable"},
]
# 两边一起拿掉之后,共同覆盖里的分数相同才是可比的。
assert comparison["comparison"] == "common_coverage"
def test_legacy_rows_without_contributions_never_exclude_anything() -> None:
left = _row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2})
right = _row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_AD"])
result = _adjudicate([left, right])
# 没有贡献明细的行不会被当成「拆不开」,所以不会排除任何单元。
assert "excluded_contributions" not in result["coverage_comparison"]
# 层名对照照常生效(那是输入适配,与 contribution 无关)。
assert result["coverage_comparison"]["comparison"] == "common_coverage"
# --- P1 第 3 条:missing_mandatory_layers ---
def test_missing_mandatory_layers_lists_candidate_layer_and_events() -> None:
left = _row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2})
right = _row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_AD"])
right["contributions"] = [_contribution("e5", "dasha_varga_core", 2.0, decomposable=False,
reason="Narayana_AD_unresolved")]
result = _adjudicate([left, right])
assert result["missing_mandatory_layers"] == [
{"candidate_time": "12:01", "layer": "Narayana_AD", "event_ids": ["e5"]},
]
assert "missing_mandatory_layers" in result["reasons"]
def test_legacy_rows_mark_the_event_ids_as_unknown() -> None:
result = _adjudicate([_row("12:00", {"e1": 2}), _row("12:01", {"e1": 2}, ["D9"])])
entry = next(item for item in result["missing_mandatory_layers"] if item["layer"] == "D9")
assert entry["event_ids"] is None
assert entry["event_ids_source"] == "legacy_row_without_contributions"
def test_the_missing_list_is_never_null() -> None:
clean = _adjudicate([_row("12:00", {"e1": 2}), _row("12:01", {"e1": 2})])
assert clean["missing_mandatory_layers"] == []
assert "missing_mandatory_layers" not in clean["reasons"]
empty = adjudicate_candidate_rows([], event_count=5, domain_count=3, request_fingerprint="synthetic-empty")
assert empty["missing_mandatory_layers"] == []
# --- 层名对照(输入适配) ---
def _alias_row(time: str, points: dict[str, float], missing: list[str]) -> dict:
return _row(time, points, missing)
def test_the_astrologer_spelling_is_explained_and_recorded() -> None:
full = _alias_row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}, [])
short_her = _alias_row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_AD"])
her = _adjudicate([full, short_her])
assert her["coverage_comparison"]["comparison"] == "common_coverage"
assert her["coverage_comparison"]["layer_aliases_applied"] == {"Narayana_AD": "Narayana_MD_AD"}
full2 = _alias_row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}, [])
short_product = _alias_row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_MD_AD"])
product = _adjudicate([full2, short_product])
assert product["coverage_comparison"]["comparison"] == "common_coverage"
assert "layer_aliases_applied" not in product["coverage_comparison"]
def test_a_second_gating_layer_blocks_the_alias() -> None:
full = _alias_row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}, [])
short = _alias_row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_AD", "D9"])
result = _adjudicate([full, short])
assert result["coverage_comparison"]["comparison"] == "not_reducible"
assert "layer_aliases_applied" not in result["coverage_comparison"]
def test_the_product_spelling_for_only_the_antardasha_stays_unreducible() -> None:
left = _alias_row("12:00", {"e1": 2, "e2": 2}, [])
right = _alias_row("12:01", {"e1": 2, "e2": 1}, ["Narayana_AD"])
result = _adjudicate([left, right])
# 产品的 Narayana_AD 意思是「这件事仍计分、只缺小运那一项」:不能套对照表。
assert result["coverage_comparison"]["comparison"] == "not_reducible" or (
result["coverage_comparison"].get("unreducible_layers") == ["Narayana_AD"]
)
# --- 真实形状:引擎行上确实带 contributions,且与非空分值对得上 ---
def test_real_engine_rows_carry_contributions_that_add_up_to_the_score() -> None:
request = {
**NEUTRAL_BIRTH_PAYLOAD,
"birth_date": "1990-01-01",
"start_time": "12:00",
"end_time": "12:03",
"events": [
{"id": "e1", "domain": "career", "date": "2015-06", "precision": "month", "description": "synthetic"},
{"id": "e2", "domain": "relationship", "date": "2017-09", "precision": "month", "description": "synthetic"},
{"id": "e3", "domain": "finance", "date": "2019-02", "precision": "month", "description": "synthetic"},
],
}
rows = compute_event_candidate_rows(request)
assert rows
for row in rows:
contributions = row["contributions"]
assert contributions, "every candidate row records its per-layer contributions"
scored = round(sum(item["points"] for item in contributions if item["points"] is not None), 4)
assert scored == row["score"], (scored, row["score"])
# layer_points 与 contributions 一一对应(同一件事、同一层)。
from_points = {(event_id, layer) for event_id, layers in row["layer_points"].items() for layer in layers}
from_contributions = {
(item["event_id"], item["layer"]) for item in contributions if item["points"] is not None
}
assert from_points == from_contributions, (sorted(from_points), sorted(from_contributions))
def test_real_engine_rows_expose_the_planned_layer_set() -> None:
request = {
**NEUTRAL_BIRTH_PAYLOAD,
"birth_date": "1990-01-01",
"start_time": "12:00",
"end_time": "12:01",
"events": [
{"id": "e1", "domain": "career", "date": "2015-06", "precision": "month", "description": "synthetic"},
],
}
row = compute_event_candidate_rows(request)[0]
layers = {item["layer"] for item in row["contributions"]}
assert "dasha_varga_core" in layers
core = next(item for item in row["contributions"] if item["layer"] == "dasha_varga_core")
assert core["dependency"][:3] == ["Vimshottari_MD_AD_PD", "Narayana_MD", "Narayana_AD"]
assert isinstance(core["decomposable"], bool)
# --- FIX-3:排除之后要按剩下的共同覆盖比较(真实形状行) ---
def _units_row(time: str, units: dict[str, dict[str, float]], *,
missing: list[str] | None = None,
indecomposable: tuple[str, str] | None = None) -> dict:
"""真实形状行:layer_points 与 contributions 一一对应;`indecomposable=(event, reason)` 标拆不开的那一项。"""
score = round(sum(sum(layers.values()) for layers in units.values()), 4)
evidence = [
{"event_id": event_id, "domain": DOMAINS[int(event_id[1:]) - 1], "candidate_time": time,
"rule_ids": ["synthetic"], "points": round(sum(layers.values()), 4)}
for event_id, layers in units.items()
]
contributions = []
for event_id, layers in units.items():
for layer, points in layers.items():
flag = indecomposable is not None and layer == "dasha_varga_core" and event_id == "e5"
contributions.append(_contribution(
event_id, layer, points,
decomposable=not flag,
reason=indecomposable[1] if flag else None,
))
return {
"time": time, "score": score, "evidence": evidence,
"missing_layers": list(missing or []),
"layer_points": {event_id: dict(layers) for event_id, layers in units.items()},
"contributions": contributions,
}
CORE = {"dasha_varga_core": 2.0, "controlled_transit": 0.5}
def test_indivisible_dasha_is_excluded_and_the_rest_is_compared() -> None:
full = _units_row("12:00", {"e1": CORE, "e2": CORE})
short = _units_row("12:01", {"e1": CORE, "e2": CORE, "e5": CORE},
missing=["Narayana_AD"], indecomposable=("e5", "Narayana_AD_unresolved"))
result = _adjudicate([full, short])
comparison = result["coverage_comparison"]
assert comparison["comparison"] == "common_coverage", comparison
assert comparison["excluded_contributions"] == [
{"event_id": "e5", "layer": "dasha_varga_core", "reason": "md_ad_not_decomposable"},
]
assert "unreducible_layers" not in comparison
# 共同覆盖里 e5 的那一层已被拿掉,两侧都按 e1、e2 的剩余单元计分。
assert comparison["common_scores"] == [
{"time": "12:00", "score": 5.0},
{"time": "12:01", "score": 5.0},
]
assert comparison.get("comparable_tied") is True or result["comparable_leader"] is not None
def test_a_second_missing_layer_keeps_it_unreducible_but_reports_the_exclusion() -> None:
full = _units_row("12:00", {"e1": CORE, "e2": CORE})
short = _units_row("12:01", {"e1": CORE, "e2": CORE, "e5": CORE},
missing=["Narayana_AD", "D9"], indecomposable=("e5", "Narayana_AD_unresolved"))
result = _adjudicate([full, short])
comparison = result["coverage_comparison"]
assert comparison["comparison"] == "not_reducible"
# 第二个缺失层让这一处差异说不清,所以仍是 not_reducible;但排除清单照常输出。
assert comparison["unreducible_layers"]
assert comparison["excluded_contributions"] == [
{"event_id": "e5", "layer": "dasha_varga_core", "reason": "md_ad_not_decomposable"},
]
def test_legacy_rows_never_report_exclusions() -> None:
left = _row("12:00", {"e1": 2, "e2": 2}, [])
right = _row("12:01", {"e1": 2, "e2": 2}, ["Narayana_AD"])
result = _adjudicate([left, right])
assert "excluded_contributions" not in result["coverage_comparison"]
def test_negative_contributions_still_count_after_exclusion() -> None:
negative = {"dasha_varga_core": -1.0, "controlled_transit": 0.5}
full = _units_row("12:00", {"e1": CORE, "e2": negative})
short = _units_row("12:01", {"e1": CORE, "e2": negative, "e5": CORE},
missing=["Narayana_AD"], indecomposable=("e5", "Narayana_AD_unresolved"))
result = _adjudicate([full, short])
comparison = result["coverage_comparison"]
assert comparison["comparison"] == "common_coverage"
# e1: 2.5 + e2: -0.5 = 2.0;负分没有被抹掉,也没有被当成 0。
assert [item["score"] for item in comparison["common_scores"]] == [2.0, 2.0]