#312 生时纠正:保存自选情景并拒绝旧预览 #317

Merged
Claude merged 8 commits from codex/rect-self-choice-scenario-20261117 into staging 2026-11-17 15:05:51 +08:00
33 changed files with 2985 additions and 223 deletions
+4
View File
@@ -1,5 +1,9 @@
# BLOCKED
## #312 自选情景独立验收
- 登录后浏览器走查与真实模型回答待独立验收。本机已用虚构档案、原生引擎、React 流程和隔离 PostgreSQL 提供替代证据。Windows 预检的工作台镜像路径断言失败,远端和外部引擎适配器检查通过。见 [#312 进度](docs/tasks/PROGRESS-rect-self-choice-scenario-20261117.md)。
## #310 出生输入版本的独立验收
- 本机 Windows 全量仍有既有失败。按同机 staging 基线逐项对照没有新增失败,相关的 5 项 PostgreSQL 用例已在隔离容器复跑通过。
+4
View File
@@ -1,5 +1,9 @@
# 印度占星 Skill 更新日志
## 2026-11-17 · 生时纠正自选保存为用户情景
- 结果页可展开全部换座,聊天区分自选情景与时间核实,旧预览遇到资料或当前记录变化会重新加载。占星 Skill 版本不变(BUG-1958)。
## 2026-11-17 · 历史报告与星盘缓存核对出生输入版本
- 报告接口返回出生输入核对状态,在途任务和星盘缓存按版本核对。Skill 版本沿用(BUG-1956)。
+12
View File
@@ -26309,3 +26309,15 @@
- 验证与防复发:用仓内迁移和隔离 PostgreSQL 验证空库、其他人物、错绑、双边去重、同秒换来源和模糊组屏蔽,详见 [#311 进度](tasks/PROGRESS-rect-p0-aggregate-v3-20261117.md)。
- 关联记录:#311、#296、BUG-1931、BUG-1890、BUG-1936。
- 修复版本:`codex/rect-p0-aggregate-v3-20261117`,待独立验收。
## BUG-1958 | 生时纠正自选的采纳状态被误认为核实,旧预览可重放
- 状态:fixed-pending-verify,待独立验收。
- 首次发现 / 最近更新:2026-11-17 / 2026-11-17。
- 触发与现象:用户选线前、线后或不确定后,档案与部分工具输入可把采纳时刻视作已核实;宽区间的多条换座会被压成单一另一版;原申报或当前记录改变后,旧预览仍可能被重放。
- 根因:状态字段同时承担可用于计算与证据确认两层含义;结果摘要和提示词围绕最近一条线;保存重算与采用写入缺少事务化的版本核对。
- 修复:区分自选情景、原申报和本次计算范围;展示全部换座、按剩余线分段并按最近四段供聊天读取。采用时在主体行锁内比较记录号和指纹,分配自选序号,幂等处理相同选择。旧预览返回 409 后刷新结果。
- 验证与防复发:原生引擎分段、真实 PostgreSQL 并发与声明变化、接口重放及页面恢复均有定向回归。见 [#312 进度](tasks/PROGRESS-rect-self-choice-scenario-20261117.md)。
- 关联记录:BUG-1936、BUG-1952、BUG-1956。
- 修复版本:`codex/rect-self-choice-scenario-20261117`。
@@ -0,0 +1,43 @@
# #312 生时纠正用户自选情景
开工基线 `0ee6b7c7c`,交付前合入 `f8e0db21f` 并复跑受影响入口。执行者 Codex。任务书 [自选情景](TASK-rect-self-choice-scenario-20261117.md)。
## 交付
- 结果页只说明六张盘的上升星座是否变化,按唯一换座时刻计数。可展开一张盘的完整列表,各项显示时刻与两侧星座。线前、线后、不确定固定排序。确认页给出剩余线以及原申报保留的说明。
- 保存记录保留用户原申报、这次计算用的范围、所选情景及剩余换座。只有已明确申报的区间写入 `declared_window`,误差未申报时保留为空。独立 PostgreSQL 函数以档案行锁核对记录号及申报指纹,在同一事务分配自选序号并调用既有写入函数。两个新增函数只授予 service role,可随旧应用并存。旧记录按 `basis` 识别,无数据回填。
- 原生引擎对剩余线分段,用 BUG-1952 的同一规则取每段代表时刻,保留离所填时间最近四段,另计省略量。恰好两段仍带旧两版字段。聊天收到主段、实际计算的其他段及分盘上升差异。最后一次明确取舍时,计算相邻的另一侧供对照。会话第一次用盘、或用户问出生时间时加入经批准的开头说明。
## accepted 被当作已确认的位置
| 位置 | 处理与验证 |
| --- | --- |
| `home-profile`、`people-archive-view`、`chart-subject-write` | 旧/新自选在档案显示「用户自选情景」,不会显示「已校正」徽标。自选仍用已保存的时刻算盘。第三方档案输出布尔标识。定向检查覆盖读取、标签和徽标;既有来源仍走原判断。 |
| `api/account` | `hasConfirmedBirthTime` 排除自选,`hasUsableBirthTime` 仍认可可算盘的采纳。账户源码合同核对确认条件。 |
| `consultation-route-service`、`api/consult`、`consultation-workflow`、`consultation-tools` | 接受已选的出生时刻,工具接收 `minute` 精度及自选来源、实际计算的备选,准确保留存储秒数。非自选提示不附自选说明;测试首答、普通追问、问生时、多情景与异常数据。 |
| `personal-report-longform-birth`、`personal-report-route-core`,长报告、合盘的共享输入 | 已选时间仍参与计算,`reading_minute_confirmed` 不升级为真,报告精度保持 `provisional`。即使候选范围只有一点也按该规则。断言覆盖长报告、报告精度与合盘输入。 |
| `chart-birth-truth`、`effective-birth-date`、`consultation-subject-resolver`、`birth-time-consultation-consent`、`lagna-precheck`、`rectification-links`、`onboarding-journey`、`home-bootstrap-run` | 这些判断决定有无可用出生时刻、是否重复提醒及计算路由。保持可用性,并由接收输入的调用方表达是否核实。 |
| `chart-view-mapper`、`birth-time-intake` / `birth-time-intake-model`、`retired-birth-window` | 「已采用」「校正采用」与恢复申报入口沿用现有采纳状态。个人报告的 `accepted_directional_only` 原本就只给方向,`personal-report-worker-subject` 读取采用的日期与时间作为计算输入。 |
| `annual-birth-time`、报告生成/解释、年运、合盘及导出显示 | 年运使用 `adopted` 表示采用。本轮校验共享输入,显示与产物解释由 BUG-1959 处理。 |
## 既有断言调整
| 原值 | 新值 | 原因 |
| --- | --- | --- |
| 「不受影响:主盘」「差几分钟就不同」「可以直接用」 | 只说明哪些上升星座变动,以及全稳定时六张盘的上升星座不变 | 任务书限定已检查的内容。 |
| 最近一次换座与「等 5 处」为普通文字 | 同一时刻、两侧和计数必须位于可展开的 `summary`,另由新测试核对所有列表项 | 让界面实际列出换座。 |
| 预览直接返回引擎对象,预览与保存发送相同字段 | 预览追加记录号和指纹,保存须原样回传;预览请求键原样断言 | 绑定预览与保存,旧客户端省略证明返回 400。 |
| 自选直接调用通用采用 RPC,测试历史共用固定记录号 | 调用事务内校验的自选 RPC,新保存各自生成记录号;恢复仍用既有 RPC,原空区间参数断言留在恢复分支 | 检验状态推进,重放和申报变化都在写入前被拦截。 |
| 宽区间第一次「不确定」固定 after,旧另一版为 04:58、四领域 | 三段及以上用 none/null 与多情景,宽区间保留四段及省略计数,已计算的相邻备选仍验证 04:58 合格整分钟 | 多条线无法用一条另一版表示;独立两段测试仍检查另一版精度和旧读取。 |
## 已知边界
聊天对照限于已计算的分盘上升差异。时间窗漂移、精细事实或事件窗口的独立核验依赖 BUG-1953 以后的用途扫描;旧聊天和报告内容处理见 BUG-1960、BUG-1959。模型答复与登录后浏览器真机走查留待独立验收。Windows 预检的工作台镜像路径断言失败,远端可见性及引擎适配器检查通过。
## 验证
- Python quick 门禁通过。生时纠正原生引擎定向 61 项、仓库隐私定向 62 项通过。
- 前端自选与旧载荷定向 15 项通过。合入 staging 后复跑 133 项相关消费入口,账户确认与聊天再跑 21 项,均通过。
- 隔离 PostgreSQL 17 实跑迁移和两连接并发。一个请求提交,另一个收到过期错误,活动记录号等于成功提交的记录;后续序号递增,原申报修改后拒绝旧请求,两名主体的历史分开,认证角色无权限执行该接口。
- TypeScript 检查、ESLint(0 错误、63 条警告)与生产构建通过,首页 `/` 为 Static。开工基线首屏压缩脚本合计 528,246 字节;交付分支并入 staging 后为 528,703 字节(+0.09%)。
- Windows 同机前端全量对比采用同一配置,暂时从两个全量进程的 PATH 中移除 Docker,并另跑本单的真实数据库用例。staging 3,965 项,3,880 通过、46 失败、39 跳过;本分支 3,971 项,3,884 通过、47 失败、40 跳过,均无取消及用例删除。基线的 46 个失败名称相同;另一次 250 毫秒回答计时测试在并发全量中超时,单独复跑通过。新增跳过的是已在 PostgreSQL 单跑通过的并发用例。
+9
View File
@@ -7,6 +7,7 @@
- 被环境或依赖挡住的事项写进根目录 `BLOCKED.md`;Bug 事实写进 `docs/BUG_HISTORY.md`;两者不在这里重复。
- 纯文档改动不触发 staging 门禁(见 `deploy/gated-paths.txt`)。
- [生时纠正用户自选情景(#312)](PROGRESS-rect-self-choice-scenario-20261117.md) — 换座列表、保存重放校验及聊天口径。
- [出生输入版本与报告核对(#310)](PROGRESS-rect-birth-input-revision-20261117.md) — 生成、读取、导出元数据及缓存验证。
- [生时纠正 P0 聚合统计 v3(#311)](PROGRESS-rect-p0-aggregate-v3-20261117.md) — 输出段、绑定行为及 PostgreSQL 验证。
- [生时纠正开发集复验(#272)](PROGRESS-rect-repro-20261114.md) — 配对重跑、三项消融和逐例数据。
@@ -36,6 +37,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| [#279 任务书](TASK-rect-p0-20261115.md) | [执行进度](PROGRESS-rect-p0-20261115.md) | 生时纠正恢复原范围及复跑审计(BUG-1890) | 待验收 | `codex/rect-p0-continuation-20261115` |
| [#264 任务书](TASK-annual-kp-20261114.md) | [执行进度](PROGRESS-annual-kp-20261114.md) | 年运 KP 宫头子主与出生精度(BUG-1884) | 待验收 | `codex/annual-kp-20261114` |
| [#263 任务书](TASK-annual-transit-checks-20261114.md) | [执行进度](PROGRESS-annual-transit-checks-20261114.md) | 年运行运交叉与其他参照(BUG-1883) | 待验收 | `codex/annual-transit-checks-20261114` |
@@ -60,6 +62,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-rectification-d60-two-way-20261028.md` | `PROGRESS-rectification-d60-two-way-20261028.md`(执行方写) | **D60 换格要不要进生时校正:双向对比(issue #149)**:纳迪 / D150 已在 BUG-1240 证伪,本单只测 D60。A 组生产 V9、B 组加 D60 换格判据,同一批 v5 77 例看「有没有帮助」和「有没有伤害」;先登记再跑,G1 三引擎对账、G2 找回记录分钟、G3 不伤真值、G4 安慰剂、G5 换岁差噪声地板;另做 20 例模型参与的端到端对话对比(报告项)。离线研究、生产零改动。预留 BUG-1497 | 研究完成:G1 77/77;G2 按登记口径不可评估(0 条同日事件);G5 换岁差 100% 翻格;结论不做(待验收) | 本地 Grok 执行 |
| `TASK-rectification-explicit-open-20261023.md` | `PROGRESS-rectification-explicit-open-20261023.md` | **明说要校正只回一句话(issue #103)**:找会话直接读一张对服务角色撤权的表、必然失败被吞(真正进行中的也续不上);`candidate_accepted` 被算作进行中挡住入口和提议卡;兜底只给一句话。产品选 C;只改入口口径、经 RPC 找会话、删兜底,不改共享状态集合、不动表。BUG-1423 | 已合入 staging | 分支 `codex/rectification-explicit-open-20261023` |
| `TASK-chart-table-span-20261023.md` | `PROGRESS-chart-table-span-20261023.md` | **星盘页本命 / 月亮行星表挤进左栏(issue #102)**:#87 给表包了 `ChartSymbolHelp` 后跨栏规则失配;根因修法是 `VedicLayout` 用固定整行容器承载表格,跨栏只认容器;加结构断言防复发。BUG-1422 | 已合入 staging | 分支 `codex/chart-table-span-20261023` |
@@ -168,6 +171,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-composer-first-glyph-clip-20261013.md` | `PROGRESS-composer-first-glyph-clip-20261013.md` | **输入框第一个字被圆角裁掉(agent 循环 issue #52)**:`Textarea` 原语自带 12px 圆角,`.composer textarea` 清了边框与左右内边距却没清圆角,浏览器按圆角裁滚动内容,第一个字左缘被裁成圆弧;只在 `.composer textarea` 加 `border-radius: 0`,原语不动。执行方 Grok。BUG-1311 | 待验收 | `codex/composer-first-glyph-clip-20261013` |
| `TASK-composer-first-glyph-clip-fix-20261013.md` | — | **#52 第 1 次打回(只需 rebase)**:`6e6fae8d` 内容全部通过,因 staging 前进了一个纯文档提交而不能快进 | 待领取 | `codex/composer-first-glyph-clip-20261013` |
| `TASK-consult-card-full-source-20261007.md` | `PROGRESS-consult-card-full-source-20261007.md` | **对话数据卡与报告同源 + 领域综合判断表**:事业卡只有约 7,600 字符、无自然代表星、无大运主星关系、D10 联动只能补取、补取上限 1;全 12 领域;综合判断表、参与清单(不止 D1/D9,含精度闸)、补取 3 次、资料目录均已确认;KP 不上卡、不联网、不接书籍语料;排在 sync6 与报告单之后 | 验收未通过(`35dafd1e`,见 fix-20261009) | `codex/consult-card-full-source-20261007` |
@@ -245,6 +249,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-rectification-step0-entry-20261013.md` | — | **明说要校正时第一步就能打开(agent 循环 issue #54,BUG-1306 复发)**:第 0 步只放排盘工具、规则正向句埋在禁止句里、「纠正」撞词,模型没带 explicitRequest 调工具(BUG-1317)。产品选 B:第 0 步放出校正工具 + 规则重排;推翻 BUG-923 第 0 步限制,保险用现有 runtime-contract-retry。执行方 Grok | 待领取 | `codex/rectification-step0-entry-20261013` |
| `TASK-report-focus-card-20261013.md` | — | **报告开篇「重点」做成摘要卡(agent 循环 issue #55)**:10-08 加的开篇重点从未设计——三重「重点」、标题无样式、MD/AD/PD 行话、数据句堆砌(BUG-1316)。产品选 A 摘要卡 + 名字与日期 + 保留提醒句;引擎出 `jyotish-focus` 围栏,前端一个组件渲染。执行方 Grok | 待领取 | `codex/report-focus-card-20261013` |
| `TASK-chart-ascendant-row-20261015.md` | `PROGRESS-chart-ascendant-row-20261015.md` | **星盘页上升行无星宿 / 表头错位 / 大运卡左边线(issue #53 第二轮)**:`/api/chart` 重建上升时丢了星宿三字段(BUG-1352,复发自 BUG-1201);状态改「不适用」;居中列表头对齐;当前大运去掉左边线(BUG-1353) | 待验收 | `codex/chart-ascendant-row-20261015` |
@@ -283,6 +288,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| issue #86(无独立任务书) | [PROGRESS](PROGRESS-chart-subject-table-20261021.md) | 星盘页人名看得出能点、出生资料就地改、报告行星表不再从中间断开(BUG-1410) | 待验收 | `codex/chart-subject-table-20261021` |
| [TASK-chart-surface-polish-20260929](TASK-chart-surface-polish-20260929.md)([验收修复](TASK-chart-surface-polish-fix-20260929.md)) | [PROGRESS](PROGRESS-chart-surface-polish-20260929.md) | 去引擎展示、庙旺三档保留、同位仅 D9、宫位左对齐、图标解释与桌面盘宽收紧(BUG-1098 / 1099) | 本地实施完成(定向/浏览器通过;全量保留 29 项基线失败,未推送) | `codex/chart-surface-polish-20260929`;不发布、不提升 main |
| `TASK-docs-reconcile-20260926.md` | `PROGRESS-docs-reconcile-20260926.md` | **状态板 / BUG / BLOCKED 过期对账**(纯文档):约 35 行校正任务状态过期、BUG-085/086/743/981/984 记录过期、BLOCKED latency 条目过期;逐条附证据改,不把欠真机写成通过 | 待验收 | `codex/docs-reconcile-20260926`(本地提交,未推送) |
@@ -343,6 +349,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-staging-gate-red-20260923.md` | `PROGRESS-staging-gate-red-20260923.md` | **staging 门禁修复(BUG-1012~1014)**:375px 并入 480px;人物选择器恢复焦点禁止滚动;输入框合同跟上资料删除限制并独立守住生成态可输入。真实 Gitea run 2857 已确认本单三项通过;总门禁仅 BUG-1011 失败(`spawnSync docker E2BIG`),publish skipped,尚未部署 | **已验收(待 BUG-1011)** | `36a73761`(staging,未部署) |
| `TASK-repo-hygiene-20260903.md` | `PROGRESS-repo-hygiene-20260903.md` | 岁差默认 Raman + 用户设置可选、参考集锁口径、发布门本地可复现、注册表白名单、仓库地址、早期日志搬家、远端分支清理 | 已验收(带修复单) | `b6a70aa7`、`2415e751`、`01a45363`(BUG-511);验收结论见修复单附录 |
| `TASK-repo-hygiene-fix-20260903.md` | `PROGRESS-repo-hygiene-fix-20260903.md` | Gulika 全局岁差泄漏(P1)、设置类名无样式、提示语对齐校正现状、剩余 lahiri 字面量、测试不写仓库 | 已验收 | `027e4b08`、`c1e3f32a`(BUG-512/513);Gulika 泄漏实验已复核为不泄漏,全量 pytest 后仓库干净 |
@@ -351,6 +358,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-upstream-sync-20260903.md` | `PROGRESS-upstream-sync-20260903.md`、`PROGRESS-upstream-capabilities-20260903.md` | 上游快照推进到 `a6f47abd`、引擎三方合并、health 三窗 / VedAstro REST 桥 / 专业报告导出 / 新字段接聊天与报告 / 校正解冻三项 | 已验收 | 0/1/2/4/6:`45d13258`、`f2241463`、`734d2059`;3/5/7:`c2f23131`~`6063c1f7`(BUG-514)。staging 已部署 `6063c1f7`。修复单 `4ee79210` 已验收 |
| `TASK-upstream-sync-fix-20260903.md` | `PROGRESS-upstream-sync-fix-20260903.md` | 非原生主题恢复 `degraded`、finance Yogi/D11/confidence cap、模板注册表引用、VedAstro/MCP finance 路由与 quick CORE 扩列 | 已验收 | `4ee79210`(BUG-515);staging health 已到该 SHA;十主题 e2e 合同全对,Python 红 90→69 无新增 |
| `TASK-upstream-sync2-20260909.md` | `PROGRESS-upstream-sync2-20260909.md` | 上游活跃分支 `b9a0ef8f`(未进 main):婚恋三层触发模型(punarphoo / event_class_split 进证据链)+ 十套条件大运接 full reading 与长报告时间系统表;快照锁推进;Skill 6.9.16;不取 shadbala profile / PL9 用户版 / 校正泄漏项 | 已验收(04ad3325):定向 176 通过、quick 门 708/1 env 失败、pl9 时间系统表 5+10 行;1 P1(网页咨询路径 `dasha_info` 无 MD/AD,事件类拆分空转)→ 修复单 `TASK-upstream-sync2-fix-20260909.md` | 分支 `codex/upstream-sync2-20260909`(BUG-608) |
@@ -510,6 +518,7 @@
| 任务书 | 进度 | 主题 | 状态 | 落点 |
| --- | --- | --- | --- | --- |
| `TASK-rect-self-choice-scenario-20261117.md` | `PROGRESS-rect-self-choice-scenario-20261117.md` | 保存自选情景、展示全部换座并拦截旧预览 | 待验收 | `codex/rect-self-choice-scenario-20261117` |
| `TASK-rect-scoring-perf-20261013.md` | `PROGRESS-rect-scoring-perf-20261013.md` | 校正打分提速:引导窗口平方扫描、候选不变量重复算、响应带无读取点字段、候选数上限 241(BUG-1323~1325、1345) | 待验收 | `codex/rect-scoring-perf-20261013` |
| `TASK-node-runtime-resources-20261013.md` | `PROGRESS-node-runtime-resources-20261013.md` | 报告 worker abort 监听泄漏、本地 PG 适配层往返与元数据缓存、无上限内存表、用户端会话读缓存(BUG-1326~1328、1346,PG 与缓存部分 A/B) | 待验收 | `codex/node-runtime-resources-20261013` |
| `TASK-node-runtime-resources-fix-20261014.md` | `PROGRESS-node-runtime-resources-20261013.md` | **#58 第 1 次打回**:`4c3485bc` 其余全过;压测脚本放在 `frontend/scripts/` 却从 `frontend/tests/` 导入,镜像构建会失败(BUG-1140 形状,任务书指定的路径有误)。挪到 `frontend/tests/` 下非 `.test` 文件名 | 待验收 | `codex/node-runtime-resources-20261013` |
@@ -0,0 +1,95 @@
# 生时纠正自选:改成「用户自选情景」,按占星师 11-17 要求修订(2026-11-17,Claude)
Bug 编号:BUG-1958。关联 BUG-1936(#301)、BUG-1952(#306)。
## 背景
占星师 11-17 审了 #301 的任务单。结论:允许用户自己选线前线后,报告和聊天可以按所选一侧作主叙述;但这只是「用户选的情景」,不是出生时间已核实,来源可信度不能升级。她点名了几处必须改。产品负责人 11-17 同意照她的要求改,并同意:自选过的用户在回答开头看到一句说明(只出现一次,写成事实陈述)。
本单改自选页面、自选的保存记录、聊天。**报告、年运、合盘、导出里的说明不在本单**(依赖 BUG-1956 的出生输入版本,另开 BUG-1959)。
## 一、页面文案只描述已检查的东西
`frontend/src/components/chart-choice/chart-choice-page.tsx`:
- `这个时间范围内六张盘都不变,可以直接用。` → `这个时间范围内,六张盘的上升星座都不变。`(去掉「可以直接用」:六张盘的上升没变,不等于任何问题都不受影响。)
- `不受影响:主盘。` → `上升星座不变:主盘。`
- `差几分钟就不同:婚恋、事业…。` → `上升星座会变:婚恋、事业…。`
- 首页「当前使用」里 `按你自己的选择` 保留。确认页 `这是你自己选的,可以随时改。` 后面加一句:`这不是出生时间已核实,你填的时间和范围都还保留着。`
- 每张盘一行里的 `等 N 处`:现在只是文字。改成可以展开,展开后列出这张盘在范围内的全部换座时刻和前后星座(用现有的行样式,不新造组件)。结果页的统计、「还有几条线没选」的计数必须按**全部**线算,不能只按最近那条。
- 以上都是正文,不是提示性小字副标题;不用加新的样式类。
- 检查复用的 `ChooseStep` / 选项列表:选项顺序固定为 线前、线后、不确定;说明文字里不得出现任何旧的推荐、打分、「更符合」之类残留。加一条测试扫这些词。
## 二、保存记录写清这是情景
`frontend/src/lib/chart-choice/server.ts::adoptSelfChoice` 写入的 `provenance` 增加(已有字段不删):
- `selection_kind: "self_selected_scenario"`;
- `declared_window`:用户原始申报的范围(现在的 `window` 是本次用的范围,可能是页面上选的宽度;两者都留,写清各是什么);
- `scenario_segment`:所选情景的范围(等于现有 `segment`,保留 `segment` 以兼容旧读取);
- `choice_revision`:这个主体的自选次数序号,从 1 起,每次保存加 1(从历史记录数出来,不新建表);
- `remaining_lines`:所选情景范围内**还剩下**的换座线(时刻 + 换座的盘),用户点了「就到这里」或选了「不确定」时非空。
出生时间状态继续写 `accepted`,但新增并导出一个判断函数(放 `frontend/src/lib/chart-choice/` 下):`isSelfSelectedScenario(provenance)`。然后全仓搜索把 `accepted` 当作「已确认/已核实」对待的地方(界面标签、提示词、报告入参、合盘指纹里的 `reading_minute_confirmed` 等),**逐处列进 PROGRESS**,并改成:来源是自选情景时不显示、不传递「已确认」含义。拿不准某处该不该改的,列出来不要改,验收时定。
## 三、「不确定」不再硬凑两版
现状:「不确定」时为了让聊天的「两版都读」生效,硬写了 `chosen_side` 和一个 `other_saved_at`。占星师指出:多条线时情景可能不止两种,一个 `other_saved_at` 代表不了。
改成:
- Python `scripts/chart_choice/service.py::_self_choice` 的结果增加 `scenarios`:所选情景范围内,按剩余换座线切开的每一段各一条,字段为 `segment`(起止)、`saved_at`(用 `_self_choice_at` 的同一规则取代表时刻)、`key_charts`(六张盘上升)、`is_primary`(主叙述用的那一段:所填时间所在段;所填时间不在范围内时取离它最近的一段)。没有剩余线时只有一条。
- `scenarios` 多于 4 条时只保留离所填时间最近的 4 条,另加 `scenarios_omitted: N`。
- `provenance` 存 `scenarios`。旧字段 `chosen_side`、`other_saved_at`、`both_versions` 的处理:恰好两段时照旧写(兼容现有读取);一段时不写 `other_saved_at`;三段及以上时 `other_saved_at` 写 `null`、`chosen_side` 写 `"none"`,由 `scenarios` 表达。
- `frontend/src/lib/chart-choice-both-versions.ts`:优先读 `scenarios`。两段时行为与现在一致;三段及以上时把非主段都作为「另外的情景」交给聊天(各段的分盘上升差异),被省略的段写明「另有 N 种情景没有算」。没有算的情景不得编内容。
- 聊天侧现有的说明文字(`bothVersionsNotice`)相应改成能表达多种情景;不新增工具。
## 四、聊天开头的一句说明
来源是自选情景时,聊天回答里用到星盘的**每个会话的第一次回答**开头写一句(之后的回答不重复,除非用户问到出生时间):
`这次按你自己选的线后情景来看,不是出生时间已核实;你填的时间和范围都还保留着。`
「线后」按实际所选替换成「线前」;选的是「不确定」时写 `你没有选定线前还是线后,受影响的地方我会把几种情况分开说。`
实现放在现有咨询提示词装配处(`frontend/src/mastra/consultation-workflow.ts` 及其调用的提示词片段),作为一条条件指令,只在 `isSelfSelectedScenario` 为真时加入。这是产品负责人批准的例外,不违反「回答直接下判断」的规则:除这一句外,不得因为自选而在正文里加任何额外的保留语气。
两边结论不同的地方照现有「两版都读」的做法分开说;占星师要求以下情况即使用户选了一侧也要点出另一侧:两侧结论相反、一侧有时间窗另一侧没有、时间窗明显错开、父母手足等客观事实不同。本单的范围是**上升星座换座造成的分盘差异**(现有 `scenarios` 能给出的);时间窗漂移的比较依赖用途扫描(BUG-1953 之后),本单不做,在 PROGRESS「已知边界」写明。
## 五、旧请求重放不得覆盖新申报
`/api/chart-choice/adopt` 的 `selfChoice` 请求增加必填字段 `baseRecordId`(字符串或 `null`):客户端在 `preview` 时从响应里拿到当前记录号(服务端在 preview 响应里返回 `current_record_id`),保存时原样带回。服务端保存前比对当前记录号:
- 不一致(期间有过别的保存、改回、改申报)→ 409,稳定码 `stale_choice`,不写入;
- 申报范围或原始填写时间在 preview 之后变过 → 同样 409(把申报的指纹也放进比对:preview 响应返回 `declaration_fingerprint`,保存时带回)。
- 两个相同请求并发:只成功一次或两次结果完全相同(现有 `alreadyUsingSelfChoice` 的幂等保留)。
页面收到 409 时重新加载当前状态,回到结果页,不显示报错弹窗以外的新样式(用现有的错误提示)。
旧客户端不带 `baseRecordId` 的 `selfChoice` 请求:400。(自选还没上生产,不需要兼容期。)
## 六、不做的事
- 不恢复问卷、事件打分、任何推荐;`RECT_QUESTIONNAIRE_ENABLED` 不动。
- 不改报告、年运、合盘、导出(BUG-1959)。不改聊天历史的处理(BUG-1960)。
- 不改 `_self_choice_at` 的取分钟规则(BUG-1952 刚定)。
- 不迁移已保存的自选记录:旧记录没有 `selection_kind` 时,`isSelfSelectedScenario` 按 `basis === "self_choice_20261116"` 也判为真。
## 七、测试
- `frontend/tests/chart-choice-self-choice-scenario-20261117.test.tsx`(新):三句文案替换;`等 N 处` 展开列出全部线;页面不出现「可以直接用」「不受影响」「推荐」「更符合」「已核实」(确认页那句「不是出生时间已核实」除外,按整句匹配放行)「已确认」「已校正」;409 后回到结果页。
- 接口测试:`provenance` 新字段齐全;`choice_revision` 递增;`baseRecordId` 不一致 409 且无写入;申报变化后 409;并发两次幂等;不带 `baseRecordId` 400;#292/#294/#301 的旧载荷拒绝断言不删、照旧通过。
- Python `tests/test_chart_choice.py`:`scenarios` 在 0、1、2、5 条剩余线时的段数、代表时刻落在各自段内且满足 BUG-1952 的规则、`is_primary` 唯一、超过 4 条时 `scenarios_omitted` 正确;第一条线就选「不确定」时不再有硬凑的 `other_saved_at`(两段时除外)。
- 聊天:`isSelfSelectedScenario` 为真时提示词含开头说明的指令,为假时不含;三段情景时交给模型的块含全部非主段且不含未算的内容;既有 `chart-choice-both-versions` 测试照旧通过(确需调整的逐条在 PROGRESS 说明)。
- `accepted` 审计:对 PROGRESS 列出的每一处改动各有一条断言。
## 八、文档
- `docs/BUG_HISTORY.md` 新增 BUG-1958,关联 BUG-1936、BUG-1952(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-self-choice-scenario-20261117.md`,含「`accepted` 被当作已确认的位置」清单和「已知边界」。
## 验收
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
- `cd frontend && npx tsc --noEmit` 通过;`npx eslint .` 0 错误;新旧自选测试全部通过;前端全量测试不新增失败;
- 验收时会用合成输入实跑引擎走:单线、三条线逐条选、第一条线不确定、就到这里、重放旧请求。
+3 -3
View File
@@ -399,9 +399,9 @@ The birth-time rectification session is the consultation transcript plus a house
### 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.
- The reported-time result names which of the six ascendant signs change and counts distinct transition times. A chart row with multiple transitions uses its existing band and an expandable list of all transition times and signs on either side. A nearby transition still shows its distance from the time entered.
- The secondary action opens one transition at a time. The buttons appear in the order 线前、线后、不确定. The confirmation shows the remaining range, distinct transitions still within it, the saved time, and the status of the original declaration.
- Current use shows the adopted time and selected range, with the source copy “按你自己的选择” and the restore action. If the declaration or current record changes before save, the existing error notice accompanies the refreshed result.
### Birth time intake
+2
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { isSelfSelectedScenario } from "@/lib/chart-choice/self-selected-scenario";
import {
parseRectificationPriceCredits,
} from "@/lib/birth-time-consultation-consent";
@@ -212,6 +213,7 @@ export async function GET() {
entitlements: activeSubscription.entitlement_snapshot,
} : null,
hasConfirmedBirthTime: profile.birth_time_status === "confirmed"
&& !isSelfSelectedScenario(profile.active_birth_provenance)
&& typeof profile.active_birth_time === "string",
hasUsableBirthTime: (profile.birth_time_status === "accepted" || profile.birth_time_status === "confirmed")
&& typeof profile.active_birth_time === "string",
@@ -25,18 +25,24 @@ const choiceSchema = z.object({
rangeChosen: z.boolean().optional(),
...evidenceInput,
}).strict();
const selfChoiceSchema = z.object({
const selfChoiceFields = {
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),
};
const selfChoicePreviewSchema = z.object({ ...selfChoiceFields, mode: z.literal("preview") }).strict();
const selfChoiceSaveSchema = z.object({
...selfChoiceFields,
mode: z.literal("choice").default("choice"),
baseRecordId: z.string().uuid().nullable(),
declarationFingerprint: z.string().regex(/^[a-f0-9]{64}$/),
}).strict();
const bodySchema = z.union([selfChoiceSchema, choiceSchema, z.object({
const bodySchema = z.union([selfChoicePreviewSchema, selfChoiceSaveSchema, choiceSchema, z.object({
mode: z.literal("restore_default"),
subjectId: z.string().max(64).optional(),
recordId: z.string().uuid(),
@@ -63,9 +69,10 @@ export async function POST(request: Request) {
if (!parsed.success) return NextResponse.json({ error: "请求格式不对", code: "bad_request" }, { status: 400 });
try {
if ("selfChoice" in parsed.data) {
const admin = createAdminSupabaseClient();
return NextResponse.json(parsed.data.mode === "preview"
? await previewSelfChoice(caller.supabase, caller.userId, parsed.data)
: await adoptSelfChoice(caller.supabase, createAdminSupabaseClient(), caller.userId, parsed.data));
? await previewSelfChoice(caller.supabase, admin, caller.userId, parsed.data)
: await adoptSelfChoice(caller.supabase, admin, caller.userId, parsed.data));
}
if (!RECT_QUESTIONNAIRE_ENABLED && (parsed.data.mode === "preview" || parsed.data.mode === "choice")) {
const { subjectId, window, rangeChosen } = parsed.data;
+8 -4
View File
@@ -11,6 +11,7 @@ import {
runConsultationWorkflow,
} from "@/mastra";
import { blocksPromptExtraction } from "@/lib/consult-safety";
import { selfSelectedScenarioOpening } from "@/mastra/consultation-workflow";
import { consultDomainConcurrency, consultPrepParallelEnabled, modelVersionCacheTtlMs } from "@/lib/consult/prep-flags";
import {
ConsultationInputBlockedError,
@@ -1201,8 +1202,10 @@ export async function POST(request: Request) {
// override it for this question only. Earlier turns no longer set the mode.
const answerMode = consultationAnswerMode({ question: visibleQuestion, baseMode: requestedAnswerMode });
const natalInstruction = `${natalToolInstruction}${natalUserTurnShape({ entrypoint: consultEntrypoint, history, summaryText: historyWindow.summaryText, answerMode })}`;
const scenarioOpening = selfSelectedScenarioOpening(prepared.serverChart?.selfSelectedScenario, followUpTurn, visibleQuestion);
const adoptedRangeNote = consultationMode === "verified_chart"
&& prepared.serverChart?.truth.birthTimeStatus === "accepted"
&& !prepared.serverChart.selfSelectedScenario
&& prepared.serverChart.toolInput.candidate_range
? ` ${ACCEPTED_RANGE_READING_INSTRUCTION}`
: "";
@@ -1210,7 +1213,7 @@ export async function POST(request: Request) {
? generalNoMinuteInstruction(Boolean(generalDailyContext))
: consultationMode === "declared_birth_window"
? declaredWindowInstruction()
: `${natalInstruction}${adoptedRangeNote}`;
: `${natalInstruction}${adoptedRangeNote}${scenarioOpening}`;
const consultationBaseMessages = (overflow: boolean) => {
const tail = overflow ? lastConsultationPair(history) : history;
const mapped = tail.map((message) => message.role === "user"
@@ -1836,7 +1839,8 @@ export async function POST(request: Request) {
// The grounded fallback writes from the injected workflow; same first-turn
// / follow-up split as the agentic path (BUG-1071), one statement of it.
const legacyAnswerMode = consultationAnswerMode({ question: visibleQuestion, baseMode: requestedAnswerMode });
const legacyNatalInstruction = hasPriorAssistantAnswer(history, { summaryText: historyWindow.summaryText })
const legacyFollowUp = hasPriorAssistantAnswer(history, { summaryText: historyWindow.summaryText });
const legacyNatalInstruction = legacyFollowUp
? followUpAnswerShapeInstruction(legacyAnswerMode)
: `${answerModeTurnLine(legacyAnswerMode)}${natalAnswerShapeBody(legacyAnswerMode)}${legacyAnswerMode === "plain" ? "文末技法审计表由产品界面折叠展示,不写进正文。" : ""}星盘事实只使用系统里已经注入的计算结果,不要复述内部字段、JSON 或再跑一遍咨询流程。`;
@@ -1855,7 +1859,7 @@ export async function POST(request: Request) {
content: consultationUserTurnContent({
currentTime: currentTimeContext(requestTime),
name,
instruction: legacyNatalInstruction,
instruction: legacyNatalInstruction + selfSelectedScenarioOpening(prepared.serverChart.selfSelectedScenario, legacyFollowUp, visibleQuestion),
summaryText: historyWindow.summaryText,
droppedCount: historyWindow.droppedCount,
question: resolvedQuestion.modelQuestion,
@@ -1880,7 +1884,7 @@ export async function POST(request: Request) {
content: consultationUserTurnContent({
currentTime: currentTimeContext(requestTime),
name,
instruction: legacyNatalInstruction,
instruction: legacyNatalInstruction + selfSelectedScenarioOpening(prepared.serverChart.selfSelectedScenario, legacyFollowUp, visibleQuestion),
summaryText: historyWindow.summaryText,
droppedCount: historyWindow.droppedCount,
question: resolvedQuestion.modelQuestion,
@@ -34,6 +34,7 @@ import {
type ChartChoiceWindow,
type SelfChoicePick,
type SelfChoicePreview,
type SelfChoicePreviewResponse,
} from "@/lib/chart-choice/contract";
import {
SIDE_TEXT,
@@ -74,29 +75,33 @@ type Step =
| { kind: "home" }
| { kind: "packet_loading" }
| { kind: "narrow"; packet: Extract<ChartChoicePacket, { status: "needs_narrowing" }> }
| { kind: "certain"; packet: Extract<ChartChoicePacket, { status: "certain" }> }
| { kind: "certain"; packet: Extract<ChartChoicePacket, { status: "certain" }>; notice?: string }
| { kind: "range"; packet: Choose | Complete; request: ChartChoiceRequest }
| { kind: "choose"; packet: Choose; request: ChartChoiceRequest; previous?: Step; draft?: RoundDraft }
| { kind: "result"; packet: Choose; decision: ChartChoiceDecision; saving: boolean; overrideSide?: ChartChoiceSide }
| { 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: "self_choice"; preview: SelfChoicePreview; final: Extract<Step, { kind: "final" }>; stopped?: boolean };
| { kind: "final"; packet: FinalPacket; decision: FinalDecision; body: ResultRequest; back: Step; notice?: string }
| { kind: "self_choice"; preview: SelfChoicePreviewResponse; final: Extract<Step, { kind: "final" }>; stopped?: boolean };
const COPY = {
title: "生时纠正",
profileHref: (subjectId: string) => (subjectId === "self" ? "/people?self=1" : `/people?edit=${encodeURIComponent(subjectId)}`),
};
class ChartChoiceRequestError extends Error {
constructor(message: string, readonly code?: string) { super(message); }
}
async function postJson<T>(url: string, body: unknown): Promise<T> {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const payload = await response.json().catch(() => null) as (T & { error?: string }) | null;
if (!response.ok || !payload) throw new Error(payload?.error || "暂时没有响应,请稍后再试。");
const payload = await response.json().catch(() => null) as (T & { error?: string; code?: string }) | null;
if (!response.ok || !payload) throw new ChartChoiceRequestError(payload?.error || "暂时没有响应,请稍后再试。", payload?.code);
return payload;
}
@@ -154,7 +159,7 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) {
const [rangeChosen, setRangeChosen] = useState(false);
const generation = useRef(0);
const loadPacket = useCallback(async (request: ChartChoiceRequest, showRange = true, previous?: Step) => {
const loadPacket = useCallback(async (request: ChartChoiceRequest, showRange = true, previous?: Step, notice?: string) => {
const ticket = ++generation.current;
setWindow(request.window);
setAnswers({});
@@ -168,11 +173,11 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) {
if (ticket !== generation.current) return;
if (!RECT_QUESTIONNAIRE_ENABLED) {
if (packet.status === "certain") {
setStep({ kind: "certain", packet });
setStep({ kind: "certain", packet, notice });
} else if (packet.status === "complete" && packet.decision.reported_choice) {
setStep({ kind: "final", packet, decision: packet.decision,
body: { subjectId, adaptive: true, mode: "choice", ...(request.window ? { window: request.window } : {}) },
back: { kind: "home" },
back: { kind: "home" }, notice,
});
} else {
throw new Error("暂时没有可用的结果,请重试。");
@@ -276,7 +281,11 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) {
? <RangeChips window={packet.window} reportedAt={packet.reported_at} onPick={pickRange} />
: null);
return <>{renderStep()}</>;
return <>
{(step.kind === "final" || step.kind === "certain") && step.notice
? <p className="chart-choice-note" role="alert">{step.notice}</p> : null}
{renderStep()}
</>;
function retry(target: Retry) {
if (target.kind === "start") {
@@ -332,18 +341,31 @@ export function ChartChoiceFlow({ subjectId }: { readonly subjectId: string }) {
async function runSelfChoice(
final: Extract<Step, { kind: "final" }>,
choices: readonly SelfChoicePick[],
mode: "preview" | "choice",
binding?: SelfChoicePreviewResponse,
) {
setPending(true);
const back = step;
const body = { selfChoice: true, subjectId, choices, ...(final.body.window ? { window: final.body.window } : {}) };
try {
const preview = await postJson<SelfChoicePreview>("/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));
if (binding) {
const saved = await postJson<SelfChoicePreview>("/api/chart-choice/adopt", {
...body, mode: "choice", baseRecordId: binding.current_record_id,
declarationFingerprint: binding.declaration_fingerprint,
});
afterSave(adoptedClock(saved.decision.saved_at, final.packet.reported_at));
} else {
const preview = await postJson<SelfChoicePreviewResponse>("/api/chart-choice/adopt", { ...body, mode: "preview" });
setStep({ kind: "self_choice", final, preview });
}
} catch (error) {
setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: back } });
if (error instanceof ChartChoiceRequestError && error.code === "stale_choice") {
const refreshed = await readStart(subjectId);
if ("ready" in refreshed) {
setStart(refreshed.ready);
setRangeChosen(false);
await loadPacket({}, false, undefined, error.message);
} else setStep(refreshed);
} else setStep({ kind: "failed", message: (error as Error).message, retry: { kind: "back", step: back } });
} finally {
setPending(false);
}
@@ -506,15 +528,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")}
onSelfChoice={() => void runSelfChoice(step, [])}
onAccept={() => void saveFinal(step)} />;
case "self_choice":
return <SelfChoiceStep preview={step.preview} stopped={step.stopped} pending={pending}
reference={step.final.packet.reported_at}
onBack={() => restore(step.final)}
onPick={(pick) => void runSelfChoice(step.final, [...step.preview.decision.choices, pick], "preview")}
onPick={(pick) => void runSelfChoice(step.final, [...step.preview.decision.choices, pick])}
onStop={() => setStep({ ...step, stopped: true })}
onAccept={() => void runSelfChoice(step.final, step.preview.decision.choices, "choice")} />;
onAccept={() => void runSelfChoice(step.final, step.preview.decision.choices, step.preview)} />;
}
}
}
@@ -853,13 +875,14 @@ function FlipSummary({ summary, reportedAt }: {
readonly summary: ChartChoiceLineSummary;
readonly reportedAt?: string | null;
}) {
if (!summary.nearest_at) return <p className="chart-choice-note">这个时间范围内六张盘都不变,可以直接用。</p>;
if (!summary.nearest_at) return <p className="chart-choice-note">这个时间范围内,六张盘的上升星座都不变。</p>;
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 <div>
<p className="chart-choice-note">不受影响:{stable.join("、") || "无"}。</p>
<p className="chart-choice-note">差几分钟就不同:{changing.join("、")}。</p>
<p className="chart-choice-note">上升星座不变:{stable.join("、") || "无"}。</p>
<p className="chart-choice-note">上升星座会变:{changing.join("、")}。</p>
{summary.line_count ? <p className="chart-choice-note">共有 {summary.line_count} 处换座。</p> : null}
{reportedAt && seconds !== null && seconds < 120 ? <p className="chart-choice-note">
你填的 {clockLabel(reportedAt)} 离 {clockLabel(summary.nearest_at, reportedAt, true)} 这条线只有 {seconds >= 60 ? Math.floor(seconds / 60) + " 分 " : ""}{seconds % 60} 秒。
</p> : null}
@@ -881,12 +904,17 @@ function KeyCharts({ charts, undetermined, reference, segment, window = segment,
const uncertain = Boolean(row.flips_at || undetermined?.includes(row.chart));
const flip = summary?.charts[row.chart];
const flipAt = flip?.at ?? row.flips_at;
const allFlips = flip?.lines ?? [];
const describeFlip = (value: { at: string; before: string; after: string }) =>
clockLabel(value.at, reference, true) + " 之前" + value.before + "上升,之后" + value.after + "上升";
return <Fragment key={row.chart}>
<dt>{CHART_NAMES[row.chart]}</dt>
<dd>{segment ? <ChoiceBand window={segment} reportedAt={reference} small
segments={splitBand(segment, flipAt ? [flipAt] : [])} highlighted={[0]} /> : null}
{flip ? <span>{clockLabel(flip.at, reference, true)} 之前{flip.before}上升,之后{flip.after}上升
{flip.count > 1 ? "等 " + flip.count + " 处" : null}</span> : <span>{row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)}
segments={splitBand(segment, allFlips.length ? allFlips.map(({ at }) => at) : flipAt ? [flipAt] : [])} highlighted={[0]} /> : null}
{flip && allFlips.length > 1 ? <details>
<summary>{describeFlip(flip)}等 {allFlips.length} 处</summary>
<ul>{allFlips.map((line) => <li key={line.at}>{describeFlip(line)}</li>)}</ul>
</details> : flip ? <span>{describeFlip(flip)}</span> : <span>{row.sign ? `${row.sign}上升,` : ""}{uncertain ? "范围内会换座" : noSignChange(trial, window)}
{row.flips_at ? `(${clockLabel(row.flips_at, reference, true)} 换)` : null}</span>}
</dd>
</Fragment>;
@@ -1153,7 +1181,7 @@ function ReadingPlan({
<dl className="chart-choice-plan">
{chosen !== "none" && byChosen.length ? (<><dt>按{SIDE_TEXT[chosen]}读</dt><dd>{byChosen.join("、")}</dd></>) : null}
{twoWays.length ? (<><dt className="is-accent">两版都读</dt><dd>{twoWays.join("、")}</dd></>) : null}
{unchanged.length ? (<><dt>不受影响</dt><dd>{unchanged.join("、")}</dd></>) : null}
{unchanged.length ? (<><dt>上升星座不变</dt><dd>{unchanged.join("、")}</dd></>) : null}
</dl>
);
}
@@ -1267,11 +1295,13 @@ export function SelfChoiceStep({ preview, reference, stopped, pending, onBack, o
readonly onAccept: () => void;
}) {
const { decision, next } = preview;
const remaining = decision.remaining_lines?.length ?? decision.line_summary.line_count ?? 0;
if (next && !stopped) return <>
<Card>
{!pending ? <BackLink onClick={onBack}>返回</BackLink> : null}
<h2 className="chart-choice-heading">{clockLabel(next.at, reference, true)} 分界线</h2>
<p className="chart-choice-fine">范围 {segmentLabel(decision.segment)}</p>
<p className="chart-choice-note">范围 {segmentLabel(decision.segment)}</p>
{remaining > 0 ? <p className="chart-choice-note">还有 {remaining} 条线没选。</p> : null}
<TimeRuler window={decision.segment} lineAt={next.at} reportedAt={reference} />
</Card>
{next.comparisons.map((comparison) => <CompareCard
@@ -1301,8 +1331,10 @@ export function SelfChoiceStep({ preview, reference, stopped, pending, onBack, o
{clockLabel(pick.line_at, reference, true)} {SELF_CHOICE_OPTIONS[pick.side]}
</li>)}
</ul> : null}
{remaining > 0 ? <p className="chart-choice-note">还有 {remaining} 条线没选。</p> : null}
<SelfChoiceBothVersions domains={decision.both_versions} />
<p className="chart-choice-note">这是你自己选的,可以随时改。</p>
<p className="chart-choice-note">这不是出生时间已核实,你填的时间和范围都还保留着。</p>
<div className="chart-choice-foot is-end"><Primary disabled={pending} onClick={onAccept}>用 {saved}</Primary></div>
</Card>;
}
+65 -4
View File
@@ -6,8 +6,9 @@
* 咨询照常按采用的分钟排盘;这里只为这些领域另外算出另一边的分盘,
* 交给模型一段写明「两版都读」的说明。没有这些字段的旧资料完全不受影响。
*/
import { z } from "zod";
import { recordOrEmpty as record } from "@/lib/guards";
import { SELF_CHOICE_BASIS } from "./chart-choice/contract";
import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario";
/** Domain keys and charts written by scripts/chart_choice/readings.py DOMAIN. */
export const CHART_CHOICE_DOMAIN_CHARTS: Readonly<Record<string, Readonly<{ chart: string; label: string }>>> = {
@@ -32,15 +33,75 @@ export type ChartChoiceBothVersionsInput = 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)?$/;
const scenarioSchema = z.object({
segment: z.object({ start_at: z.string().regex(CHART_CHOICE_OTHER_AT), end_at: z.string().regex(CHART_CHOICE_OTHER_AT) }),
saved_at: z.string().regex(CHART_CHOICE_OTHER_AT),
key_charts: z.array(z.object({
chart: z.enum(["D1", "D2", "D6", "D8", "D9", "D10"]),
sign: z.enum(["白羊", "金牛", "双子", "巨蟹", "狮子", "处女", "天秤", "天蝎", "射手", "摩羯", "水瓶", "双鱼"]),
})).min(1).max(6),
is_primary: z.boolean(),
});
export const chartChoiceScenariosSchema = z.object({
primary: scenarioSchema,
alternatives: z.array(scenarioSchema).max(3),
comparison: scenarioSchema.optional(),
omitted: z.number().int().min(0),
});
export type ChartChoiceScenariosInput = z.infer<typeof chartChoiceScenariosSchema>;
function readScenarios(value: unknown) {
const provenance = record(value);
if (!isSelfSelectedScenario(provenance)) return null;
const items = z.array(scenarioSchema).min(1).max(4).safeParse(provenance.scenarios);
if (!items.success || items.data.filter((item) => item.is_primary).length !== 1) return null;
return items.data;
}
export function chartChoiceScenariosFromProvenance(value: unknown): ChartChoiceScenariosInput | null {
const items = readScenarios(value);
if (!items) return null;
const provenance = record(value);
const omitted = z.number().int().min(0).catch(0).parse(provenance.scenarios_omitted);
const outside = scenarioSchema.safeParse(provenance.comparison_scenario);
const comparison = outside.success && !outside.data.is_primary ? outside.data : undefined;
const alternatives = items.length > 2 || omitted ? items.filter((item) => !item.is_primary) : [];
if (!alternatives.length && !comparison && !omitted) return null;
return { primary: items.find((item) => item.is_primary)!, alternatives, comparison, omitted };
}
export function compareChartChoiceScenarios(input: ChartChoiceScenariosInput) {
const primary = new Map(input.primary.key_charts.map(({ chart, sign }) => [chart, sign]));
const evidence = (scenario: (typeof input.alternatives)[number]) => ({
segment: scenario.segment,
saved_at: scenario.saved_at,
ascendant_changes: scenario.key_charts.flatMap(({ chart, sign }) => {
const before = primary.get(chart);
return before && before !== sign ? [{ chart, primary: before, alternative: sign }] : [];
}),
});
return {
primary_segment: input.primary.segment,
other_scenarios: input.alternatives.map(evidence),
...(input.comparison ? { opposite_side: evidence(input.comparison) } : {}),
scenarios_omitted: input.omitted,
notice: "使用主情景。若已计算的换座使这个问题的结论不同,按情景分开说明。若两边结论相反,或改变对父母手足等客观事实的判断,即使用户已选定一侧也要点出另一侧。"
+ (input.omitted ? `另有 ${input.omitted} 种情景没有算。不能编写其结论。` : ""),
};
}
/** Read the both-versions request from a profile's provenance; null when there is none. */
export function chartChoiceBothVersionsFromProvenance(value: unknown): ChartChoiceBothVersionsInput | null {
const provenance = record(value);
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 : "";
const selfChoice = provenance.basis === SELF_CHOICE_BASIS && provenance.declared_by_user === true;
const selfChoice = isSelfSelectedScenario(provenance);
const scenarios = readScenarios(provenance);
if (scenarios && (scenarios.length !== 2 || provenance.scenarios_omitted)) return null;
const otherAt = scenarios?.find((item) => !item.is_primary)?.saved_at
?? (typeof provenance.other_saved_at === "string" ? provenance.other_saved_at : "");
if (!(selfChoice ? CHART_CHOICE_OTHER_AT : minutePattern).test(otherAt)) return null;
const chosen = provenance.chosen_side;
const chosen = scenarios ? scenarios[0].is_primary ? "before" : "after" : provenance.chosen_side;
if (chosen !== "before" && chosen !== "after") return null;
const seen = new Set<string>();
const domains = [];
+21 -3
View File
@@ -52,7 +52,10 @@ export type ChartChoiceLine = {
};
export type ChartChoiceLineSummary = Readonly<{
nearest_at: string | null;
charts: Readonly<Record<string, ChartChoiceFlip & Readonly<{ at: string; count: number }>>>;
line_count?: number;
charts: Readonly<Record<string, ChartChoiceFlip & Readonly<{
at: string; count: number; lines?: readonly (ChartChoiceFlip & Readonly<{ at: string }>)[];
}>>>;
}>;
export type ChartChoiceMinorLine = Pick<ChartChoiceLine, "at" | "charts">;
export type ChartChoiceKeyChart = {
@@ -239,20 +242,35 @@ export type SelfChoiceRequest = Readonly<{
window?: ChartChoiceWindow;
choices: readonly SelfChoicePick[];
}>;
export type SelfChoiceBinding = Readonly<{ baseRecordId: string | null; declarationFingerprint: string }>;
export type SelfChoiceScenario = Readonly<{
segment: ChartChoiceWindow;
saved_at: string;
key_charts: readonly ChartChoiceKeyChart[];
is_primary: boolean;
}>;
export type SelfChoiceDecision = Readonly<{
saved_at: string;
segment: ChartChoiceWindow;
choices: readonly SelfChoicePick[];
key_charts: readonly ChartChoiceKeyChart[];
line_summary: ChartChoiceLineSummary;
chosen_side?: ChartChoiceSide;
chosen_side?: ChartChoiceSide | "none";
both_versions: readonly string[];
other_saved_at?: string;
other_saved_at?: string | null;
remaining_lines?: readonly ChartChoiceMinorLine[];
scenarios?: readonly SelfChoiceScenario[];
scenarios_omitted?: number;
comparison_scenario?: SelfChoiceScenario;
}>;
export type SelfChoicePreview = Readonly<{
decision: SelfChoiceDecision;
next?: ChartChoiceLine & { readonly comparisons: readonly ChartChoiceComparison[] };
}>;
export type SelfChoicePreviewResponse = SelfChoicePreview & Readonly<{
current_record_id: string | null;
declaration_fingerprint: string;
}>;
export type ChartChoiceStart =
| {
@@ -51,6 +51,7 @@ const ERROR_TEXT: Record<ChartChoiceError["code"], string> = {
engine_unavailable: "排盘服务暂时没有响应,请稍后再试。",
no_choice: "这个范围里没有需要选的分界线。",
record_stale: "出生资料改过了,这次的结果不能再用。",
stale_choice: "出生资料改过了,这次的结果不能再用。",
answer_window_disabled: "答题得出的时间范围已停用。可以保存填写的时间和原范围。",
};
@@ -0,0 +1,20 @@
import { asRecord } from "../guards.ts";
import { SELF_CHOICE_BASIS } from "./contract.ts";
export function isSelfSelectedScenario(provenance: unknown): boolean {
const source = asRecord(provenance);
return source?.selection_kind === "self_selected_scenario" || source?.basis === SELF_CHOICE_BASIS;
}
export type ScenarioSelection = "before" | "after" | "unsure";
export function selfSelectedScenarioSide(value: unknown): ScenarioSelection | undefined {
if (!isSelfSelectedScenario(value)) return undefined;
const source = asRecord(value);
const choices = source?.choices;
const last = Array.isArray(choices) ? asRecord(choices.at(-1))?.side : undefined;
if (last === "before" || last === "after" || last === "unsure") return last;
if (!Array.isArray(choices) && !source?.other_saved_at
&& (source?.chosen_side === "before" || source?.chosen_side === "after")) return source.chosen_side;
return "unsure";
}
+65 -17
View File
@@ -7,7 +7,8 @@ import { resolveAyanamsa } from "../ayanamsa.ts";
import { CHART_VIEW_NODE_MODE } from "../chart-view-load.ts";
import { prepareChartViewProfile } from "../chart-view-profile-read.ts";
import { lagnaPrecheckWindow, type LagnaPrecheckWindow } from "../lagna-precheck.ts";
import { ConsultationSubjectError, loadSubjectBirth, SELF_SUBJECT_ID } from "../subject-birth.ts";
import { ConsultationSubjectError, isChartSubjectId, loadSubjectBirth, SELF_SUBJECT_ID, subjectIdFromQuery } from "../subject-birth.ts";
import { isSelfSelectedScenario } from "./self-selected-scenario.ts";
import type {
ChartChoiceAdoptRequest,
ChartChoiceHistory,
@@ -21,7 +22,9 @@ import type {
ChartChoiceQuestionnaire,
ChartChoiceStart,
ChartChoiceWindow,
SelfChoiceBinding,
SelfChoiceDecision,
SelfChoicePreviewResponse,
SelfChoicePreview,
SelfChoiceRequest,
} from "./contract.ts";
@@ -37,7 +40,7 @@ const ROUNDS_VERSION = "chart-choice-v2";
const MAX_RECORD_SPAN_MINUTES = Math.max(...RECORD_RANGE_CHOICES);
export class ChartChoiceError extends Error {
constructor(readonly code: "subject_not_found" | "profile_incomplete" | "bad_window" | "bad_event_date" | "engine_unavailable" | "no_choice" | "record_stale" | "answer_window_disabled", readonly status: number) {
constructor(readonly code: "subject_not_found" | "profile_incomplete" | "bad_window" | "bad_event_date" | "engine_unavailable" | "no_choice" | "record_stale" | "stale_choice" | "answer_window_disabled", readonly status: number) {
super(code);
this.name = "ChartChoiceError";
}
@@ -577,8 +580,7 @@ export async function restoreChartChoiceDefault(
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;
const selfChoice = isSelfSelectedScenario(provenance);
if (current?.id !== request.recordId || !current.reusable
|| (!selfChoice && provenance?.source !== "user_choice_from_answers")) {
throw new ChartChoiceError("record_stale", 409);
@@ -611,9 +613,37 @@ async function evaluateSelfChoice(
return { subject, window, result, reported: subject.declared ? reportedAt(subject.declared) : null };
}
export async function previewSelfChoice(supabase: unknown, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch) {
async function readSelfChoiceState(admin: RpcClient, userId: string, requested: unknown) {
const subjectId = subjectIdFromQuery(requested);
if (subjectId !== SELF_SUBJECT_ID && !isChartSubjectId(subjectId)) throw new ChartChoiceError("subject_not_found", 404);
const { data, error } = await admin.rpc("chart_choice_scenario_state_v1", {
p_user_id: userId, p_chart_profile_id: subjectId === SELF_SUBJECT_ID ? null : subjectId,
});
if (error) throw new ChartChoiceError("engine_unavailable", 503);
const state = asRecord(data);
if (!state) throw new ChartChoiceError("subject_not_found", 404);
const id = state.current_record_id;
const fingerprint = state.declaration_fingerprint;
if ((id !== null && (typeof id !== "string" || !isChartSubjectId(id)))
|| typeof fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(fingerprint)) {
throw new ChartChoiceError("engine_unavailable", 503);
}
return { baseRecordId: id, declarationFingerprint: fingerprint };
}
function requireSelfChoiceState(actual: SelfChoiceBinding, expected: SelfChoiceBinding) {
if (actual.baseRecordId !== expected.baseRecordId || actual.declarationFingerprint !== expected.declarationFingerprint) {
throw new ChartChoiceError("stale_choice", 409);
}
}
export async function previewSelfChoice(
supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest, fetchImpl?: typeof fetch,
): Promise<SelfChoicePreviewResponse> {
const before = await readSelfChoiceState(admin, userId, request.subjectId);
const { result } = await evaluateSelfChoice(supabase, userId, request, false, fetchImpl);
return result;
requireSelfChoiceState(await readSelfChoiceState(admin, userId, request.subjectId), before);
return { ...result, current_record_id: before.baseRecordId, declaration_fingerprint: before.declarationFingerprint };
}
function sameWindow(value: unknown, window: ChartChoiceWindow): boolean {
@@ -624,7 +654,7 @@ function sameWindow(value: unknown, window: ChartChoiceWindow): boolean {
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
return prior?.selection_kind === "self_selected_scenario"
&& 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
@@ -632,45 +662,63 @@ function alreadyUsingSelfChoice(active: Subject["active"], window: ChartChoiceWi
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)
&& (prior.other_saved_at ?? null) === (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,
supabase: unknown, admin: RpcClient, userId: string, request: SelfChoiceRequest & SelfChoiceBinding, fetchImpl?: typeof fetch,
): Promise<{ decision: SelfChoiceDecision }> {
const { subject, window, result: { decision }, reported } = await evaluateSelfChoice(supabase, userId, request, true, fetchImpl);
requireSelfChoiceState(await readSelfChoiceState(admin, userId, request.subjectId), request);
const { subject, window, result: { decision }, reported } = await evaluateSelfChoice(supabase, userId, request, true, fetchImpl)
.catch(async (error: unknown) => {
requireSelfChoiceState(await readSelfChoiceState(admin, userId, request.subjectId), request);
throw error;
});
const active = await activeChoice(supabase, subject, userId);
if (alreadyUsingSelfChoice(active, window, decision)) return { decision };
if (alreadyUsingSelfChoice(active, window, decision)) {
requireSelfChoiceState(await readSelfChoiceState(admin, userId, subject.subjectId), request);
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,
selection_kind: "self_selected_scenario",
declared_window: subject.declared && !declaredNeedsRange(subject.declared)
? { start_at: subject.declared.start_at, end_at: subject.declared.end_at } : null,
segment: decision.segment, scenario_segment: decision.segment, window, reported_at: reported, choices: decision.choices,
chosen_side: decision.chosen_side, both_versions: decision.both_versions,
...(decision.other_saved_at === undefined ? {} : { other_saved_at: decision.other_saved_at }),
remaining_lines: decision.remaining_lines ?? [],
scenarios: decision.scenarios ?? [],
scenarios_omitted: decision.scenarios_omitted ?? 0,
...(decision.comparison_scenario ? { comparison_scenario: decision.comparison_scenario } : {}),
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: [],
other_lines: decision.remaining_lines?.length ?? 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", {
const { error } = await admin.rpc("chart_choice_adopt_scenario_v1", {
p_user_id: userId,
p_chart_profile_id: subject.subjectId === SELF_SUBJECT_ID ? null : subject.subjectId,
p_base_record_id: request.baseRecordId, p_declaration_fingerprint: request.declarationFingerprint,
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);
const reason = error.message ?? "";
if (reason.includes("chart_choice_stale_choice")) throw new ChartChoiceError("stale_choice", 409);
if (reason.includes("chart_choice_subject_not_found")) throw new ChartChoiceError("subject_not_found", 404);
throw new ChartChoiceError("engine_unavailable", 503);
}
return { decision };
+2
View File
@@ -1,4 +1,5 @@
import { birthWindowRetired, RETIRED_BIRTH_WINDOW_REASON } from "./retired-birth-window.ts";
import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario.ts";
import { isAyanamsaName, resolveAyanamsa } from "./ayanamsa.ts";
import { parsePersonRelation } from "./person-relation.ts";
import { parseProfileGender } from "./profile-gender.ts";
@@ -239,6 +240,7 @@ export function libraryProfileFromSubjectRow(row: Record<string, unknown>): Reco
uncertaintyAfterMinutes: typeof row.uncertainty_after_minutes === "number" ? row.uncertainty_after_minutes : null,
...readBirthTimeDeclarationDetail(row),
birthTimeStatus: status,
...(isSelfSelectedScenario(row.active_birth_provenance) ? { selfSelectedScenario: true } : {}),
countryCode: typeof stored.countryCode === "string" ? stored.countryCode : "CN",
provinceCode: typeof stored.provinceCode === "string" ? stored.provinceCode : "",
cityCode: typeof stored.cityCode === "string" ? stored.cityCode : "",
+22 -7
View File
@@ -25,7 +25,8 @@ import {
type OwnedChartProfile,
} from "./consultation-subject-resolver.ts";
import { asRecord as record } from "@/lib/guards";
import { chartChoiceBothVersionsFromProvenance, type ChartChoiceBothVersionsInput } from "./chart-choice-both-versions.ts";
import { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance, type ChartChoiceBothVersionsInput, type ChartChoiceScenariosInput } from "./chart-choice-both-versions.ts";
import { selfSelectedScenarioSide, type ScenarioSelection } from "./chart-choice/self-selected-scenario.ts";
export type ConsultationProfileTruthErrorCode =
| "profile_unavailable"
@@ -67,11 +68,14 @@ type ServerChartToolInput = Readonly<{
candidate_range?: Readonly<{ start_time: string; end_time: string; candidate_intervals?: ReportCandidateClockRange["candidate_intervals"] }>;
unreliable_vargas?: readonly ("D1" | "D9" | "D10")[];
chart_choice_both_versions?: ChartChoiceBothVersionsInput;
chart_choice_scenarios?: ChartChoiceScenariosInput;
second?: number;
}>;
export type ServerChartConsultation = Readonly<{
name: string;
toolInput: ServerChartToolInput;
selfSelectedScenario?: ScenarioSelection;
truth: Readonly<{
birthDate: string;
reportedBirthTime: string | null;
@@ -380,11 +384,14 @@ function serverChartFromProfile(
hasActiveBirthTime: Boolean(activeBirthTime),
});
const retired = birthWindowRetired(profile.active_birth_provenance);
const scenario = mode === "verified_chart" ? selfSelectedScenarioSide(profile.active_birth_provenance) : undefined;
const second = /^\d\d:\d\d:([0-5]\d)(?:\.\d+)?$/.exec(String(profile.active_birth_time))?.[1];
const original = retired ? declaredBirthWindow(profile) : null;
return Object.freeze({
name,
gender: parseProfileGender(profile.gender),
...(scenario ? { selfSelectedScenario: scenario } : {}),
toolInput: Object.freeze({
year,
month,
@@ -399,9 +406,10 @@ function serverChartFromProfile(
// BUG-1828:绑定盘显式带口径,缺省是产品默认值。
node_mode: PRODUCT_DEFAULT_NODE_MODE,
position_mode: PRODUCT_DEFAULT_POSITION_MODE,
declared_accuracy: accuracy.declaredAccuracy,
time_source: accuracy.timeSource,
...(retired ? { birth_time_accuracy: "provisional" as const } : {}),
declared_accuracy: scenario ? "minute" : accuracy.declaredAccuracy,
time_source: scenario ? "self_selected_scenario" : accuracy.timeSource,
...(scenario && second ? { second: Number(second) } : {}),
...(retired || scenario ? { birth_time_accuracy: "provisional" as const } : {}),
...(original && original.minutes > 1 ? { candidate_range: {
start_time: original.start_at.slice(11), end_time: original.end_at.slice(11),
candidate_intervals: [{ start_at: original.start_at, end_at: original.end_at }],
@@ -601,17 +609,24 @@ export async function prepareConsultationRoute<Reservation, GuardResult>(
serverChart = serverChartFromProfile(profile, consultationMode);
if (consultationMode === "verified_chart" && serverChart.truth.birthTimeStatus === "accepted") {
// 生时纠正「两版都读」的领域(产品 2026-11-07);旧资料没有这些字段时不变。
const bothVersions = chartChoiceBothVersionsFromProvenance(record(profile)?.active_birth_provenance);
if (bothVersions) {
const provenance = record(profile)?.active_birth_provenance;
const bothVersions = chartChoiceBothVersionsFromProvenance(provenance);
const scenarios = chartChoiceScenariosFromProvenance(provenance);
if (bothVersions || scenarios) {
serverChart = Object.freeze({
...serverChart,
toolInput: Object.freeze({ ...serverChart.toolInput, chart_choice_both_versions: bothVersions }),
toolInput: Object.freeze({
...serverChart.toolInput,
...(bothVersions ? { chart_choice_both_versions: bothVersions } : {}),
...(scenarios ? { chart_choice_scenarios: scenarios } : {}),
}),
});
}
}
if (
consultationMode === "verified_chart"
&& serverChart.truth.birthTimeStatus === "accepted"
&& !serverChart.selfSelectedScenario
&& subjectRole === "self"
&& input.loadCandidateRange
) {
+5
View File
@@ -35,6 +35,7 @@ import { effectiveBirthDate } from "@/lib/effective-birth-date";
import type { OnboardingIntakeHint } from "@/lib/onboarding-intake";
import { parsePersonRelation } from "@/lib/person-relation";
import { parseProfileGender } from "@/lib/profile-gender";
import { isSelfSelectedScenario } from "@/lib/chart-choice/self-selected-scenario";
/** Needs the city table loaded (china-locations-client.ts); undefined until then. */
export function findProvince(code: string) {
@@ -167,6 +168,7 @@ export function profileBirthTimeLabel(profile: Profile) {
}
export function profileBirthTimeStatusLabel(profile: Profile) {
if (profile.selfSelectedScenario) return "用户自选情景";
if (profile.birthTimeStatus === "confirmed") return "时间已确认";
if (profile.birthTimeStatus === "candidate" || profile.birthTimeStatus === "accepted") return "时间为候选";
if (profile.birthTimeStatus === "rectifying" || profile.birthTimeStatus === "assessing") return "正在评估时间";
@@ -298,6 +300,7 @@ export function readProfile(value: unknown): Profile {
birth_time?: unknown;
reported_birth_time?: unknown;
active_birth_time?: unknown;
active_birth_provenance?: unknown;
birth_time_source?: unknown;
birth_time_period?: unknown;
declared_window_start?: unknown;
@@ -401,6 +404,8 @@ export function readProfile(value: unknown): Profile {
? profile.uncertainty_after_minutes
: typeof profile.uncertaintyAfterMinutes === "number" ? profile.uncertaintyAfterMinutes : null,
birthTimeStatus: status,
...(profile.selfSelectedScenario === true || isSelfSelectedScenario(profile.active_birth_provenance)
? { selfSelectedScenario: true } : {}),
rectificationCaseId: typeof profile.rectification_case_id === "string" ? profile.rectification_case_id : "",
countryCode: typeof countryCode === "string" && countryCode ? countryCode : "CN",
provinceCode: typeof provinceCode === "string" ? provinceCode : "",
+1
View File
@@ -32,6 +32,7 @@ export type Profile = BirthTimeDraft & {
rectificationCaseId: string;
activeDate?: string;
activeTimezoneOffset?: number;
selfSelectedScenario?: boolean;
ayanamsa: AyanamsaName;
/** Optional; absent or null = not filled (TASK-consult-gender-optional-20260927). */
gender?: ProfileGender | null;
+2 -1
View File
@@ -70,7 +70,8 @@ export function peopleRowMeta(profile: Profile): string {
* has a time, and a hospital-record time is not a 校正结果.
*/
export function peopleTimeRectified(profile: Profile): boolean {
return (profile.birthTimeStatus === "accepted" || profile.birthTimeStatus === "confirmed")
return !profile.selfSelectedScenario
&& (profile.birthTimeStatus === "accepted" || profile.birthTimeStatus === "confirmed")
&& profile.rectificationCaseId.trim() !== "";
}
@@ -1,4 +1,5 @@
import { birthRowForReading, birthWindowRetired } from "./retired-birth-window.ts";
import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario.ts";
import {
globalBirthProfileFromAccountRow,
} from "./server-owned-birth-profile";
@@ -146,12 +147,13 @@ export function buildLongformBirthPayload(
const year = Number.parseInt(dateMatch[1], 10);
const provenance = asRecord(account?.active_birth_provenance);
const retired = birthWindowRetired(provenance);
const scenario = isSelfSelectedScenario(provenance);
const multiClock = provenance?.contract === "chart-choice-v2" &&
(account?.birth_time_status === "accepted" || account?.birth_time_status === "confirmed")
? reportAdoptedClock(account.active_birth_time) : undefined;
const rectified = account && (provenance?.contract !== "chart-choice-v2" || multiClock)
? rectifiedReadingWindow(account, dateMatch[0], multiClock ?? timeMatch[0]) : null;
const readingMinuteConfirmed = !retired && (rectified
const readingMinuteConfirmed = !retired && !scenario && (rectified
? rectified.source === "rectified_range" && rectified.before_minutes === 0 && rectified.after_minutes === 0
: extras.readingMinuteConfirmed ?? extras.birthTimeAccuracy === "confirmed");
const birthWindow = rectified ?? (!readingMinuteConfirmed && account ? readingBirthWindow(account, timeMatch[0]) : undefined);
@@ -173,10 +175,10 @@ export function buildLongformBirthPayload(
today: extras.today,
target_year: extras.targetYear,
age: extras.targetYear - year,
birth_time_accuracy: retired ? "provisional" : rectified && readingMinuteConfirmed ? "confirmed" : extras.birthTimeAccuracy,
birth_time_accuracy: retired || scenario ? "provisional" : rectified && readingMinuteConfirmed ? "confirmed" : extras.birthTimeAccuracy,
...(readingMinuteConfirmed ? {} : { reading_minute_confirmed: false }),
...(birthWindow ? { birth_time_window: birthWindow } : {}),
...(!retired && extras.candidateRange ? { candidate_range: extras.candidateRange } : {}),
...(!retired && !scenario && extras.candidateRange ? { candidate_range: extras.candidateRange } : {}),
birthplace_label: accountText(row, "birth_place_label") ?? undefined,
coordinate_source: "user_reported",
coordinate_precision: "unverified_user_coordinates",
@@ -19,6 +19,7 @@ import { parseReportCandidateRange, type ReportCandidateClockRange } from "./rep
import { effectiveBirthDate } from "./effective-birth-date";
import { asRecord as record, finiteNumberOrNull as finiteNumber } from "@/lib/guards";
import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario";
import {
personalReportCreateRequestSchema,
type PersonalReportCreateRequest,
@@ -255,7 +256,9 @@ export function resolveReportBirthTimeSensitivityInput(
representativeTime: string,
candidateRange: ReportCandidateClockRange | null,
): Partial<ConsultationInput> {
void profileValue;
if (isSelfSelectedScenario(record(profileValue)?.active_birth_provenance)) {
return { birth_time_accuracy: "provisional", representative_time: representativeTime };
}
if (birthTimeStatus === "confirmed") {
return { birth_time_accuracy: "confirmed", representative_time: representativeTime };
}
@@ -907,6 +907,8 @@ function mergeConsultationEvidencePackets(
...(audit !== undefined ? { technique_audit_table: audit } : {}),
...(varga !== undefined ? { varga_spectrum: varga } : {}),
...(western !== undefined ? { western_spectrum: western } : {}),
chart_choice_both_versions: contracts.find((contract) => contract.chart_choice_both_versions)?.chart_choice_both_versions,
chart_choice_scenarios: contracts.find((contract) => contract.chart_choice_scenarios)?.chart_choice_scenarios,
must_use_layers: unionStringList(contracts.map((contract) => contract.must_use_layers)),
},
claim_cards: options.claimCards,
+25 -3
View File
@@ -10,7 +10,19 @@ import {
} from "../lib/calculation-modes.ts";
import { applyUnreliableVargasToWorkflowContext } from "../lib/consultation-birth-time-mode.ts";
import { recordOrEmpty as record } from "@/lib/guards";
import { applyBothVersionsToWorkflowContext, CHART_CHOICE_OTHER_AT, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts";
import { applyBothVersionsToWorkflowContext, CHART_CHOICE_OTHER_AT, chartChoiceScenariosSchema, compareChartChoiceScenarios, loadOtherVersionCharts } from "../lib/chart-choice-both-versions.ts";
import type { ScenarioSelection } from "../lib/chart-choice/self-selected-scenario.ts";
export function selfSelectedScenarioOpening(selection: ScenarioSelection | undefined, followUp: boolean, question: string): string {
if (!selection) return "";
if (followUp && !/出生(?:时间|时刻|钟点)|生时|时辰|几点出生|birth\s+time/i.test(question)) {
return " 已经说明过所用情景,本轮直接回答,不重复说明。";
}
const opening = selection === "unsure"
? "你没有选定线前还是线后,受影响的地方我会把几种情况分开说。"
: `这次按你自己选的${selection === "before" ? "线前" : "线后"}情景来看,不是出生时间已核实;你填的时间和范围都还保留着。`;
return ` 回答开头原样写一次:「${opening}」其余正文根据已计算的情景回答,不加重复的自选提示。`;
}
export const consultationInputSchema = z.object({
year: z.number().int().min(1900).max(2100),
@@ -18,6 +30,7 @@ export const consultationInputSchema = z.object({
day: z.number().int().min(1).max(31),
hour: z.number().int().min(0).max(23),
minute: z.number().int().min(0).max(59),
second: z.number().int().min(0).max(59).optional(),
lat: z.number().min(-90).max(90),
lon: z.number().min(-180).max(180),
tz: z.number().min(-12).max(14),
@@ -43,6 +56,7 @@ export const consultationInputSchema = z.object({
unreliable_vargas: z.array(z.enum(["D1", "D9", "D10"])).min(1).optional(),
// 生时纠正「两版都读」(产品 2026-11-07)。Server-owned, never sent to the
// consultation workflow; only the other side's charts are fetched for it.
chart_choice_scenarios: chartChoiceScenariosSchema.optional(),
chart_choice_both_versions: z.object({
chosen_side: z.enum(["before", "after"]),
other_at: z.string().regex(CHART_CHOICE_OTHER_AT),
@@ -173,7 +187,7 @@ export async function runConsultationWorkflow(
) {
const {
entryMode, question, theme, unreliable_vargas: unreliableVargas,
chart_choice_both_versions: bothVersions, ...workflowInput
chart_choice_both_versions: bothVersions, chart_choice_scenarios: scenarios, ...workflowInput
} = input;
const plan = options?.plan ?? createConsultationPlan({ userIntent: question, theme });
const workflowRequest = projectConsultationWorkflowRequest(question, theme, plan);
@@ -227,7 +241,10 @@ export async function runConsultationWorkflow(
"Jyotish API returned an incomplete consultation contract",
);
}
const context = applyUnreliableVargasToWorkflowContext(attachMinuteSensitiveThemes(parsed.data), unreliableVargas);
const base = applyUnreliableVargasToWorkflowContext(attachMinuteSensitiveThemes(parsed.data), unreliableVargas);
const context = scenarios ? {
...base, consumer_context: { ...base.consumer_context, chart_choice_scenarios: compareChartChoiceScenarios(scenarios) },
} : base;
if (!bothVersions) return context;
const block = await loadOtherVersionCharts(
{ lat: input.lat, lon: input.lon, tz: input.tz, ayanamsa: input.ayanamsa, city: input.city, node_mode: input.node_mode, position_mode: input.position_mode },
@@ -316,6 +333,7 @@ export const consultationEvidencePacketSchema = z.object({
western_spectrum: modelOutputEvidenceSchema.optional(),
must_use_layers: modelOutputEvidenceSchema.optional(),
chart_choice_both_versions: modelOutputEvidenceSchema.optional(),
chart_choice_scenarios: modelOutputEvidenceSchema.optional(),
}),
claim_cards: z.array(z.object({
category: z.enum(consultationEvidenceCategoryValues),
@@ -878,6 +896,9 @@ function projectEvidenceContract(
...(contract.chart_choice_both_versions && typeof contract.chart_choice_both_versions === "object"
? { chart_choice_both_versions: contract.chart_choice_both_versions as ModelOutputValue }
: {}),
...(contract.chart_choice_scenarios && typeof contract.chart_choice_scenarios === "object"
? { chart_choice_scenarios: contract.chart_choice_scenarios as ModelOutputValue }
: {}),
};
}
@@ -974,6 +995,7 @@ export function toAgentConsultationContext(data: JsonRecord) {
varga_spectrum: consumerContext.varga_spectrum,
western_spectrum: consumerContext.western_spectrum,
chart_choice_both_versions: consumerContext.chart_choice_both_versions,
chart_choice_scenarios: consumerContext.chart_choice_scenarios,
},
chart: {
birth: chart.birth, ascendant: chart.ascendant, planets: chart.planets, houses: chart.houses,
@@ -0,0 +1,94 @@
-- BUG-1958: compare the preview against the same row that receives the save.
-- Existing adoption RPCs and stored records remain compatible.
begin;
create or replace function public.chart_choice_scenario_state_v1(
p_user_id uuid, p_chart_profile_id uuid
)
returns jsonb
language sql
stable
security definer
set search_path = ''
as $$
with subject as (
select to_jsonb(p) as doc
from public.profiles p where p_chart_profile_id is null and p.id = p_user_id
union all
select to_jsonb(p) from public.chart_profiles p
where p.id = p_chart_profile_id and p.user_id = p_user_id and p.role = 'other'
), declaration as (
select jsonb_object_agg(field, coalesce(doc->field, 'null'::jsonb)) as value
from subject
cross join unnest(array[
'birth_date', 'reported_birth_time', 'birth_time_source', 'birth_time_period',
'declared_window_start', 'declared_window_end', 'uncertainty_before_minutes',
'uncertainty_after_minutes', 'birth_time_uncertainty_known', 'birth_time_clue', 'birth_time_record_kind',
'birth_time_shichen', 'latitude', 'longitude', 'timezone_offset', 'timezone_id',
'ayanamsa', 'country_code', 'province_code', 'city_code', 'district_code'
]) as fields(field)
)
select jsonb_build_object(
'current_record_id', case when doc->>'birth_time_status' in ('accepted','confirmed')
then doc#>>'{active_birth_provenance,record_id}' end,
'declaration_fingerprint', encode(sha256(convert_to(declaration.value::text, 'UTF8')), 'hex')
)
from subject cross join declaration;
$$;
create or replace function public.chart_choice_adopt_scenario_v1(
p_user_id uuid, p_chart_profile_id uuid, p_base_record_id uuid,
p_declaration_fingerprint text, p_time time without time zone, p_date date,
p_offset double precision, p_provenance jsonb, p_detail jsonb
)
returns jsonb
language plpgsql
security definer
set search_path = ''
as $$
declare
v_state jsonb;
v_revision bigint;
begin
if p_chart_profile_id is null then
perform 1 from public.profiles where id = p_user_id for update;
else
perform 1 from public.chart_profiles
where id = p_chart_profile_id and user_id = p_user_id and role = 'other' for update;
end if;
if not found then
raise exception 'chart_choice_subject_not_found' using errcode = 'P0001';
end if;
v_state := public.chart_choice_scenario_state_v1(p_user_id, p_chart_profile_id);
if p_base_record_id::text is distinct from v_state->>'current_record_id'
or p_declaration_fingerprint is distinct from v_state->>'declaration_fingerprint' then
raise exception 'chart_choice_stale_choice' using errcode = 'P0001';
end if;
if p_provenance->>'selection_kind' is distinct from 'self_selected_scenario'
or p_provenance->>'basis' is distinct from 'self_choice_20261116' then
raise exception 'chart_choice_invalid_input' using errcode = 'P0001';
end if;
select count(*) + 1 into v_revision
from public.chart_choice_records r
where r.user_id = p_user_id and r.chart_profile_id is not distinct from p_chart_profile_id
and (r.detail#>>'{provenance,basis}' = 'self_choice_20261116'
or r.detail#>>'{provenance,selection_kind}' = 'self_selected_scenario');
return public.chart_choice_adopt_v4(
p_user_id, p_chart_profile_id, p_time, p_date, p_offset,
p_provenance || jsonb_build_object('choice_revision', v_revision),
null, null, null, null, p_detail
);
end;
$$;
revoke all on function public.chart_choice_scenario_state_v1(uuid, uuid) from public, anon, authenticated;
grant execute on function public.chart_choice_scenario_state_v1(uuid, uuid) to service_role;
revoke all on function public.chart_choice_adopt_scenario_v1(uuid, uuid, uuid, text, time without time zone, date,
double precision, jsonb, jsonb) from public, anon, authenticated;
grant execute on function public.chart_choice_adopt_scenario_v1(uuid, uuid, uuid, text, time without time zone, date,
double precision, jsonb, jsonb) to service_role;
commit;
+1
View File
@@ -30,6 +30,7 @@ test("account API reads and returns the server-configured rectification price",
test("account API separates engine confirmation from an accepted usable chart time", () => {
assert.match(source, /hasConfirmedBirthTime:\s*profile\.birth_time_status === "confirmed"/);
assert.match(source, /hasConfirmedBirthTime:\s*profile\.birth_time_status === "confirmed"\s*&& !isSelfSelectedScenario\(profile\.active_birth_provenance\)/);
assert.match(source, /hasUsableBirthTime:\s*\(profile\.birth_time_status === "accepted" \|\| profile\.birth_time_status === "confirmed"\)/);
});
@@ -25,15 +25,15 @@ test("self-choice result describes the six charts from real transitions and only
const render = (packet: Complete) => renderToStaticMarkup(<FinalStep packet={packet} decision={packet.decision}
pending={false} defaultOnly onAccept={() => {}} onSelfChoice={() => {}} />);
const reported = render(fixtures.reported);
assert.match(reported, /不受影响:主盘。/);
assert.match(reported, /差几分钟就不同:婚恋、事业、钱财、日常、突变。/);
assert.match(reported, /04:59:43 之前巨蟹上升,之后狮子上升等 5 处/);
assert.match(reported, /上升星座不变:主盘。/);
assert.match(reported, /上升星座会变:婚恋、事业、钱财、日常、突变。/);
assert.match(reported, /<summary>04:59:43 之前巨蟹上升,之后狮子上升等 5 处<\/summary>/);
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.match(stable, /这个时间范围内,六张盘的上升星座都不变。/);
assert.doesNotMatch(stable, /自己选线前线后/);
const midnight = render(fixtures.midnight);
assert.match(midnight, /你填的 00:00 离 8月8日 23:59:35 这条线只有 25 秒。/);
@@ -77,14 +77,17 @@ test("self-choice page selects each line once, stops or keeps narrowing, and off
};
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") {
assert.deepEqual(Object.keys(body).sort(), ["choices", "mode", "selfChoice", "subjectId"]);
const next = [fixtures.first, ...scenario.previews][calls++];
assert.deepEqual(body.choices, next.decision.choices);
return Response.json(next);
return Response.json({ ...next, current_record_id: current?.id ?? null, declaration_fingerprint: "a".repeat(64) });
}
assert.equal(body.mode, "choice");
assert.deepEqual(Object.keys(body).sort(), ["baseRecordId", "choices", "declarationFingerprint", "mode", "selfChoice", "subjectId"]);
assert.equal(body.baseRecordId, null);
assert.equal(body.declarationFingerprint, "a".repeat(64));
const decision = scenario.end.decision;
assert.deepEqual(body.choices, decision.choices);
current = {
@@ -162,22 +165,35 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica
};
const writes = [];
const records = [];
let fingerprint = "a".repeat(64);
const admin = { rpc: async (name, args) => {
const current = row.active_birth_provenance?.record_id ?? null;
if (name === "chart_choice_records_v1") {
return { data: { current_record_id: recordId, records }, error: null };
return { data: { current_record_id: current, records }, error: null };
}
if (name === "chart_choice_scenario_state_v1") {
return { data: { current_record_id: current, declaration_fingerprint: fingerprint }, 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);
if (name === "chart_choice_adopt_scenario_v1") {
assert.equal(args.p_base_record_id, current);
assert.equal(args.p_declaration_fingerprint, fingerprint);
assert.equal(args.p_window_start, undefined);
args.p_provenance.choice_revision = 1 + writes.filter((write) => write.p_provenance.selection_kind).length;
} else {
assert.equal(name, "chart_choice_adopt_v4");
for (const key of ["p_window_start", "p_window_end", "p_before_minutes", "p_after_minutes"]) {
assert.equal(args[key], null);
}
}
const savedId = recordId.slice(0, -1) + String(writes.length + 1);
writes.push(args);
row.active_birth_provenance = { ...args.p_provenance, record_id: recordId };
row.active_birth_provenance = { ...args.p_provenance, record_id: savedId };
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 };
records.unshift({ id: savedId, reusable: true, detail: { ...args.p_detail, provenance: args.p_provenance } });
return { data: { record_id: savedId }, error: null };
} };
mock.module("server-only", { namedExports: {} });
mock.module("@/lib/supabase/server", { namedExports: { createServerSupabaseClient: async () => supabase } });
@@ -185,7 +201,7 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica
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 { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance } = await import("./src/lib/chart-choice-both-versions.ts");
const engine = [];
globalThis.fetch = async (url, init) => {
const body = JSON.parse(init.body);
@@ -211,16 +227,39 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica
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);
assert.deepEqual(await preview.json(), { ...first, current_record_id: null, declaration_fingerprint: fingerprint });
assert.equal((await post({ selfChoice: true, choices: [] })).status, 400);
const narrow = { start_at: reported.reported_at, end_at: reported.window.end_at };
const binding = async () => {
const response = await post({ selfChoice: true, mode: "preview", choices: [] });
assert.equal(response.status, 200);
const data = await response.json();
return { baseRecordId: data.current_record_id, declarationFingerprint: data.declaration_fingerprint };
};
const initial = await binding();
for (let repeat = 0; repeat < 2; repeat++) {
const response = await post({ selfChoice: true, choices: finished.decision.choices, window: narrow });
const response = await post({ selfChoice: true, choices: finished.decision.choices, window: narrow, ...await binding() });
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 replay = await post({ selfChoice: true, choices: finished.decision.choices, ...initial });
assert.equal(replay.status, 409);
assert.equal((await replay.json()).code, "stale_choice");
const beforeEdit = await binding();
fingerprint = "b".repeat(64);
const changed = await post({ selfChoice: true, choices: finished.decision.choices, ...beforeEdit });
assert.equal(changed.status, 409);
assert.equal((await changed.json()).code, "stale_choice");
assert.equal(writes.length, 1);
const saved = row.active_birth_provenance;
assert.equal(saved.selection_kind, "self_selected_scenario");
assert.equal(saved.choice_revision, 1);
assert.deepEqual(saved.declared_window, reported.window);
assert.deepEqual(saved.scenario_segment, saved.segment);
assert.deepEqual(saved.remaining_lines, finished.decision.remaining_lines);
assert.deepEqual(saved.scenarios, finished.decision.scenarios);
assert.equal(saved.source, "user_choice");
assert.equal(saved.rule, "user_override");
assert.equal(saved.declared_by_user, true);
@@ -232,15 +271,18 @@ test("self-choice API recomputes from storage, preserves declaration, de-duplica
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 });
const uncertain = await post({ selfChoice: true, choices: unsure.decision.choices, ...await binding() });
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(chartChoiceBothVersionsFromProvenance(row.active_birth_provenance), null);
const scenarios = chartChoiceScenariosFromProvenance(row.active_birth_provenance);
assert.equal(scenarios.alternatives.length, 3);
assert.ok(scenarios.omitted > 0);
assert.equal(row.active_birth_time, declared.reported_birth_time + ":00");
assert.ok(both.other_at < first.next.at);
assert.equal(row.active_birth_provenance.choice_revision, 2);
assert.equal(row.active_birth_provenance.other_saved_at, null);
assert.equal(row.active_birth_provenance.chosen_side, "none");
const restored = await post({ mode: "restore_default", recordId });
const restored = await post({ mode: "restore_default", recordId: row.active_birth_provenance.record_id });
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");
@@ -0,0 +1,181 @@
import "./install-test-document";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { ChartChoiceFlow, FinalStep, SelfChoiceStep } from "../src/components/chart-choice/chart-choice-page";
import { SELF_CHOICE_BASIS, type ChartChoiceEnginePacket, type SelfChoicePreview } from "../src/lib/chart-choice/contract";
import { isSelfSelectedScenario } from "../src/lib/chart-choice/self-selected-scenario";
import { chartChoiceBothVersionsFromProvenance, chartChoiceScenariosFromProvenance, compareChartChoiceScenarios } from "../src/lib/chart-choice-both-versions";
import { libraryProfileFromSubjectRow } from "../src/lib/chart-subject-write";
import { readProfile, profileBirthTimeStatusLabel } from "../src/lib/home-profile";
import { peopleTimeRectified } from "../src/lib/people-archive-view";
import { buildLongformBirthPayload } from "../src/lib/personal-report-longform-birth";
import { marriageMatchBirthBody } from "../src/lib/marriage-match-service";
import { resolveReportBirthTimeSensitivityInput } from "../src/lib/personal-report-route-core";
import { prepareConsultationRoute } from "../src/lib/consultation-route-service";
import { selfSelectedScenarioOpening } from "../src/mastra/consultation-workflow";
import { createClientLifecycleHarness } from "./react-client-lifecycle-test-support";
Object.assign(globalThis, { React });
type Complete = Extract<ChartChoiceEnginePacket, { status: "complete" }>;
const fixture = JSON.parse(readFileSync(new URL("./fixtures/chart-choice-self-choice-20261116.json", import.meta.url), "utf8")) as {
reported: Complete; stable: Complete; first: SelfChoicePreview; unsure: SelfChoicePreview; finished: SelfChoicePreview; three: SelfChoicePreview;
};
const AGE = { today: "2042-02-03", targetYear: 2042, candidateRange: null, birthTimeAccuracy: "confirmed" as const };
const basis = { source: "user_choice", basis: SELF_CHOICE_BASIS, declared_by_user: true };
const row = {
name: "Fictional Scenario", birth_date: "1997-08-08", reported_birth_time: "05:00:00", active_birth_time: "05:00:17",
active_birth_date: "1997-08-08", active_birth_timezone_offset: 8, birth_time_source: "approximate", birth_time_status: "accepted",
latitude: 36.42, longitude: 114.21, timezone_offset: 8, timezone_id: "Asia/Shanghai", birth_place_label: "虚构市",
rectification_case_id: "synthetic-case", ayanamsa: "lahiri",
};
test("self-selected scenario results disclose the full list of checked ascendant transitions", () => {
const render = (packet: Complete) => renderToStaticMarkup(<FinalStep packet={packet} decision={packet.decision}
defaultOnly pending={false} onAccept={() => {}} onSelfChoice={() => {}} />);
const result = render(fixture.reported);
assert.match(result, /上升星座不变:主盘。/);
assert.match(result, /上升星座会变:婚恋、事业、钱财、日常、突变。/);
assert.match(render(fixture.stable), /这个时间范围内,六张盘的上升星座都不变。/);
const summary = fixture.reported.decision.reported_choice!.line_summary!;
assert.match(result, new RegExp(`共有 ${summary.line_count} 处换座。`));
const lists = [...result.matchAll(/<details><summary>[^<]+等 (\d+) 处<\/summary><ul>(.*?)<\/ul><\/details>/g)];
const expected = Object.values(summary.charts).filter((row) => (row.lines?.length ?? 0) > 1);
assert.ok(expected.length >= 2);
assert.equal(lists.length, expected.length);
for (const [, count, list] of lists) {
const rows = [...list.matchAll(/<li>([^<]+)<\/li>/g)];
assert.equal(rows.length, Number(count));
assert.ok(rows.every(([, text]) => /\d{2}:\d{2}:\d{2} 之前.+上升,之后.+上升/.test(text)));
}
});
test("self-selected scenario UI keeps fixed option order and explains the unverified choice once", () => {
const render = (preview: SelfChoicePreview) => renderToStaticMarkup(<SelfChoiceStep preview={preview}
reference={fixture.reported.reported_at} pending={false} onBack={() => {}} onPick={() => {}}
onStop={() => {}} onAccept={() => {}} />);
const choosing = render(fixture.first);
const confirmation = render(fixture.unsure);
const group = choosing.match(/<div[^>]*role="group"[^>]*>(.*?)<\/div>/)?.[1] ?? "";
assert.deepEqual(Array.from(group.matchAll(/<button[^>]*>([^<]*)<\/button>/g), ([, label]) => label),
["线前", "线后", "不确定"]);
assert.match(confirmation, new RegExp(`还有 ${fixture.unsure.decision.remaining_lines?.length} 条线没选。`));
const approved = "这不是出生时间已核实,你填的时间和范围都还保留着。";
assert.equal(confirmation.split(approved).length, 2);
assert.doesNotMatch(choosing + confirmation.replace(approved, ""), /可以直接用|不受影响|推荐|打分|更符合|已核实|已确认|已校正/);
});
test("stale self-choice save reloads the current start and returns to a fresh result", async () => {
const h = createClientLifecycleHarness();
const previous = globalThis.fetch;
const fp = "d".repeat(64);
let starts = 0;
let packets = 0;
let saves = 0;
globalThis.fetch = async (url, init) => {
const path = String(url);
if (path.startsWith("/api/chart-choice?")) {
starts++;
return Response.json({
status: "ready", subjectId: "self", name: row.name, window: fixture.reported.window,
reportedAt: fixture.reported.reported_at, precision: "minutes", rangeAdjustable: false,
history: { current_record_id: null, records: [] },
});
}
if (path === "/api/chart-choice/packet") {
packets++;
return Response.json(fixture.reported);
}
assert.equal(path, "/api/chart-choice/adopt");
const body = JSON.parse(String(init?.body));
if (body.mode === "preview") return Response.json({ ...(body.choices.length ? fixture.unsure : fixture.first),
current_record_id: null, declaration_fingerprint: fp });
assert.equal(body.baseRecordId, null);
assert.equal(body.declarationFingerprint, fp);
saves++;
return Response.json({ code: "stale_choice", error: "出生资料改过了,这次的结果不能再用。" }, { status: 409 });
};
const click = async (text: string) => {
const find = () => h.elements().find((item) => item.tagName === "BUTTON" && item.text === text);
for (let i = 0; i < 10 && !find(); i++) await h.idle();
const target = find();
assert.ok(target, text);
await h.event(target);
};
try {
await h.render(<ChartChoiceFlow subjectId="self" />);
await click("自己选线前线后");
await click("不确定");
await click("用 " + fixture.unsure.decision.saved_at.slice(11));
for (let i = 0; i < 10 && packets < 2; i++) await h.idle();
assert.equal(starts, 2);
assert.equal(packets, 2);
assert.equal(saves, 1);
assert.ok(h.elements().some((item) => item.text === "出生资料改过了,这次的结果不能再用。"));
assert.ok(h.elements().some((item) => item.text === "自己选线前线后"));
assert.equal(h.errors.length, 0);
} finally {
globalThis.fetch = previous;
await h.close();
}
});
test("new and historical self-selected scenarios remain usable without a confirmed badge or report input", () => {
assert.equal(isSelfSelectedScenario(basis), true);
assert.equal(isSelfSelectedScenario({ selection_kind: "self_selected_scenario" }), true);
assert.equal(isSelfSelectedScenario({ source: "reported_time_default" }), false);
const point = "1997-08-08T05:00:17";
const provenance = { ...basis, contract: "chart-choice-v2", segment: { start_at: point, end_at: point } };
const stored = { ...row, active_birth_provenance: provenance };
const profile = readProfile(stored);
assert.equal(profile.time, "05:00");
assert.equal(profileBirthTimeStatusLabel(profile), "用户自选情景");
assert.equal(peopleTimeRectified(profile), false);
assert.equal(peopleTimeRectified(readProfile(row)), true);
assert.equal(libraryProfileFromSubjectRow(stored).selfSelectedScenario, true);
assert.equal(buildLongformBirthPayload(stored, AGE)?.reading_minute_confirmed, false);
assert.equal(buildLongformBirthPayload(stored, AGE)?.birth_time_accuracy, "provisional");
assert.equal(marriageMatchBirthBody(stored, AGE.today).reading_minute_confirmed, undefined);
assert.equal(resolveReportBirthTimeSensitivityInput(stored, "accepted", "05:00", {
startTime: "05:00", endTime: "05:00",
}).birth_time_accuracy, "provisional");
});
test("chat uses the saved scenario with one opening and computed alternatives only", async () => {
const legacy = { ...basis, choices: [{ side: "before" }] };
const { scenarios, scenarios_omitted } = fixture.unsure.decision;
assert.ok(scenarios && scenarios.length >= 3 && scenarios_omitted);
const provenance = { ...basis, choices: [{ side: "unsure" }], scenarios, scenarios_omitted };
assert.equal(chartChoiceBothVersionsFromProvenance(provenance), null);
const comparison = chartChoiceScenariosFromProvenance(provenance)!;
const block = compareChartChoiceScenarios(comparison);
assert.deepEqual(block.other_scenarios.map((item) => item.saved_at),
scenarios.filter((item) => !item.is_primary).map((item) => item.saved_at));
assert.match(block.notice, new RegExp(`另有 ${scenarios_omitted} 种情景没有算`));
const three = chartChoiceScenariosFromProvenance({ ...basis, scenarios: fixture.three.decision.scenarios })!;
assert.equal(compareChartChoiceScenarios(three).other_scenarios.length, 2);
assert.equal(compareChartChoiceScenarios(three).scenarios_omitted, 0);
const adjacent = chartChoiceScenariosFromProvenance({
...basis, scenarios: fixture.finished.decision.scenarios, comparison_scenario: fixture.finished.decision.comparison_scenario,
})!;
assert.ok(compareChartChoiceScenarios(adjacent).opposite_side?.ascendant_changes.length);
const prepared = await prepareConsultationRoute({
userId: "synthetic-owner", mode: "verified_chart", loadProfile: async () => ({ ...row, active_birth_provenance: provenance }),
resolveTimezoneOffset: async (value) => value,
loadCandidateRange: async () => { throw new Error("Unrelated candidate range should not be read"); },
reserve: async () => true,
});
assert.equal(prepared.serverChart?.selfSelectedScenario, "unsure");
assert.equal(prepared.serverChart?.toolInput.birth_time_accuracy, "provisional");
assert.equal(prepared.serverChart?.toolInput.time_source, "self_selected_scenario");
assert.equal(prepared.serverChart?.toolInput.second, 17);
assert.ok(prepared.serverChart?.toolInput.chart_choice_scenarios);
assert.match(selfSelectedScenarioOpening("unsure", false, "事业"), /你没有选定线前还是线后/);
assert.match(selfSelectedScenarioOpening("before", false, "事业"), /自己选的线前情景/);
assert.doesNotMatch(selfSelectedScenarioOpening("after", true, "事业"), /出生时间已核实/);
assert.match(selfSelectedScenarioOpening("after", true, "出生时间是哪一天?"), /自己选的线后情景/);
assert.equal(selfSelectedScenarioOpening(undefined, false, "事业"), "");
assert.equal(isSelfSelectedScenario(legacy), true);
});
@@ -0,0 +1,112 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import test from "node:test";
import { fileURLToPath } from "node:url";
import { Client } from "pg";
import { runMigrations } from "../scripts/db-migrate.mjs";
import { startPostgresFixture } from "./helpers/postgres-fixture.ts";
const docker = spawnSync("docker", ["version"], { stdio: "ignore" }).status === 0;
const migrationDirs = ["../db/migrations", "../supabase/migrations"].map(
(dir) => fileURLToPath(new URL(dir, import.meta.url)),
);
const provenance = {
selection_kind: "self_selected_scenario",
basis: "self_choice_20261116",
source: "user_choice",
rule: "user_override",
declared_by_user: true,
chosen_side: "before",
contract: "chart-choice-v2",
segment: { start_at: "2041-02-03T09:00", end_at: "2041-02-03T09:05" },
rounds: [],
undetermined_charts: [],
events: [],
};
type State = { current_record_id: string | null; declaration_fingerprint: string };
test("BUG-1958 compares preview and allocates scenario revisions under the same PostgreSQL lock", {
skip: !docker && "docker unavailable",
}, async () => {
const fixture = startPostgresFixture();
const migrationUrl = fixture.connectionUrl("schema_owner", "schema-owner-test-password");
const owner = randomUUID();
const otherOwner = randomUUID();
const person = randomUUID();
const editor = new Client({ connectionString: migrationUrl });
const first = new Client({ connectionString: fixture.connectionUrl("service_runtime", "service-runtime-test-password") });
const second = new Client({ connectionString: fixture.connectionUrl("service_runtime", "service-runtime-test-password") });
const ordinary = new Client({ connectionString: fixture.connectionUrl("app_runtime", "app-runtime-test-password") });
try {
assert.equal(await runMigrations({ connectionString: migrationUrl, migrationsDirectory: undefined, migrationsDirectories: migrationDirs }), 0);
await Promise.all([editor.connect(), first.connect(), second.connect(), ordinary.connect()]);
for (const id of [owner, otherOwner]) {
fixture.psqlAs("identity_runtime", "identity-runtime-test-password",
"insert into identity.users(id,name,email,email_verified) values ('" + id
+ "','Fictional Scenario','" + id + "@example.invalid',true)");
}
await editor.query(
"update public.profiles set birth_date='2041-02-03', reported_birth_time='09:00', "
+ "birth_time_source='approximate', birth_time_status='reported', declared_window_start='08:45', declared_window_end='09:15' where id=$1", [owner],
);
await editor.query(
"insert into public.chart_profiles (id,user_id,role,name,profile,birth_date,reported_birth_time,birth_time_source,birth_time_status) "
+ "values ($1,$2,'other','Fictional Scenario','{}','2041-02-03','09:00','approximate','reported')", [person, owner],
);
await Promise.all([first.query("set role service_role"), second.query("set role service_role"), ordinary.query("set role authenticated")]);
async function state(client: Client, user = owner, subject: string | null = null) {
const result = await client.query<{ value: State | null }>(
"select public.chart_choice_scenario_state_v1($1,$2) as value", [user, subject],
);
return result.rows[0].value;
}
function save(client: Client, expected: State, subject: string | null = null) {
return client.query<{ value: { record_id: string } }>(
"select public.chart_choice_adopt_scenario_v1($1,$2,$3,$4,'09:02','2041-02-03',0,$5,$6) as value",
[owner, subject, expected.current_record_id, expected.declaration_fingerprint, provenance, {}],
);
}
await assert.rejects(state(ordinary), /permission denied/);
assert.equal(await state(first, otherOwner, person), null);
const preview = (await state(first))!;
assert.equal(preview.current_record_id, null);
assert.match(preview.declaration_fingerprint, /^[a-f0-9]{64}$/);
const concurrent = await Promise.allSettled([save(first, preview), save(second, preview)]);
assert.equal(concurrent.filter((item) => item.status === "fulfilled").length, 1,
concurrent.flatMap((item) => item.status === "rejected" ? [item.reason.message] : []).join(", "));
const loser = concurrent.find((item) => item.status === "rejected");
assert.ok(loser && loser.status === "rejected");
assert.match(loser.reason.message, /chart_choice_stale_choice/);
const afterFirst = (await state(first))!;
const winner = concurrent.find((item) => item.status === "fulfilled");
assert.ok(winner && winner.status === "fulfilled");
assert.equal(afterFirst.current_record_id, winner.value.rows[0].value.record_id);
assert.equal(afterFirst.declaration_fingerprint, preview.declaration_fingerprint);
await assert.rejects(save(first, preview), /chart_choice_stale_choice/);
await save(first, afterFirst);
const saved = (await state(first))!;
const revisions = await editor.query<{ revision: string; kind: string }>(
"select detail#>>'{provenance,choice_revision}' as revision, detail#>>'{provenance,selection_kind}' as kind "
+ "from public.chart_choice_records where user_id=$1 and chart_profile_id is null order by created_at", [owner],
);
assert.deepEqual(revisions.rows, [1, 2].map((revision) => ({ revision: String(revision), kind: provenance.selection_kind })));
await editor.query("update public.profiles set declared_window_start='08:35' where id=$1", [owner]);
assert.notEqual((await state(first))!.declaration_fingerprint, saved.declaration_fingerprint);
await assert.rejects(save(first, saved), /chart_choice_stale_choice/);
assert.equal((await editor.query("select id from public.chart_choice_records where user_id=$1", [owner])).rowCount, 2);
const other = (await state(first, owner, person))!;
await save(first, other, person);
const otherRevision = await editor.query<{ revision: string }>(
"select detail#>>'{provenance,choice_revision}' as revision from public.chart_choice_records where chart_profile_id=$1", [person],
);
assert.equal(otherRevision.rows[0].revision, "1");
} finally {
try {
await Promise.allSettled([editor.end(), first.end(), second.end(), ordinary.end()]);
} finally {
fixture.stop();
}
}
});
File diff suppressed because it is too large Load Diff
+69 -19
View File
@@ -162,14 +162,18 @@ def _line_view(line: Line, order: tuple[str, ...]) -> dict:
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:
ordered = sorted((line for line in lines if line.flips.keys() & set(KEY_CHARTS)), key=lambda line: line.at)
nearest = min(ordered, key=lambda line: (abs(line.at - reference), line.at), default=None)
chart_lines: dict[str, list[dict]] = {}
for line in ordered:
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}
chart_lines.setdefault(chart, []).append({"at": view["at"], **signs})
charts: dict[str, dict] = {}
for chart, flips in chart_lines.items():
closest = min(flips, key=lambda flip: abs(_input_line(flip["at"]) - reference))
charts[chart] = {**closest, "count": len(flips), "lines": flips}
return {"nearest_at": _at_s(nearest.at) if nearest else None, "line_count": len(ordered), "charts": charts}
def _comparisons(req: ChartRequest, before_at: datetime, after_at: datetime, charts: list[str]) -> list[dict]:
@@ -645,6 +649,30 @@ def _self_choice_lines(req: ChartRequest, start: datetime, end: datetime) -> lis
return sorted(by_time.values(), key=lambda line: line.at)
def _self_choice_scenarios(
req: ChartRequest, segment: Segment, lines: list[Line], reported: datetime, original: Segment,
) -> tuple[list[dict], int]:
starts = [segment[0], *(line.at for line in lines)]
ends = [*(line.at - ONE_SECOND for line in lines), segment[1]]
pieces = list(zip(starts, ends))
def distance(index: int) -> tuple[timedelta, int]:
lo, hi = pieces[index]
return max(lo - reported, reported - hi, timedelta()), index
nearest = sorted(range(len(pieces)), key=distance)[:4]
primary = nearest[0]
scenarios = []
for index in sorted(nearest):
piece = pieces[index]
saved = _self_choice_at(piece, reported, original)
scenarios.append({
"segment": _segment(*piece), "saved_at": _saved_at(saved),
"key_charts": _key_chart_rows(req, saved, [], []), "is_primary": index == primary,
})
return scenarios, len(pieces) - len(scenarios)
def _self_choice(
body: dict, req: ChartRequest, segment: Segment, reported: datetime, *, deciding: bool,
) -> dict:
@@ -658,7 +686,7 @@ def _self_choice(
lines = all_lines
next_line = nearest_line(lines, reported)
unsure = None
comparison_segment = 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")
@@ -667,23 +695,45 @@ def _self_choice(
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
next_line = None
else:
opposing = "after" if side == "before" else "before"
lo, hi = _side(segment, next_line, opposing)
opposing_lines = [line.at for line in lines if lo < line.at <= hi]
if opposing_lines:
if opposing == "before":
lo = opposing_lines[-1]
else:
hi = opposing_lines[0] - ONE_SECOND
comparison_segment = (lo, hi)
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, original)
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, original)),
both_versions=[DOMAIN[key]["key"] for key in KEY_CHARTS if key in unsure.flips])
scenarios, omitted = _self_choice_scenarios(req, segment, lines, reported, original)
primary = next(item for item in scenarios if item["is_primary"])
saved = datetime.fromisoformat(primary["saved_at"])
resolved = {
"saved_at": primary["saved_at"], "segment": _segment(*segment), "choices": choices,
"key_charts": _key_chart_rows(req, saved, lines, []), "line_summary": _line_summary(lines, reported),
"remaining_lines": [{"at": _at_s(line.at), "charts": [key for key in KEY_CHARTS if key in line.flips]}
for line in lines],
"scenarios": scenarios, "scenarios_omitted": omitted, "both_versions": [],
}
if comparison_segment:
comparison_at = _self_choice_at(comparison_segment, reported, original)
resolved["comparison_scenario"] = {
"segment": _segment(*comparison_segment), "saved_at": _saved_at(comparison_at),
"key_charts": _key_chart_rows(req, comparison_at, [], []), "is_primary": False,
}
if len(lines) == 1:
line = lines[0]
other = next(item for item in scenarios if not item["is_primary"])
resolved.update(chosen_side="before" if saved < line.at else "after",
other_saved_at=other["saved_at"],
both_versions=[DOMAIN[key]["key"] for key in KEY_CHARTS if key in line.flips])
elif lines:
resolved.update(chosen_side="none", other_saved_at=None)
elif choices:
resolved["chosen_side"] = choices[-1]["side"]
+34 -5
View File
@@ -27,7 +27,7 @@ from scripts.chart_choice.boundaries import ( # noqa: E402
from scripts.chart_choice import adaptive, astrologer, chart_questions, interview # noqa: E402
from scripts.chart_choice.decision import decide, decide_with_evidence, reported_is_neutral # noqa: E402
from scripts.chart_choice.readings import SIGN_CN # noqa: E402
from scripts.chart_choice.service import _self_choice_at, build_packet, decide_packet # noqa: E402
from scripts.chart_choice.service import _self_choice_at, _self_choice_scenarios, build_packet, decide_packet # noqa: E402
# Fictional reference input (not a user record): mid-latitude north China, early morning.
BODY = {
@@ -759,18 +759,47 @@ def test_self_choice_replays_real_lines_without_scoring(monkeypatch):
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"].endswith("04:58")
other_saved = datetime.fromisoformat(unsure["decision"]["other_saved_at"])
assert unsure["decision"]["chosen_side"] == "none"
assert unsure["decision"]["other_saved_at"] is None
assert unsure["decision"]["both_versions"] == []
assert len(unsure["decision"]["scenarios"]) == 4
assert unsure["decision"]["scenarios_omitted"] > 0
primary = next(item for item in unsure["decision"]["scenarios"] if item["is_primary"])
assert primary["saved_at"] == BODY["reported_at"]
alternative = next(item for item in unsure["decision"]["scenarios"]
if item["segment"]["end_at"].endswith("04:59:42"))
other_saved = datetime.fromisoformat(alternative["saved_at"])
assert datetime.fromisoformat(first["at"]) - other_saved >= timedelta(seconds=60)
assert signature(ascendant_longitude(REQ, other_saved), charts) == expected_signs
assert unsure["decision"]["both_versions"] == ["career", "money", "pressure", "change"]
assert len(unsure["decision"]["remaining_lines"]) == initial["decision"]["line_summary"]["line_count"]
assert len(initial["decision"]["line_summary"]["charts"]["D10"]["lines"]) == 5
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")]})
@pytest.mark.parametrize(("line_count", "expected_count", "omitted"), [(0, 1, 0), (1, 2, 0), (2, 3, 0), (5, 4, 2)])
def test_self_choice_partitions_every_remaining_line_and_caps_nearest(line_count, expected_count, omitted):
lo = datetime(1997, 8, 8, 4, 30)
hi = lo + timedelta(minutes=40)
reported = lo + timedelta(minutes=17)
lines = [Line(lo + timedelta(minutes=5 * i, seconds=30), 0, {"D10": (1, 2)})
for i in range(1, line_count + 1)]
scenarios, omitted_count = _self_choice_scenarios(REQ, (lo, hi), lines, reported, (lo, hi))
assert (len(scenarios), omitted_count) == (expected_count, omitted)
assert sum(item["is_primary"] for item in scenarios) == 1
assert next(item["saved_at"] for item in scenarios if item["is_primary"]) == "1997-08-08T04:47"
assert [item["segment"]["start_at"] for item in scenarios] == sorted(item["segment"]["start_at"] for item in scenarios)
for item in scenarios:
start, end, saved = (datetime.fromisoformat(value) for value in
(item["segment"]["start_at"], item["segment"]["end_at"], item["saved_at"]))
assert start <= saved <= end
assert saved == _self_choice_at((start, end), reported, (lo, hi))
assert len(item["key_charts"]) == 6
assert not any(start < line.at <= end for line in lines)
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}