diff --git a/CHANGELOG.md b/CHANGELOG.md index b3e1bbd33..8738cb0fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # 印度占星 Skill 更新日志 +## 2026-11-16 · 生时纠正说明六张盘的变化并开放用户自选 + +- 结果页展示各盘换座的分界,可自己选线前、线后或不确定,采用后可恢复填写的时间。占星 Skill 版本不变(BUG-1936)。 + + ## 2026-11-16 · 用途范围绑定与敏感界限的离线复验 - BUG-1932(#297):新增用途指纹、原生计算扫描和离线 JSON 复验入口。Skill 版本不变。 diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 95769fd1a..b56038979 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -26070,6 +26070,17 @@ - 关联记录:BUG-147、BUG-135。 - 修复版本:`claude/admin-usage-rls-1935`,待 staging 实测。 +## BUG-1936 | 生时纠正结果没有说明六张盘哪里不同 + +- 状态:fixed-pending-verify(待独立验收)。 +- 首次发现 / 最近更新:2026-11-16 / 2026-11-16。 +- 触发与现象:暂停问答后进入生时纠正,只能看到采用时刻和分盘的换座提示,具体变化和可做的操作不清楚。 +- 根因:默认结果只显示分盘第一次换座的时刻,未展示线前、线后的上升星座。停用入口时也撤下了手选路径。 +- 修复:按产品负责人决定开放逐线自选。六盘由原生分界线生成说明,两侧读法沿用既有文本。采用时服务端重算,并以独立来源记录用户选择。问卷、事件评分、再用旧问答范围继续停用。 +- 验证与防复发:覆盖六盘说明、跨午夜、逐线缩窄、不确定、恢复申报、客户端伪造时刻及重复提交。验收入口见 [#301 进度](tasks/PROGRESS-rect-self-choice-20261116.md)。 +- 关联记录:#301、BUG-1890、BUG-1896、BUG-1925。 +- 修复版本:`codex/rect-self-choice-20261116`,待独立验收。 + ## BUG-1937 | 后台上线配置的成本和毛利在没有用量时是空的;功能开关页可以新增没人读的开关;对话质量页不说明何时有记录 - 状态:fixed-pending-verify(待 staging 实测)。 diff --git a/docs/research/rect-p0-evidence-20261116.md b/docs/research/rect-p0-evidence-20261116.md index ba910e7b8..bc3c0e9ff 100644 --- a/docs/research/rect-p0-evidence-20261116.md +++ b/docs/research/rect-p0-evidence-20261116.md @@ -41,3 +41,7 @@ python -m pytest -q tests/test_chart_choice.py tests/test_rectification_replay_c 四臂全量共 2 464 行。Windows 与归档精确一致。Linux 的排序、选题、分差、答案、命中、区间和汇总精确一致,切片时长有 763 处差异,最大 88 微秒。半毫秒容差仅用于切片时长的比较。两端独立生成的 32 行烟测都精确通过。 复跑与时长见 [四臂复跑比较](../../references/real_case_calibration/rect_repro_20261116/)。聚合统计见 [只读 SQL](../operations/rect-p0-aggregate-20261116.sql) 与 [执行记录](../tasks/PROGRESS-rect-p0-evidence-20261116.md)。生产统计由负责人按受控流程执行。 + +## 11-16 之后的变更 + +#301 恢复用户自己选线前线后的入口。新保存记录标注 `source=user_choice`、`rule=user_override`、`declared_by_user=true` 和 `basis=self_choice_20261116`。这里记录的是用户声明,既有问答、事件打分和答题窄范围仍停用。上面的 P0 复跑和历史审计保留原结论。 diff --git a/docs/tasks/PROGRESS-rect-self-choice-20261116.md b/docs/tasks/PROGRESS-rect-self-choice-20261116.md new file mode 100644 index 000000000..e3020853f --- /dev/null +++ b/docs/tasks/PROGRESS-rect-self-choice-20261116.md @@ -0,0 +1,22 @@ +# #301 生时纠正结果说明与用户自选 + +- 任务书:[TASK-rect-self-choice-20261116.md](TASK-rect-self-choice-20261116.md)。实现基线为 `origin/staging` 的 `ee311ff92`。 +- 逐线选择沿用 v1 `ChooseStep` 的比较卡和选项样式。结果与「当前使用」复用六盘条和中文盘名。确认面显示选择记录、采用时刻和剩余范围。 +- `selfChoice: true` 通过独立的请求形状进入。服务端依据申报和原生线,按距原申报时刻的距离逐条缩窄。同刻多盘换座属于一次选择。没有声明范围时只接受现有快速试算范围。 +- 采用时刻优先保留落在所选区间内的填写时刻,否则用 `representative_minute`。区间内没有整数分钟时沿用 `representative_time` 取有效秒。范围的端点包含在内,线前区间截止于线前一秒。 +- 「不确定」保留当时的区间。`chosen_side` 记录采用时刻实际所在的一侧,`other_saved_at` 取相邻另一侧的有效时刻,`choices` 仍记录 `unsure`。两版都读沿用现有聊天投影,包括日常、突变和跨午夜的秒级时刻。 +- 保存使用现有 v4 RPC,状态 `accepted`。时刻和范围的原申报字段继续保留;相同自选记录顺序重试返回同一个计算结果。恢复使用既有 `restore_default`。历史记录保持原样。 + +## 验证 + +- 测试使用原生引擎的虚构资料夹具。覆盖六盘说明、多次换座、跨午夜、按两侧缩窄、提前停止、不确定、采用和恢复。 +- 新旧接口回归覆盖客户端时刻伪造、旧请求停用、原申报和历史读回、重复提交及聊天的两版分盘。 +- 生时纠正 Python 定向 67 项通过,前端定向 23 项通过,隐私标记 62 项通过。独立 PostgreSQL 实例验证保存、顺序重试只留一条历史、不确定两版读回和恢复,原申报字段保持原值。 +- 前端完整测试按相同的 Windows 受控配置配对运行,Docker 专项另行烟测。开工基线 3,909 项,交付 3,913 项。44 个既有失败的名称和次数完全一致,38 项跳过,取消 0。原测试名全保留,新增 4 项均通过。 +- TypeScript 通过,ESLint 0 错误。生产构建通过,首页仍是静态路由。两边首页共 39 个压缩资源,均为 616,927 字节。 +- 合并最新 `staging` 后的提交 `260349e8d` 在隔离 Linux 上通过 `python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime`。前端运行检查见上两行。 + +## 已知边界 + +- 新生成报告和年运由现有读盘链使用采用时刻。已生成报告不重算,也不加标记。 +- 登录后的手工流程由独立验收方在本地构建上核对。 diff --git a/docs/tasks/TASK-rect-self-choice-20261116.md b/docs/tasks/TASK-rect-self-choice-20261116.md new file mode 100644 index 000000000..18fb215de --- /dev/null +++ b/docs/tasks/TASK-rect-self-choice-20261116.md @@ -0,0 +1,80 @@ +# 生时纠正页面:讲清哪些方面受影响,并让用户自己选线前线后(2026-11-16,Claude) + +Bug 编号:BUG-1936。关联 BUG-1890(#279)、BUG-1896(#292)、BUG-1925(#294)。 + +## 背景 + +#292 停掉问答后,生时纠正页面只剩「显示时间、选范围、看六张盘、用这个时间」,用户进来没有任何结果。产品负责人 11-16 的决定: + +1. 页面要直接讲清:哪些方面不受时间范围影响,哪些方面会因为差几分钟而不同,分别差在哪条线上、线前线后各是什么。 +2. **允许用户自己选线前还是线后。** 这是用户自己的选择(按自己的做事风格判断),不是系统验证出来的结果。选了,报告和聊天就按那一边写;不确定,受影响的方面两版都读。 +3. 系统不推荐任何一边,不打分,不问事件题。 + +这是对 #279/#292「停用选边」的**有意调整**,只恢复「用户自选」这一条路;问答、事件打分、答题得出的时间范围继续停用。 + +## 不做的事 + +- 不改 `RECT_QUESTIONNAIRE_ENABLED`,不恢复问答(`questionnaire`、`adaptive`、`chart_answers`、`resumeRecordId`)和事件证据输入。`useAnswerWindow` 继续被拒绝。 +- 不调用 `scripts/chart_choice/astrologer.py`、`adaptive.py`、`interview.py`、`chart_questions.py` 的任何打分或选题。 +- 不显示票数、推荐、把握、概率、「更可能」「系统判断」之类的任何措辞;不显示「已纠正」「已校正」「已确认」。 +- 不改报告、年运的渲染代码(`scripts/report_render/` 不动)。聊天侧只复用已有的「两版都读」(`frontend/src/lib/chart-choice-both-versions.ts`),不新写提示词。 +- 不删除、不改写历史记录;不改 `references/real_case_calibration/`。 +- 不新造按钮、卡片样式:沿用页面现有的 `Card`、`Primary`、范围按钮、六张盘条形图、`ChooseStep` 的选项样式。不加提示性的小字副标题。 + +## 一、结果页讲清结论 + +在现有「按你填的 HH:MM」这一步(`defaultOnly` 的 `FinalStep`)和「当前使用」首页,把「现有信息不足以确认更准确的出生时间。」这句换成由数据生成的结论,放在六张盘上方: + +- 范围内没有任何盘换座:`这个时间范围内六张盘都不变,可以直接用。`(已有的 `certain` 步骤保持不变。) +- 有换座:分两行。 + - `不受影响:主盘。`(列出范围内不换座的那些盘的名称,用页面已有的盘名:主盘、婚恋、事业、钱财、日常、突变。) + - `差几分钟就不同:婚恋、事业、钱财、日常、突变。`(列出会换座的。) +- 六张盘每行现有文案 `狮子上升,范围内会换座(04:59:43 换)` 改成把两边都写出来:`04:59:43 之前巨蟹上升,之后狮子上升`。一个盘在范围内换座多于一次时,只写离所填时间最近的那一次,后面加 `等 N 处`。星座名用现有的中文映射,时刻格式沿用现有的。 +- 所填时间离最近的线不到 2 分钟时,在结论下加一行:`你填的 05:00 离 04:59:43 这条线只有 17 秒。`(秒数、分钟数按实际计算;1 分钟以上写「X 分 Y 秒」。) + +所有句子由后端 packet 里已有的线和分盘星座生成;packet 缺「线前星座」时在 `scripts/chart_choice/service.py` 的线视图里补上(`Line.flips` 已有前后星座)。不改任何计算。 + +## 二、用户自选 + +在结果页「用 05:00」按钮旁加一个次级按钮 `自己选线前线后`(范围内没有换座线时不显示)。 + +流程复用已有的逐条线选边步骤(`ChooseStep` / v1 的 `runDecision` + `overrideSide`,或 v2 的 `RoundStep`,以哪个更容易去掉打分为准,在 PROGRESS 写明选了哪个): + +1. 从离所填时间最近的线开始,一次一条线。每条线列出在这条线上换座的方面,每个方面给线前、线后两段说明(用 `scripts/chart_choice/readings.py` 现有的文字,不新写)。 +2. 每条线一个三选一:`线前`、`线后`、`不确定`。整条线选一次,不是每个方面各选一次(同一条线上的各方面在同一时刻一起换,分开选会自相矛盾)。 +3. 选了线前或线后:范围收到那一侧,继续问这一侧里剩下的线(如果有),直到这一段里没有线或用户选了「不确定」或点了 `就到这里`。 +4. 选「不确定」:这条线不收范围,这条线上换座的方面记入「两版都读」(现有 `both_versions` 字段),流程结束。 +5. 结束后到确认页:写明最终用的时间、选过的每条线和选的哪一边,以及 `这是你自己选的,可以随时改。`。保存按钮文案 `用 HH:MM`。 + +保存规则: + +- 采用时刻:选定的那一段里的代表时刻,沿用现有 `representative_minute` 规则;所填时间本来就在选定段内时保持所填时间不变。 +- 来源链写明是用户自选:`source = user_choice`、`rule = user_override`,并新增 `declared_by_user: true` 和 `basis: self_choice_20261116`,与旧问答、旧事件采纳区分开。不写 `votes`,不写任何打分回执。 +- **原始填写的时间和原范围必须原样保留**在记录里(现有的申报字段不动);首页「当前使用」显示采用时刻、选定的范围,以及一行 `按你自己的选择`。提供 `改回我填的时间`(复用现有的恢复默认 `restore_default`)。 +- 出生时间状态不得升级为「已确认」一类;沿用现有 `accepted`。 +- 服务器重新计算线和代表时刻,不信任客户端传来的时刻或范围。 +- 接口:在 `/api/chart-choice/adopt` 现有 schema 上加一个明确的入口字段(建议 `selfChoice: true` + 每条线的选择列表),只有带这个字段的请求才走自选;不带的旧载荷(`overrideSide`、非空 `resolved`、`answers`、`chart_answers`、`resumeRecordId`、`useAnswerWindow`)继续按 #279/#292/#294 的方式被拒绝或走默认。**不要靠放开旧字段来实现。** + +## 三、下游 + +- 聊天:采用时刻变了,照常按采用时刻排盘;`both_versions` 非空时现有「两版都读」逻辑照常生效。确认 `chartChoiceBothVersionsFromProvenance` 认得本单写出的来源(它要求 `source === "user_choice"`、`chosen_side`、`other_saved_at`);「不确定」发生在第一条线、没有选定任何一侧时,`chosen_side` 怎么写、`other_saved_at` 取哪一侧,按现有字段约束给出一个能让两版都读生效的写法,并写测试。 +- 报告、年运:不改代码。它们读采用时刻,本单后自然按用户选的那边生成。旧报告不重算、不标记;这一点写进 PROGRESS 的「已知边界」。 + +## 四、测试 + +- `frontend/tests/chart-choice-self-choice-20261116.test.tsx`:结论两行的生成(全不变、部分换座、多次换座、离线不到 2 分钟);自选按钮只在有线时出现;三选一流程(线前→下一条线、线后、不确定结束、就到这里);确认页文案;页面任何位置不出现「推荐」「更可能」「把握」「已纠正」「已校正」「已确认」和票数。 +- 接口测试:带 `selfChoice` 的请求保存后读回,原始时间和原范围未变、来源字段齐全、无 `votes`;不带 `selfChoice` 的旧载荷行为与现在完全一致(#294 的 `rectification-p0-evidence-20261116.test.ts` 与 `chart-choice-pause-20261115.test.tsx` 不删断言、照旧通过;确需调整的断言逐条在 PROGRESS 说明原因);客户端伪造时刻被服务器重算覆盖;重复提交两次结果相同。 +- `改回我填的时间` 后读回等于原始申报。 +- 「两版都读」:不确定的线上换座的方面进入 `both_versions`,聊天侧读取函数返回非空。 +- Python:`service.py` 线视图补字段的测试;既有 `tests/` 里 chart_choice 相关测试照旧通过。 + +## 五、文档 + +- `docs/BUG_HISTORY.md` 新增 BUG-1936,关联 BUG-1890、BUG-1896、BUG-1925,写明这是产品负责人对「停用选边」的有意调整及其范围(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。 +- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-self-choice-20261116.md`。 +- `docs/research/rect-p0-evidence-20261116.md` 末尾追加一段「11-16 之后的变更」,说明用户自选入口的恢复及其来源标记,不改原有内容。 + +## 验收 + +- Python quick gate 通过;`cd frontend && npx eslint .` 0 错误;`npx tsc --noEmit` 通过;前端全量测试不新增失败。 +- 验收时会用测试账号在 staging 之前的本地构建上走一遍:结论两行、自选三条路径、改回原时间。 diff --git a/frontend/DESIGN.md b/frontend/DESIGN.md index 30dd76cca..252130473 100644 --- a/frontend/DESIGN.md +++ b/frontend/DESIGN.md @@ -397,6 +397,12 @@ The birth-time rectification session is the consultation transcript plus a house - **Board:** before any candidate exists the header clock shows the declared birth minute and the body names it by source — “出生记录时间 HH:MM”, “你填的大概时间 HH:MM”, or “你给的时间段” — then “回答几个问题后,这里会显示宫位随时间的变化.”; the column narrows to `minmax(16rem, 18rem)` (`is-board-empty`) and widens once a result arrives. No house table is invented for the declared time; the snapshot API does not provide one. The range card may add a caption comparing the declared clock to the current range (“与你填的大概时间相差 N 分钟”, or a hospital-record offset with no preference). - **Accessibility:** the sidebar opening note sets `aria-busy`; the live row is the timeline row (`role="status"` shimmer label); the repair and start actions are real 44px buttons. +### Chart choice result and self-choice + +- The reported-time result places the stability summary above the six chart rows. Each row uses the existing band and names the signs on both sides of the nearest transition. When the reported time is close to a line, the summary gives the exact distance. +- The existing secondary action opens one transition at a time. It reuses the comparison cards and the choice buttons. One action applies to every chart changing on that line. The confirmation shows the remaining range and the saved time. +- Current use shows the adopted time and selected range, with the source copy “按你自己的选择” and the restore action. An unsure selection also lists the areas read both ways. + ### Birth time intake - **Structure (issue #144, 2026-11-02):** birth date, then the sentence 「请填写您知道的出生时间,并注明它来自哪里。只记得大概时段,或完全不知道,也可以如实选择,不需要猜一个准确时间。」 (the fieldset's name 「时间来源」 is screen-reader only), then six radio rows, each with its verbatim line from the astrologer's note: 出生证明、医院记录 / 户口本、其他证件 / 家人记得大概几点 / 只记得时辰 / 只知道凌晨、上午等时段 / 完全不知道. No row turns into a fixed error and no 「前后 N 分钟」 button exists any more. diff --git a/frontend/src/app/api/chart-choice/adopt/route.ts b/frontend/src/app/api/chart-choice/adopt/route.ts index b03332d6e..1f1129cc5 100644 --- a/frontend/src/app/api/chart-choice/adopt/route.ts +++ b/frontend/src/app/api/chart-choice/adopt/route.ts @@ -3,7 +3,7 @@ import { isRectQuestionnaireRequest, RECT_QUESTIONNAIRE_ENABLED, RECT_QUESTIONNA import { z } from "zod"; import { chartAnswersSchema, chartChoiceCaller, chartChoiceErrorResponse, evidenceInput, resolvedSchema, windowSchema } from "@/lib/chart-choice/route-support"; -import { adoptCertainTime, adoptChartChoice, adoptDefaultChartChoice, previewAdaptiveChartChoice, previewChartChoice, readDefaultChartChoice, restoreChartChoiceDefault } from "@/lib/chart-choice/server"; +import { adoptCertainTime, adoptChartChoice, adoptDefaultChartChoice, adoptSelfChoice, previewAdaptiveChartChoice, previewChartChoice, previewSelfChoice, readDefaultChartChoice, restoreChartChoiceDefault } from "@/lib/chart-choice/server"; import { createAdminSupabaseClient } from "@/lib/supabase/admin"; export const runtime = "nodejs"; @@ -25,7 +25,18 @@ const choiceSchema = z.object({ rangeChosen: z.boolean().optional(), ...evidenceInput, }).strict(); -const bodySchema = z.union([choiceSchema, z.object({ +const selfChoiceSchema = z.object({ + selfChoice: z.literal(true), + subjectId: z.string().max(64).optional(), + window: windowSchema.optional(), + mode: z.enum(["preview", "choice"]).default("choice"), + choices: 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", "unsure"]), + }).strict()).max(720), +}).strict(); + +const bodySchema = z.union([selfChoiceSchema, choiceSchema, z.object({ mode: z.literal("restore_default"), subjectId: z.string().max(64).optional(), recordId: z.string().uuid(), @@ -51,6 +62,11 @@ export async function POST(request: Request) { const parsed = bodySchema.safeParse(body); if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 }); try { + if ("selfChoice" in parsed.data) { + return NextResponse.json(parsed.data.mode === "preview" + ? await previewSelfChoice(caller.supabase, caller.userId, parsed.data) + : await adoptSelfChoice(caller.supabase, createAdminSupabaseClient(), caller.userId, parsed.data)); + } if (!RECT_QUESTIONNAIRE_ENABLED && (parsed.data.mode === "preview" || parsed.data.mode === "choice")) { const { subjectId, window, rangeChosen } = parsed.data; if (parsed.data.mode === "preview") { diff --git a/frontend/src/components/chart-choice/chart-choice-page.tsx b/frontend/src/components/chart-choice/chart-choice-page.tsx index c4c854448..639a7b3c8 100644 --- a/frontend/src/components/chart-choice/chart-choice-page.tsx +++ b/frontend/src/components/chart-choice/chart-choice-page.tsx @@ -13,6 +13,7 @@ import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { RECORD_RANGE_CHOICES, + SELF_CHOICE_BASIS, type ChartChoiceAnswer, type ChartChoiceAdoptRequest, type ChartChoiceChartAnswers, @@ -23,6 +24,7 @@ import { type ChartChoiceEnginePacket, type ChartChoiceEvidenceInput, type ChartChoiceKeyChart, + type ChartChoiceLineSummary, type ChartChoiceRequest, type ChartChoiceHistory, type ChartChoicePacket, @@ -30,6 +32,8 @@ import { type ChartChoiceSide, type ChartChoiceStart, type ChartChoiceWindow, + type SelfChoicePick, + type SelfChoicePreview, } from "@/lib/chart-choice/contract"; import { SIDE_TEXT, @@ -43,6 +47,7 @@ import { segmentLabel, windowAround, } from "@/lib/chart-choice/view"; +import { CHART_CHOICE_DOMAIN_CHARTS } from "@/lib/chart-choice-both-versions"; import { useCurrentSubject, useCurrentSubjectReady } from "@/lib/current-subject"; import { notifySuccess } from "@/lib/notify"; import { cn } from "@/lib/utils"; @@ -76,7 +81,8 @@ type Step = | { kind: "chart_range"; packet: ChartChoiceQuestionnaire; request: ChartChoiceRequest; previous?: Step } | { kind: "chart_question"; packet: ChartChoiceQuestionnaire; request: ChartChoiceRequest; back: Step; submitted: ChartChoiceChartAnswers; answer: ChartAnswer } - | { kind: "final"; packet: FinalPacket; decision: FinalDecision; body: ResultRequest; back: Step }; + | { kind: "final"; packet: FinalPacket; decision: FinalDecision; body: ResultRequest; back: Step } + | { kind: "self_choice"; preview: SelfChoicePreview; final: Extract; stopped?: boolean }; const COPY = { title: "生时纠正", @@ -323,6 +329,40 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { } } + async function runSelfChoice( + final: Extract, + choices: readonly SelfChoicePick[], + mode: "preview" | "choice", + ) { + setPending(true); + const back = step; + try { + const preview = await postJson("/api/chart-choice/adopt", { + selfChoice: true, subjectId, mode, choices, ...(final.body.window ? { window: final.body.window } : {}), + }); + if (mode === "preview") setStep({ kind: "self_choice", final, preview }); + else afterSave(adoptedClock(preview.decision.saved_at, final.packet.reported_at)); + } catch (error) { + setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: back } }); + } finally { + setPending(false); + } + } + + async function restoreReportedTime(recordId: string) { + setPending(true); + try { + const { saved_at: at } = await postJson<{ saved_at: string }>("/api/chart-choice/adopt", { + mode: "restore_default", subjectId, recordId, + }); + afterSave(adoptedClock(at, start?.reportedAt ?? undefined)); + } catch (error) { + setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: { kind: "home" } } }); + } finally { + setPending(false); + } + } + async function finishQuestions( currentStep: Extract, submitted: ChartChoiceChartAnswers, @@ -371,7 +411,8 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { ); case "home": return ; + window={start?.window} activeRetired={Boolean(start?.activeRetiredReason)} trial={trial} pending={pending} + onRestore={(recordId) => void restoreReportedTime(recordId)} />; case "narrow": return ( @@ -465,7 +506,15 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) { defaultOnly={!RECT_QUESTIONNAIRE_ENABLED} rangeChips={!RECT_QUESTIONNAIRE_ENABLED ? rangeChips(step.packet) : null} onBack={RECT_QUESTIONNAIRE_ENABLED ? () => restore(step.back) : hasHistory ? toHome : undefined} + onSelfChoice={() => void runSelfChoice(step, [], "preview")} onAccept={() => void saveFinal(step)} />; + case "self_choice": + return restore(step.final)} + onPick={(pick) => void runSelfChoice(step.final, [...step.preview.decision.choices, pick], "preview")} + onStop={() => setStep({ ...step, stopped: true })} + onAccept={() => void runSelfChoice(step.final, step.preview.decision.choices, "choice")} />; } } } @@ -796,24 +845,49 @@ function noSignChange(trial: boolean, window?: ChartChoiceWindow): string { return Number.isInteger(minutes) && minutes > 0 ? `前后 ${minutes} 分钟试算里没有变化` : "这次试算里没有变化"; } -function KeyCharts({ charts, undetermined, reference, segment, window = segment, trial = false }: { +function adoptedClock(at: string, reference?: string): string { + return clockLabel(at, reference, at.length === 19 && !at.endsWith(":00")); +} + +function FlipSummary({ summary, reportedAt }: { + readonly summary: ChartChoiceLineSummary; + readonly reportedAt?: string | null; +}) { + if (!summary.nearest_at) return

