Merge #227 report birth window from chart-choice adoption (BUG-1865)
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m16s
Independent Staging Quality Gate / validate-python (push) Successful in 6m58s
Independent Staging Quality Gate / publish (push) Canceled after 2m46s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXozsiu43ob7B8UZCmDM
This commit is contained in:
2026-11-13 08:48:59 +08:00
co-authored by Claude Opus 5.5
19 changed files with 592 additions and 47 deletions
+7
View File
@@ -1,5 +1,12 @@
# BLOCKED
## BUG-1865 · 选盘保存的计算时刻可能落在所选区间外(#227,2026-11-13)
- ~~旧流程区间缺少采纳凭据。~~ 修订任务书已明确优先读取档案的选盘采纳记录,并限定旧流程的凭据。
- ~~报告需明确怎样处理区间外的计算时刻。~~ 第二份修订任务书已授权报告侧回退。选盘服务保存时刻的问题转 #229。
- 替代证据:现有合成样本复现默认选择与手动选侧两条路径。隔离 PostgreSQL 17 用现行采纳函数复现了档案与选盘记录都保存区间外时刻。详见 [#227 进度](docs/tasks/PROGRESS-reading-rectified-window-20261113.md)。
- 解除:#227 待验收报告侧回退,#229 跟踪选盘保存。
## BUG-1862 · 模型稿回放(#219,2026-11-13)
- ~~模型稿待回放。~~ Claude 已回放,结果见 [#219 修复单](docs/tasks/FIX-reading-claim-binding-1.md)。修复后的重新生成与回放由独立验收执行。
+5
View File
@@ -10,6 +10,11 @@
- 出生分钟未确认时,个人报告用填报的时间范围核对各分盘上升。误差未知时按前后各 30 分钟。必需分盘在范围内换座的结论暂不能判断。
- 沿用当前 Skill 版本(BUG-1864)。
## 2026-11-13 — 个人报告优先使用已采纳的选盘区间
- 个人报告按已采纳且包含计算时刻的选盘区间核对分盘。选盘时刻落在所选侧之外时,报告保留原计算时刻并改用填写范围或默认范围。
- 出生时间范围及分盘向前、向后的换座距离由系统生成说明。沿用当前 Skill 版本(BUG-1865)。
## 2026-11-12 — 个人报告补充事实核对与依据清单
- 逐节核对宫主与落宫、标准 SAV 总和、阻碍宫及具体健康风险,并拦截没有依据的数值准确率说法。
+16
View File
@@ -25172,3 +25172,19 @@
- 防复发:分别核对边界行的状态、两侧误差及来源,并验证临界分盘只影响依赖它的结论。
- 关联记录:#224、#144、BUG-1858、BUG-1848。
- 修复版本:`codex/reading-birth-window-20261113`,待发布。
## BUG-1865 | 报告未按可核对的采纳区间计算出生时间误差
- 状态:fixed-pending-verify(#227 报告侧待独立验收,选盘保存另见 #229)。
- 复查:修订任务书已明确选盘采纳凭据。合成样本又复现了选盘保存的计算时刻可早于所选侧起点。报告无法据此生成一致的前后误差。
- 首次发现 / 最近更新:2026-11-13 / 2026-11-13。
- 影响面:个人报告的出生资料来源、时间误差范围与证据等级。
- 现象:报告附录能读到校正区间,解读仍可用默认误差范围。将当前候选区间直接作为采纳区间,会把旧流程中待确认的范围用于证据判断。
- 触发条件:报告读取一个带候选起止的旧流程 case,状态为 `completed`,候选仍为 `pending_validation`。
- 根因:`read_report_candidate_range` 的旧流程分支同时读取 `completed` 和 `confirmed`,只返回起止时间,与新流程已采纳普通区间同形。报告的误差范围逻辑原先只读填写记录。
- 验证:隔离 PostgreSQL 17 按当前 RPC 定义核对合成记录,待确认旧区间、已确认旧区间和新流程已采纳普通区间的返回值一致;新流程仅候选就绪时返回空。详见 `docs/tasks/PROGRESS-reading-rectified-window-20261113.md`。
- 第二次验证:用现行选盘引擎生成合成采纳结果,默认选择和手动选侧均复现;隔离 PostgreSQL 执行现行 v2、v3 采纳函数,确认不一致的时刻与所选侧同时落库。
- 修复:报告使用选盘采纳凭据和实际计算日期、时刻,按秒核对所选侧。区间外的时刻保留原值,时间误差改用填写范围或默认值,并记录拒用原因。事实包生成来源和换座方向说明。
- 防复发:补充报告入口的采纳来源与当前计算时刻绑定回归。保持候选范围读取的权限边界(BUG-526)。
- 关联记录:BUG-1864、BUG-568、BUG-526、BUG-982、BUG-983。
- 修复版本:`codex/reading-rectified-window-20261113`,待发布。
@@ -0,0 +1,33 @@
# #227 需拍板答复:生时纠正区间从选盘页的采纳记录取,不走旧接口(2026-11-13,Claude)
本文件补充 `TASK-reading-rectified-window-20261113.md`,两者冲突时以本文件为准。
## 结论
你的诊断是对的:`read_report_candidate_range` 分不清「待确认」和「已采纳」,不能直接用。但现在的生时纠正(11-06 改版,BUG-1644/48/49/54,选盘页)本来就不走这个接口。采纳时,`chart_choice_adopt_v2/v3` 会写档案:
- `birth_time_status = 'accepted'`,`active_birth_time` 等于 `decision.saved_at`;
- `active_birth_provenance`,内容为 `contract: "chart-choice-v1"`、`window`(`start_at`/`end_at`)、`line_at`、`line_charts`、`chosen_side`、`both_versions`、`adopted_at` 等,完整字段见 `frontend/src/lib/chart-choice/server.ts::adoptChartChoice`。
这份记录本身就是「已采纳、对应当前出生资料」的凭据。写入声明范围时会清掉旧的采纳(`guard_adopted_birth_date` / `chart_profiles_drop_adopted_on_declaration`)。
**授权的做法,取值按以下顺序:**
1. **选盘页采纳**,`source = "rectified_range"`。条件:`birth_time_status` 为 `accepted` 或 `confirmed`,且 `active_birth_provenance.contract == "chart-choice-v1"`。
- 有 `line_at` 时,区间取所选一侧:`chosen_side == "before"` 为 `window.start_at` 到 `line_at`;`after` 为 `line_at` 到 `window.end_at`。
- 没有 `line_at` 时,取整个 `window`。这对应选盘结果为 `certain`,即窗口内不换盘。
- 前误差、后误差都相对 `active_birth_time` 计算。`active_birth_time` 不在区间内的,按需拍板处理,并在 PROGRESS 里写明。
- `window.label_zh` 写成「按生时纠正选定的区间 HH:MM–HH:MM(前 X 分钟、后 Y 分钟)」。
- 另外把 `line_charts` 和 `both_versions` 原样放进 `window`,例如 `resolved_line_charts` 和 `both_versions_domains`。只记录,不参与证据等级的计算。
2. **旧流程的已采纳区间**:只认 `adopted_credible_range` 非空的记录。授权对 `read_report_candidate_range` 做一个只读的小改动:返回值加 `range_source` 字段,取值为 `adopted_credible_range` 或 `candidate_range`,用一个新迁移文件,不改旧迁移。报告只在 `range_source == "adopted_credible_range"`、档案状态是 `accepted` 或 `confirmed`、并且 `rectification_case_id` 与档案一致时才使用。`candidate_range` 一律不用。如果改这个 RPC 牵涉的范围比预想大,这一项可以先不做,在 PROGRESS 写明,直接走第 3 项。
3. **填写时的范围**:`user_stated`、`shichen`、`period`,与 #224 相同。
4. **`default_unknown_30`**。
**哪些旧记录算已采纳:**只有上面第 1、2 项的情况。其余一律走填写范围或默认值,不猜。
## 验收补充
- 合成档案:`accepted` + `chart-choice-v1`,`window` 04:41–05:19,`line_at` 04:59:42,`chosen_side = "after"`,`active_birth_time` 05:00。期望结果:`source = rectified_range`,前约 0.3 分钟、后 19 分钟,`label_zh` 的内容与之对应。
- 同一个档案,若同时有 `declared_window_*`,以选盘页的采纳为准。
- `reported` 状态,或 `provenance` 不是 `chart-choice-v1` 时,走第 2、3、4 项。
- 原任务书里的 `label_zh` / `summary_zh` 和合同两句话,照原样要求。
@@ -0,0 +1,20 @@
# #227 第二次需拍板答复:本单只做报告侧回退,选盘保存的问题转 #229(2026-11-13,Claude)
本文件补充 `TASK-…` 与 `FIX-reading-rectified-window-1.md`,冲突时以本文件为准。
## 结论
你复现的问题是真的:`scripts/chart_choice/boundaries.py::representative_minute` 在所选一侧不足一个整分钟时(例如 04:59:43–05:00:00),会退到 04:59,落在分界线的另一侧。保存的时刻和用户选的一侧对不上,选盘页上「前后两版」的对比盘也可能是按错的一侧算的。
这是生时纠正模块自身的缺陷,**不在本单修**。已转给 #229(生时纠正按分盘边界切分)作为第一项具体缺陷。本单只做报告侧的防护:
1. 用选盘采纳的区间之前,先核对 `active_birth_time` 是否落在所选一侧的区间内,比较时精确到秒。
- 不在区间内:不用这个区间,退回到填写范围;没有填写范围就用默认 ±30。
- `window.source` 写 `user_stated` 或 `default_unknown_30`,并在 `birth_precision.window` 里加上 `rectified_range_rejected: "clock_outside_chosen_side"`,同时写进 PROGRESS。
2. 报告使用的计算时刻照旧是 `active_birth_time`,不得改动档案。
3. 其余按 FIX-1 执行。
## 验收补充
- 合成档案:所选一侧为 04:59:43–05:00:00,`active_birth_time` 为 04:59。结果应走填写范围或默认值,并带上 `rectified_range_rejected`。
- 合成档案:所选一侧为 04:59:42–05:19,`active_birth_time` 为 05:00。结果为 `rectified_range`。
@@ -0,0 +1,59 @@
# #227 报告出生时间范围诊断
- BUG-1865。执行 Codex,任务书来自 Claude。基线 `65fab6ebdfd6bc5c22324c6857af562097a99d3e`。
- 首轮状态:需拍板。命中任务书中「采纳了生时纠正」与「生时纠正还在进行中」无法从候选范围返回值区分的条件。
## 证据
- `20260720030000_conversational_rectification_transitions.sql` 保存候选范围的起止。`20260722190000_refund_unconfirmed_rectification.sql` 的 `complete_conversational_rectification_with_range` 可在候选仍为 `pending_validation` 时把旧流程 case 标记为 `completed`。
- `20260920020000_adopted_birth_date.sql` 的 `read_report_candidate_range` 优先读匹配的旧 case。它接受 `confirmed` 和 `completed`,两者都只返回 `start_time`、`end_time`。新流程已采纳的普通区间也返回相同形状。
- 报告 worker 对本人报告在分钟尚未确认时会请求候选范围。报告在采纳状态下使用 `active_birth_time`,即用户选中并保存的候选时刻。它可以与推断推荐的代表时刻不同。读取接口没有返回本次范围的采纳状态或与当前计算时刻对应的采纳记录,因此仅凭 `candidateRange` 无法保证两者匹配。
- 验证使用本机独立、无外部网络的 PostgreSQL 17 容器。按基线迁移原文加载该 RPC,配最小测试表和合成记录。四项断言通过:旧流程待确认记录返回区间,其 JSON 分别等于旧流程已确认记录和新流程已采纳记录,新流程仅候选就绪返回空。这是 RPC 查询复现,数据库迁移套件和应用端到端验收仍待实现后运行。
## 首轮拍板与答复
- 建议给报告读取链路提供与当前出生资料关联的采纳凭据。范围有采纳凭据时用于证据判断,其余情形走任务书的填写范围与默认范围。需明确旧流程哪些记录可认作已采纳,并确认是否授权扩展报告读取接口。
- 只用档案状态过滤,改动较小,但仍需核实返回区间确实对应本次采纳,尤其是旧 case 优先和存量记录。需要明确哪些旧记录可以回退到填写范围。
- [修订任务书](FIX-reading-rectified-window-1.md) 已指定选盘采纳记录为首选,并限定旧流程可用的凭据。
## 复查发现采纳时刻落在所选侧之外
- 用 `tests/test_chart_choice.py` 的虚构样本,把窗口终点设为填报分钟。现有 `decide_packet` 的默认平票选择和手动选择都选分界后。分界为 04:59:43,终点为 05:00,返回的 `saved_at` 却是 04:59,早于分界 43 秒。
- 当所选侧上端等于下一整分钟、分界在上一分钟内时,`representative_minute` 先向上取整,遇到上端再回退至上一整分钟。这里缺少回退后是否仍位于所选侧的核对。
- `adoptChartChoice` 把 `decision.saved_at` 写入档案,报告在 `accepted` / `confirmed` 下读这个时刻。它是选盘服务给所选侧的代表分钟。隔离 PostgreSQL 17 使用现行 `chart_choice_adopt_v2/v3` 和最小合成表,核对档案为 `accepted`、计算时刻早于已存分界、所选侧仍是 `after`、历史记录保存同一时刻。四项断言通过。
- 现有选盘测试 21 项通过。该复现命中修订任务书所列的停工条件。本轮提交诊断记录,报告实现与迁移待拍板。
## 第二次拍板前的提案
- 建议修正选盘保存逻辑,使新保存的代表分钟落在所选侧。对已保存的不一致记录,保留档案的计算时刻,报告经核对后回退至填写范围或默认范围。
- 若先做报告回退,可以避免用不一致的采纳区间给证据分级。选盘保存的问题可另行修复。
## 第二份修订任务书的报告侧实现
- [修订答复](FIX-reading-rectified-window-2.md) 将选盘保存交给 #229,并授权 #227 的报告回退。报告使用当前档案的采纳时间和有效日期。所选侧按秒核对,传给分级的分钟数保留三位小数,与分盘边界的精度一致。单点沿用前后各 1 分钟。
- 他人档案和重新采纳的历史记录通过既有 `chart_choice_records_v1` 读取当前记录。读取使用已解析的属主与对象,校验当前记录号、可重用状态和保存日期时刻与本次报告一致。历史接口无法返回匹配记录时走填写或默认范围。
- 计算时刻落在所选侧以外时,报告仍使用已存时刻,误差来自填写范围或前后各 30 分钟。`birth_precision.window.rectified_range_rejected` 为 `clock_outside_chosen_side`。附录的误差分钟数也用同一个有效范围。
- 旧流程采用 FIX-1 允许的回退。现有共享 RPC 优先按档案中的旧表 case ID 读旧记录,随后按用户取最新 agentic case,后者没有和档案 case ID 对应的关系。仅加 `range_source` 无法证明同一采纳。为补足关联还需改共享接口及调用方,本轮保留接口,报告的精度和误差数不用未绑定的旧候选范围。
- 事实包用 `label_zh` 说明来源,用每张分盘的 `summary_zh` 分开说明提前与推后的距离。搜索到上限仍未换座时写搜索范围内未换座。保留原始分盘边界数值与分级逻辑。选盘分界涉及的盘和两版领域只作为窗口资料保留。
| 原断言 | 新断言 | 原因 |
| --- | --- | --- |
| `test_report_birth_window_20261113.py` 比较原样时辰和已确认范围 | 相同数值和来源,另检查对应 `label_zh` | 事实包由代码给出固定的来源说明 |
| `test_report_reading_facts.py` 按原样窗口核对缓存结果 | 相同窗口,并核对该窗口的 `label_zh` | 确认缓存仍按窗口区分,也能返回正确文案 |
### 验证
- Python 定向 57 项通过,涵盖出生时间范围、事实包、证据等级、用途稳定性和现有选盘行为。
- 前端定向 69 项通过,取消 0,涵盖报告请求、分段生成、worker、存储和显示兼容。
- 本机真实 PostgreSQL 3 项通过。使用完整迁移链覆盖选盘采纳、历史复用及他人报告通过当前记录复现区间外回退。没有新增迁移。
- Windows 前端全量 3,682 项,3,654 通过、28 失败、0 取消。staging 基线 3,677 项,3,650 通过、27 失败、0 取消。测试名称无移除,新增 5 项全通过。额外的会话容量数据库用例在首次迁移准备时失败,单文件复跑通过。
- Python 快速门 1,462 项通过、2 跳过、4 失败。3 项 PyJHora 与 Windows 基线一致,额外的 `test_the_new_layer_leaves_every_existing_output_unchanged` VedAstro 差异单独复跑通过。
- 最终 TypeScript 与 Next 构建通过。首页 Static,首屏 JS gzip 515,860 字节、CSS gzip 90,906 字节,均与基线相同。
- ESLint 0 错误、62 条既有警告,隐私标记测试 62 项通过。
### 与 #219 合并后的验证
- PR #231 创建时,staging 已合入 #219(`b8da77f43`)。在执行分支合入该提交,解决 `BLOCKED.md` 冲突并保留两单的记录。报告合同同时保留出生时间来源与分盘边界文案规则和 #219 的逐段证据绑定。
- 前端定向 75 项通过,覆盖出生时间范围、worker 和逐段证据绑定。Python 定向 60 项和隐私 62 项通过。TypeScript、Next 构建和 ESLint 通过,首页保持 Static,首屏 JS/CSS gzip 大小仍与开工基线相同。
- 前端全量 3,688 项,3,661 通过、27 失败、0 取消。失败名称与开工的 Windows 基线逐项一致。新增 11 项通过,其中 #227 新增 5 项,#219 新增 6 项。上次全量曾出现的会话容量用例本次通过。
- Python 快速门首轮在构建并行更新 `.next` 时中断。构建结束后复跑,1,463 项通过、2 跳过、3 项 PyJHora 失败,与开工基线一致。上次出现的 VedAstro 差异本次通过。
@@ -0,0 +1,78 @@
# TASK:报告的出生时间误差优先用生时纠正得到的区间,其次用填写时选的范围,最后才用 ±30 分钟(2026-11-13)
- Gitea:#227
- 分支:`codex/reading-rectified-window-20261113`,基于 staging `65fab6ebdfd6bc5c22324c6857af562097a99d3e`
- Bug 编号:开工时取 `docs/BUG_HISTORY.md` 末尾的下一个空号,在 PROGRESS 里写明。关联 BUG-1864(#224)。
- 验收:Claude(jyotisha-e6)
不得自行写「产品决定/裁定」。任务书没写到的取舍,一律选「需拍板」。
不得修改或删除既有断言来让测试通过。确需修改的,在 PROGRESS 里逐条写明原值、新值和原因。
占星师的引擎和资料(`scripts/jyotish_engine.py`、`scripts/yoga_engine.py`、`references/` 下她仓库已有的文件、`SKILL.md`)一律不改。产品差异只能放进单独的产品文件,并在 `references/product_runtime_contract.md` 公告(项目规则 2026-11-07)。
占星师回复原文:staging 上的 `docs/tasks/ref-astrologer-acceptance-reply-20261112.md`。下文的「她 §N」都指这份文件。
## 背景(产品负责人 2026-11-13 实测)
产品负责人的账号做过生时纠正,也存下了结果。新导出的报告里有三处矛盾:
- 附录「出生资料来源与不确定范围」写着「时间不确定范围(分钟):19」。这个数来自 `provenanceUncertaintyMinutes(row, candidateRange)`,也就是生时纠正采纳后的可信区间。
- 但解读写的是「出生时间由填报提供……报时窗取前后各 30 分钟」,证据等级也是按 ±30 分钟算的。
- 原因:#224 的 `readingBirthWindow`(`frontend/src/lib/personal-report-longform-birth.ts`)只读填写时的字段(`declared_window_*`、`uncertainty_*`、时辰、时段),没有读 `generatePersonalReportLongform` 手里已经拿到的 `candidateRange`(`read_report_candidate_range` 的结果)。这个账号的来源是旧选项 `family_exact`,填写时也没有给范围,所以落到了默认 ±30。生时纠正、填写信息、报告三个模块没有接起来。这是 #224 任务书漏写的,不是执行错。
**产品负责人的要求:**
1. 做过生时纠正的,按生时纠正得到的时间和区间来算。
2. 没做生时纠正的,按填写出生信息时选的误差区间来算。
3. 两者都没有,才用 ±30 分钟。
## 要做的
1. **确定误差区间,按以下优先级取值**,写进 `birth_time_window` 的 `source` 字段:
1. `rectified_range`:`candidateRange` 存在时使用。
- 普通区间:前误差 = 计算时刻 − 起点,后误差 = 终点 − 计算时刻(跨午夜按现有 `uncertaintyFromDeclaredRange` 的规则处理)。
- 有 `candidate_intervals` 时,取第一段起点到最后一段终点。另外把各段原样放进 `intervals` 字段,以后可以逐段检查边界。
- 计算时刻取报告实际使用的时刻(生时纠正采纳后的 `active_birth_time`)。在 PROGRESS 里写明:这个时刻是不是代表时刻,是否一定落在区间内。不在区间内的,选需拍板。
- 区间只有一分钟(起点等于终点)的,维持现状:按已确认到分钟处理,±1 分钟。
2. `user_stated` / `shichen` / `period`:保持 #224 的现有逻辑。
3. `default_unknown_30`。
2. **Python 端**:`report_birth_window` 的合法来源加上 `rectified_range`。`birth_precision.window` 原样保留 `intervals`。
3. **解读能写对来源**:事实包 `birth_precision.window` 加一个中文说明字段 `label_zh`,由代码固定生成,不交给模型拼。例如:
- 「按生时纠正的可信区间 04:51–05:09(前 9 分钟、后 9 分钟)」
- 「按填写时给的范围(前 10 分钟、后 20 分钟)」
- 「没有误差信息,按前后各 30 分钟」
在产品合同 report-reading 块里加一句:写出生时间精度时,照抄 `birth_precision.window.label_zh`,不得改写成别的来源。这一句之外,合同不改。
4. **边界分钟数的方向**:样稿把「向后 147 分钟才换座」读成了「延伸到 147 分钟、整段都不稳」。
- `birth_precision.ascendant_margins` 每张分盘加 `summary_zh`,由代码生成,例如:「出生时间提前 0.3 分钟上升就换座;推后 147 分钟才换座」。
- 有区间时,再加一句结论:「区间内会换座」或「区间内不换座」。
- 合同里同一处加一句:引用分盘边界时照抄 `summary_zh`。
## 不要碰
- `scripts/report_render/evidence_grade.py` 的边界判断逻辑。它只读 `window`,取值来源变了,逻辑本身不用改。
- `frontend/src/lib/personal-report-reading.ts`(#219 在改)。
- 生时纠正本身的计算和存储、聊天证据卡、冻结文件。
## 验收标准(新测试)
1. 采纳区间 04:51–05:09、计算时刻 05:00 → `window` 为前 9、后 9,`source` 为 `rectified_range`。同一账号同时有填写范围(例如前 30、后 30)时,仍以生时纠正为准。
2. 没有采纳区间、有填写范围 → `user_stated`,行为与 #224 相同。
3. 两者都没有 → `default_unknown_30`。
4. 有 `candidate_intervals` → 用第一段起点和最后一段终点,`intervals` 原样保留。
5. `label_zh`、`summary_zh` 的中文与上面的例子一致,前后方向不颠倒。
6. 改动的旧测试按惯例写明原值、新值和原因。#224、#215、#216 的测试全部通过。
## 自测命令
```
python3 -m pytest -q tests/test_report_birth_window_20261113.py tests/test_report_evidence_grade_20261112.py tests/test_reading_facts_v3_20261112.py tests/test_report_reading_facts.py
python3 scripts/run_quality_gate.py --profile quick --skip-frontend-runtime
cd frontend && npx tsx --test tests/personal-report-birth-window-20261113.test.ts tests/personal-report-longform*.test.ts && npx tsc --noEmit -p . && npx eslint .
```
## 何时停下来选「需拍板」
- 生时纠正采纳的计算时刻不在采纳区间内。
- `read_report_candidate_range` 对「采纳了生时纠正」和「生时纠正还在进行中」返回的结构分不开。
@@ -3,6 +3,7 @@ import {
} from "./server-owned-birth-profile";
import { uncertaintyFromDeclaredRange } from "./birth-time-intake-model";
import { declaredClockRangeFromProfile, isBirthClockText, isShichenId, SHICHEN_RANGES } from "./declared-birth-window";
import { asRecord } from "./guards";
export function utcToday(now = new Date()): string {
return now.toISOString().slice(0, 10);
@@ -16,24 +17,7 @@ function accountText(row: unknown, key: string): string | undefined {
return trimmed.length > 0 ? trimmed : undefined;
}
function clockToMinutes(value: string): number | null {
const match = /^(\d{2}):(\d{2})$/.exec(value);
if (!match) return null;
return Number.parseInt(match[1], 10) * 60 + Number.parseInt(match[2], 10);
}
export function provenanceUncertaintyMinutes(
row: unknown,
candidateRange: { start_time: string; end_time: string; candidate_intervals?: readonly Readonly<{ start_at: string; end_at: string }>[] } | null,
): number | undefined {
if (candidateRange?.candidate_intervals) {
return candidateRange.candidate_intervals.reduce((total, part) => total + (Date.parse(part.end_at + "Z") - Date.parse(part.start_at + "Z")) / 60_000, 0);
}
if (candidateRange) {
const start = clockToMinutes(candidateRange.start_time);
const end = clockToMinutes(candidateRange.end_time);
if (start !== null && end !== null) return Math.max(0, end - start);
}
function provenanceUncertaintyMinutes(row: unknown): number | undefined {
if (!row || typeof row !== "object" || Array.isArray(row)) return undefined;
const record = row as Record<string, unknown>;
const before = typeof record.uncertainty_before_minutes === "number"
@@ -76,6 +60,50 @@ function readingBirthWindow(profile: Readonly<Record<string, unknown>>, clock: s
: undefined;
}
function localTimestamp(value: unknown): { text: string; millis: number } | null {
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?$/.test(value)) return null;
const millis = Date.parse(value + "Z");
return Number.isFinite(millis) && new Date(millis).toISOString().slice(0, value.length) === value
? { text: value, millis } : null;
}
function rectifiedReadingWindow(profile: Record<string, unknown>, date: string, clock: string) {
if (profile.birth_time_status !== "accepted" && profile.birth_time_status !== "confirmed") return null;
const provenance = asRecord(profile.active_birth_provenance);
if (provenance?.contract !== "chart-choice-v1") return null;
const window = asRecord(provenance.window);
let start = localTimestamp(window?.start_at);
let end = localTimestamp(window?.end_at);
const active = localTimestamp(`${date}T${clock}`);
if (!start || !end || !active || end.millis < start.millis) return null;
if (provenance.line_at != null) {
const line = localTimestamp(provenance.line_at);
if (!line || line.millis < start.millis || line.millis > end.millis) return null;
if (provenance.chosen_side === "before") end = line;
else if (provenance.chosen_side === "after") start = line;
else return null;
}
if (active.millis < start.millis || active.millis > end.millis) {
const declared = readingBirthWindow(profile, clock);
return {
before_minutes: declared?.before_minutes ?? 30,
after_minutes: declared?.after_minutes ?? 30,
source: declared ? "user_stated" : "default_unknown_30",
rectified_range_rejected: "clock_outside_chosen_side",
} as const;
}
// The grading inputs and ascendant distances both use thousandths of a minute.
return {
before_minutes: Math.round((active.millis - start.millis) / 60) / 1_000,
after_minutes: Math.round((end.millis - active.millis) / 60) / 1_000,
source: "rectified_range",
start_at: start.text,
end_at: end.text,
...(Array.isArray(provenance.line_charts) ? { resolved_line_charts: provenance.line_charts } : {}),
...(Array.isArray(provenance.both_versions) ? { both_versions_domains: provenance.both_versions } : {}),
} as const;
}
export function buildLongformBirthPayload(
row: unknown,
extras: Readonly<{
@@ -99,10 +127,12 @@ export function buildLongformBirthPayload(
return null;
}
const year = Number.parseInt(dateMatch[1], 10);
const readingMinuteConfirmed = extras.readingMinuteConfirmed ?? extras.birthTimeAccuracy === "confirmed";
const birthWindow = !readingMinuteConfirmed && row && typeof row === "object"
? readingBirthWindow(row as Record<string, unknown>, timeMatch[0])
: undefined;
const account = asRecord(row);
const rectified = account && rectifiedReadingWindow(account, dateMatch[0], timeMatch[0]);
const readingMinuteConfirmed = rectified
? rectified.source === "rectified_range" && rectified.before_minutes === 0 && rectified.after_minutes === 0
: extras.readingMinuteConfirmed ?? extras.birthTimeAccuracy === "confirmed";
const birthWindow = rectified ?? (!readingMinuteConfirmed && account ? readingBirthWindow(account, timeMatch[0]) : undefined);
return {
year,
month: Number.parseInt(dateMatch[2], 10),
@@ -118,7 +148,7 @@ export function buildLongformBirthPayload(
today: extras.today,
target_year: extras.targetYear,
age: extras.targetYear - year,
birth_time_accuracy: extras.birthTimeAccuracy,
birth_time_accuracy: rectified && readingMinuteConfirmed ? "confirmed" : extras.birthTimeAccuracy,
...(readingMinuteConfirmed ? {} : { reading_minute_confirmed: false }),
...(birthWindow ? { birth_time_window: birthWindow } : {}),
...(extras.candidateRange ? { candidate_range: extras.candidateRange } : {}),
@@ -126,6 +156,6 @@ export function buildLongformBirthPayload(
coordinate_source: "user_reported",
coordinate_precision: "unverified_user_coordinates",
time_source: accountText(row, "birth_time_source") ?? accountText(row, "birth_time_status") ?? undefined,
uncertainty_minutes: provenanceUncertaintyMinutes(row, extras.candidateRange),
uncertainty_minutes: birthWindow ? birthWindow.before_minutes + birthWindow.after_minutes : provenanceUncertaintyMinutes(row),
};
}
@@ -199,7 +199,7 @@ export async function generatePersonalReportLongform(
: null;
const rangeProvisional = range && (range.candidate_intervals || range.start_time !== range.end_time);
// A single calculation clock does not certify the birth minute for the reading.
const readingMinuteConfirmed = !rangeProvisional && (deps.birthTimeStatus === "confirmed" || deps.birthTimeStatus === "accepted");
const readingMinuteConfirmed = !rangeProvisional && deps.birthTimeStatus === "confirmed";
const payload = buildLongformBirthPayload(deps.profile, {
today,
targetYear: Number(today.slice(0, 4)),
@@ -1,9 +1,43 @@
import { resolveMissingBirthTimezoneOffset } from "./birth-profile-timezone.ts";
import { asRecord } from "./guards.ts";
import { resolveReportBirthClock } from "./personal-report-route-core.ts";
import { PersonalReportWorkerError } from "./personal-report-worker-core.ts";
import { stampReportBirthFingerprint } from "./report-birth-binding.ts";
import { globalBirthProfileFromAccountRow } from "./server-owned-birth-profile.ts";
import { ConsultationSubjectError, loadSubjectBirth } from "./subject-birth.ts";
async function readCurrentChartChoice(client: unknown, userId: string, subjectId: string, row: unknown) {
const rpcClient = client as { rpc?: (name: string, args: Record<string, unknown>) =>
PromiseLike<{ data: unknown; error: unknown }> };
if (typeof rpcClient.rpc !== "function") return null;
try {
const { data, error } = await rpcClient.rpc("chart_choice_records_v1", {
p_user_id: userId,
p_chart_profile_id: subjectId === "self" ? null : subjectId,
});
const history = asRecord(data);
if (error || typeof history?.current_record_id !== "string" || !Array.isArray(history.records)) return null;
const active = globalBirthProfileFromAccountRow(row);
const currentId = history.current_record_id;
const record = history.records.map(asRecord).find((entry) =>
entry && entry.id === currentId && entry.reusable === true
&& entry.saved_date === active.date && entry.saved_time === active.time);
const detail = asRecord(record?.detail);
if (!record || !detail?.window) return null;
const line = asRecord(detail.line);
return {
contract: "chart-choice-v1",
window: detail.window,
line_at: line?.at,
line_charts: line?.charts,
chosen_side: record.chosen_side,
both_versions: asRecord(detail.decision)?.both_versions_domains,
};
} catch {
return null;
}
}
export async function loadReportWorkerProfile(client: unknown, userId: string, subjectId: string): Promise<unknown> {
try {
const resolved = await loadSubjectBirth(client, userId, subjectId);
@@ -21,6 +55,14 @@ export async function loadReportWorkerProfile(client: unknown, userId: string, s
if (error) throw new PersonalReportWorkerError("profile_incomplete", true);
row = { ...row, rectification_case_id: data?.rectification_case_id ?? null };
}
const provenance = asRecord(row.active_birth_provenance);
const adopted = row.birth_time_status === "accepted" || row.birth_time_status === "confirmed";
if (adopted && !provenance?.window && (resolved.role === "other" || provenance?.contract === "chart-choice-v1")) {
// Other subjects' direct service-role projection excludes provenance.
// Reused choices also keep only a pointer to the active history record.
const choice = await readCurrentChartChoice(client, userId, resolved.subjectId, row);
if (choice) row = { ...row, active_birth_provenance: choice };
}
// The cover binding fingerprint is taken from the stored row, before the fill.
return stampReportBirthFingerprint(resolved.row, await resolveMissingBirthTimezoneOffset(row, { useActiveDate: true }));
} catch (error) {
@@ -6,6 +6,7 @@ import test from "node:test";
import { closeLocalPostgresDataPool, createLocalPostgresDataClient } from "../src/lib/db/local-postgres-client-core.ts";
import { loadReportWorkerProfile } from "../src/lib/personal-report-worker-subject.ts";
import { buildLongformBirthPayload } from "../src/lib/personal-report-longform-birth.ts";
import { CHART_SUBJECT_SELECT } from "../src/lib/subject-birth.ts";
import { startPostgresFixture, type PostgresFixture } from "./helpers/postgres-fixture.ts";
@@ -58,6 +59,27 @@ test("service_role can read another person's chart profile for a report", {
const loaded = await loadReportWorkerProfile(admin, owner, subjectId) as { name?: string };
assert.equal(loaded.name, "虚构乙");
const adopted = await admin.rpc("chart_choice_adopt_v3", {
p_user_id: owner, p_chart_profile_id: subjectId, p_time: "07:59:00", p_date: "1990-01-01", p_offset: 8,
p_provenance: { contract: "chart-choice-v1", source: "user_choice", chosen_side: "after" },
p_window_start: null, p_window_end: null, p_before_minutes: null, p_after_minutes: null,
p_detail: {
window: { start_at: "1990-01-01T07:45", end_at: "1990-01-01T08:00" },
line: { at: "1990-01-01T07:59:43", charts: ["D10"] },
decision: { both_versions_domains: [] },
},
});
assert.equal(adopted.error, null);
const adoptedProfile = await loadReportWorkerProfile(admin, owner, subjectId);
const payload = buildLongformBirthPayload(adoptedProfile, {
today: "2026-11-13", targetYear: 2026, candidateRange: null, birthTimeAccuracy: "confirmed",
});
assert.equal(payload?.minute, 59);
assert.deepEqual(payload?.birth_time_window, {
source: "default_unknown_30", before_minutes: 30, after_minutes: 30,
rectified_range_rejected: "clock_outside_chosen_side",
});
for (const column of CHART_SUBJECT_SELECT.split(",")) {
assert.equal(
fixture.psql(`select has_column_privilege('service_role', 'public.chart_profiles', '${column}', 'select')`),
@@ -48,3 +48,92 @@ test("a selected calculation clock inside a declared shichen or period uses the
assert.deepEqual(request({ birth_time_source: "period_only", birth_time_period: "afternoon", reported_birth_time: "16:00" }).birth_time_window,
{ before_minutes: 240, after_minutes: 119, source: "period" });
});
const choice = {
contract: "chart-choice-v1",
window: { start_at: "2000-01-01T04:41", end_at: "2000-01-01T05:19" },
line_at: "2000-01-01T04:59:42",
chosen_side: "after",
line_charts: ["D2", "D10"],
both_versions: ["career"],
};
const adopted = {
birth_time_status: "accepted", active_birth_time: "05:00:00",
active_birth_provenance: choice,
};
test("the adopted side takes precedence over declared bounds and uses the saved minute", () => {
const payload = request({ ...adopted, declared_window_start: "04:30", declared_window_end: "05:30" }, true);
assert.equal(payload.hour, 5);
assert.equal(payload.minute, 0);
assert.equal(payload.reading_minute_confirmed, false);
assert.equal(payload.uncertainty_minutes, 19.3);
assert.deepEqual(payload.birth_time_window, {
before_minutes: 0.3, after_minutes: 19, source: "rectified_range",
start_at: "2000-01-01T04:59:42", end_at: "2000-01-01T05:19",
resolved_line_charts: ["D2", "D10"], both_versions_domains: ["career"],
});
assert.deepEqual(request({
...adopted, active_birth_time: "04:50",
active_birth_provenance: { ...choice, chosen_side: "before" },
}).birth_time_window, {
before_minutes: 9, after_minutes: 9.7, source: "rectified_range",
start_at: "2000-01-01T04:41", end_at: "2000-01-01T04:59:42",
resolved_line_charts: ["D2", "D10"], both_versions_domains: ["career"],
});
assert.equal((request({
...adopted, active_birth_provenance: { ...choice, line_at: "2000-01-01T04:59:43" },
}).birth_time_window as { before_minutes: number }).before_minutes, 0.283);
});
test("rejecting an out-of-side saved minute keeps the minute and falls back", () => {
const invalid = {
...adopted, active_birth_time: "04:59",
active_birth_provenance: { ...choice, line_at: "2000-01-01T04:59:43",
window: { ...choice.window, end_at: "2000-01-01T05:00" } },
};
const declared = request({ ...invalid, declared_window_start: "04:45", declared_window_end: "05:00" }, true);
assert.equal(declared.hour, 4);
assert.equal(declared.minute, 59);
assert.equal(declared.reading_minute_confirmed, false);
assert.deepEqual(declared.birth_time_window, {
before_minutes: 14, after_minutes: 1, source: "user_stated",
rectified_range_rejected: "clock_outside_chosen_side",
});
assert.deepEqual(request(invalid, true).birth_time_window, {
before_minutes: 30, after_minutes: 30, source: "default_unknown_30",
rectified_range_rejected: "clock_outside_chosen_side",
});
});
test("a certain choice spans the dated window across midnight and a point keeps minute confirmation", () => {
const overnight = request({
...adopted, active_birth_time: "00:00", active_birth_date: "2000-01-02", active_birth_timezone_offset: 0,
active_birth_provenance: { contract: "chart-choice-v1", window: { start_at: "2000-01-01T23:51", end_at: "2000-01-02T00:09" } },
});
assert.equal(overnight.day, 2);
assert.deepEqual(overnight.birth_time_window, {
before_minutes: 9, after_minutes: 9, source: "rectified_range",
start_at: "2000-01-01T23:51", end_at: "2000-01-02T00:09",
});
const point = request({
...adopted,
active_birth_provenance: { contract: "chart-choice-v1", window: { start_at: "2000-01-01T05:00", end_at: "2000-01-01T05:00" } },
});
assert.equal(point.reading_minute_confirmed, undefined);
assert.equal(point.birth_time_accuracy, "confirmed");
});
test("reported and legacy profiles use intake bounds without treating candidate bounds as adopted", () => {
const intake = { uncertainty_before_minutes: 10, uncertainty_after_minutes: 20 };
for (const row of [
{ ...adopted, ...intake, birth_time_status: "reported" },
{ ...adopted, ...intake, active_birth_provenance: { contract: "dated-v1" } },
]) {
const payload = buildLongformBirthPayload({ ...SYNTHETIC, ...row }, {
...REQUEST, readingMinuteConfirmed: false, candidateRange: { start_time: "04:51", end_time: "05:09" },
});
assert.deepEqual(payload?.birth_time_window, { before_minutes: 10, after_minutes: 20, source: "user_stated" });
assert.equal(payload?.uncertainty_minutes, 30);
}
});
@@ -416,6 +416,33 @@ test("queued report worker passes only persisted other birth data to the fake en
assert.equal(harness.report?.chartProfileId, OTHER_ID);
});
test("the report worker recovers only the active reusable chart-choice record for an owned subject", async () => {
const row = { ...typedOther, birth_time_status: "accepted", active_birth_date: typedOther.birth_date,
active_birth_time: "07:40:00", active_birth_timezone_offset: 8 };
const active = {
id: "active", reusable: true, saved_date: row.active_birth_date, saved_time: "07:40", chosen_side: "after",
detail: {
window: { start_at: "1988-03-04T07:30", end_at: "1988-03-04T07:55" },
line: { at: "1988-03-04T07:39:30", charts: ["D9"] },
decision: { both_versions_domains: ["relationship"] },
},
};
let current = active;
const client = { ...subjectClient(row), async rpc(name: string, args: Record<string, unknown>) {
assert.equal(name, "chart_choice_records_v1");
assert.deepEqual(args, { p_user_id: USER_ID, p_chart_profile_id: OTHER_ID });
return { error: null, data: { current_record_id: "active", records: [{ ...active, id: "other" }, current] } };
} };
const profile = await loadReportWorkerProfile(client, USER_ID, OTHER_ID) as Record<string, unknown>;
assert.deepEqual(profile.active_birth_provenance, {
contract: "chart-choice-v1", window: active.detail.window, line_at: active.detail.line.at,
line_charts: ["D9"], chosen_side: "after", both_versions: ["relationship"],
});
current = { ...active, saved_time: "07:41" };
const stale = await loadReportWorkerProfile(client, USER_ID, OTHER_ID) as Record<string, unknown>;
assert.equal(stale.active_birth_provenance, undefined);
});
test("deleted or foreign report subject fails terminally and releases reservation without owner fallback", async () => {
for (const row of [null, { ...typedOther, user_id: "foreign-owner" }]) {
const harness = createHarness({
+1
View File
@@ -289,6 +289,7 @@ evidence_card.backstage records, for the backend only, that global web evidence
- 现在这几年:写明实际覆盖哪几年。行运只是 observation_date 那一天的位置,不外推成几个月或几年的结论;时间粒度由证据决定。
- 几条建议:两到四条,每条只能落在前面已经有依据的主题上。只是一般性的建议,就写明「一般建议」,不装成星盘算出来的结论;不从数值门槛推出具体作息时刻、贷款或资产安排。
- 依据与边界:功能吉星、功能凶星及与自然吉凶的冲突;实际用到的技法;没有使用的层及原因(按 participation 的 state 和 reason_code 写:not_routed 是路由把它分给了别的领域;not_in_domain_route 是占星师这一领域的必查模块没有列它,带 computed 的已经算出数值,要写「已算出,本报告不用它下结论」,不能说参考资料里没有、没有来源或没有计算;not_computed 才是没有计算);参数敏感的层;出生时间精度与 birth_precision 里接近边界的分盘;岁差、交点、宫制。
写出生时间精度时,照抄 birth_precision.window.label_zh,不得改写成别的来源。引用分盘边界时,照抄该分盘的 summary_zh。
<!-- 产品规则,不是占星师的方法:R-04 证据等级。她 §1.3–1.4、§5.2,合同 report_evidence_grade_v1。 -->
九节逐段区分判断和纯事实。判断段填写 claims 和 grade,claims 至少一类。evidence_grades.claims 列出各类的上限 cap(A 最高,D 最低)及 required、checked。混合多类判断可拆段,也可合写并取最严格的上限。refs 可选,列出主要依据即可,只能从所列各类的 required 和 checked 并集中取。正文点名的层由系统按 dependency_catalog 自动绑定到这些结论允许的依赖,并计入等级判断。引用的依赖缺失、未评估或在时间误差范围内跨边界,等级只能是 D。判断段提到四位年份、数字连写的月份、大运、小运、次小运或窗口时,claims 必须含 timing_window。总评和建议只能引用本稿性格、事业、财富、感情、健康、现在这几年六节已经分级的判断,沿用其中最严格的等级。只复述盘面事实、交代方法或给一般操作说明时,填 kind 为 fact,正文不夹带「意味着」「适合」等推断,省略 claims、grade 和 refs。
等级含义:C 是有星盘来源和可计算的依据、还没有经过案例校准;D 是这条结论需要的关键依据缺失或无法判别。D 的段落只写缺了什么、暂不能判断,不写结果。不要在正文里写「置信度:」或「证据等级:」,等级由页面显示。must_disclose 里的缺口和参数敏感的层要在相关段落里说出来。只有某类结论的必需依据全部可用时,才能说它「没有关键阻塞」。
@@ -45,10 +45,23 @@ def _margin(longitude_at, division, direction, cap_seconds):
)
if change is not None:
return round(abs(change) / 60, 3)
return cap_seconds / 60
return None
def ascendant_margins(birth: dict, divisions: set[int], *, search_minutes: float = 0) -> dict:
def _margin_summary_zh(before: float | None, after: float | None, cap: float, window: dict) -> str:
earlier = (f"出生时间提前 {before:g} 分钟上升就换座" if before is not None
else f"出生时间提前 {cap:g} 分钟内上升未换座")
later = (f"推后 {after:g} 分钟才换座" if after is not None
else f"推后 {cap:g} 分钟内未换座")
crosses = (
before is not None and 0 < window["before_minutes"] and before <= window["before_minutes"]
or after is not None and 0 < window["after_minutes"] and after <= window["after_minutes"]
)
conclusion = "区间内会换座" if crosses else "区间内不换座"
return f"{earlier};{later}。{conclusion}。"
def ascendant_margins(birth: dict, divisions: set[int], *, window: dict) -> dict:
"""Return distances in minutes, searching strictly past the report window."""
try:
natal = datetime.fromisoformat(f"{birth['date']}T{birth['time']}")
@@ -60,6 +73,7 @@ def ascendant_margins(birth: dict, divisions: set[int], *, search_minutes: float
hour_ut = _birth_hour_decimal(natal.hour, natal.minute, natal.second) - tz
natal_jd = swe.julday(natal.year, natal.month, natal.day, hour_ut)
# A capped distance is outside the tolerance, including for windows of 240 minutes or more.
search_minutes = max(window["before_minutes"], window["after_minutes"])
cap_seconds = max(_CAP_SECONDS, (int(search_minutes * 60) // _STEP_SECONDS + 1) * _STEP_SECONDS)
@lru_cache(maxsize=None)
@@ -71,10 +85,14 @@ def ascendant_margins(birth: dict, divisions: set[int], *, search_minutes: float
return (cusps[0] - offset) % 360
with swiss_ephemeris_lock(), temporary_ayanamsa(ayanamsa, swe):
return {
f"D{division}": {
"before_minutes": _margin(longitude_at, division, -1, cap_seconds),
"after_minutes": _margin(longitude_at, division, 1, cap_seconds),
rows = {}
cap = cap_seconds / 60
for division in sorted(divisions):
before = _margin(longitude_at, division, -1, cap_seconds)
after = _margin(longitude_at, division, 1, cap_seconds)
rows[f"D{division}"] = {
"before_minutes": cap if before is None else before,
"after_minutes": cap if after is None else after,
"summary_zh": _margin_summary_zh(before, after, cap, window),
}
for division in sorted(divisions)
}
return rows
@@ -1,26 +1,79 @@
"""Birth-time tolerance used by the personal report's evidence grading."""
from datetime import datetime
from math import isfinite
import re
CONFIRMED_TOLERANCE_MINUTES = 1.0
DEFAULT_TOLERANCE_MINUTES = 30.0
WINDOW_POLICY = "birth_record_window_v1"
_DECLARED_SOURCES = {"user_stated", "shichen", "period"}
_DECLARED_SOURCES = {"user_stated", "shichen", "period", "rectified_range"}
_MAX_SIDE_MINUTES = 720
_LOCAL_AT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?\Z")
def _valid_side(value: object) -> bool:
return type(value) in (float, int) and 0 <= value <= _MAX_SIDE_MINUTES and isfinite(value)
def _local_at(value: object) -> bool:
if not isinstance(value, str) or not _LOCAL_AT.fullmatch(value):
return False
try:
datetime.fromisoformat(value)
except ValueError:
return False
return True
def _window_metadata(value: dict) -> dict:
metadata = {}
if _local_at(value.get("start_at")) and _local_at(value.get("end_at")):
metadata.update(start_at=value["start_at"], end_at=value["end_at"])
intervals = value.get("intervals")
if isinstance(intervals, list) and all(
isinstance(part, dict) and set(part) == {"start_at", "end_at"}
and _local_at(part["start_at"]) and _local_at(part["end_at"])
for part in intervals
):
metadata["intervals"] = intervals
for key in ("resolved_line_charts", "both_versions_domains"):
entries = value.get(key)
if isinstance(entries, list) and all(isinstance(entry, str) for entry in entries):
metadata[key] = entries
return metadata
def report_birth_window(value: object, *, minute_confirmed: bool) -> dict:
supplied = value if isinstance(value, dict) else {}
if minute_confirmed:
tolerance = CONFIRMED_TOLERANCE_MINUTES
return {"before_minutes": tolerance, "after_minutes": tolerance, "source": "confirmed_minute"}
if isinstance(value, dict):
before, after, source = value.get("before_minutes"), value.get("after_minutes"), value.get("source")
if isinstance(source, str) and source in _DECLARED_SOURCES and _valid_side(before) and _valid_side(after) and (before or after):
return {"before_minutes": before, "after_minutes": after, "source": source}
tolerance = DEFAULT_TOLERANCE_MINUTES
return {"before_minutes": tolerance, "after_minutes": tolerance, "source": "default_unknown_30"}
metadata = _window_metadata(supplied) if supplied.get("source") in ("rectified_range", "confirmed_minute") else {}
return {"before_minutes": tolerance, "after_minutes": tolerance, "source": "confirmed_minute", **metadata}
before, after, source = supplied.get("before_minutes"), supplied.get("after_minutes"), supplied.get("source")
if not (isinstance(source, str) and source in _DECLARED_SOURCES
and _valid_side(before) and _valid_side(after) and (before or after)):
before = after = DEFAULT_TOLERANCE_MINUTES
source = "default_unknown_30"
result = {"before_minutes": before, "after_minutes": after, "source": source}
if source == "rectified_range":
result.update(_window_metadata(supplied))
if source in ("user_stated", "default_unknown_30") and supplied.get("rectified_range_rejected") == "clock_outside_chosen_side":
result["rectified_range_rejected"] = "clock_outside_chosen_side"
return result
def birth_window_label_zh(window: dict) -> str:
source = window["source"]
before, after = window["before_minutes"], window["after_minutes"]
if source == "confirmed_minute":
return f"已确认到分钟,按前后各 {before:g} 分钟核对"
if source == "default_unknown_30":
return f"没有误差信息,按前后各 {before:g} 分钟"
label = "按填写时给的范围"
if source == "rectified_range":
label = "按生时纠正选定的区间"
if "start_at" in window and "end_at" in window:
label += f" {window['start_at'][11:16]}–{window['end_at'][11:16]}"
return f"{label}(前 {round(before, 3):g} 分钟、后 {round(after, 3):g} 分钟)"
+3 -3
View File
@@ -22,7 +22,7 @@ from datetime import date
from typing import Any
from .birth_precision_margins import ascendant_margins
from .birth_precision_window import report_birth_window
from .birth_precision_window import birth_window_label_zh, report_birth_window
from .evidence_grade import evidence_grades
from .parity_chapters import _VIMSOPAKA_DIGNITY
from .technique_status_axes import technique_audit_axes
@@ -841,8 +841,8 @@ def _birth_precision(full_reading: dict, view: dict, domains: dict, minute_confi
"minute_confirmed": minute_confirmed,
"purpose_stability": "not_evaluated",
"basis": "The purpose-specific interval contract (2026-11-09 interval_rectification handoff) is not integrated.",
"window": tolerance,
"ascendant_margins": ascendant_margins(birth, divisions, search_minutes=max(tolerance["before_minutes"], tolerance["after_minutes"])),
"window": {**tolerance, "label_zh": birth_window_label_zh(tolerance)},
"ascendant_margins": ascendant_margins(birth, divisions, window=tolerance),
}
+44 -1
View File
@@ -1,6 +1,7 @@
"""#224: grade report claims against the stated or default birth-time window."""
from scripts.professional_report_reference import _reading_request
from scripts.report_render.birth_precision_margins import _margin_summary_zh
from scripts.report_render.evidence_grade import evidence_grades
from scripts.report_render.reading_facts import _birth_precision
from tests.test_report_evidence_grade_20261112 import _facts
@@ -61,10 +62,11 @@ def test_shichen_request_reaches_facts_even_with_a_single_calculation_clock():
"birth_time_window": shichen})
assert request["minute_confirmed"] is False
precision = _birth_precision({}, {}, {}, request["minute_confirmed"], request["birth_time_window"])
assert precision["window"] == shichen
assert precision["window"] == {**shichen, "label_zh": "按填写时给的范围(前 40 分钟、后 79 分钟)"}
assert precision["purpose_stability"] == "not_evaluated"
assert _birth_precision({}, {}, {}, True, shichen)["window"] == {
"before_minutes": 1, "after_minutes": 1, "source": "confirmed_minute",
"label_zh": "已确认到分钟,按前后各 1 分钟核对",
}
@@ -84,3 +86,44 @@ def test_report_request_can_reuse_existing_asymmetric_minute_fields():
}
body["birth_time_uncertainty_known"] = False
assert _reading_request(body)["birth_time_window"]["source"] == "default_unknown_30"
def test_rectified_metadata_survives_request_and_facts_normalization():
intervals = [{"start_at": "2000-01-01T04:59:42", "end_at": "2000-01-01T05:19"}]
rectified = {
"source": "rectified_range", "before_minutes": 0.3, "after_minutes": 19,
**intervals[0], "intervals": intervals,
"resolved_line_charts": ["D2", "D10"], "both_versions_domains": ["career"],
}
request = _reading_request({"include_reading_facts": True, "birth_time_accuracy": "confirmed",
"reading_minute_confirmed": False, "birth_time_window": rectified})
assert request["birth_time_window"] == rectified
assert _birth_precision({}, {}, {}, False, request["birth_time_window"])["window"] == {
**rectified, "label_zh": "按生时纠正选定的区间 04:59–05:19(前 0.3 分钟、后 19 分钟)",
}
def test_rejected_rectified_range_stays_marked_for_intake_and_default():
for source, before, after, label in [
("user_stated", 14, 1, "按填写时给的范围(前 14 分钟、后 1 分钟)"),
("default_unknown_30", 30, 30, "没有误差信息,按前后各 30 分钟"),
]:
window = {"source": source, "before_minutes": before, "after_minutes": after,
"rectified_range_rejected": "clock_outside_chosen_side"}
request = _reading_request({"include_reading_facts": True, "birth_time_accuracy": "confirmed",
"reading_minute_confirmed": False, "birth_time_window": window})
assert _birth_precision({}, {}, {}, False, request["birth_time_window"])["window"] == {
**window, "label_zh": label,
}
def test_margin_summary_distinguishes_the_two_directions_and_search_cap():
assert _margin_summary_zh(0.3, 147, 240, {"before_minutes": 0.3, "after_minutes": 19}) == (
"出生时间提前 0.3 分钟上升就换座;推后 147 分钟才换座。区间内会换座。"
)
assert _margin_summary_zh(0.3, 147, 240, {"before_minutes": 0, "after_minutes": 19}) == (
"出生时间提前 0.3 分钟上升就换座;推后 147 分钟才换座。区间内不换座。"
)
assert _margin_summary_zh(None, 19, 240, {"before_minutes": 5, "after_minutes": 19}) == (
"出生时间提前 240 分钟内上升未换座;推后 19 分钟才换座。区间内会换座。"
)
+4 -2
View File
@@ -260,10 +260,12 @@ def test_reading_birth_window_is_part_of_the_report_cache_key(stubbed, monkeypat
reading_minute_confirmed=False)
windows = [{"before_minutes": 40, "after_minutes": 79, "source": "shichen"},
{"before_minutes": 0, "after_minutes": 20, "source": "user_stated"}]
for window in (*windows, windows[-1]):
labels = ["按填写时给的范围(前 40 分钟、后 79 分钟)",
"按填写时给的范围(前 0 分钟、后 20 分钟)"]
for window, label in zip((*windows, windows[-1]), (*labels, labels[-1])):
result = build_professional_report_reference(handler, {**body, "birth_time_window": window}, engine=engine)
facts = result["reading_facts"]
assert facts["minute_confirmed"] is False
assert facts["birth_precision"]["window"] == window
assert facts["birth_precision"]["window"] == {**window, "label_zh": label}
assert facts["evidence_grades"]["precision_policy"] == "birth_record_window_v1"
assert handler.calls == 2