Compare commits

...
Author SHA1 Message Date
jesse-ux 42b9f44963 Reject out-of-range event dates and record validation
Independent Staging Quality Gate / validate-python (pull_request) Successful in 6m55s
Independent Staging Quality Gate / validate-frontend (pull_request) Successful in 7m38s
Independent Staging Quality Gate / publish (pull_request) Skipped
Refs #241, BUG-1875
2026-11-13 14:44:05 +08:00
jesse-ux ff2ba338c0 Merge remote-tracking branch 'origin/staging' into codex/chart-choice-questions-20261113
# Conflicts:
#	BLOCKED.md
#	CHANGELOG.md
#	docs/BUG_HISTORY.md
#	docs/tasks/README.md
2026-11-13 14:36:51 +08:00
jesse-ux 2c87c6b1dc Add dated evidence to multi-round chart choice
Refs #241, BUG-1875
2026-11-13 14:36:26 +08:00
ClaudeandClaude Opus 5.5 feb305fc1f Merge #240 reading timeout 240s with deadline-aware retry (BUG-1874)
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m11s
Independent Staging Quality Gate / validate-python (push) Successful in 6m40s
Independent Staging Quality Gate / publish (push) Successful in 3m22s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXozsiu43ob7B8UZCmDM
2026-11-13 14:24:54 +08:00
ClaudeandClaude Opus 5.5 a5c25b8282 docs(tasks): #241 decision — no D6/D8 event questions until astrologer defines them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXozsiu43ob7B8UZCmDM
2026-11-13 13:45:19 +08:00
jesse-ux f1048e375d Record chart-choice event mapping blocker
Refs #241, BUG-1875
2026-11-13 13:44:01 +08:00
ClaudeandClaude Opus 5.5 46b6fc249e docs(tasks): brief for #241 chart-choice-questions (on #238)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXozsiu43ob7B8UZCmDM
2026-11-13 13:15:10 +08:00
17 changed files with 658 additions and 37 deletions
+6
View File
@@ -1,5 +1,11 @@
# BLOCKED
## #241 · D6、D8 事件类别待占星师定义
- ~~D6、D8 缺少事件评分映射,暂停 #241。~~ 修订任务书放行 D9、D10、D2 的事件题。D6、D8 照常参与选线,只使用补充题。
- 占星师待回答的问题:D6 的日常压力或冲突、D8 的非医疗突变或重大转折,各适用哪些宫位和行星?现有纠纷和重大失落类别使用 D30。
- 替代证据:用虚构分界线验证两侧可取得 Vimshottari AD/PD 和 Narayana MD/AD。现有选盘与占星师测试通过。见 [#241 进度](docs/tasks/PROGRESS-chart-choice-questions-20261113.md)。
## #240 · Windows 门禁与公开盘复核
- Docker Desktop 的 Linux 引擎返回 HTTP 500,容器用例无法在本机验证。目录预检扫描超时。生产模型对两张公开盘的实跑留给独立验收。
+4
View File
@@ -1,5 +1,9 @@
# 印度占星 Skill 更新日志
## 2026-11-13 — 多轮选盘按已发生的事件核对候选段
- 选盘接口可为感情、工作和财务提供有时段依据的事件题,逐轮保留日期与判边依据。少于三件有日期的事时,结果只给倾向。页面由 #239 接入,沿用当前 Skill 版本(BUG-1875)。
## 2026-11-13 — 个人报告解读可等待较慢的模型返回
- 单次解读等待上限从 120 秒增至 240 秒。剩余时间不足一次完整重试时,报告保留第一稿中通过检查的内容。沿用当前 Skill 版本(BUG-1874)。
+13
View File
@@ -25269,3 +25269,16 @@
- 防复发:锁定两次尝试上限、起算点、跳过原因、快照结果及脱敏日志字段。
- 关联记录:#240、#220、BUG-1863。详见 [执行进度](tasks/PROGRESS-reading-timeout-20261113.md)。
- 修复版本:`codex/reading-timeout-20261113`,待发布。
## BUG-1875 | 多轮选盘缺少分界线事件题与判边依据
- 状态:fixed-pending-verify(修订范围待独立验收)。
- 首次发现 / 最近更新:2026-11-13 / 2026-11-13。
- 影响面:多轮选盘事件题、跨轮日期清单和最终候选段依据。
- 现象:已有分界线性格对比,多轮结果的事件清单为空。任务书要求对部分换盘线增加按年龄段选择的事件题。
- 触发条件:选盘范围内存在关键分盘换座线,用户需要依据事件来确认所选一侧。
- 根因:原多轮流程只复用了性格对比和票数判定,事件评分和日期只在独立占星师流程。
- 修复:D9、D10、D2 以已有事件类别从两侧实际时段生成事件题。D1 增加外表和胎记。逐轮保留答案与判边来源,最终仅评分候选段内的时刻。D6、D8 事件评分待占星师定义,当前用补充题。
- 验证及防复发:覆盖有与无可区分时段、D1 问题范围、日期跨轮、平分兜底、候选段内评分和三件事件门槛。见 [#241 进度](tasks/PROGRESS-chart-choice-questions-20261113.md)。
- 关联记录:#229、#238、#241、BUG-405、BUG-1703、BUG-1759、BUG-1872。
- 修复版本:`codex/chart-choice-questions-20261113`,待发布。
@@ -0,0 +1,13 @@
# #241 需拍板答复:D6、D8 本轮不出事件题(2026-11-13,Claude)
本文件补充任务书,冲突时以本文件为准。
**结论:本轮只给 D9、D10、D2 出事件题。D6、D8 的线只出补充题(#238 已写的日常说法),不新增事件类别。**
原因:D6、D8 的事件类别要用哪些宫位和行星属于占星方法。她的事件表里没有定义,最接近的两个类别打分用的是 D30。按项目规则,产品不能自己发明她的方法。
处理:
1. D6、D8 的线照常按 #238 的顺序排进轮次。这些线的问题只有补充题。判边用补充题分数(每题 0.5)加上现有的 `decide()` 兜底,规则不变。
2. 在 PROGRESS 和产品合同 G 节写明:「D6、D8 的生时纠正事件题待占星师定义宫位与行星;在此之前只用补充题。」这条另外整理成问题,交给占星师。
3. 结果页「六张盘」里,靠补充题定下的 D6、D8,要和靠事件定下的分开记录(例如 `decided_by: "supplement"`),页面单可以据此显示。
@@ -0,0 +1,23 @@
# #241 分界线事件题与判边进度
- 执行者 Codex。可信规划评论 42921 指向 staging `92ef755c6e3ea1a70d89f834b0f27f4f3c013586`,分支首个任务书提交为 `46b6fc249e6f5dc7468aed954a672bd447757276`。
- `_minute_row` 为每侧生成 Vimshottari 时间线和 Narayana MD/AD。既有浮点拆分可以取得 AD/PD 边界,`_dasha_score` 可在同一时段采样两侧,`_varga_score` 提供类别分盘的静态得分。在一条虚构 D9 分界线上已验证这些层均可取得。对婚恋开始类别抽查的日期中,两侧的大运分数相同,此样本不能据此声称存在可出题时段。
- `EVENT_CATEGORIES` 已有 D9 感情、D10 工作和 D2 财务的类别。D6、D8 可计算,但事件表没有相应条目。现有纠纷、重大失落均取 D30,且会触发 D30 路由。直接改其定义会影响旧占星师入口。另加类别则需要明确该类别的宫位和行星,才能复用原评分函数。
- 建议为多轮流程指定 D6 日常压力或冲突、D8 突变或重大转折的独立非医疗类别,确认每类评分对应的分盘、宫位与行星。也可先放行 D9、D10、D2 事件题,D6、D8 保留原补充题,等类别确定再接入。
- `python -m pytest -q tests/test_chart_choice.py tests/test_chart_choice_astrologer.py` 通过 45 项。预检的 Python、目录扫描、外部适配器和 Gitea 可见性通过,既有 `.workbuddy` 历史镜像路径断言失败。本轮为任务书冲突诊断,评分代码与产品合同尚未变更。
## 按修订任务书实施
- 评论 42948 与 [修订任务书](FIX-chart-choice-questions-1.md) 放行 D9、D10、D2。发布前同步 staging `feb305fc1f5520db166a23fec53db55b27e0a34c`,保留 #240 的报告修复和共享文档。D6、D8 的生时纠正事件题待占星师定义宫位与行星。在此之前只用补充题。待占星师回答的问题记在 [BLOCKED](../../BLOCKED.md)。
- 每条线最多两道事件题。两侧使用同一组 Vimshottari AD/PD 与 Narayana MD/AD 边界,比较已支持的时段,按现有强匹配口径找一侧强、另一侧无大运激活且总分差为正的窗口。两侧缺失的大运层不相同时跳过对应时段。两侧没有不重叠的年龄段时省略该题。真实引擎的虚构盘探测同时覆盖了可出题和无区分度两种情况。
- `event_questions` 给出 `id`、`before_ages`、`after_ages`、选项和 `follow_up`。日期追问接受 `YYYY` 或 `YYYY-MM`,事件类别来自该题的 `follow_up.categories[].value`。财务用三个选项表达已有两个类别。两段都有时各提交一个日期。月份和年份只需与所选年龄段相交。否定和记不清仍保留在回答里。
- `POST /api/chart-choice/adopt` 可传 `event_answers`、`appearance`、`birthmarks`,旧 `answers` 继续用于补充题。示例为 `event_answers: {"D9":{"choice":"before","dates":{"before":{"date":"2020","category":"relationship"}}}}`。同样的三个字段可跟随每条 `decision.resolved` 原样回传。服务端重算问题、日期和判边,返回累计 `events`,并保存在 v2 provenance。D1 才有外表和胎记,胎记每侧最多加 1 分。补充题标 `optional: true`。
- 新版每轮返回 `scores`、`sources` 和 `decided_by`,供 #239 标注依据。分值采用任务书的产品规则,现有占星评分权重和阈值保持。最后一段用现有 `score_minute`、`engine_confidence` 和 `coverage`,只对段内分钟评分。段内没有整分钟时取段内中点。少于三件独立日期事件时返回 `tendency_only`。结果保留原回测说明。
- 旧 v1 行为和独立占星师入口保留。页面和报告接入由 #239 完成。
## 验证
- 50 项 Python 选盘与占星师定向测试通过,基线 45 项。另用实际引擎的虚构盘复验 D9 出题、日期跨轮和最终段评分。20 项前端选盘定向与 20 项 API 降级和咨询定向通过。
- TypeScript 与生产构建通过,ESLint 0 error、62 条既有 warning。首页仍为静态,HTML 直接引用的 JS 494476 B、CSS 90906 B(gzip),与基线一致。
- Windows 前端同配置对比 3693 项,3610 通过、46 失败、37 跳过、0 取消。测试名单与基线相同,45 项失败逐条相同,额外一项咨询时钟用例定向复跑通过。Docker HTTP 500,容器用例按原条件跳过。
- Python 快速门运行至 pytest,1475 项通过、2 项跳过、29 项子测试通过、3 项失败。失败名称与 Windows staging 基线相同,均为 Kaala / PyJHora 校验。最后一次日期边界修正和 staging 同步后另跑选盘与占星师定向。
+1
View File
@@ -33,6 +33,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| [#241 修订任务书](FIX-chart-choice-questions-1.md) | [执行进度](PROGRESS-chart-choice-questions-20261113.md) | 多轮选盘事件题与判边(BUG-1875) | 待验收 | `codex/chart-choice-questions-20261113` |
| [#240 任务书](TASK-reading-timeout-20261113.md) | [执行进度](PROGRESS-reading-timeout-20261113.md) | 报告解读超时与租期内重试(BUG-1874) | 待验收 | `codex/reading-timeout-20261113` |
| [#238 任务书](TASK-chart-choice-rounds-engine-20261113.md) | [执行进度](PROGRESS-chart-choice-rounds-engine-20261113.md) | 多轮选盘与秒级采纳(BUG-1872) | 待验收 | `codex/chart-choice-rounds-engine-20261113` |
| [#237 任务书](TASK-reading-window-edge-20261113.md) | [执行进度](PROGRESS-reading-window-edge-20261113.md) | 个人报告区间端点换座判定(BUG-1871) | 待验收 | `codex/reading-window-edge-20261113` |
@@ -0,0 +1,99 @@
# TASK:合并流程的出题与判边:每条线按「年龄段 + 具体事件」出题,D1 线加外表和胎记,结果给出依据与把握(2026-11-13)
- Gitea:#241(父单 #229)
- 分支:`codex/chart-choice-questions-20261113`,基于 staging(#238 已合入)。
- Bug 编号:BUG-1875
- 验收:Claude(jyotisha-e6)
不得自行写「产品决定/裁定」;任务书没写的取舍一律选「需拍板」。不得修改或删除既有断言来让测试通过;确需修改的,写明原值、新值和原因。
## 补充:产品负责人 2026-11-13 已同意合并方案(以本节为准)
画布:https://claude.ai/artifact/XcxXXAfHEyAmhWbxGGbEW7 ,父单 #229 的规划评论里也有文字版。选盘和占星师方法合成一条流程:
1. 时间范围
2. 找关键换盘线
3. 逐处确认,最多 3 处
4. 结果是候选时间段
5. 「用这个时间段继续」
三处拍板:
- 每处的主问题是「某个年龄段有没有发生某件事」,即她的 A–D 四档;性格对比降为可跳过的补充。
- 外表、胎记只在主盘 D1 上升换座时问。
- 有日期的事少于 3 件时,结果只写「倾向」,不给把握等级。
问哪条线的顺序按她的决策树:D1 → D9 → D10 → D2/D6/D8。不再按「离填写时刻最近」。
本任务书里与上面冲突的地方,一律按本节执行。
## 背景
合并以前有两套流程:
- **选盘**:每条线给两版盘的性格描述,问「更像哪一种」(`readings.py::build_question`)。
- **占星师方法**:`scripts/chart_choice/astrologer.py`。先做 A/B/C/D 问卷,再收外表、胎记,再收至少 5 件有日期的事,最后整段扫描打分。
她上游最新的写法(yinduzhanxing `8aaf6099`,`skills/jyotish-birth-time-rectification/references/interview_playbook.md` 的「Main-repository override: candidate-first interview」一节):
- 先算候选差异,再选问题。
- 问具体事件类别;**只有在实际算出的时间依据支持时**,才给具体时段。
- 用户认出事件之后,才问确切日期。
- 不能把「有 5 件有日期的事」当成开场任务。
- 接受「没有」「时间不对」「不确定」三种回答,否定的回答也要保留。
## 要做的(只改 `scripts/chart_choice/` 及其测试、API 路由的出入参)
1. **每条线的事件题。** 对 #238 选出的那条线:
- 取线两侧代表时刻的盘(#238 已修过的、落在各自一侧内的时刻)。
- 对这条线翻转的每个关键分盘,按领域映射到 `EVENT_CATEGORIES` 的类别:D9 → 感情 / 婚姻,D10 → 工作,D2 → 收入 / 财务,D6 → 日常压力 / 冲突,D8 → 突变 / 重大转折。D6、D8 的题面用日常说法,不涉及疾病和身体部位,题面要能直接显示给用户。
- 用她现有的大运打分(`_dasha_score` / `_varga_score` 那一套,现成函数直接复用,不新写评分),在 15 岁到今天之间,按 AD/PD 粒度找出「两侧激活程度差得最多」的时段:一侧明显激活、另一侧不激活。每侧最多取 1 段,换算成年龄段(例如 25–27 岁)。
- 题面形如:「感情上的大变化,线前多落在 X–Y 岁,线后多落在 P–Q 岁。你哪一段有过恋爱开始、分开或结婚?」
- 选项:X–Y 岁有 / P–Q 岁有 / 两段都有 / 两段都没有 / 记不清。
- 两侧找不到有区分度的时段时,不出这类题。这种情况要记进 PROGRESS,不得编造年龄段。
- 每条线的事件题最多 2 道。
2. **追问日期。** 选了某段「有」,接着问:
- 大概哪一年(必填一个年份,月份可选);
- 是哪种事(按类别给 3–4 个选项,例如感情:开始恋爱 / 结婚 / 分开 / 其他)。
答案按 `parse_events` 现有的格式进入事件清单(`events`),在多轮之间累积。前端会把清单带在 `resolved` 请求里,格式由你定,写进 contract。
3. **D1 线的外表和胎记。** 只有这条线翻转 D1 时才问:
- 外表:用 `appearance_options` 现有的表,只列线两侧这两个上升的描述,外加「说不清」;
- 胎记:用现有的 13 个部位,可多选,有「没有」。
其他线一律不问这两题。
4. **补充的性格对比。** 沿用 `readings.py` 的对比文字和「更像哪一种」,标记为 `optional: true`,前端放在折叠里。
5. **判边规则**(每条线;在 `decision.py` 旁新增一个函数,原函数不改):
- 事件题:选中某侧年龄段,给那一侧 +2;「两段都有」两侧各 +1;「两段都没有」「记不清」0 分。
- 外表题:选中的那侧 +1。胎记:用 `_birthmark_supported` 判断,支持哪侧就给哪侧 +1。
- 性格对比:每答一题,选中的那侧 +0.5。
- 一侧比另一侧至少多 2 分,选这一侧,`rule = "evidence"`。否则沿用现有 `decide()` 的「保留填写那一侧 / 中性时按多数」,`rule` 照旧。
- 分数和每一项的来源都放进返回结果,前端要显示「依据」。
- 这些分值是产品规则,**不是**她的方法。在 PROGRESS 里写明,并在 `references/product_runtime_contract.md` 的 G 节公告区追加一段「生时纠正判边规则(产品)」,写明原值、新值和原因。
6. **结果的依据和把握。** 最终段确定后:
- 用现有的 `score_minute`、`engine_confidence`、`coverage` 对**最终段内**的分钟和累积的事件清单打分。
- 给出:提到几件事;几件和这一段的大运对上(`matched` 的口径照她的打分);她的把握分级。
- 有日期的事少于 3 件时,不给把握分级,`confidence = "tendency_only"`,前端显示「倾向」。
- 回测说明(`astrologer.py` 里现有的 19/20/34 那句)原样附在结果里。
7. **旧入口。** `/api/chart_choice/astrologer` 的独立流程保留,但前端会去掉入口(#239)。本单不删它,只在 docstring 里写明「合并后由多轮流程调用其中的函数」。
## 不要碰
- 她的打分权重和阈值
- `astrologer_engine.py`
- 冻结文件
- 前端(#239 负责)
## 验收(新测试)
1. 合成一条 D9 线:两侧算出的年龄段不同,题面、选项正确;选「X–Y 岁有」并填年份后,事件进入清单。
2. 两侧找不到有区分度的时段:不出事件题,只出补充题。
3. 只有 D1 线才出外表、胎记题;D10 线不出。
4. 判边:事件题选线后、外表选线前、两道补充题都选线前 → 线后 +2,线前 +1 +1 = +2,差距不到 2,按现有规则判;把分数和来源都核对一遍。
5. 有日期的事 2 件 → `tendency_only`;4 件 → 返回她的分级。
6. #238 的测试和现有选盘测试全部通过;Python 快速门通过。
## 何时停下来选「需拍板」
- 她的大运打分无法按侧、按时段给出可比较的激活度。
- D6、D8 的事件题绕不开医疗含义。
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { chartChoiceCaller, chartChoiceErrorResponse, resolvedSchema, windowSchema } from "@/lib/chart-choice/route-support";
import { chartChoiceCaller, chartChoiceErrorResponse, evidenceInput, resolvedSchema, windowSchema } from "@/lib/chart-choice/route-support";
import { adoptCertainTime, adoptChartChoice, previewChartChoice } from "@/lib/chart-choice/server";
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
@@ -19,6 +19,7 @@ const bodySchema = z.object({
overrideSide: side.optional(),
readBothAll: z.boolean().optional(),
rangeChosen: z.boolean().optional(),
...evidenceInput,
}).strict();
/**
+57 -10
View File
@@ -1,13 +1,40 @@
/**
* Chart choice: shared client/server shapes.
*
* Mirrors scripts/chart_choice/service.py. The engine never scores life
* events (BUG-1091). It describes both sides of the selected line and applies
* fixed rules to the user's own answers.
* Mirrors scripts/chart_choice/service.py, including optional dated evidence
* in multi-round chart choice.
*/
export type ChartChoiceSide = "before" | "after";
export type ChartChoiceAnswer = ChartChoiceSide | "unsure";
export type ChartChoiceDatedEvent = { readonly date: string; readonly category: string };
export type ChartChoiceEventChoice = ChartChoiceAnswer | "both" | "neither";
export type ChartChoiceEvidenceInput = {
readonly event_answers?: Readonly<Record<string, {
readonly choice: ChartChoiceEventChoice;
readonly dates?: Readonly<Partial<Record<ChartChoiceSide, ChartChoiceDatedEvent>>>;
}>>;
readonly appearance?: ChartChoiceAnswer;
readonly birthmarks?: readonly string[];
};
type ChartChoiceEvidence = {
readonly scores?: Readonly<Record<ChartChoiceSide, number>>;
readonly sources?: readonly {
readonly kind: "event" | "appearance" | "birthmark" | "supplement";
readonly id?: string;
readonly choice?: string;
readonly before: number;
readonly after: number;
}[];
readonly decided_by?: "event" | "appearance" | "supplement" | "reported" | "override";
};
type ChartChoiceEvidenceSummary = {
readonly event_count: number;
readonly matched: number;
readonly confidence: "tendency_only" | "high" | "medium" | "low" | "none";
readonly coverage: { readonly level: "thin" | "usable" | "strong" };
readonly caveat: string;
};
export type ChartChoiceWindow = { readonly start_at: string; readonly end_at: string };
export type ChartChoiceResolved = {
@@ -15,7 +42,7 @@ export type ChartChoiceResolved = {
readonly side: ChartChoiceSide;
readonly answers?: Readonly<Record<string, ChartChoiceAnswer>>;
readonly override_side?: ChartChoiceSide;
};
} & ChartChoiceEvidenceInput;
export type ChartChoiceLine = { readonly at: string; readonly degree: number; readonly charts: readonly string[] };
export type ChartChoiceRound = {
readonly line_at: string;
@@ -23,12 +50,13 @@ export type ChartChoiceRound = {
readonly chosen_side: ChartChoiceSide;
readonly rule: string;
readonly votes: ChartChoiceDecision["votes"];
};
} & ChartChoiceEvidence;
export type ChartChoiceRoundResult = {
readonly segment: ChartChoiceWindow;
readonly rounds: readonly ChartChoiceRound[];
readonly undetermined_charts: readonly string[];
readonly events: readonly unknown[];
readonly events: readonly ChartChoiceDatedEvent[];
readonly evidence_summary?: ChartChoiceEvidenceSummary;
readonly remaining_key_lines: number;
readonly has_next: boolean;
readonly resolved: readonly ChartChoiceResolved[];
@@ -64,9 +92,24 @@ export type ChartChoiceQuestion = {
readonly chart: string;
readonly label: string;
readonly prompt: string;
readonly optional?: boolean;
readonly options: readonly { readonly value: ChartChoiceAnswer; readonly text: string }[];
};
type ChartChoiceOption<T extends string> = { readonly value: T; readonly text: string };
type ChartChoiceEventQuestion = {
readonly id: string;
readonly chart: string;
readonly before_ages: readonly [number, number];
readonly after_ages: readonly [number, number];
readonly prompt: string;
readonly options: readonly ChartChoiceOption<ChartChoiceEventChoice>[];
readonly follow_up: {
readonly prompt: string;
readonly categories: readonly (ChartChoiceOption<string> & { readonly id: string })[];
};
};
type PacketBase = {
readonly engine_version: string;
readonly window: ChartChoiceWindow;
@@ -78,6 +121,7 @@ type PacketBase = {
readonly ordered_lines?: readonly ChartChoiceLine[];
readonly segment?: ChartChoiceWindow;
readonly resolved?: readonly ChartChoiceResolved[];
readonly events?: readonly ChartChoiceDatedEvent[];
readonly resume?: ChartChoiceResolved;
};
@@ -101,6 +145,9 @@ export type ChartChoicePacket =
readonly comparisons: readonly ChartChoiceComparison[];
readonly unchanged: readonly { readonly chart: string; readonly label: string }[];
readonly questions: readonly ChartChoiceQuestion[];
readonly event_questions?: readonly ChartChoiceEventQuestion[];
readonly appearance_question?: { readonly prompt: string; readonly options: readonly ChartChoiceOption<ChartChoiceAnswer>[] };
readonly birthmark_question?: { readonly prompt: string; readonly multiple: true; readonly options: readonly ChartChoiceOption<string>[] };
});
export type ChartChoiceEnginePacket = ChartChoicePacket
@@ -108,12 +155,12 @@ export type ChartChoiceEnginePacket = ChartChoicePacket
export type ChartChoiceDecision = {
readonly chosen_side: ChartChoiceSide;
readonly rule: "majority" | "tie_keeps_reported" | "strong_override" | "reported_kept" | "user_override";
readonly rule: "majority" | "tie_keeps_reported" | "strong_override" | "reported_kept" | "user_override" | "evidence";
readonly votes: { readonly before: number; readonly after: number; readonly unsure: number } | null;
readonly both_versions_domains: readonly string[];
readonly both_versions: readonly { readonly domain: string; readonly label: string }[];
readonly saved_at: string;
} & Partial<ChartChoiceRoundResult>;
} & Partial<ChartChoiceRoundResult> & ChartChoiceEvidence;
/** What the page shows before any engine call: the declared range, or a prompt to give one. */
export type ChartChoiceStart =
@@ -145,7 +192,7 @@ export type ChartChoiceRecordDetail = {
readonly votes: ChartChoiceDecision["votes"];
readonly both_versions_domains: readonly string[];
readonly saved_at: string;
} & Partial<ChartChoiceRoundResult>;
} & Partial<ChartChoiceRoundResult> & ChartChoiceEvidence;
/** Labels of the flipped charts with both sides' ascendant, in comparison order. */
readonly charts: readonly { readonly chart: string; readonly label: string; readonly domain: string }[];
};
@@ -176,7 +223,7 @@ export type ChartChoiceRequest = {
readonly resumeRecordId?: string;
};
export type ChartChoiceAdoptRequest = ChartChoiceRequest & {
export type ChartChoiceAdoptRequest = ChartChoiceRequest & ChartChoiceEvidenceInput & {
/** The user tapped a quick range; only then is it written back to the profile. */
readonly rangeChosen?: boolean;
readonly answers?: Readonly<Record<string, ChartChoiceAnswer>>;
@@ -14,11 +14,26 @@ export const windowSchema = z.object({
end_at: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/),
}).strict();
const eventDate = z.object({
date: z.string().regex(/^\d{4}(?:-\d{2})?$/),
category: z.string().min(1).max(32),
}).strict();
export const evidenceInput = {
event_answers: z.record(z.enum(["D9", "D10", "D2"]), z.object({
choice: z.enum(["before", "after", "both", "neither", "unsure"]),
dates: z.object({ before: eventDate.optional(), after: eventDate.optional() }).strict().optional(),
}).strict()).optional(),
appearance: z.enum(["before", "after", "unsure"]).optional(),
birthmarks: z.array(z.string().min(1).max(32)).max(13).optional(),
};
export const resolvedSchema = z.array(z.object({
line_at: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
side: z.enum(["before", "after"]),
answers: z.record(z.string().max(32), z.enum(["before", "after", "unsure"])).optional(),
override_side: z.enum(["before", "after"]).optional(),
...evidenceInput,
}).strict()).max(3);
const ERROR_TEXT: Record<ChartChoiceError["code"], string> = {
+6 -1
View File
@@ -285,6 +285,7 @@ function recordDetail(
both_versions_domains: decision.both_versions_domains,
saved_at: decision.saved_at,
...roundFields(decision),
...(decision.decided_by ? { decided_by: decision.decided_by, scores: decision.scores, sources: decision.sources } : {}),
},
charts: packet.comparisons.map((item) => ({ chart: item.chart, label: item.label, domain: item.before.domain })),
};
@@ -297,11 +298,12 @@ type DecidedChoice = { subject: Subject; answers: Record<string, string> } & (
| { packet: CompletePacket; decision: ChartChoiceCompletion }
);
function roundFields(decision: Partial<ChartChoiceRoundResult>) {
function roundFields(decision: Partial<ChartChoiceRoundResult>): Partial<ChartChoiceRoundResult> {
if (!decision.segment || !decision.rounds || !decision.undetermined_charts || !decision.events) return {};
return {
segment: decision.segment, rounds: decision.rounds, undetermined_charts: decision.undetermined_charts,
events: decision.events, remaining_key_lines: decision.remaining_key_lines, has_next: decision.has_next,
...(decision.evidence_summary ? { evidence_summary: decision.evidence_summary } : {}),
};
}
@@ -318,6 +320,9 @@ async function decideChartChoice(
{
...await chartChoiceEngineBody(subject, userId, request, admin),
answers: request.answers ?? {},
...(request.event_answers !== undefined ? { event_answers: request.event_answers } : {}),
...(request.appearance !== undefined ? { appearance: request.appearance } : {}),
...(request.birthmarks !== undefined ? { birthmarks: request.birthmarks } : {}),
...(request.overrideSide ? { override_side: request.overrideSide } : {}),
...(request.readBothAll ? { read_both_all: true } : {}),
...(request.stop !== undefined ? { stop: request.stop } : {}),
+6
View File
@@ -238,6 +238,12 @@ evidence_card.backstage records, for the backend only, that global web evidence
- Q2 公历年(BUG-1731):引擎已算出的 `calendar_year`(两个 Tajika 年的覆盖区间与分界回归日)送到卡上 `timing.annual_brief.calendar_year`;写法见「A」块 A-08。
- Q5 先答后证(BUG-1733):见「F」第 8 条。
### 生时纠正判边规则(产品)
- 原值为性格题投票和填写侧兜底。新值为事件选中一侧加 2,两段都有各加 1,两个否定或不确定选项为 0。外表选择和胎记支持各加 1,性格补充题每题加 0.5。两侧相差至少 2 分才按证据选边,其余沿用原判边规则。
- 改动用于记录每条分界线的依据,并允许用已发生的事件区分候选。分值是产品规则,已有事件评分的权重与置信度阈值继续使用原实现。
- D6、D8 的生时纠正事件题待占星师定义宫位与行星。在此之前只用补充题。
## H. 占星师 2026-11-08 第五轮裁定在代码里的落实
- 裁定 3 功能吉凶:默认 `functional_profile = pvr_table_30`(PVR §13.2 表 30)。原产品表另存为 `bphs_exception_profile`,只在调用方明确选中时参与打分(生时校正打分原先明确选中它;产品 2026-11-08 批准后校正也用默认档 `pvr_table_30`,重跑记录 `round5_pvr_narayana_2026_11_08`,BUG-1759)。两档不同的格在 `profile_divergence` 并列,不合并;动星座上升(白羊、天秤、摩羯)的月亮表 30 不列,按表下注释:盈月管角宫 → 功能凶,亏月 → 功能中性;盈亏未知时不分类。双宫主按 PVR §13.2 综合判断(`dual_lordship_note`)。
+1 -1
View File
@@ -698,7 +698,7 @@ def _clean_answers(raw: Any) -> dict[str, str]:
def evaluate(body: dict[str, Any]) -> dict[str, Any]:
"""Run her five stages on whatever the user has supplied so far."""
"""Run the legacy five-stage flow. The merged multi-round flow reuses the scoring and question helpers in this module."""
from scripts.chart_choice.service import _request
req, start, end, reported, reported_known = _request(body)
+34
View File
@@ -55,3 +55,37 @@ def decide(
"votes": votes,
"both_versions_domains": both_versions,
}
def decide_with_evidence(
answers: dict[str, str], sources: list[dict[str, Any]], *,
reported_side: Side, neutral: bool, override: Side | None,
) -> dict[str, Any]:
sources = [*sources, *(
{"kind": "supplement", "id": key, "choice": value,
"before": 0.5 if value == "before" else 0, "after": 0.5 if value == "after" else 0}
for key, value in answers.items()
)]
scores = {side: sum(row[side] for row in sources) for side in ("before", "after")}
result = decide(answers, reported_side=reported_side, neutral=neutral)
side, rule = result["chosen_side"], result["rule"]
if override in ("before", "after"):
side, rule = override, "user_override"
result["votes"] = None
elif abs(scores["before"] - scores["after"]) >= 2:
side = "before" if scores["before"] > scores["after"] else "after"
rule = "evidence"
if rule == "user_override":
decided_by = "override"
elif rule == "evidence":
decided_by = "event" if any(r["kind"] == "event" and r[side] > 0 for r in sources) else (
"appearance" if any(r["kind"] in ("appearance", "birthmark") and r[side] > 0 for r in sources) else "supplement"
)
else:
decided_by = "supplement" if rule in ("majority", "strong_override") else "reported"
return {
**result, "chosen_side": side, "rule": rule, "scores": scores, "sources": sources, "decided_by": decided_by,
"both_versions_domains": [] if override else sorted(
key for key, value in answers.items() if value in ("before", "after") and value != side
),
}
+228
View File
@@ -0,0 +1,228 @@
"""Questions and dated evidence for the multi-round chart-choice flow."""
from __future__ import annotations
import re
from datetime import datetime, timedelta, timezone
from typing import Any
from scripts.chart_choice import astrologer
from scripts.chart_choice.boundaries import ChartChoiceInputError, ChartRequest
from chart_dasha.birth_moment import YEAR_DAYS, split_period
TOPICS = {
"D9": ("感情", "开始恋爱、结婚或分开", ("relationship", "marriage", "divorce")),
"D10": ("工作", "入职、升职、离职、换工作或创业", ("career", "job_change", "business")),
"D2": ("收入和支出", "收入明显增加、意外支出或较大的损失", ("finance_pos", "finance_neg")),
}
CHOICES = ("before", "after", "both", "neither", "unsure")
def _today(req: ChartRequest) -> datetime:
return (datetime.now(timezone.utc) + timedelta(hours=req.tz)).replace(
tzinfo=None, hour=0, minute=0, second=0, microsecond=0,
)
def _boundaries(row: dict, start: datetime, end: datetime) -> set[datetime]:
points = set()
for major in row["timeline"]:
if major["end"] <= start or major["start"] >= end:
continue
for minor in split_period(major):
if minor["end"] > start and minor["start"] < end:
points.update(p["start"] for p in split_period(minor))
majors, minors = row["narayana"]
periods = list(majors or [])
if minors:
for children in minors.values():
periods.extend(children or [])
for period in periods:
points.add(row["at"] + timedelta(days=float(period["start_age"]) * YEAR_DAYS))
points.add(row["at"] + timedelta(days=float(period["end_age"]) * YEAR_DAYS))
return {at for at in points if start < at < end}
def _age(at: datetime, birth: datetime) -> int:
return at.year - birth.year - ((at.month, at.day) < (birth.month, birth.day))
def _age_label(ages: tuple[int, int]) -> str:
return f"{ages[0]} 岁" if ages[0] == ages[1] else f"{ages[0]}–{ages[1]} 岁"
def _date_span(at: datetime, precision: str) -> tuple[datetime, datetime]:
if precision == "year":
return at.replace(month=1, day=1), at.replace(month=12, day=31)
start = at.replace(day=1)
next_month = (start.replace(day=28) + timedelta(days=4)).replace(day=1)
return start, next_month - timedelta(days=1)
def _follow_up_options(chart: str, categories: tuple[str, ...]) -> list[dict]:
if chart == "D2":
return [
{"id": "income_increase", "value": "finance_pos", "text": "收入明显增加"},
{"id": "unexpected_expense", "value": "finance_neg", "text": "一笔较大的意外支出"},
{"id": "financial_loss", "value": "finance_neg", "text": "一笔较大的损失"},
]
return [{"id": key, "value": key, "text": astrologer.EVENT_CATEGORIES[key]["label"]} for key in categories]
def _event_question(chart: str, rows: tuple[dict, dict], points: list[datetime], birth: datetime) -> dict | None:
label, examples, categories = TOPICS[chart]
windows: list[dict[tuple[int, int], tuple[float, float]]] = [{}, {}]
for category in categories:
event = {"category": category}
varga = [astrologer._varga_score(event, row) for row in rows]
for lo, hi in zip(points, points[1:]):
event["at"] = lo + (hi - lo) / 2
(before, left), (after, right) = (astrologer._dasha_score(event, row) for row in rows)
if left.get("unavailable") != right.get("unavailable"):
continue
scores = (before, after)
ages = (_age(lo, birth), _age(hi - timedelta(microseconds=1), birth))
strong = [score >= 4 or (score > 0 and v > 0) for score, v in zip(scores, varga)]
for i, score in enumerate(scores):
difference = score - scores[1 - i] + varga[i] - varga[1 - i]
if strong[i] and scores[1 - i] == 0 and difference > 0:
rank = (difference, (hi - lo).total_seconds())
windows[i][ages] = max(windows[i].get(ages, rank), rank)
pairs = (
(left, right) for left in windows[0] for right in windows[1]
if left[1] < right[0] or right[1] < left[0]
)
pair = max(pairs, key=lambda p: (windows[0][p[0]][0] + windows[1][p[1]][0],
windows[0][p[0]][1] + windows[1][p[1]][1]), default=None)
if pair is None:
return None
before, after = map(_age_label, pair)
return {
"id": chart, "chart": chart, "before_ages": pair[0], "after_ages": pair[1],
"prompt": f"{label}上的变化,线前候选对应 {before},线后候选对应 {after}。你在哪一段有过这些变化?比如{examples}。",
"options": [{"value": key, "text": text} for key, text in zip(
CHOICES, (f"{before}有", f"{after}有", "两段都有", "两段都没有", "记不清"),
)],
"follow_up": {
"prompt": "大概是哪一年?月份记得的话,也可以填。那次发生了什么?",
"categories": _follow_up_options(chart, categories),
},
}
def questions(req: ChartRequest, charts: list[str], before: datetime, after: datetime) -> dict:
eligible = [key for key in TOPICS if key in charts]
if not eligible and "D1" not in charts:
return {"event_questions": []}
rows = (astrologer._minute_row(req, before), astrologer._minute_row(req, after))
birth = min(before, after)
result: dict[str, Any] = {"event_questions": []}
if eligible:
start = birth.replace(year=birth.year + 15, day=28 if (birth.month, birth.day) == (2, 29) else birth.day)
end = min(_today(req) + timedelta(days=1), *(row["timeline"][-1]["end"] for row in rows))
if start < end:
points = sorted({start, end} | _boundaries(rows[0], start, end) | _boundaries(rows[1], start, end))
for chart in eligible:
if question := _event_question(chart, rows, points, birth):
result["event_questions"].append(question)
if len(result["event_questions"]) == 2:
break
if "D1" in charts:
options = astrologer.appearance_options(list(rows))
if len(options) == 2:
result["appearance_question"] = {
"prompt": "哪一组外表描述更接近你?",
"options": [
{"value": side, "text": item["features"]} for side, item in zip(("before", "after"), options)
] + [{"value": "unsure", "text": "说不清"}],
}
result["birthmark_question"] = {
"prompt": "你有胎记吗?有的话,可以选它所在的位置。",
"multiple": True,
"options": [{"value": part, "text": spec["label"]} for part, spec in astrologer.BIRTHMARK_PARTS.items()]
+ [{"value": "none", "text": "没有"}],
}
return result
def _event_answers(packet: dict, raw: Any, birth: datetime, today: datetime) -> tuple[dict, list[dict], list[dict]]:
if not isinstance(raw, dict):
raise ChartChoiceInputError("event_answers must be an object")
normalized, events, sources = {}, [], []
asked = {q["id"]: q for q in packet["event_questions"]}
for question_id, response in raw.items():
if question_id not in asked or not isinstance(response, dict) or response.get("choice") not in CHOICES:
raise ChartChoiceInputError("event answer must match an offered question and option")
choice = response["choice"]
sides = ("before", "after") if choice == "both" else (choice,) if choice in CHOICES[:2] else ()
dates = response.get("dates", {})
if not isinstance(dates, dict) or dates.keys() != set(sides):
raise ChartChoiceInputError("each selected event window needs a date")
categories = TOPICS[question_id][2]
recorded = {}
for side, event in dates.items():
if (not isinstance(event, dict) or event.get("category") not in categories
or not isinstance(event.get("date"), str) or not re.fullmatch(r"\d{4}(?:-\d{2})?", event["date"])):
raise ChartChoiceInputError("event follow-up needs an offered category and a year or month")
item = {key: event[key] for key in ("date", "category")}
parsed = astrologer.parse_events([item], birth)[0]
if parsed["at"].year > today.year:
raise ChartChoiceInputError("event date is outside the selected age window")
lower, upper = _date_span(parsed["at"], parsed["precision"])
upper = min(today, upper)
ages = asked[question_id][f"{side}_ages"]
if lower > upper or _age(upper, birth) < ages[0] or _age(lower, birth) > ages[1]:
raise ChartChoiceInputError("event date is outside the selected age window")
recorded[side] = item
events.append(item)
normalized[question_id] = {"choice": choice, "dates": recorded}
sources.append({"kind": "event", "id": question_id, "choice": choice,
**{side: (1 if choice == "both" else 2) if side in sides else 0 for side in CHOICES[:2]}})
return normalized, events, sources
def evidence(req: ChartRequest, packet: dict, body: dict, birth: datetime) -> tuple[dict, list[dict], list[dict]]:
result: dict[str, Any] = {}
answers, events, sources = _event_answers(packet, body.get("event_answers", {}), birth, _today(req))
if "event_answers" in body:
result["event_answers"] = answers
if "appearance" in body:
choice = body["appearance"]
if "appearance_question" not in packet or choice not in (*CHOICES[:2], "unsure"):
raise ChartChoiceInputError("appearance answer requires a D1 question")
result["appearance"] = choice
sources.append({"kind": "appearance", "choice": choice, "before": int(choice == "before"), "after": int(choice == "after")})
if "birthmarks" in body:
marks = body["birthmarks"]
if ("birthmark_question" not in packet or not isinstance(marks, list)
or any(not isinstance(part, str) or part not in (*astrologer.BIRTHMARK_PARTS, "none") for part in marks)
or ("none" in marks and marks != ["none"])):
raise ChartChoiceInputError("birthmark answers require D1 and valid positions")
result["birthmarks"] = list(dict.fromkeys(marks))
if marks and marks != ["none"]:
points = {}
for side in CHOICES[:2]:
row = astrologer._minute_row(req, datetime.fromisoformat(packet["sides"][side]["saved_at"]))
points[side] = int(any(astrologer._birthmark_supported(part, row) for part in marks))
sources.append({"kind": "birthmark", **points})
elif marks:
sources.append({"kind": "birthmark", "choice": "none", "before": 0, "after": 0})
return result, events, sources
def summarize(req: ChartRequest, segment: tuple[datetime, datetime], reported: datetime, raw: list[dict]) -> dict:
events, _ = astrologer._independent_events(astrologer.parse_events(raw, reported))
cov = astrologer.coverage(events)
base = astrologer._minute_row(req, reported) if events else None
start, end = segment
first = start.replace(second=0, microsecond=0)
if first < start:
first += timedelta(minutes=1)
rows = astrologer.scan(req, first, end) if base and first <= end else []
if base and not rows:
rows = [astrologer._minute_row(req, start + (end - start) // 2)]
ranked = sorted((astrologer.score_minute(events, row, base) for row in rows), key=lambda row: -row["total"])
exact_tie = len(ranked) > 1 and ranked[0]["total"] == ranked[1]["total"]
confidence = ("tendency_only" if len(events) < 3
else astrologer.engine_confidence(ranked, cov["level"] == "thin", exact_tie)["key"])
return {"event_count": len(events), "matched": ranked[0]["matched"] if ranked else 0,
"confidence": confidence, "coverage": cov, "caveat": astrologer.CAVEAT}
+43 -23
View File
@@ -11,6 +11,8 @@ from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any, Final, TypeAlias
from scripts.chart_choice import interview
from scripts.chart_choice.boundaries import (
LEGACY_DIVISIONS,
MAX_WINDOW_MINUTES,
@@ -24,7 +26,7 @@ from scripts.chart_choice.boundaries import (
representative_time,
segment_around,
)
from scripts.chart_choice.decision import decide, reported_is_neutral
from scripts.chart_choice.decision import decide, decide_with_evidence, reported_is_neutral
from scripts.chart_choice.readings import DOMAIN, DOMAIN_ORDER, LEGACY_DOMAIN_ORDER, build_question, describe, varga_chart
ENGINE_VERSION: Final = "chart-choice-v1"
@@ -174,7 +176,7 @@ def _choice(
comparisons.append({"chart": key, "label": DOMAIN[key]["label"], "chart_label": DOMAIN[key]["chart"],
"before": before, "after": after})
if len(questions) < MAX_QUESTIONS and (q := build_question(before, after)):
questions.append(q)
questions.append({**q, "optional": True} if multi else q)
return {
**base,
@@ -191,10 +193,11 @@ def _choice(
"comparisons": comparisons,
"unchanged": [{"chart": k, "label": DOMAIN[k]["label"]} for k in unchanged],
"questions": questions,
**(interview.questions(req, flipped, before_min, after_min) if multi else {}),
}
def _answer(packet: dict, body: dict) -> tuple[dict, dict]:
def _answer(packet: dict, body: dict, evidence: list[dict] | None = None) -> tuple[dict, dict]:
if packet["status"] != "choose":
raise ChartChoiceInputError(f"no choice to make (status {packet['status']})")
raw = body.get("answers") or {}
@@ -203,7 +206,10 @@ def _answer(packet: dict, body: dict) -> tuple[dict, dict]:
asked = {q["domain"] for q in packet["questions"]}
answers = {k: str(v) for k, v in raw.items() if k in asked and v in ("before", "after", "unsure")}
override = body.get("override_side")
if override in ("before", "after"):
if evidence is not None:
decision = decide_with_evidence(answers, evidence, reported_side=packet["reported_side"],
neutral=packet["reported_neutral"], override=override)
elif override in ("before", "after"):
decision = {"chosen_side": override, "rule": "user_override",
"votes": None, "both_versions_domains": []}
else:
@@ -253,9 +259,10 @@ def _input_line(value: Any) -> datetime:
raise ChartChoiceInputError("line_at must be YYYY-MM-DDTHH:MM:SS") from exc
def _round_record(line: Line, side: str, rule: str, votes: Any) -> dict:
def _round_record(line: Line, side: str, rule: str, votes: Any, receipt: dict | None = None) -> dict:
return {"line_at": _at_s(line.at), "charts": _line_view(line, DOMAIN_ORDER)["charts"],
"chosen_side": side, "rule": rule, "votes": votes}
"chosen_side": side, "rule": rule, "votes": votes,
**({key: receipt[key] for key in ("scores", "sources", "decided_by")} if receipt else {})}
def _multi(
@@ -285,6 +292,8 @@ def _multi(
legacy_line = nearest_line(find_lines(req, start, end, LEGACY_DIVISIONS), recorded_reported)
segment = (start, end)
rounds: list[dict] = []
normalized: list[dict] = []
events: list[dict] = []
for index, entry in enumerate([resume, *raw] if resume is not None else raw):
if not isinstance(entry, dict) or entry.get("side") not in ("before", "after"):
raise ChartChoiceInputError("each resolved entry needs line_at and a side")
@@ -305,21 +314,25 @@ def _multi(
if segment[0] > segment[1]:
raise ChartChoiceInputError("resolved choice leaves no time in the window")
history = _round_record(line, side, "legacy_record" if is_resume else "resolved", None)
if not is_resume and ("answers" in entry or "override_side" in entry):
normalized_entry = {"line_at": history["line_at"], "side": side}
if not is_resume and entry.keys() & {"answers", "override_side", "event_answers", "appearance", "birthmarks"}:
prior = _multi_choice(req, base, lines, segment_before, candidates, reported, reported_known)
_, receipt = _answer(prior, entry)
extras, dated, sources = interview.evidence(req, prior, entry, reported)
answers, receipt = _answer(prior, entry, sources)
if receipt["chosen_side"] != side:
raise ChartChoiceInputError("resolved side disagrees with its answers")
history = _round_record(line, side, receipt["rule"], receipt["votes"])
history = _round_record(line, side, receipt["rule"], receipt["votes"], receipt)
events.extend(dated)
normalized_entry.update(extras)
if "answers" in entry:
normalized_entry["answers"] = answers
if receipt["rule"] == "user_override":
normalized_entry["override_side"] = entry["override_side"]
rounds.append(history)
if not is_resume:
normalized.append(normalized_entry)
ordered = _ordered(lines, segment, reported)
current_rounds = rounds[1:] if resume is not None else rounds
normalized = [
{**{key: entry[key] for key in ("answers", "override_side") if key in entry},
"line_at": row["line_at"], "side": row["chosen_side"]}
for row, entry in zip(current_rounds, raw)
]
result = {
**base,
"round": min(len(rounds) + 1, MAX_ROUNDS),
@@ -328,6 +341,7 @@ def _multi(
"ordered_lines": [_line_view(line, DOMAIN_ORDER) for line in ordered],
"segment": _segment(*segment),
"resolved": normalized,
"events": events,
**({"resume": {"line_at": rounds[0]["line_at"], "side": rounds[0]["chosen_side"]}} if resume is not None else {}),
}
stop = body.get("stop", False)
@@ -335,7 +349,7 @@ def _multi(
if deciding and not stop and body.get("override_side") in ("before", "after"):
raise ChartChoiceInputError("no active line to override")
rule = "stopped" if stop else "round_limit" if ordered else "no_line_in_range"
decision = _round_result(segment, ordered, rounds, reported, rule)
decision = _round_result(req, segment, ordered, rounds, reported, rule, events)
decision["resolved"] = normalized
return {**result, "status": "certain" if not ordered and not stop else "complete",
"saved_at": decision["saved_at"], "decision": decision}
@@ -343,15 +357,16 @@ def _multi(
packet = _multi_choice(req, result, lines, segment, ordered, reported, reported_known)
if not deciding:
return packet
answers, decision = _answer(packet, body)
extras, dated, sources = interview.evidence(req, packet, body, reported)
answers, decision = _answer(packet, body, sources)
side = decision["chosen_side"]
segment = _side(segment, line, side)
rounds.append(_round_record(line, side, decision["rule"], decision["votes"]))
rounds.append(_round_record(line, side, decision["rule"], decision["votes"], decision))
remaining = _ordered(lines, segment, reported)
decision.update(_round_result(segment, remaining, rounds, reported, decision["rule"]))
decision.update(_round_result(req, segment, remaining, rounds, reported, decision["rule"], [*events, *dated]))
decision["resolved"] = [
*normalized,
{"line_at": _at_s(line.at), "side": side, "answers": answers,
{"line_at": _at_s(line.at), "side": side, "answers": answers, **extras,
**({"override_side": body["override_side"]} if decision["rule"] == "user_override" else {})},
]
return {**packet, "answers": answers, "decision": decision}
@@ -370,15 +385,20 @@ def _multi_choice(
return _choice(req, base, line, before, after, reported, reported_known, DOMAIN_ORDER, len(ordered) - 1)
def _round_result(segment: Segment, lines: list[Line], rounds: list[dict], reported: datetime, rule: str) -> dict:
def _round_result(
req: ChartRequest, segment: Segment, lines: list[Line], rounds: list[dict],
reported: datetime, rule: str, events: list[dict],
) -> dict:
has_next = bool(lines and len(rounds) < MAX_ROUNDS and rule != "stopped")
return {
"saved_at": _saved_at(representative_time(segment, reported)),
"segment": _segment(*segment),
"rounds": rounds,
"undetermined_charts": [key for key in KEY_CHARTS if any(key in line.flips for line in lines)],
"events": [],
"events": events,
**({"evidence_summary": interview.summarize(req, segment, reported, events)} if not has_next else {}),
"remaining_key_lines": len(lines),
"has_next": bool(lines and len(rounds) < MAX_ROUNDS and rule != "stopped"),
"has_next": has_next,
"rule": rule,
}
+107 -1
View File
@@ -23,7 +23,8 @@ from scripts.chart_choice.boundaries import ( # noqa: E402
segment_around,
signature,
)
from scripts.chart_choice.decision import decide, reported_is_neutral # noqa: E402
from scripts.chart_choice import astrologer, interview # noqa: E402
from scripts.chart_choice.decision import decide, decide_with_evidence, reported_is_neutral # noqa: E402
from scripts.chart_choice.service import build_packet, decide_packet # noqa: E402
# Fictional reference input (not a user record): mid-latitude north China, early morning.
@@ -287,3 +288,108 @@ def test_v2_same_second_combines_flips_and_a_one_second_side_can_be_kept(monkeyp
assert result["decision"]["segment"] == {"start_at": at, "end_at": at}
assert result["decision"]["saved_at"] == "1997-08-08T05:00"
assert not result["decision"]["undetermined_charts"]
def test_v2_uses_supported_d9_age_windows_and_carries_dated_events(monkeypatch):
first, second = synthetic_scan(monkeypatch, ("04:59:00", ["D9"]), ("05:03:00", ["D6"]))
birth = datetime(1997, 8, 8, 5)
left_end, right_start, cutoff = (birth.replace(year=year, hour=0) for year in (2019, 2020, 2026))
monkeypatch.setattr(interview, "_today", lambda _: cutoff)
monkeypatch.setattr(interview, "_boundaries", lambda *_: {left_end, right_start})
monkeypatch.setattr(astrologer, "_minute_row", lambda req, at: {
"at": at, "timeline": [{"end": cutoff}], "before": at < datetime.fromisoformat(first),
})
monkeypatch.setattr(astrologer, "_varga_score", lambda *_: 0)
monkeypatch.setattr(astrologer, "_dasha_score", lambda event, row: (
6 if (row["before"] and event["at"] < left_end) or (not row["before"] and event["at"] >= right_start) else 0, {},
))
req = {**BODY, "resolved": []}
packet = build_packet(req)
question, = packet["event_questions"]
assert question["chart"] == "D9"
assert question["before_ages"] == (15, 21)
assert question["after_ages"] == (23, 28)
assert "15–21 岁" in question["prompt"] and "23–28 岁" in question["prompt"]
assert [o["value"] for o in question["options"]] == ["before", "after", "both", "neither", "unsure"]
assert len(question["follow_up"]["categories"]) == 3
event = {"date": "2022-06", "category": "relationship"}
answer = {"D9": {"choice": "after", "dates": {"after": event}}}
result = decide_packet({**req, "event_answers": answer})["decision"]
assert result["rule"] == "evidence" and result["chosen_side"] == "after"
assert result["events"] == [event]
continued = build_packet({**req, "resolved": result["resolved"]})
assert continued["events"] == [event]
assert continued["resolved"][0]["event_answers"] == answer
assert continued["line"]["at"] == second
assert continued["event_questions"] == []
for invalid_date in ("2015", "9999-12"):
with pytest.raises(ChartChoiceInputError, match="outside"):
decide_packet({**req, "event_answers": {"D9": {"choice": "after", "dates": {
"after": {"date": invalid_date, "category": "relationship"},
}}}})
def test_v2_equal_event_windows_are_omitted_and_only_d1_has_appearance_and_marks(monkeypatch):
d1, _ = synthetic_scan(monkeypatch, ("04:59:00", ["D1", "D9"]), ("05:03:00", ["D10"]))
monkeypatch.setattr(astrologer, "_minute_row", lambda req, at: {
"at": at, "timeline": [{"end": datetime(2026, 1, 1)}], "asc": int(at >= datetime.fromisoformat(d1)),
})
monkeypatch.setattr(interview, "_boundaries", lambda *_: set())
monkeypatch.setattr(astrologer, "_dasha_score", lambda *_: (6, {}))
monkeypatch.setattr(astrologer, "_varga_score", lambda *_: 0)
monkeypatch.setattr("scripts.chart_choice.service.build_question", lambda before, after: {"chart": before["chart"]})
first = build_packet({**BODY, "resolved": []})
assert first["event_questions"] == []
assert first["questions"] and all(q["optional"] for q in first["questions"])
assert [o["value"] for o in first["appearance_question"]["options"]] == ["before", "after", "unsure"]
assert first["birthmark_question"]["multiple"] and len(first["birthmark_question"]["options"]) == 14
next_packet = build_packet({**BODY, "resolved": [{"line_at": d1, "side": "after"}]})
assert next_packet["line"]["charts"] == ["D10"]
assert "appearance_question" not in next_packet and "birthmark_question" not in next_packet
def test_v2_evidence_scores_report_the_fallback_and_each_source():
evidence = [
{"kind": "event", "id": "D9", "choice": "after", "before": 0, "after": 2},
{"kind": "appearance", "choice": "before", "before": 1, "after": 0},
]
result = decide_with_evidence({"career": "before", "money": "before"}, evidence,
reported_side="after", neutral=True, override=None)
assert result["scores"] == {"before": 2, "after": 2}
assert result["rule"] == "majority" and result["chosen_side"] == "before"
assert result["decided_by"] == "supplement"
assert result["sources"][:2] == evidence
assert [(item["id"], item["before"]) for item in result["sources"][2:]] == [("career", 0.5), ("money", 0.5)]
def test_v2_d6_d8_can_be_decided_by_supplements(monkeypatch):
synthetic_scan(monkeypatch, ("04:59:00", ["D6", "D8"]))
monkeypatch.setattr("scripts.chart_choice.service.build_question", lambda before, after: {
"chart": before["chart"], "domain": before["domain"],
})
result = decide_packet({**BODY, "resolved": [], "answers": {"pressure": "before", "change": "before"}})
assert result["event_questions"] == []
assert all(q["optional"] for q in result["questions"])
decision = result["decision"]
assert decision["scores"] == {"before": 1, "after": 0}
assert decision["rounds"][0]["decided_by"] == "supplement"
assert set(decision["rounds"][0]["charts"]) == {"D6", "D8"}
def test_v2_final_evidence_scores_only_minutes_inside_the_selected_segment(monkeypatch):
seen = []
monkeypatch.setattr(astrologer, "_minute_row", lambda req, at: {"at": at})
def score(events, row, base):
seen.append(row["at"])
return {"matched": len(events), "total": 65 if row["at"].minute == 1 else 45}
monkeypatch.setattr(astrologer, "score_minute", score)
start, end = datetime(1997, 8, 8, 5, 0, 15), datetime(1997, 8, 8, 5, 2, 15)
events = [{"date": str(year), "category": "relationship"} for year in range(2020, 2024)]
two = interview.summarize(REQ, (start, end), datetime(1997, 8, 8, 5), events[:2])
four = interview.summarize(REQ, (start, end), datetime(1997, 8, 8, 5), events)
assert (two["event_count"], two["matched"], two["confidence"]) == (2, 2, "tendency_only")
assert (four["event_count"], four["matched"], four["confidence"]) == (4, 4, "medium")
assert four["caveat"] == astrologer.CAVEAT
assert seen == [start.replace(minute=minute, second=0) for minute in (1, 2, 1, 2)]