这个时间范围内六张盘都不变,可以直接用。

; + const stable = Object.keys(CHART_NAMES).filter((chart) => !summary.charts[chart]).map((chart) => CHART_NAMES[chart]); + const changing = Object.keys(CHART_NAMES).filter((chart) => summary.charts[chart]).map((chart) => CHART_NAMES[chart]); + const seconds = reportedAt ? Math.round(Math.abs(minutesFrom(reportedAt) - minutesFrom(summary.nearest_at)) * 60) : null; + return
+

不受影响:{stable.join("、") || "无"}。

+

差几分钟就不同:{changing.join("、")}。

+ {reportedAt && seconds !== null && seconds < 120 ?

+ 你填的 {clockLabel(reportedAt)} 离 {clockLabel(summary.nearest_at, reportedAt, true)} 这条线只有 {seconds >= 60 ? Math.floor(seconds / 60) + " 分 " : ""}{seconds % 60} 秒。 +

: null} +
; +} + +function KeyCharts({ charts, undetermined, reference, segment, window = segment, trial = false, summary }: { readonly charts: readonly ChartChoiceKeyChart[] | undefined; readonly undetermined: readonly string[] | undefined; readonly reference: string; readonly segment?: ChartChoiceWindow; readonly window?: ChartChoiceWindow; readonly trial?: boolean; + readonly summary?: ChartChoiceLineSummary; }) { const rows = charts ?? Object.keys(CHART_NAMES).map((chart): ChartChoiceKeyChart => ({ chart, sign: "", decided_by: null })); return
{rows.map((row) => { const uncertain = Boolean(row.flips_at || undetermined?.includes(row.chart)); + const flip = summary?.charts[row.chart]; + const flipAt = flip?.at ?? row.flips_at; return
{CHART_NAMES[row.chart]}
{segment ? : null} - {row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)} - {row.flips_at ? `(${clockLabel(row.flips_at, reference, true)} 换)` : null} + segments={splitBand(segment, flipAt ? [flipAt] : [])} highlighted={[0]} /> : null} + {flip ? {clockLabel(flip.at, reference, true)} 之前{flip.before}上升,之后{flip.after}上升 + {flip.count > 1 ? "等 " + flip.count + " 处" : null} : {row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)} + {row.flips_at ? `(${clockLabel(row.flips_at, reference, true)} 换)` : null}}
; })} @@ -991,7 +1065,7 @@ function matchedEvidence(decision: FinalDecision): string | null { return `${labels.join("、")},和这段时间的大运对得上${count < 3 ? ",先作参考" : ""}。`; } -export function FinalStep({ packet, decision, pending, onBack, onAccept, trial = false, defaultOnly = false, rangeChips }: { +export function FinalStep({ packet, decision, pending, onBack, onAccept, onSelfChoice, trial = false, defaultOnly = false, rangeChips }: { readonly packet: FinalPacket; readonly decision: FinalDecision; readonly pending: boolean; @@ -999,6 +1073,7 @@ export function FinalStep({ packet, decision, pending, onBack, onAccept, trial = readonly onAccept: () => void; readonly trial?: boolean; readonly defaultOnly?: boolean; + readonly onSelfChoice?: () => void; readonly rangeChips?: ReactNode; }) { const seconds = decision.saved_at.length === 19 && !decision.saved_at.endsWith(":00"); @@ -1010,19 +1085,21 @@ export function FinalStep({ packet, decision, pending, onBack, onAccept, trial = const hasReportedTime = reported?.reported_known ?? packet.reported_known; const clock = clockLabel(reference); const events = defaultOnly ? [] : decision.events ?? []; + const summary = defaultOnly ? reported?.line_summary : undefined; return
{!pending && onBack ? {defaultOnly ? "返回" : "改答案"} : null}

{hasReportedTime ? `按你填的 ${clock}` : `按范围中点 ${clock}`}

范围 {segmentLabel(defaultWindow, reference)}

{rangeChips} -

现有信息不足以确认更准确的出生时间。

+ {defaultOnly ? null :

现有信息不足以确认更准确的出生时间。

}
{reported ?

按 {clock} 看六张盘

+ {summary ? : null} + reference={reported.saved_at} segment={reported.segment} trial={trial} summary={summary} />
: null} {events.length ?

你提到的事

@@ -1030,6 +1107,8 @@ export function FinalStep({ packet, decision, pending, onBack, onAccept, trial =
: null}
用 {clock} + {summary?.nearest_at && onSelfChoice + ? 自己选线前线后 : null}
; } @@ -1079,9 +1158,10 @@ function ReadingPlan({ ); } -export function HomeView({ history, onStartOver, reportedAt, pending, window, trial = false, activeRetired = false }: { +export function HomeView({ history, onStartOver, onRestore, reportedAt, pending, window, trial = false, activeRetired = false }: { readonly history: ChartChoiceHistory; readonly onStartOver: () => void; + readonly onRestore?: (recordId: string) => void; readonly reportedAt: string | null; readonly pending: boolean; readonly window?: ChartChoiceWindow; @@ -1090,6 +1170,7 @@ export function HomeView({ history, onStartOver, reportedAt, pending, window, tr }) { const current = history.records.find((record) => record.id === history.current_record_id) ?? null; const decision = current?.detail.decision; + const ownChoice = current?.detail.provenance?.basis === SELF_CHOICE_BASIS && current.detail.provenance.declared_by_user === true; const retired = activeRetired || Boolean(current?.retired_reason); const retiredHistory = history.records.filter((record) => record.retired_reason); const reference = reportedAt ?? (window ? new Date(Math.floor((minutesFrom(window.start_at) + minutesFrom(window.end_at)) / 2) * 60_000).toISOString().slice(0, 16) : null); @@ -1114,9 +1195,14 @@ export function HomeView({ history, onStartOver, reportedAt, pending, window, tr )} {decision?.segment ? <>

范围 {segmentLabel(decision.segment)}

+ {ownChoice ? <> +

按你自己的选择

+ + : null} + {decision.line_summary ? : null} + reference={decision.saved_at} segment={decision.segment} trial={trial} summary={decision.line_summary} /> : <>

范围 {segmentLabel(current.detail.window)}

看星盘 重新纠正 + {ownChoice && onRestore ? onRestore(current.id)}>改回我填的时间 : null} ) : (
开始纠正
@@ -1162,6 +1249,64 @@ function BigTime({ time, side }: { readonly time: string; readonly side: ChartCh ); } +function SelfChoiceBothVersions({ domains }: { readonly domains: readonly string[] }) { + const names = domains.map((domain) => CHART_NAMES[CHART_CHOICE_DOMAIN_CHARTS[domain]?.chart]).filter(Boolean); + return names.length ?

两版都读:{names.join("、")}。

: null; +} + +const SELF_CHOICE_OPTIONS = { ...SIDE_TEXT, unsure: "不确定" } as const; + +export function SelfChoiceStep({ preview, reference, stopped, pending, onBack, onPick, onStop, onAccept }: { + readonly preview: SelfChoicePreview; + readonly reference: string; + readonly stopped?: boolean; + readonly pending: boolean; + readonly onBack: () => void; + readonly onPick: (pick: SelfChoicePick) => void; + readonly onStop: () => void; + readonly onAccept: () => void; +}) { + const { decision, next } = preview; + if (next && !stopped) return <> + + {!pending ? 返回 : null} +

{clockLabel(next.at, reference, true)} 分界线

+

范围 {segmentLabel(decision.segment)}

+ +
+ {next.comparisons.map((comparison) => )} + +
+ {(Object.keys(SELF_CHOICE_OPTIONS) as ChartChoiceAnswer[]).map((side) => )} +
+
就到这里
+
+ ; + + const saved = adoptedClock(decision.saved_at, reference); + return + {!pending ? 返回 : null} +

{saved}

+

范围 {segmentLabel(decision.segment)}

+ {decision.choices.length ?
    + {decision.choices.map((pick) =>
  • + {clockLabel(pick.line_at, reference, true)} {SELF_CHOICE_OPTIONS[pick.side]} +
  • )} +
: null} + +

这是你自己选的,可以随时改。

+
用 {saved}
+
; +} + function ChooseStep({ packet, rangeChips, @@ -1234,8 +1379,8 @@ function CompareCard({ }: { readonly comparison: Choose["comparisons"][number]; readonly question: Choose["questions"][number] | null; - readonly answer: ChartChoiceAnswer | undefined; - readonly onAnswer: (domain: string, value: ChartChoiceAnswer) => void; + readonly answer?: ChartChoiceAnswer; + readonly onAnswer?: (domain: string, value: ChartChoiceAnswer) => void; }) { return ( @@ -1270,7 +1415,7 @@ function CompareCard({ role="radio" aria-checked={answer === option.value} className={cn("chart-choice-answer", option.value === "unsure" && "is-unsure", answer === option.value && "is-selected")} - onClick={() => onAnswer(question.domain, option.value)} + onClick={() => onAnswer?.(question.domain, option.value)} > {option.value === "unsure" ? option.text : `${SIDE_TEXT[option.value as ChartChoiceSide]},${option.text}`} diff --git a/frontend/src/lib/chart-choice-both-versions.ts b/frontend/src/lib/chart-choice-both-versions.ts index 4c5815c02..620e6a8f5 100644 --- a/frontend/src/lib/chart-choice-both-versions.ts +++ b/frontend/src/lib/chart-choice-both-versions.ts @@ -7,6 +7,7 @@ * 交给模型一段写明「两版都读」的说明。没有这些字段的旧资料完全不受影响。 */ import { recordOrEmpty as record } from "@/lib/guards"; +import { SELF_CHOICE_BASIS } from "./chart-choice/contract"; /** Domain keys and charts written by scripts/chart_choice/readings.py DOMAIN. */ export const CHART_CHOICE_DOMAIN_CHARTS: Readonly>> = { @@ -15,6 +16,8 @@ export const CHART_CHOICE_DOMAIN_CHARTS: Readonly[]; }>; const minutePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/; +export const CHART_CHOICE_OTHER_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::[0-5]\d)?$/; /** Read the both-versions request from a profile's provenance; null when there is none. */ export function chartChoiceBothVersionsFromProvenance(value: unknown): ChartChoiceBothVersionsInput | null { @@ -33,7 +38,8 @@ export function chartChoiceBothVersionsFromProvenance(value: unknown): ChartChoi if (provenance.source !== "user_choice") return null; if (!Array.isArray(provenance.both_versions) || provenance.both_versions.length === 0) return null; const otherAt = typeof provenance.other_saved_at === "string" ? provenance.other_saved_at : ""; - if (!minutePattern.test(otherAt)) return null; + const selfChoice = provenance.basis === SELF_CHOICE_BASIS && provenance.declared_by_user === true; + if (!(selfChoice ? CHART_CHOICE_OTHER_AT : minutePattern).test(otherAt)) return null; const chosen = provenance.chosen_side; if (chosen !== "before" && chosen !== "after") return null; const seen = new Set(); @@ -46,7 +52,7 @@ export function chartChoiceBothVersionsFromProvenance(value: unknown): ChartChoi domains.push({ domain, chart: known.chart, label: known.label }); } if (domains.length === 0) return null; - return { chosen_side: chosen, other_at: otherAt, domains }; + return { chosen_side: chosen, other_at: otherAt, domains, ...(selfChoice ? { self_choice: true } : {}) }; } export type OtherVersionChart = Readonly<{ @@ -98,9 +104,9 @@ export async function loadOtherVersionCharts( ): Promise { const [date, time] = input.other_at.split("T"); const [year, month, day] = date.split("-").map(Number); - const [hour, minute] = time.split(":").map(Number); + const [hour, minute, second] = time.split(":").map(Number); const birth = { - year, month, day, hour, minute, + year, month, day, hour, minute, ...(second === undefined ? {} : { second }), lat: place.lat, lon: place.lon, tz: place.tz, ...(place.ayanamsa ? { ayanamsa: place.ayanamsa } : {}), ...(place.city ? { city: place.city } : {}), @@ -129,8 +135,10 @@ export async function loadOtherVersionCharts( export function bothVersionsNotice(input: ChartChoiceBothVersionsInput, status: "computed" | "unavailable"): string { const labels = input.domains.map((item) => `${item.label}(${item.chart})`).join("、"); const side = input.chosen_side === "before" ? "分界线前" : "分界线后"; - const otherClock = input.other_at.slice(11, 16); - const head = `这些领域两版都读:${labels}。用户在生时纠正里选了${side}这一版,盘面按它算;但这几个领域用户的回答偏向另一边(${otherClock})。`; + const otherClock = input.other_at.slice(11); + const head = input.self_choice + ? `这些领域两版都读:${labels}。用户在这条分界线上选了「不确定」。当前采用时刻在${side},另一侧用 ${otherClock}。` + : `这些领域两版都读:${labels}。用户在生时纠正里选了${side}这一版,盘面按它算;但这几个领域用户的回答偏向另一边(${otherClock})。`; return status === "computed" ? `${head}讲这几个领域时,两版都说:先按采用的盘讲,再用 chart_choice_both_versions 里另一边的分盘说明哪里不同,不要只给一版的结论。` : `${head}另一边的分盘这次没有算出来,讲这几个领域时要说明还有另一种读法,不要说死。`; diff --git a/frontend/src/lib/chart-choice/contract.ts b/frontend/src/lib/chart-choice/contract.ts index d9aff9df9..34c9742e8 100644 --- a/frontend/src/lib/chart-choice/contract.ts +++ b/frontend/src/lib/chart-choice/contract.ts @@ -43,7 +43,17 @@ export type ChartChoiceResolved = { readonly answers?: Readonly>; readonly override_side?: ChartChoiceSide; } & ChartChoiceEvidenceInput; -export type ChartChoiceLine = { readonly at: string; readonly degree: number; readonly charts: readonly string[] }; +export type ChartChoiceFlip = Readonly<{ before: string; after: string }>; +export type ChartChoiceLine = { + readonly at: string; + readonly degree: number; + readonly charts: readonly string[]; + readonly flips?: Readonly>; +}; +export type ChartChoiceLineSummary = Readonly<{ + nearest_at: string | null; + charts: Readonly>>; +}>; export type ChartChoiceMinorLine = Pick; export type ChartChoiceKeyChart = { readonly chart: string; @@ -89,6 +99,7 @@ export type ChartChoiceRoundResult = { readonly evidence_summary?: ChartChoiceEvidenceSummary; readonly events_detail?: readonly ChartChoiceEventDetail[]; readonly key_charts?: readonly ChartChoiceKeyChart[]; + readonly line_summary?: ChartChoiceLineSummary; readonly conflict?: readonly { readonly chart: string; readonly question: string; readonly kind: ChartChoiceQuestionKind }[]; readonly asked?: readonly { readonly id: string; @@ -107,7 +118,7 @@ export type ChartChoiceCompletion = ChartChoiceRoundResult & { readonly rule: "stopped" | "round_limit" | "no_line_in_range" | "chart_answers" | "reported_time_default" | "window_midpoint_default"; readonly reported_choice?: Pick & { + "segment" | "key_charts" | "line_summary" | "undetermined_charts" | "remaining_key_lines"> & { readonly saved_at: string; readonly reported_known?: boolean; }; @@ -220,6 +231,29 @@ export type ChartChoiceDecision = { } & Partial & ChartChoiceEvidence; /** What the page shows before any engine call: the declared range, or a prompt to give one. */ +export const SELF_CHOICE_BASIS = "self_choice_20261116"; + +export type SelfChoicePick = Readonly<{ line_at: string; side: ChartChoiceAnswer }>; +export type SelfChoiceRequest = Readonly<{ + subjectId?: string; + window?: ChartChoiceWindow; + choices: readonly SelfChoicePick[]; +}>; +export type SelfChoiceDecision = Readonly<{ + saved_at: string; + segment: ChartChoiceWindow; + choices: readonly SelfChoicePick[]; + key_charts: readonly ChartChoiceKeyChart[]; + line_summary: ChartChoiceLineSummary; + chosen_side?: ChartChoiceSide; + both_versions: readonly string[]; + other_saved_at?: string; +}>; +export type SelfChoicePreview = Readonly<{ + decision: SelfChoiceDecision; + next?: ChartChoiceLine & { readonly comparisons: readonly ChartChoiceComparison[] }; +}>; + export type ChartChoiceStart = | { readonly status: "ready"; @@ -247,12 +281,18 @@ export type ChartChoiceRecordDetail = { readonly decision: { readonly chosen_side: ChartChoiceSide | "none"; readonly rule: string; - readonly votes: ChartChoiceDecision["votes"]; + readonly votes?: ChartChoiceDecision["votes"]; readonly both_versions_domains: readonly string[]; readonly saved_at: string; } & Partial & ChartChoiceEvidence; /** The adoption data saved by the history RPC. */ - readonly provenance?: { readonly contract?: string; readonly segment?: ChartChoiceWindow; readonly source?: string }; + readonly provenance?: { + readonly contract?: string; + readonly segment?: ChartChoiceWindow; + readonly source?: string; + readonly basis?: string; + readonly declared_by_user?: boolean; + }; /** Labels of the flipped charts with both sides' ascendant, in comparison order. */ readonly charts: readonly { readonly chart: string; readonly label: string; readonly domain: string }[]; }; diff --git a/frontend/src/lib/chart-choice/server.ts b/frontend/src/lib/chart-choice/server.ts index 26b6631cc..471e75760 100644 --- a/frontend/src/lib/chart-choice/server.ts +++ b/frontend/src/lib/chart-choice/server.ts @@ -21,8 +21,11 @@ import type { ChartChoiceQuestionnaire, ChartChoiceStart, ChartChoiceWindow, + SelfChoiceDecision, + SelfChoicePreview, + SelfChoiceRequest, } from "./contract.ts"; -import { DEFAULT_RANGE_MINUTES, RECORD_RANGE_CHOICES } from "./contract.ts"; +import { DEFAULT_RANGE_MINUTES, RECORD_RANGE_CHOICES, SELF_CHOICE_BASIS } from "./contract.ts"; import type { AstrologerPacket, AstrologerRequest } from "./astrologer-contract.ts"; import { windowAround } from "./view.ts"; import { declaredNeedsRange } from "./declared.ts"; @@ -207,6 +210,16 @@ export async function readChartChoiceStart(supabase: unknown, admin: RpcClient, if (!declared) return { status: "unavailable", subjectId: subject.subjectId, reason: "profile_incomplete" }; const adjustable = declaredNeedsRange(declared); const history = await readHistory(admin, userId, subject.subjectId); + const current = history.records.find((record) => record.id === history.current_record_id && record.reusable); + // Older default records predate the flip summaries. Fill this view from the + // original scan range without changing the saved record. + const currentDecision = current?.detail.decision; + const display = current && currentDecision && !currentDecision.line_summary + && ["reported_time_default", "window_midpoint_default", "no_line_in_range"].includes(current.rule) + ? await defaultChartChoiceOutcome(subject, current.detail.window) + .then(({ reported }) => reported.saved_at === currentDecision.saved_at ? reported : undefined) + .catch(() => undefined) + : undefined; return { status: "ready", subjectId: subject.subjectId, @@ -219,8 +232,12 @@ export async function readChartChoiceStart(supabase: unknown, admin: RpcClient, history: { ...history, records: history.records.map((record) => { const retired = historicChoiceRetired(record); const retirement = retired ? { retired_reason: RETIRED_BIRTH_WINDOW_REASON, reusable: false } as const : {}; - if (!record.detail.decision.asked) return { ...record, ...retirement }; - const decision = { ...record.detail.decision }; + const currentView = record.id === current?.id && display?.line_summary ? display : undefined; + if (!record.detail.decision.asked && !currentView) return { ...record, ...retirement }; + const decision = currentView + ? { ...record.detail.decision, segment: currentView.segment, line_summary: currentView.line_summary, + key_charts: currentView.key_charts } + : { ...record.detail.decision }; delete decision.asked; delete decision.conflict; return { ...record, ...retirement, detail: { ...record.detail, decision } }; @@ -389,6 +406,7 @@ function roundFields(decision: Partial): Partial; +function originalChoiceWindow(subject: Subject, window?: ChartChoiceWindow): ChartChoiceWindow { + const requested = scanWindow(subject, window); + return subject.declared && declaredNeedsRange(subject.declared) ? requested : scanWindow(subject, undefined); +} + async function loadDefaultChartChoice(supabase: unknown, userId: string, request: DefaultChoiceRequest, fetchImpl?: typeof fetch) { const subject = await loadSubject(supabase, userId, request.subjectId); - const requested = scanWindow(subject, request.window); - const window = subject.declared && declaredNeedsRange(subject.declared) ? requested : scanWindow(subject, undefined); - return defaultChartChoiceOutcome(subject, window, fetchImpl); + return defaultChartChoiceOutcome(subject, originalChoiceWindow(subject, request.window), fetchImpl); } export async function readDefaultChartChoice( @@ -555,8 +576,11 @@ export async function restoreChartChoiceDefault( const subject = await loadSubject(supabase, userId, request.subjectId); const history = await readHistory(admin, userId, subject.subjectId); const current = history.records.find((record) => record.id === history.current_record_id); + const provenance = current?.detail.provenance; + const selfChoice = provenance?.source === "user_choice" && provenance.basis === SELF_CHOICE_BASIS + && provenance.declared_by_user === true; if (current?.id !== request.recordId || !current.reusable - || current.detail.provenance?.source !== "user_choice_from_answers") { + || (!selfChoice && provenance?.source !== "user_choice_from_answers")) { throw new ChartChoiceError("record_stale", 409); } const choice = await defaultChartChoiceOutcome(subject, scanWindow(subject, undefined), fetchImpl); @@ -568,6 +592,90 @@ export async function restoreChartChoiceDefault( return { saved_at: decision.saved_at }; } +async function evaluateSelfChoice( + supabase: unknown, userId: string, request: SelfChoiceRequest, saving: boolean, fetchImpl?: typeof fetch, +) { + const subject = await loadSubject(supabase, userId, request.subjectId); + const window = originalChoiceWindow(subject, request.window); + if (request.window && subject.declared && declaredNeedsRange(subject.declared)) { + const reference = subject.declared.start_at; + if (!RECORD_RANGE_CHOICES.some((minutes) => sameWindow(window, windowAround(reference, minutes)))) { + throw new ChartChoiceError("bad_window", 400); + } + } + const body = { ...engineBody(subject, window), self_choice: true, choices: request.choices }; + const result = await engine( + saving ? "/api/chart_choice/decide" : "/api/chart_choice/packet", + body, fetchImpl, RESTORE_WIDE_RANGE_TIMEOUT_MS, + ); + return { subject, window, result, reported: subject.declared ? reportedAt(subject.declared) : null }; +} + +export async function previewSelfChoice(supabase: unknown, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch) { + const { result } = await evaluateSelfChoice(supabase, userId, request, false, fetchImpl); + return result; +} + +function sameWindow(value: unknown, window: ChartChoiceWindow): boolean { + const prior = asRecord(value); + return prior?.start_at === window.start_at && prior?.end_at === window.end_at; +} + +function alreadyUsingSelfChoice(active: Subject["active"], window: ChartChoiceWindow, decision: SelfChoiceDecision): boolean { + const prior = asRecord(active.provenance); + const [date, time] = decision.saved_at.split("T"); + return prior?.source === "user_choice" && prior.basis === SELF_CHOICE_BASIS && prior.declared_by_user === true + && active.date === date && sameSavedClock(time, active.time) + && sameWindow(prior.window, window) && sameWindow(prior.segment, decision.segment) + && Array.isArray(prior.choices) && prior.choices.length === decision.choices.length + && prior.choices.every((value, index) => { + const pick = asRecord(value); + return pick?.line_at === decision.choices[index].line_at && pick.side === decision.choices[index].side; + }) + && prior.other_saved_at === (decision.other_saved_at ?? null) + && JSON.stringify(prior.both_versions) === JSON.stringify(decision.both_versions); +} + +export async function adoptSelfChoice( + supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch, +): Promise<{ decision: SelfChoiceDecision }> { + const { subject, window, result: { decision }, reported } = await evaluateSelfChoice(supabase, userId, request, true, fetchImpl); + const active = await activeChoice(supabase, subject, userId); + if (alreadyUsingSelfChoice(active, window, decision)) return { decision }; + + const [date, time] = decision.saved_at.split("T"); + const rule = "user_override"; + const provenance = { + contract: ROUNDS_VERSION, engine_version: ROUNDS_VERSION, + source: "user_choice", rule, declared_by_user: true, basis: SELF_CHOICE_BASIS, + segment: decision.segment, window, reported_at: reported, choices: decision.choices, + chosen_side: decision.chosen_side, other_saved_at: decision.other_saved_at ?? null, both_versions: decision.both_versions, + undetermined_charts: Object.keys(decision.line_summary.charts), rounds: [], events: [], + adopted_at: new Date().toISOString(), + }; + const detail: ChartChoiceRecordDetail = { + window, reported_at: reported ?? midpointAt(window), line: null, + other_lines: 0, questions: [], answers: {}, unchanged: [], charts: [], + decision: { + saved_at: decision.saved_at, segment: decision.segment, key_charts: decision.key_charts, + line_summary: decision.line_summary, undetermined_charts: provenance.undetermined_charts, + both_versions_domains: decision.both_versions, chosen_side: decision.chosen_side ?? "none", rule, + }, + }; + const { error } = await admin.rpc("chart_choice_adopt_v4", { + p_user_id: userId, + p_chart_profile_id: subject.subjectId === SELF_SUBJECT_ID ? null : subject.subjectId, + p_time: time.length === 5 ? time + ":00" : time, + p_date: date, p_offset: subject.location.tz, p_detail: detail, p_provenance: provenance, + ...rangeToSave(subject, undefined, false), + }); + if (error) { + if (String(error.message ?? "").includes("chart_choice_subject_not_found")) throw new ChartChoiceError("subject_not_found", 404); + throw new ChartChoiceError("engine_unavailable", 503); + } + return { decision }; +} + function choiceFromEvent(packet: ChartChoiceEnginePacket, decision: ChartChoiceDecision | ChartChoiceCompletion): boolean { return packet.engine_version !== ROUNDS_VERSION && birthWindowRetired({ contract: "chart-choice-v1" }, decision); } @@ -589,6 +697,7 @@ async function saveChartChoice(admin: RpcClient, userId: string, request: ChartC decision = { ...reported, rule, resolved: [], rounds: [], events: [], has_next: false, asked: decision.asked, + ...(reported.line_summary ? { line_summary: reported.line_summary } : {}), }; } const multi = packet.engine_version === ROUNDS_VERSION; diff --git a/frontend/src/mastra/consultation-workflow.ts b/frontend/src/mastra/consultation-workflow.ts index cb644795b..f705fda4a 100644 --- a/frontend/src/mastra/consultation-workflow.ts +++ b/frontend/src/mastra/consultation-workflow.ts @@ -10,7 +10,7 @@ import { } from "../lib/calculation-modes.ts"; import { applyUnreliableVargasToWorkflowContext } from "../lib/consultation-birth-time-mode.ts"; import { recordOrEmpty as record } from "@/lib/guards"; -import { applyBothVersionsToWorkflowContext, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts"; +import { applyBothVersionsToWorkflowContext, CHART_CHOICE_OTHER_AT, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts"; export const consultationInputSchema = z.object({ year: z.number().int().min(1900).max(2100), @@ -45,7 +45,8 @@ export const consultationInputSchema = z.object({ // consultation workflow; only the other side's charts are fetched for it. chart_choice_both_versions: z.object({ chosen_side: z.enum(["before", "after"]), - other_at: z.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/), + other_at: z.string().regex(CHART_CHOICE_OTHER_AT), + self_choice: z.literal(true).optional(), domains: z.array(z.object({ domain: z.string(), chart: z.string(), label: z.string() })).min(1), }).optional(), }); diff --git a/frontend/tests/chart-choice-self-choice-20261116.test.tsx b/frontend/tests/chart-choice-self-choice-20261116.test.tsx new file mode 100644 index 000000000..fc712e055 --- /dev/null +++ b/frontend/tests/chart-choice-self-choice-20261116.test.tsx @@ -0,0 +1,274 @@ +import "./install-test-document"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { ChartChoiceFlow, FinalStep } from "../src/components/chart-choice/chart-choice-page"; +import { chartChoiceBothVersionsFromProvenance, loadOtherVersionCharts } from "../src/lib/chart-choice-both-versions"; +import { SELF_CHOICE_BASIS, type ChartChoiceEnginePacket, type ChartChoiceRecord, + type ChartChoiceStart, type SelfChoicePreview } from "../src/lib/chart-choice/contract"; +import { createClientLifecycleHarness } from "./react-client-lifecycle-test-support"; + +Object.assign(globalThis, { React }); +type Complete = Extract; +const fixtures = JSON.parse(readFileSync(new URL("./fixtures/chart-choice-self-choice-20261116.json", import.meta.url), "utf8")) as { + reported: Complete; stable: Complete; midnight: Complete; minuteDistance: Complete; + first: SelfChoicePreview; before: SelfChoicePreview; after: SelfChoicePreview; + finished: SelfChoicePreview; unsure: SelfChoicePreview; +}; +const forbiddenCopy = /推荐|更可能|把握|已纠正|已校正|已确认|票数|\d+\s*票/; + +test("self-choice result describes the six charts from real transitions and only offers a choice with lines", () => { + const render = (packet: Complete) => renderToStaticMarkup( {}} onSelfChoice={() => {}} />); + const reported = render(fixtures.reported); + assert.match(reported, /不受影响:主盘。/); + assert.match(reported, /差几分钟就不同:婚恋、事业、钱财、日常、突变。/); + assert.match(reported, /04:59:43 之前巨蟹上升,之后狮子上升等 5 处/); + assert.match(reported, /你填的 05:00 离 04:59:43 这条线只有 17 秒。/); + assert.match(reported, />自己选线前线后<\/button>/); + assert.doesNotMatch(reported, forbiddenCopy); + + const stable = render(fixtures.stable); + assert.match(stable, /这个时间范围内六张盘都不变,可以直接用。/); + assert.doesNotMatch(stable, /自己选线前线后/); + const midnight = render(fixtures.midnight); + assert.match(midnight, /你填的 00:00 离 8月8日 23:59:35 这条线只有 25 秒。/); + assert.match(render(fixtures.minuteDistance), /这条线只有 1 分 17 秒。/); +}); + +test("self-choice page selects each line once, stops or keeps narrowing, and offers restore on readback", async () => { + for (const scenario of [ + { actions: ["线前", "线后"], previews: [fixtures.before, fixtures.finished], end: fixtures.finished, time: "04:55" }, + { actions: ["线后", "就到这里"], previews: [fixtures.after], end: fixtures.after, time: "05:00" }, + { actions: ["不确定"], previews: [fixtures.unsure], end: fixtures.unsure, time: "05:00" }, + ]) { + const h = createClientLifecycleHarness(); + let current: ChartChoiceRecord | undefined; + let calls = 0; + let restored = false; + const originalFetch = globalThis.fetch; + const packet = fixtures.reported; + const recordId = "00000000-0000-4000-8000-000000000301"; + globalThis.fetch = async (url, request) => { + const path = String(url); + if (path.startsWith("/api/chart-choice?")) { + const start: ChartChoiceStart = { + status: "ready", subjectId: "self", name: "虚构人物", window: packet.window, + reportedAt: packet.reported_at, precision: "minutes", rangeAdjustable: false, + history: { current_record_id: current?.id ?? null, records: current ? [current] : [] }, + }; + return Response.json(start); + } + if (path === "/api/chart-choice/packet") return Response.json(packet); + assert.equal(path, "/api/chart-choice/adopt"); + const body = JSON.parse(String(request?.body)); + if (body.mode === "restore_default") { + assert.deepEqual(body, { mode: "restore_default", subjectId: "self", recordId }); + restored = true; + const original = packet.decision.reported_choice!; + current = { + ...current!, rule: "reported_time_default", saved_time: original.saved_at.slice(11), + detail: { ...current!.detail, provenance: { source: "reported_time_default" }, + decision: { ...current!.detail.decision, ...original, rule: "reported_time_default", both_versions_domains: [] } }, + }; + return Response.json({ saved_at: original.saved_at }); + } + assert.deepEqual(Object.keys(body).sort(), ["choices", "mode", "selfChoice", "subjectId"]); + assert.equal(body.selfChoice, true); + if (body.mode === "preview") { + const next = [fixtures.first, ...scenario.previews][calls++]; + assert.deepEqual(body.choices, next.decision.choices); + return Response.json(next); + } + assert.equal(body.mode, "choice"); + const decision = scenario.end.decision; + assert.deepEqual(body.choices, decision.choices); + current = { + id: recordId, created_at: "2026-11-16T00:00:00Z", saved_date: decision.saved_at.slice(0, 10), + saved_time: decision.saved_at.slice(11), chosen_side: decision.chosen_side ?? "none", rule: "user_override", reusable: true, + detail: { + window: packet.window, reported_at: packet.reported_at, + line: null, other_lines: 0, questions: [], answers: {}, unchanged: [], charts: [], + decision: { ...decision, chosen_side: decision.chosen_side ?? "none", rule: "user_override", + both_versions_domains: decision.both_versions }, + provenance: { source: "user_choice", basis: SELF_CHOICE_BASIS, declared_by_user: true }, + }, + }; + return Response.json({ decision }); + }; + const waitFor = async (text: string) => { + for (let i = 0; i < 10 && !h.elements().some((element) => element.text === text); i += 1) await h.idle(); + assert.ok(h.elements().some((element) => element.text === text), text); + assert.equal(h.elements().some((element) => forbiddenCopy.test(element.text)), false); + }; + const click = async (name: string) => { + await waitFor(name); + await h.event(h.elements().find((element) => element.tagName === "BUTTON" && element.text === name)!); + }; + try { + await h.render(); + await click("自己选线前线后"); + await waitFor("04:59:43 分界线"); + for (const action of scenario.actions) { + assert.equal(h.elements().filter((element) => element.tagName === "BUTTON" && element.text === "不确定").length, 1); + await click(action); + if (action === "线前") await waitFor("04:51:30 分界线"); + if (action === "线后" && scenario.end === fixtures.after) await waitFor("05:07:55 分界线"); + } + await waitFor("这是你自己选的,可以随时改。"); + for (const pick of scenario.end.decision.choices) { + const side = { before: "线前", after: "线后", unsure: "不确定" }[pick.side]; + await waitFor(pick.line_at.slice(11) + " " + side); + } + await click("用 " + scenario.time); + await waitFor("当前使用"); + await waitFor("按你自己的选择"); + await click("改回我填的时间"); + await waitFor("05:00"); + assert.equal(restored, true); + assert.equal(h.elements().some((element) => element.text === "按你自己的选择"), false); + assert.equal(calls, 1 + scenario.previews.length); + assert.equal(h.errors.length, 0); + } finally { + globalThis.fetch = originalFetch; + await h.close(); + } + } +}); + +test("self-choice API recomputes from storage, preserves declaration, de-duplicates retries and restores the original", () => { + const program = ` + import assert from "node:assert/strict"; + import { mock } from "node:test"; + import { readFileSync } from "node:fs"; + const fixture = JSON.parse(readFileSync("tests/fixtures/chart-choice-self-choice-20261116.json", "utf8")); + const { reported, finished, unsure, first } = fixture; + const recordId = "00000000-0000-4000-8000-000000000301"; + const declared = { + name: "虚构人物", birth_date: reported.reported_at.slice(0, 10), reported_birth_time: reported.reported_at.slice(11), + birth_time_source: "approximate", declared_window_start: reported.window.start_at.slice(11), + declared_window_end: reported.window.end_at.slice(11), uncertainty_before_minutes: 30, + uncertainty_after_minutes: 30, birth_time_uncertainty_known: true, latitude: 36.42, longitude: 114.21, + timezone_offset: 8, timezone_id: "Asia/Shanghai", birth_place_label: "虚构市", + }; + const row = { ...declared, birth_time_status: "reported" }; + const supabase = { + auth: { getUser: async () => ({ data: { user: { id: "fixture" } } }) }, + from: () => ({ select: () => ({ eq: () => ({ maybeSingle: async () => ({ data: row, error: null }) }) }) }), + }; + const writes = []; + const records = []; + const admin = { rpc: async (name, args) => { + if (name === "chart_choice_records_v1") { + return { data: { current_record_id: recordId, records }, error: null }; + } + assert.equal(name, "chart_choice_adopt_v4"); + assert.equal(args.p_chart_profile_id, null); + for (const key of ["p_window_start", "p_window_end", "p_before_minutes", "p_after_minutes"]) { + assert.equal(args[key], null); + } + writes.push(args); + row.active_birth_provenance = { ...args.p_provenance, record_id: recordId }; + row.active_birth_time = args.p_time; + row.active_birth_date = args.p_date; + row.birth_time_status = "accepted"; + records.unshift({ id: recordId, reusable: true, detail: { ...args.p_detail, provenance: args.p_provenance } }); + return { data: { record_id: recordId }, error: null }; + } }; + mock.module("server-only", { namedExports: {} }); + mock.module("@/lib/supabase/server", { namedExports: { createServerSupabaseClient: async () => supabase } }); + mock.module("@/lib/supabase/admin", { namedExports: { createAdminSupabaseClient: () => admin } }); + mock.module("@/lib/product-access", { namedExports: { isProductEnabled: async () => true } }); + mock.module("@/lib/request-rate-limit", { namedExports: { consumeUserRequestRateLimit: () => ({ ok: true }) } }); + const { POST } = await import("./src/app/api/chart-choice/adopt/route.ts"); + const { chartChoiceBothVersionsFromProvenance } = await import("./src/lib/chart-choice-both-versions.ts"); + const engine = []; + globalThis.fetch = async (url, init) => { + const body = JSON.parse(init.body); + assert.equal(body.start_at, reported.window.start_at); + assert.equal(body.end_at, reported.window.end_at); + assert.equal(body.reported_at, reported.reported_at); + assert.equal("saved_at" in body || "segment" in body || "answers" in body || "resolved" in body, false); + engine.push([new URL(url).pathname, body]); + if (!body.self_choice) { + assert.equal(body.stop, true); + return Response.json(reported); + } + const result = [first, finished, unsure].find((response) => + JSON.stringify(response.decision.choices) === JSON.stringify(body.choices)); + assert.ok(result); + return Response.json(String(url).endsWith("/packet") ? result : { decision: result.decision }); + }; + const post = (body) => POST(new Request("http://localhost/api/chart-choice/adopt", { + method: "POST", body: JSON.stringify(body), + })); + const forged = await post({ selfChoice: true, choices: [], saved_at: reported.window.end_at }); + assert.equal(forged.status, 400); + assert.equal(engine.length, 0); + const preview = await post({ selfChoice: true, mode: "preview", choices: [] }); + assert.equal(preview.status, 200); + assert.deepEqual(await preview.json(), first); + const narrow = { start_at: reported.reported_at, end_at: reported.window.end_at }; + for (let repeat = 0; repeat < 2; repeat++) { + const response = await post({ selfChoice: true, choices: finished.decision.choices, window: narrow }); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { decision: finished.decision }); + } + assert.equal(writes.length, 1); + assert.equal(engine.filter(([path, body]) => path.endsWith("/decide") && body.self_choice).length, 2); + const saved = row.active_birth_provenance; + assert.equal(saved.source, "user_choice"); + assert.equal(saved.rule, "user_override"); + assert.equal(saved.declared_by_user, true); + assert.equal(saved.basis, "self_choice_20261116"); + assert.equal(saved.votes, undefined); + assert.equal(records[0].detail.decision.votes, undefined); + assert.deepEqual(saved.segment, finished.decision.segment); + assert.equal(row.active_birth_time, finished.decision.saved_at.slice(11) + ":00"); + assert.equal(row.birth_time_status, "accepted"); + assert.deepEqual(Object.fromEntries(Object.keys(declared).map((key) => [key, row[key]])), declared); + + const uncertain = await post({ selfChoice: true, choices: unsure.decision.choices }); + assert.equal(uncertain.status, 200); + const both = chartChoiceBothVersionsFromProvenance(row.active_birth_provenance); + assert.deepEqual(both.domains.map(({ chart }) => chart), ["D10", "D2", "D6", "D8"]); + assert.equal(both.chosen_side, "after"); + assert.equal(row.active_birth_time, declared.reported_birth_time + ":00"); + assert.ok(both.other_at < first.next.at); + + const restored = await post({ mode: "restore_default", recordId }); + assert.equal(restored.status, 200); + assert.deepEqual(await restored.json(), { saved_at: reported.reported_at }); + assert.equal(row.active_birth_time, declared.reported_birth_time + ":00"); + assert.deepEqual(row.active_birth_provenance.segment, reported.window); + assert.equal(row.active_birth_provenance.source, "reported_time_default"); + assert.equal(chartChoiceBothVersionsFromProvenance(row.active_birth_provenance), null); + assert.deepEqual(Object.fromEntries(Object.keys(declared).map((key) => [key, row[key]])), declared); + `; + const run = spawnSync(process.execPath, ["--experimental-test-module-mocks", "--import", "tsx", "--input-type=module", "--eval", program], { + cwd: new URL("..", import.meta.url), encoding: "utf8", timeout: 25_000, + }); + assert.equal(run.status, 0, run.stderr || run.stdout || run.error?.message); +}); + +test("self-choice two-version projection preserves the opposite side’s second", async () => { + const input = chartChoiceBothVersionsFromProvenance({ + source: "user_choice", declared_by_user: true, basis: SELF_CHOICE_BASIS, chosen_side: "before", + other_saved_at: "1997-08-08T04:59:43", both_versions: ["pressure", "change"], + }); + assert.ok(input); + const requests: Record[] = []; + const block = await loadOtherVersionCharts({ lat: 36.42, lon: 114.21, tz: 8 }, input, async (_path, body) => { + requests.push(body); + return {}; + }); + assert.equal(block.status, "computed"); + assert.deepEqual(requests.map((body) => body.second), [43, 43]); + assert.deepEqual(requests[1].divisions, ["D6", "D8"]); + assert.match(block.notice, /选了「不确定」/); + assert.doesNotMatch(block.notice, /回答偏向/); +}); diff --git a/frontend/tests/fixtures/chart-choice-self-choice-20261116.json b/frontend/tests/fixtures/chart-choice-self-choice-20261116.json new file mode 100644 index 000000000..14feaf1e6 --- /dev/null +++ b/frontend/tests/fixtures/chart-choice-self-choice-20261116.json @@ -0,0 +1,1391 @@ +{ + "reported": { + "engine_version": "chart-choice-v2", + "status": "complete", + "window": { + "start_at": "1997-08-08T04:30", + "end_at": "1997-08-08T05:30" + }, + "reported_at": "1997-08-08T05:00", + "reported_known": true, + "saved_at": "1997-08-08T05:00", + "decision": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:30:00", + "end_at": "1997-08-08T05:30:00" + }, + "rounds": [], + "undetermined_charts": [ + "D9", + "D10", + "D2", + "D6", + "D8" + ], + "events": [], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "events_detail": [], + "evidence_summary": { + "event_count": 0, + "matched": 0, + "confidence": "tendency_only", + "coverage": { + "event_count": 0, + "category_count": 0, + "group_count": 0, + "groups": [], + "year_span": 0, + "level": "thin" + }, + "caveat": "这一步按占星师的方法计算,结果只作参考,不是验证结果。2026-11-06 我们在 77 个出生时间有可靠记录的案例上回测过同类的事件打分:30 分钟范围里头名命中 19%,随机挑也是 20%,直接用报的时间是 34%。" + }, + "remaining_key_lines": 11, + "has_next": false, + "rule": "stopped", + "reported_choice": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:30", + "end_at": "1997-08-08T05:30" + }, + "reported_known": true, + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "undetermined_charts": [ + "D9", + "D10", + "D2", + "D6", + "D8" + ], + "remaining_key_lines": 11, + "line_summary": { + "nearest_at": "1997-08-08T04:59:43", + "charts": { + "D10": { + "at": "1997-08-08T04:59:43", + "count": 5, + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "at": "1997-08-08T04:59:43", + "count": 1, + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "射手", + "after": "摩羯" + }, + "D8": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "巨蟹", + "after": "狮子" + }, + "D9": { + "at": "1997-08-08T05:07:55", + "count": 4, + "before": "天蝎", + "after": "射手" + } + } + } + }, + "resolved": [], + "stop_reason": "stopped" + } + }, + "stable": { + "engine_version": "chart-choice-v2", + "status": "complete", + "window": { + "start_at": "1997-08-08T05:01", + "end_at": "1997-08-08T05:02" + }, + "reported_at": "1997-08-08T05:01", + "reported_known": true, + "saved_at": "1997-08-08T05:01", + "decision": { + "saved_at": "1997-08-08T05:01:30", + "segment": { + "start_at": "1997-08-08T05:01:00", + "end_at": "1997-08-08T05:02:00" + }, + "rounds": [], + "undetermined_charts": [], + "events": [], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "events_detail": [], + "evidence_summary": { + "event_count": 0, + "matched": 0, + "confidence": "tendency_only", + "coverage": { + "event_count": 0, + "category_count": 0, + "group_count": 0, + "groups": [], + "year_span": 0, + "level": "thin" + }, + "caveat": "这一步按占星师的方法计算,结果只作参考,不是验证结果。2026-11-06 我们在 77 个出生时间有可靠记录的案例上回测过同类的事件打分:30 分钟范围里头名命中 19%,随机挑也是 20%,直接用报的时间是 34%。" + }, + "remaining_key_lines": 0, + "has_next": false, + "rule": "stopped", + "reported_choice": { + "saved_at": "1997-08-08T05:01", + "segment": { + "start_at": "1997-08-08T05:01", + "end_at": "1997-08-08T05:02" + }, + "reported_known": true, + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null + } + ], + "undetermined_charts": [], + "remaining_key_lines": 0, + "line_summary": { + "nearest_at": null, + "charts": {} + } + }, + "resolved": [], + "stop_reason": "stopped" + } + }, + "midnight": { + "engine_version": "chart-choice-v2", + "status": "complete", + "window": { + "start_at": "1997-08-08T23:48", + "end_at": "1997-08-09T00:10" + }, + "reported_at": "1997-08-09T00:00", + "reported_known": true, + "saved_at": "1997-08-09T00:00", + "decision": { + "saved_at": "1997-08-09T00:00", + "segment": { + "start_at": "1997-08-08T23:48:00", + "end_at": "1997-08-09T00:10:00" + }, + "rounds": [], + "undetermined_charts": [ + "D1", + "D9", + "D10", + "D6", + "D8" + ], + "events": [], + "key_charts": [ + { + "chart": "D1", + "sign": "金牛", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D9", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D10", + "sign": "水瓶", + "decided_by": null, + "flips_at": "1997-08-08T23:59:35" + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "天秤", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D8", + "sign": "射手", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + } + ], + "events_detail": [], + "evidence_summary": { + "event_count": 0, + "matched": 0, + "confidence": "tendency_only", + "coverage": { + "event_count": 0, + "category_count": 0, + "group_count": 0, + "groups": [], + "year_span": 0, + "level": "thin" + }, + "caveat": "这一步按占星师的方法计算,结果只作参考,不是验证结果。2026-11-06 我们在 77 个出生时间有可靠记录的案例上回测过同类的事件打分:30 分钟范围里头名命中 19%,随机挑也是 20%,直接用报的时间是 34%。" + }, + "remaining_key_lines": 6, + "has_next": false, + "rule": "stopped", + "reported_choice": { + "saved_at": "1997-08-09T00:00", + "segment": { + "start_at": "1997-08-08T23:48", + "end_at": "1997-08-09T00:10" + }, + "reported_known": true, + "key_charts": [ + { + "chart": "D1", + "sign": "金牛", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D9", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D10", + "sign": "水瓶", + "decided_by": null, + "flips_at": "1997-08-08T23:59:35" + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "天秤", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + }, + { + "chart": "D8", + "sign": "射手", + "decided_by": null, + "flips_at": "1997-08-08T23:49:52" + } + ], + "undetermined_charts": [ + "D1", + "D9", + "D10", + "D6", + "D8" + ], + "remaining_key_lines": 6, + "line_summary": { + "nearest_at": "1997-08-08T23:59:35", + "charts": { + "D10": { + "at": "1997-08-08T23:59:35", + "count": 2, + "before": "摩羯", + "after": "水瓶" + }, + "D9": { + "at": "1997-08-09T00:00:41", + "count": 2, + "before": "摩羯", + "after": "水瓶" + }, + "D8": { + "at": "1997-08-09T00:02:03", + "count": 2, + "before": "射手", + "after": "摩羯" + }, + "D6": { + "at": "1997-08-09T00:06:13", + "count": 2, + "before": "天秤", + "after": "天蝎" + }, + "D1": { + "at": "1997-08-08T23:49:52", + "count": 1, + "before": "白羊", + "after": "金牛" + } + } + } + }, + "resolved": [], + "stop_reason": "stopped" + } + }, + "first": { + "decision": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:30:00", + "end_at": "1997-08-08T05:30:00" + }, + "choices": [], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "line_summary": { + "nearest_at": "1997-08-08T04:59:43", + "charts": { + "D10": { + "at": "1997-08-08T04:59:43", + "count": 5, + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "at": "1997-08-08T04:59:43", + "count": 1, + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "射手", + "after": "摩羯" + }, + "D8": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "巨蟹", + "after": "狮子" + }, + "D9": { + "at": "1997-08-08T05:07:55", + "count": 4, + "before": "天蝎", + "after": "射手" + } + } + }, + "both_versions": [] + }, + "next": { + "at": "1997-08-08T04:59:43", + "degree": 15.0, + "charts": [ + "D10", + "D2", + "D6", + "D8" + ], + "flips": { + "D10": { + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "before": "射手", + "after": "摩羯" + }, + "D8": { + "before": "巨蟹", + "after": "狮子" + } + }, + "comparisons": [ + { + "chart": "D10", + "label": "事业", + "chart_label": "事业盘 D10", + "before": { + "chart": "D10", + "domain": "career", + "label": "事业", + "chart_label": "事业盘 D10", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "occupant", + "fact": "金星在事业位", + "meaning": "审美、设计和人缘,讲究舒适" + }, + { + "kind": "lord", + "fact": "管事业的星(火星)落在第 5 宫", + "meaning": "靠专长、兴趣和脑力吃饭,偏技术、研究、创作或教育" + }, + { + "kind": "lord", + "fact": "代表你自己的星(月亮)落在第 3 宫", + "meaning": "主动、爱表达,靠自己闯" + } + ] + }, + "after": { + "chart": "D10", + "domain": "career", + "label": "事业", + "chart_label": "事业盘 D10", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "occupant", + "fact": "木星在事业位", + "meaning": "大平台和贵人,重学识、有分寸" + }, + { + "kind": "occupant", + "fact": "罗睺在事业位", + "meaning": "野心大、不走寻常路,和外来或新兴的东西有缘" + }, + { + "kind": "occupant", + "fact": "土星在命位", + "meaning": "慢热、担责任、能坚持,早年辛苦、后劲足" + }, + { + "kind": "lord", + "fact": "管事业的星(金星)落在第 9 宫", + "meaning": "遇到导师、去远方、读更高的学历会推动事业" + }, + { + "kind": "lord", + "fact": "代表你自己的星(太阳)落在第 3 宫", + "meaning": "主动、爱表达,靠自己闯" + } + ] + } + }, + { + "chart": "D2", + "label": "钱财", + "chart_label": "钱财盘 D2", + "before": { + "chart": "D2", + "domain": "money", + "label": "钱财", + "chart_label": "钱财盘 D2", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "hora", + "fact": "上升落在月亮这一半。月亮、水星、金星、罗睺、计都在你这一半。", + "meaning": "钱更多来自和人打交道、做买卖、做内容或和审美有关的东西,来得灵活、零散" + } + ] + }, + "after": { + "chart": "D2", + "domain": "money", + "label": "钱财", + "chart_label": "钱财盘 D2", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "hora", + "fact": "上升落在太阳这一半。太阳、火星、木星、土星在你这一半。", + "meaning": "钱更多来自自己出头、拿职位、担责任,在体系里往上走,来得慢但稳" + } + ] + } + }, + { + "chart": "D6", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "before": { + "chart": "D6", + "domain": "pressure", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "ascendant": "射手", + "ascendant_index": 8, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在射手", + "meaning": "先处理眼前最紧的一件事" + } + ] + }, + "after": { + "chart": "D6", + "domain": "pressure", + "label": "日常遇到压力时", + "chart_label": "分盘 D6", + "ascendant": "摩羯", + "ascendant_index": 9, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在摩羯", + "meaning": "先维持原有节奏,把任务逐件做完" + } + ] + } + }, + { + "chart": "D8", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "before": { + "chart": "D8", + "domain": "change", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "ascendant": "巨蟹", + "ascendant_index": 3, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在巨蟹", + "meaning": "先找熟悉的人商量下一步" + } + ] + }, + "after": { + "chart": "D8", + "domain": "change", + "label": "遇到意外变化时", + "chart_label": "分盘 D8", + "ascendant": "狮子", + "ascendant_index": 4, + "points": [ + { + "kind": "ascendant", + "fact": "上升落在狮子", + "meaning": "先动手试一个新办法" + } + ] + } + } + ] + } + }, + "before": { + "decision": { + "saved_at": "1997-08-08T04:44", + "segment": { + "start_at": "1997-08-08T04:30:00", + "end_at": "1997-08-08T04:59:42" + }, + "choices": [ + { + "line_at": "1997-08-08T04:59:43", + "side": "before" + } + ], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天秤", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "双子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "line_summary": { + "nearest_at": "1997-08-08T04:51:30", + "charts": { + "D9": { + "at": "1997-08-08T04:51:30", + "count": 2, + "before": "天秤", + "after": "天蝎" + }, + "D10": { + "at": "1997-08-08T04:44:57", + "count": 2, + "before": "双子", + "after": "巨蟹" + }, + "D8": { + "at": "1997-08-08T04:41:16", + "count": 1, + "before": "双子", + "after": "巨蟹" + }, + "D6": { + "at": "1997-08-08T04:35:08", + "count": 1, + "before": "天蝎", + "after": "射手" + } + } + }, + "both_versions": [], + "chosen_side": "before" + }, + "next": { + "at": "1997-08-08T04:51:30", + "degree": 13.333333, + "charts": [ + "D9" + ], + "flips": { + "D9": { + "before": "天秤", + "after": "天蝎" + } + }, + "comparisons": [ + { + "chart": "D9", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "before": { + "chart": "D9", + "domain": "relationship", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "ascendant": "天秤", + "ascendant_index": 6, + "points": [ + { + "kind": "occupant", + "fact": "月亮在伴侣的位置", + "meaning": "和人打交道,变化多、投入感情" + }, + { + "kind": "lord", + "fact": "管伴侣的星(火星)落在第 2 宫", + "meaning": "伴侣和家庭、钱财观念紧密相关" + }, + { + "kind": "lord", + "fact": "代表你自己的星(金星)落在第 2 宫", + "meaning": "伴侣和家庭、钱财观念紧密相关" + } + ] + }, + "after": { + "chart": "D9", + "domain": "relationship", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "ascendant": "天蝎", + "ascendant_index": 7, + "points": [ + { + "kind": "occupant", + "fact": "火星在命位", + "meaning": "竞争和技术,行动快、敢拼" + }, + { + "kind": "occupant", + "fact": "金星在命位", + "meaning": "审美、设计和人缘,讲究舒适" + }, + { + "kind": "lord", + "fact": "管伴侣的星(金星)落在第 1 宫", + "meaning": "感情里很看重自我,伴侣和自己性格相近" + }, + { + "kind": "lord", + "fact": "代表你自己的星(火星)落在第 1 宫", + "meaning": "感情里很看重自我,伴侣和自己性格相近" + } + ] + } + } + ] + } + }, + "after": { + "decision": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:59:43", + "end_at": "1997-08-08T05:30:00" + }, + "choices": [ + { + "line_at": "1997-08-08T04:59:43", + "side": "after" + } + ], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T05:07:55" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T05:14:30" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T05:24:22" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T05:18:12" + } + ], + "line_summary": { + "nearest_at": "1997-08-08T05:07:55", + "charts": { + "D9": { + "at": "1997-08-08T05:07:55", + "count": 2, + "before": "天蝎", + "after": "射手" + }, + "D10": { + "at": "1997-08-08T05:14:30", + "count": 2, + "before": "狮子", + "after": "处女" + }, + "D8": { + "at": "1997-08-08T05:18:12", + "count": 1, + "before": "狮子", + "after": "处女" + }, + "D6": { + "at": "1997-08-08T05:24:22", + "count": 1, + "before": "摩羯", + "after": "水瓶" + } + } + }, + "both_versions": [], + "chosen_side": "after" + }, + "next": { + "at": "1997-08-08T05:07:55", + "degree": 16.666667, + "charts": [ + "D9" + ], + "flips": { + "D9": { + "before": "天蝎", + "after": "射手" + } + }, + "comparisons": [ + { + "chart": "D9", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "before": { + "chart": "D9", + "domain": "relationship", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "ascendant": "天蝎", + "ascendant_index": 7, + "points": [ + { + "kind": "occupant", + "fact": "火星在命位", + "meaning": "竞争和技术,行动快、敢拼" + }, + { + "kind": "occupant", + "fact": "金星在命位", + "meaning": "审美、设计和人缘,讲究舒适" + }, + { + "kind": "lord", + "fact": "管伴侣的星(金星)落在第 1 宫", + "meaning": "感情里很看重自我,伴侣和自己性格相近" + }, + { + "kind": "lord", + "fact": "代表你自己的星(火星)落在第 1 宫", + "meaning": "感情里很看重自我,伴侣和自己性格相近" + } + ] + }, + "after": { + "chart": "D9", + "domain": "relationship", + "label": "婚恋", + "chart_label": "婚恋盘 D9", + "ascendant": "射手", + "ascendant_index": 8, + "points": [ + { + "kind": "occupant", + "fact": "计都在伴侣的位置", + "meaning": "专精、抽离,不太在乎外界认可" + }, + { + "kind": "occupant", + "fact": "罗睺在命位", + "meaning": "野心大、不走寻常路,和外来或新兴的东西有缘" + }, + { + "kind": "lord", + "fact": "管伴侣的星(水星)落在第 10 宫", + "meaning": "伴侣和事业、社会地位相关" + }, + { + "kind": "lord", + "fact": "代表你自己的星(木星)落在第 9 宫", + "meaning": "伴侣可能来自远方,或带着学识、信念上的影响" + } + ] + } + } + ] + } + }, + "finished": { + "decision": { + "saved_at": "1997-08-08T04:55", + "segment": { + "start_at": "1997-08-08T04:51:30", + "end_at": "1997-08-08T04:59:42" + }, + "choices": [ + { + "line_at": "1997-08-08T04:59:43", + "side": "before" + }, + { + "line_at": "1997-08-08T04:51:30", + "side": "after" + } + ], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null + }, + { + "chart": "D10", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D2", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D6", + "sign": "射手", + "decided_by": null + }, + { + "chart": "D8", + "sign": "巨蟹", + "decided_by": null + } + ], + "line_summary": { + "nearest_at": null, + "charts": {} + }, + "both_versions": [], + "chosen_side": "after" + } + }, + "unsure": { + "decision": { + "saved_at": "1997-08-08T05:00", + "segment": { + "start_at": "1997-08-08T04:30:00", + "end_at": "1997-08-08T05:30:00" + }, + "choices": [ + { + "line_at": "1997-08-08T04:59:43", + "side": "unsure" + } + ], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "line_summary": { + "nearest_at": "1997-08-08T04:59:43", + "charts": { + "D10": { + "at": "1997-08-08T04:59:43", + "count": 5, + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "at": "1997-08-08T04:59:43", + "count": 1, + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "射手", + "after": "摩羯" + }, + "D8": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "巨蟹", + "after": "狮子" + }, + "D9": { + "at": "1997-08-08T05:07:55", + "count": 4, + "before": "天蝎", + "after": "射手" + } + } + }, + "both_versions": [ + "career", + "money", + "pressure", + "change" + ], + "chosen_side": "after", + "other_saved_at": "1997-08-08T04:55" + } + }, + "minuteDistance": { + "engine_version": "chart-choice-v2", + "status": "complete", + "window": { + "start_at": "1997-08-08T04:30", + "end_at": "1997-08-08T05:30" + }, + "reported_at": "1997-08-08T05:01", + "reported_known": true, + "saved_at": "1997-08-08T05:01", + "decision": { + "saved_at": "1997-08-08T05:01", + "segment": { + "start_at": "1997-08-08T04:30:00", + "end_at": "1997-08-08T05:30:00" + }, + "rounds": [], + "undetermined_charts": [ + "D9", + "D10", + "D2", + "D6", + "D8" + ], + "events": [], + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "events_detail": [], + "evidence_summary": { + "event_count": 0, + "matched": 0, + "confidence": "tendency_only", + "coverage": { + "event_count": 0, + "category_count": 0, + "group_count": 0, + "groups": [], + "year_span": 0, + "level": "thin" + }, + "caveat": "这一步按占星师的方法计算,结果只作参考,不是验证结果。2026-11-06 我们在 77 个出生时间有可靠记录的案例上回测过同类的事件打分:30 分钟范围里头名命中 19%,随机挑也是 20%,直接用报的时间是 34%。" + }, + "remaining_key_lines": 11, + "has_next": false, + "rule": "stopped", + "reported_choice": { + "saved_at": "1997-08-08T05:01", + "segment": { + "start_at": "1997-08-08T04:30", + "end_at": "1997-08-08T05:30" + }, + "reported_known": true, + "key_charts": [ + { + "chart": "D1", + "sign": "巨蟹", + "decided_by": null + }, + { + "chart": "D9", + "sign": "天蝎", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D10", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:30:14" + }, + { + "chart": "D2", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:59:43" + }, + { + "chart": "D6", + "sign": "摩羯", + "decided_by": null, + "flips_at": "1997-08-08T04:35:08" + }, + { + "chart": "D8", + "sign": "狮子", + "decided_by": null, + "flips_at": "1997-08-08T04:41:16" + } + ], + "undetermined_charts": [ + "D9", + "D10", + "D2", + "D6", + "D8" + ], + "remaining_key_lines": 11, + "line_summary": { + "nearest_at": "1997-08-08T04:59:43", + "charts": { + "D10": { + "at": "1997-08-08T04:59:43", + "count": 5, + "before": "巨蟹", + "after": "狮子" + }, + "D2": { + "at": "1997-08-08T04:59:43", + "count": 1, + "before": "巨蟹", + "after": "狮子" + }, + "D6": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "射手", + "after": "摩羯" + }, + "D8": { + "at": "1997-08-08T04:59:43", + "count": 3, + "before": "巨蟹", + "after": "狮子" + }, + "D9": { + "at": "1997-08-08T05:07:55", + "count": 4, + "before": "天蝎", + "after": "射手" + } + } + } + }, + "resolved": [], + "stop_reason": "stopped" + } + } +} diff --git a/scripts/chart_choice/service.py b/scripts/chart_choice/service.py index 89daa294b..877c5b220 100644 --- a/scripts/chart_choice/service.py +++ b/scripts/chart_choice/service.py @@ -154,7 +154,32 @@ def _base(req: ChartRequest, start: datetime, end: datetime, reported: datetime, def _line_view(line: Line, order: tuple[str, ...]) -> dict: - return {"at": _at_s(line.at), "degree": line.degree, "charts": [key for key in order if key in line.flips]} + charts = [key for key in order if key in line.flips] + return {"at": _at_s(line.at), "degree": line.degree, "charts": charts, + "flips": {key: {"before": SIGN_CN[line.flips[key][0]], "after": SIGN_CN[line.flips[key][1]]} + for key in charts}} + + +def _line_summary(lines: list[Line], reference: datetime) -> dict: + nearest = sorted(lines, key=lambda line: (abs(line.at - reference), line.at)) + charts: dict[str, dict] = {} + for line in nearest: + view = _line_view(line, KEY_CHARTS) + for chart, signs in view["flips"].items(): + row = charts.setdefault(chart, {"at": view["at"], "count": 0, **signs}) + row["count"] += 1 + return {"nearest_at": _at_s(nearest[0].at) if nearest else None, "charts": charts} + + +def _comparisons(req: ChartRequest, before_at: datetime, after_at: datetime, charts: list[str]) -> list[dict]: + pb, ab = _planets_and_asc(req, before_at) + pa, aa = _planets_and_asc(req, after_at) + return [ + {"chart": key, "label": DOMAIN[key]["label"], "chart_label": DOMAIN[key]["chart"], + "before": describe(key, varga_chart(pb, ab, int(key[1:]))), + "after": describe(key, varga_chart(pa, aa, int(key[1:])))} + for key in charts + ] def _choice( @@ -168,16 +193,10 @@ def _choice( reported_side = "before" if reported < line.at else "after" flipped = [key for key in order if key in line.flips] unchanged = [key for key in order if key not in line.flips] - pb, ab = _planets_and_asc(req, before_min) - pa, aa = _planets_and_asc(req, after_min) - comparisons, questions = [], [] - for key in flipped: - division = int(key[1:]) - before = describe(key, varga_chart(pb, ab, division)) - after = describe(key, varga_chart(pa, aa, division)) - 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)): + comparisons = _comparisons(req, before_min, after_min, flipped) + questions = [] + for comparison in comparisons: + if len(questions) < MAX_QUESTIONS and (q := build_question(comparison["before"], comparison["after"])): questions.append({**q, "optional": True} if multi else q) return { @@ -588,14 +607,83 @@ def _adaptive(body: dict, req: ChartRequest, base: dict, segment: Segment, repor "key_charts": reported_charts, "undetermined_charts": [row["chart"] for row in reported_charts if "flips_at" in row], "remaining_key_lines": len(default_lines), + "line_summary": _line_summary(default_lines, default_at), } decision.update(asked=asked, conflict=result["conflict"], resolved=[], undetermined_charts=list(unsettled), stop_reason=result["stop_reason"]) return {**packet, "status": "complete", "saved_at": decision["saved_at"], "decision": decision} +def _self_choice_at(segment: Segment, reported: datetime) -> datetime: + lo, hi = segment + if lo <= reported <= hi: + return reported + minute = representative_minute((lo, hi + ONE_SECOND), reported) + return minute if lo <= minute <= hi else representative_time(segment, reported) + + +def _self_choice_lines(req: ChartRequest, start: datetime, end: datetime) -> list[Line]: + by_time: dict[datetime, Line] = {} + for line in find_lines(req, start, end, tuple(int(chart[1:]) for chart in KEY_CHARTS)): + if start < line.at <= end: + previous = by_time.setdefault(line.at, line) + if previous is not line: + previous.flips.update(line.flips) + return sorted(by_time.values(), key=lambda line: line.at) + + +def _self_choice( + body: dict, req: ChartRequest, segment: Segment, reported: datetime, *, deciding: bool, +) -> dict: + choices = body.get("choices") + if not isinstance(choices, list): + raise ChartChoiceInputError("choices must be a list") + all_lines = _self_choice_lines(req, *segment) + if not all_lines: + raise ChartChoiceInputError("no self-choice line in the window") + + lines = all_lines + next_line = nearest_line(lines, reported) + unsure = None + for entry in choices: + if not isinstance(entry, dict) or set(entry) != {"line_at", "side"}: + raise ChartChoiceInputError("each choice needs only line_at and side") + side = entry["side"] + if (side not in ("before", "after", "unsure") or next_line is None + or _input_line(entry["line_at"]) != next_line.at): + raise ChartChoiceInputError("self-choice line is not the next available line") + if side == "unsure": + unsure, next_line = next_line, None + else: + segment = _side(segment, next_line, side) + lines = [line for line in lines if segment[0] < line.at <= segment[1]] + next_line = nearest_line(lines, reported) + + saved = _self_choice_at(segment, reported) + resolved = {"saved_at": _saved_at(saved), "segment": _segment(*segment), "choices": choices, + "key_charts": _key_chart_rows(req, saved, lines, []), + "line_summary": _line_summary(lines, reported), "both_versions": []} + if unsure is not None: + chosen = "before" if saved < unsure.at else "after" + preceding = max((line.at for line in lines if line.at < unsure.at), default=segment[0]) + following = min((line.at for line in lines if line.at > unsure.at), default=segment[1] + ONE_SECOND) + other = (unsure.at, following - ONE_SECOND) if chosen == "before" else (preceding, unsure.at - ONE_SECOND) + resolved.update(chosen_side=chosen, other_saved_at=_saved_at(_self_choice_at(other, reported)), + both_versions=[DOMAIN[key]["key"] for key in KEY_CHARTS if key in unsure.flips]) + elif choices: + resolved["chosen_side"] = choices[-1]["side"] + + result = {"decision": resolved} + if not deciding and next_line is not None: + view = _line_view(next_line, KEY_CHARTS) + result["next"] = {**view, "comparisons": _comparisons(req, next_line.at - ONE_SECOND, next_line.at, view["charts"])} + return result + + def _evaluate(body: dict, *, deciding: bool) -> dict: req, start, end, reported, known = _request(body) + if body.get("self_choice") is True: + return _self_choice(body, req, (start, end), reported, deciding=deciding) adaptive_mode = body.get("adaptive") is True questionnaire = adaptive_mode or body.get("questionnaire") is True or "chart_answers" in body multi = questionnaire or "resolved" in body or "resume" in body or "resume_v2" in body or "stop" in body diff --git a/tests/test_chart_choice.py b/tests/test_chart_choice.py index 1b1d53de3..5bc1bf05d 100644 --- a/tests/test_chart_choice.py +++ b/tests/test_chart_choice.py @@ -697,3 +697,76 @@ def test_questionnaire_reuses_saved_events_and_only_asks_unresolved_charts(): }}) assert [q["chart"] for q in resumed["chart_questions"]] == ["D9"] assert resumed["events"] == decision["events"] + + +def test_self_choice_replays_real_lines_without_scoring(monkeypatch): + def unexpected(*args, **kwargs): + pytest.fail("self-choice must not score or ask questions") + + monkeypatch.setattr(adaptive, "replay", unexpected) + monkeypatch.setattr(adaptive, "confidence", unexpected) + monkeypatch.setattr(interview, "evidence", unexpected) + monkeypatch.setattr(interview, "questions", unexpected) + monkeypatch.setattr(chart_questions, "select_segment", unexpected) + body = {**BODY, "start_at": "1997-08-08T04:30", "end_at": "1997-08-08T05:30", "self_choice": True} + initial = build_packet({**body, "choices": []}) + first = initial["next"] + assert first["at"].endswith("04:59:43") + assert first["flips"]["D10"] == {"before": "巨蟹", "after": "狮子"} + assert first["charts"] == [row["chart"] for row in first["comparisons"]] + assert {row["before"]["ascendant"] for row in first["comparisons"] if row["chart"] == "D10"} == {"巨蟹"} + assert {row["after"]["ascendant"] for row in first["comparisons"] if row["chart"] == "D10"} == {"狮子"} + + def pick(line, side): + return {"line_at": line["at"], "side": side} + + before = build_packet({**body, "choices": [pick(first, "before")]}) + after = build_packet({**body, "choices": [pick(first, "after")]}) + assert before["next"]["at"].endswith("04:51:30") + assert after["next"]["at"].endswith("05:07:55") + assert after["decision"]["saved_at"] == BODY["reported_at"] + assert after["decision"]["segment"]["start_at"] == first["at"] + assert before["decision"]["segment"]["end_at"].endswith("04:59:42") + assert initial["decision"]["line_summary"]["charts"]["D10"]["count"] == 5 + + choices = [pick(first, "before"), pick(before["next"], "after")] + decided = decide_packet({**body, "choices": choices, "saved_at": BODY["end_at"], + "segment": {"start_at": BODY["start_at"], "end_at": BODY["end_at"]}}) + assert decided == decide_packet({**body, "choices": choices}) + assert decided["decision"]["saved_at"].endswith("04:55") + assert decided["decision"]["choices"] == choices + assert decide_packet({**body, "choices": choices[:1]}) == {"decision": before["decision"]} + assert "votes" not in decided["decision"] + + unsure = build_packet({**body, "choices": [pick(first, "unsure")]}) + assert "next" not in unsure + assert unsure["decision"]["segment"] == initial["decision"]["segment"] + assert unsure["decision"]["saved_at"] == BODY["reported_at"] + assert unsure["decision"]["chosen_side"] == "after" + assert unsure["decision"]["other_saved_at"] < first["at"] + assert unsure["decision"]["both_versions"] == ["career", "money", "pressure", "change"] + with pytest.raises(ChartChoiceInputError, match="next available"): + decide_packet({**body, "choices": [pick(before["next"], "after")]}) + with pytest.raises(ChartChoiceInputError, match="next available"): + decide_packet({**body, "choices": [pick(first, "unsure"), pick(before["next"], "after")]}) + + +def test_self_choice_preserves_boundary_second_when_no_whole_minute_fits(): + body = {**BODY, "start_at": "1997-08-08T04:59", "end_at": "1997-08-08T05:00", + "self_choice": True} + first = build_packet({**body, "choices": []})["next"] + assert first["at"].endswith("04:59:43") + unsure = decide_packet({**body, "choices": [{"line_at": first["at"], "side": "unsure"}]})["decision"] + assert unsure["saved_at"].endswith("05:00") + assert unsure["other_saved_at"].endswith("04:59") + body["reported_at"] = "1997-08-08T04:59" + after = decide_packet({**body, "choices": [{"line_at": first["at"], "side": "after"}]})["decision"] + assert after["saved_at"].endswith("05:00") + assert after["segment"]["start_at"] == first["at"] + + from scripts.chart_choice.service import _self_choice_at + + lo = datetime(1997, 8, 8, 23, 59, 43) + hi = lo + timedelta(seconds=10) + assert lo <= _self_choice_at((lo, hi), lo + timedelta(minutes=2)) <= hi + assert _self_choice_at((lo, lo), hi) == lo