diff --git a/BLOCKED.md b/BLOCKED.md index 487d21b04..b91bfe4c1 100644 --- a/BLOCKED.md +++ b/BLOCKED.md @@ -4,6 +4,10 @@ - Windows Docker Linux 引擎返回 500,容器数据库实测待补。已用同机 staging 测试对照、现有 RPC 契约和合成档案验证替代。预检已核对远端和外部适配器,碎片扫描与定向套件在本机超时。见 [#276 进度](docs/tasks/PROGRESS-synastry-precision-20261114.md)。 +## #275 合盘第 1 批验收环境 + +- Windows Docker Linux 引擎不可用,前端全量用同机无 Docker 基线对照。Windows 的缓存文件权限位断言在基线同样失败。碎片扫描和定向预检超时。详见 [#275 进度](docs/tasks/PROGRESS-synastry-b1-20261114.md)。 + ## #271 年运证据等级验收 - Windows Docker Linux 引擎不可用。开工预检的碎片扫描和定向套件超时。以同机 staging 对照、公开盘真实计算和桩写手回归提供替代证据。真实模型样例由独立验收方生成。见 [#271 进度](docs/tasks/PROGRESS-annual-grade-20261114.md)。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 22f670240..e1b868a33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ - 计算附录显示甲乙各自的误差来源,以及本命上升、九分盘上升、月亮星宿与四分的核对结果。会受影响的技法标明参数敏感。占星 Skill 版本不变(BUG-1889)。 +## 2026-11-14 — 合盘分列计算状态和报告用途 + +- 附录按甲方、乙方和两盘对照分组,列出核验状态。合盘计算缓存按日期区分,旧合盘链接继续打开当前选人页。占星 Skill 版本不变(BUG-1888)。 + ## 2026-11-14 — 年运逐段显示证据等级 - 报告正文和 Markdown 导出按段落、主题和时间点显示证据等级。缺少必需依据时说明哪一项受限。计算依据可查看各结论的等级上限。占星 Skill 版本不变(BUG-1887)。 diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 514869303..50b10c64e 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -25490,6 +25490,18 @@ - 关联记录:#224、#271、BUG-1650、BUG-1651、BUG-1855、BUG-1869。 - 修复版本:`codex/annual-grade-20261114`,待独立验收。 +## BUG-1888 | 合盘把两盘输入齐全标成已执行,日切后可能复用旧计算 + +- 状态:fixed-pending-verify(待独立验收)。 +- 首次发现 / 最近更新:2026-11-14 / 2026-11-14。 +- 现象与触发:打开新合盘的技术依据摘要,无法区分输入齐全、计算成功和在报告中使用。缺少两项核验状态。隔天重复请求时,缓存可返回上一日的数据。离线测试用 UTC 日期表示第二人的出生时刻,Saham 缺失。 +- 根因:附录把回执压成单一状态。缓存键没带计算日期。第二人已和第一人共用本命引擎,UTC 日期无法为该地点构造 Saham 所需的当地日出区间。 +- 修复:按甲方、乙方、两盘对照分组,分列计算状态和用途,附上核验状态。缓存按两人的计算日期区分。原生 Saham 失败原因透传到对应一侧的回执,公开样本按同一时刻的当地时间重放。旧首页打分回调和网页接口退役,旧链接继续跳转到选人页。 +- 验证与防复发:覆盖跨日缓存、Saham 本地计算和阻塞原因、回执表格、旧快照与旧链接。测试详见 [#275 进度](tasks/PROGRESS-synastry-b1-20261114.md)。 +- 首次验收返工:追问按原先的附录文字读取技法,审计改表后只拿到两条核验文案,遗漏技法状态。追问改为从审计行提取计算状态和用途,各组合计最多 12 行。误差敏感项并入同一组表格,旧快照可从已保存的回执恢复误差标记。回归核对三个分组、旧文字及核验文案过滤。 +- 关联记录:#275、BUG-1595、BUG-1679、BUG-1680、BUG-1794。 +- 修复版本:`codex/synastry-b1-20261114`。 + ## BUG-1889 | 合盘未核对两个人各自的出生时间误差 - 状态:fixed-pending-verify(待独立验收)。 diff --git a/docs/tasks/PROGRESS-synastry-b1-20261114.md b/docs/tasks/PROGRESS-synastry-b1-20261114.md new file mode 100644 index 000000000..8f6d6012a --- /dev/null +++ b/docs/tasks/PROGRESS-synastry-b1-20261114.md @@ -0,0 +1,37 @@ +# #275 合盘第 1 批 + +- 从 `origin/staging` 开独立工作树,快进到可信规划评论中的任务书提交 `8dbaf2d3`。按随任务书提交的产品契约 L 节实现。 +- 「技术依据摘要」按甲方、乙方、两盘对照分组。表内分开「计算」和「在本报告中」。两盘输入齐全写「输入已齐」,阻塞或不适用写原因。网上资料核对和真实案例校准两行只在附录。旧报告继续从快照读原有的文字列表。 +- 两人走同一个本命引擎。旧公开复现的第二人以 UTC 表达同一出生时刻,Swiss 日出流程报 `solar_day_window_unavailable`。用该地点当地时间与正确时区表达同一 UTC 时刻,原生模块返回 `partial`,有 Vivah Saham 数据。保留真实失败状态并在个人回执和两人对照中解释原因。这个部分结果继续按参数敏感展示,不抬高就绪状态。 +- 缓存对每人保存计算实际使用的日期,共用缓存版本从 v4 升至 v5。每日重新区分身份键。 +- 用户入口只打开当前合盘选人页。旧 `/?synastry=` 链接也只做重定向,传入的旧打分回调从未被调用。删除 `use-synastry.ts`、Next `/api/synastry` 和首页的旧卡片、历史绑定。保留现用的完整合盘入口、已存报告和 Python 接口。 + +## 断言调整 + +| 原值 | 新值 | 原因 | +| --- | --- | --- | +| 对照就绪等于「已执行」,阻塞只有「无法计算」,核验行隐藏 | 验证「输入已齐」、分组和用途列,阻塞说明原因,附录有两项「未完成」 | 产品契约 L 节按计算与引用分别显示 | +| 公开盘第二人用同一时刻的 UTC 日历表示 | 用相同 UTC 时刻的当地日历表示,核对两份 Saham 原生回执为参数敏感 | 日出区间依赖当地日历,出生物理时刻不变,保留原配对结果断言 | +| 针对旧接口的并发请求、域分流、旧卡和旧历史状态断言 | 移除 `synastry-chart-skip` 和 `chart-library-other-profile` 的三条旧链测试,以及 Python 旧路线编排断言。改查旧链接重定向和当前配对入口 | 任务书明确退役没有用户入口的打分路径 | +| 账户保护、属主取资料、产品开关和 Python 到达测试含旧路线 | 保留账户保护和报告路由断言,合盘检查改指向其现用创建或生成逻辑 | 被删除的路线已不承载用户操作 | +| 旧档案详情断言首页新建自绑定对话、旧报告卡带有人物 ID | 核对档案按钮带所选人物进入当前合盘选人页 | 重定向不新建对话,人物 ID 仍随入口传递 | +| 附录全部文字禁用核验措辞 | 对两条固定文案逐字断言,其余技法、状态、用途和个人及年运报告继续检查禁用词 | 契约 L 节仅为合盘附录开放两行 | + +## 验证 + +- 合盘完整报告与追问定向 29 项通过,新增的四项前端回归通过。Python 定向 83 项通过,Windows 缓存文件权限位检查一项失败。同机基线得到同样的权限位和失败。 +- TypeScript 与生产构建通过,ESLint 0 错误、63 条既有警告。首页为静态路由,首屏 gzip JS 从 517063 降至 514367 字节,CSS 同为 93168 字节。 +- Python、Gitea 远端可见性与引擎适配器预检通过。碎片扫描和定向预检分别在 90 秒、45 秒超时。 +- 同机无 Docker 前端全量均为 3743 项,修复分支 3662 通过、44 失败,基线 3661 通过、45 失败,均为 37 跳过、0 取消。四条退役测试和四条新增测试按名称比对,无新增失败。仅基线有一项答复计时失败。 +- Python 快速门为 1495 项通过、4 项失败、2 项跳过,另有 29 个子测试通过。三项 Kaala / PyJHora 失败与同机同提交基线相同。另有一项咨询 VedAstro 原始结果可用性断言,修复分支与同机基线定向重跑都复现相同差异。完整门禁待独立环境复核。 + +## 首次验收返工 + +- Claude 的退回评论 `44494` 针对 PR #277 的 `62f643425e77befc485d5f94449bab3ae9a6af75`。现以已纳入 #276 的 staging 提交 `79306979513c5da9a5f92a44f1426e968bea91d7` 为基线。 +- 追问材料从甲方、乙方及两盘对照三组提取技法状态和用途,依次从各组取行,最多 12 行。旧报告仍读取历史技法文字,附录核验文案留在附录。 +- 出生时间误差在相关人物或两盘对照的技法行标「参数敏感」「只作观察。出生时间误差内会变」。#276 已保存的快照通过原回执渲染分组。 + +| 原值 | 新值 | 原因 | +| --- | --- | --- | +| #276 断言单独误差表含「甲方 D1/Rashi」,并排除乙方行 | 断言甲方组的对应行及两盘对照标为参数敏感,乙方同技法继续显示原状态,每组仅一张表 | 按验收要求合并审计及误差展示 | +| #275 的公开双盘断言主大运对照输入已齐 | 沿用 #276 的参数敏感及双盘扫描断言,同时保留双方 Saham 有计算结果的断言 | 乙方 D1 在误差内换座,Narayana 起点受影响 | diff --git a/frontend/DESIGN.md b/frontend/DESIGN.md index 1b9a52dda..de4d386fd 100644 --- a/frontend/DESIGN.md +++ b/frontend/DESIGN.md @@ -15,7 +15,7 @@ 代号与中文释义用括号,如「AK(自我)」「D9(婚姻)」。运期层级沿用「›」,Yogini 运名后的主星用括号。Saham 公式以「白天:」或「夜晚:」开头。 -婚恋合盘技术依据的计算参数按甲乙各占一行,写出生时间误差来源和三项扫描结果。受误差影响时,技法执行情况沿用报告数据表的样式,按相关人物或双盘比较显示技法、计算状态和使用口径。 +婚恋合盘技术依据的计算参数按甲乙各占一行,写出生时间误差来源和三项扫描结果。误差影响在甲方、乙方及两盘对照各组的原技法行内显示。计算列写「参数敏感」,用途列写「只作观察。出生时间误差内会变」。 ### Palette @@ -1402,6 +1402,8 @@ Yogini 还在取时,右栏用和 Chara 相同的轨道等待(`OrbitWaiting` ## 婚恋合盘报告(2026-10-19) +- **技法执行情况(#275,BUG-1888):** 「技术依据摘要」内沿用年运的横向可拖动表格,分列方法、计算和在本报告中。按甲方、乙方、两盘对照分组,表后列网上资料核对和真实案例校准。旧报告仍可打开原附录。 + 选人页不重复标题和副标题,页名在顶栏(2026-10-25)。两个人的选择框左右并排,中间一个叉;窄屏改成上下排,叉仍在正中。各自是下拉,最多二十人。资料不全的人不能选;已经在另一边的人不能再选。下面是「新增星盘」,点开一张卡片:称呼、性别(男 / 女)、出生日期、出生时间、出生地,右下角「取消」和「保存并选中」。满二十人时这一行换成去星盘档案删人。「开始合盘」在桌面和手机上都居中,按钮上不写价格。点了先问「会用掉 N 点,余额 M 点。」,按钮是「取消 / 开始」。余额不够时说「需要 N 点,余额只有 M 点。」,主按钮换成「去补点数」。N 从计价表读,M 从账户读。计价读不到时不弹确认,只说「计费配置不可用」。进页面不等开关请求(2026-11-03,BUG-1529):开 / 关来自外壳读到的账户,账户没到时按产品注册表默认值(开)直接画出选人区;账户的 `compatibility` 为 false 才写「合盘服务暂未开放」、不画选人区,账户读失败写「合盘服务暂时连不上,请稍后再试」。人物来自外壳的人物列表,余额来自外壳的账户,页面自己不再读这两样。价格和之前的合盘在页面挂上时同一轮去读,各自到了各自填上;价格没到之前「开始合盘」不可点。这两人已经有写好的合盘、且没有一份正在生成时,按钮下面再写已经合过几次、再生成会另扣多少点。之前的合盘只列人名和日期。生成中是轨道和四步(算两张完整命盘、整理两人之间的证据、写报告、检查报告),句子是「正在写 甲 × 乙 的合盘报告…」。报告页回到「婚恋合盘」,标题下是日期和「已保存,再次打开不扣点」,语言是「中文 / English」。选中的那一个边框是 `--color-action-strong`、文字是 `--color-action`,背景仍是画布色,认 `[data-active]` 或 `[aria-selected="true"]`,不铺 `--color-action-soft`。第一次打开时两个头像仍从两侧靠拢;减少动态效果时只淡入。九节编号,分析逻辑默认收起。英文报告同样收起分析逻辑(Analysis,依据行是 Chart 和 So),时间线每段标题写出起止年月;第一段从本月起时,起点写「现在」或 Now。英文准备时同一套轨道,写「正在写英文版…」,揭幕后整份替换。报告末尾「对哪一段想再问清楚?」,下面是八枚胶囊(`.synastry-report-ask`),不含共同练习。点一枚只新建对话并预填问题,不自动发送。对话里人物选择器锁住,显示「甲 × 乙」。合盘删除后输入框占位是「这份合盘已删除」,发送停用。报告在整宽的外层滚动,两侧空白也能滚;中间一栏只负责居中排版。合盘报告单独走 `/synastry/报告`。开始合盘、之前的合盘和报告中心的合盘卡片都进这个地址,侧栏仍亮「婚恋合盘」。旧的 `/reports/报告` 会换成新地址,并保留语言。 ## 年运报告与开始遮罩(2026-11-01,issue #153 / #154) diff --git a/frontend/docs/VOICE.md b/frontend/docs/VOICE.md index 3ab98ba03..b08d35a24 100644 --- a/frontend/docs/VOICE.md +++ b/frontend/docs/VOICE.md @@ -51,7 +51,9 @@ Jyotisha 的可见文案是产品的一部分。正确性红线(真实性、 ## 婚恋合盘报告(2026-10-19) -计算附录分别称「甲方」「乙方」。无自报或纠正范围时写「没有误差信息,按前后各 30 分钟」。核对结果写「误差内稳定」或列出候选和大致偏早、偏晚的位置。会变化的技法写「出生时间误差内会变,只作观察」。正文把相应依据写成条件。 +计算附录分别称「甲方」「乙方」。无自报或纠正范围时写「没有误差信息,按前后各 30 分钟」。核对结果写「误差内稳定」或列出候选和大致偏早、偏晚的位置。会变化的技法在用途栏写「只作观察。出生时间误差内会变」。正文把相应依据写成条件。 + +- 附录把两盘对照的就绪状态写成「输入已齐」。未使用的技法说明原因。附录末尾写「网上资料核对:未完成」「真实案例校准:未完成」。正文和追问沿用原口径。 说「你们之间」,不说「你是什么人 / 他是什么人」。说倾向、需求和条件,不说注定、不合、适合结婚。不写某年结婚、领证或分开。页脚保留一句:合盘描述的是互动的质地,走不走、怎么走,仍然是你们两个人的选择。 diff --git a/frontend/src/app/(app)/page.tsx b/frontend/src/app/(app)/page.tsx index 42925f3c1..2f1b46e69 100644 --- a/frontend/src/app/(app)/page.tsx +++ b/frontend/src/app/(app)/page.tsx @@ -61,7 +61,6 @@ import { useConsultationRun } from "@/hooks/use-consultation-run"; import { useConversationScrollAnchor } from "@/hooks/use-conversation-scroll-anchor"; import { useBirthSkyReveal } from "@/hooks/use-birth-sky-reveal"; import { useProfileOnboarding } from "@/hooks/use-profile-onboarding"; -import { useSynastry } from "@/hooks/use-synastry"; import { useSessionManagement } from "@/hooks/use-session-management"; import { showChatNotice as setComposerNotice } from "@/lib/chat-notice"; import { chatReplyAnnouncement, type ChatReplyPhase } from "@/lib/chat-reply-announcement"; @@ -137,7 +136,6 @@ import { ConsultationResponseError, discardLegacyCloudMirrorKeys, fetchCloudChartLibrary, - fetchCloudSynastryHistory, payloadCode, payloadMessage, waitForUndoWindow, @@ -401,10 +399,6 @@ export default function Home() { setSessions, uiPreview, }); - const { synastryPanel, clearSynastryHistory, applyCloudSynastryHistory } = useSynastry({ - accountId, profile, chooseSuggestedQuestion, closeAccountDialog, startNewChat, - }); - useEffect(() => { activeSessionIdRef.current = activeSessionId; }, [activeSessionId]); @@ -486,10 +480,7 @@ export default function Home() { const branch = chartLibrarySessionBranch(accountId, chartLibraryLoadedAccount.current); if (branch === "clear" || !accountId) { chartLibraryLoadedAccount.current = ""; - queueMicrotask(() => { - setChartLibrary([]); - clearSynastryHistory(); - }); + queueMicrotask(() => setChartLibrary([])); return; } const profileForLibrary: Profile = account ? readProfile(account.profile) : profile; @@ -497,7 +488,6 @@ export default function Home() { chartLibraryLoadedAccount.current = accountId; discardLegacyCloudMirrorKeys(accountId); setChartLibrary(chartLibraryOnCloudFailure(profileForLibrary, upsertSelfChart)); - clearSynastryHistory(); void fetchCloudChartLibrary() .then((cloudLibrary) => { if (chartLibraryLoadedAccount.current !== accountId) return; @@ -510,27 +500,9 @@ export default function Home() { if (chartLibraryLoadedAccount.current !== accountId) return; markChatProfilesDegraded(accountId); }); - void fetchCloudSynastryHistory() - .then((cloudHistory) => { - applyCloudSynastryHistory(cloudHistory); - }) - .catch(() => { - setComposerNotice("合盘历史暂时无法读取,请重试。", { - label: "重试", - onClick: () => { - void fetchCloudSynastryHistory() - .then((cloudHistory) => { - applyCloudSynastryHistory(cloudHistory); - }) - .catch(() => { - setComposerNotice("合盘历史暂时无法读取,请重试。"); - }); - }, - }); - }); } setChartLibrary((current) => upsertSelfChart(current, profileForLibrary)); - }, [account, accountId, applyCloudSynastryHistory, beginChatProfileReload, clearSynastryHistory, markChatProfilesDegraded, markChatProfilesReady, profile]); + }, [account, accountId, beginChatProfileReload, markChatProfilesDegraded, markChatProfilesReady, profile]); // An empty stand-in is not a known empty list. Until the people list arrives, // do not treat a name-only holder as unfinished (that flashes 「看谁的盘」). @@ -1120,7 +1092,7 @@ export default function Home() { dialogOpen={activeAccountDialog !== null || onboardingPaywallOpen || sessionDeletionOpen} profile={profile} /> - + {replyAnnouncement}
diff --git a/frontend/src/app/api/synastry/route.ts b/frontend/src/app/api/synastry/route.ts deleted file mode 100644 index fa657cb42..000000000 --- a/frontend/src/app/api/synastry/route.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { NextResponse } from "next/server"; -import { refuseWhenAccountDeletionPending } from "@/lib/account-deletion-server"; -import { z } from "zod"; -import { isProductEnabled } from "@/lib/product-access"; -import { consumeUserRequestRateLimit } from "@/lib/request-rate-limit"; -import { globalBirthProfileFromAccountRow } from "@/lib/server-owned-birth-profile"; -import { ConsultationSubjectError, loadSubjectBirth } from "@/lib/subject-birth"; -import { createServerSupabaseClient } from "@/lib/supabase/server"; -import { synastryBirthPayload } from "@/lib/global-birth-payloads"; - -const apiBase = process.env.JYOTISH_API_BASE ?? "http://127.0.0.1:5200"; -const synastryRequestSchema = z.object({ - partnerChartProfileId: z.string().uuid(), - relationshipType: z.enum(["romance", "business", "family", "general"]).optional(), -}).strict(); - -function moonLongitude(chart: Record) { - const planets = chart.planets && typeof chart.planets === "object" ? chart.planets as Record : {}; - const moon = planets.Moon && typeof planets.Moon === "object" ? planets.Moon as Record : {}; - const value = moon.lon ?? moon.longitude ?? moon.degree; - const numeric = Number(value); - if (!Number.isFinite(numeric)) throw new Error("moon_longitude_missing"); - return numeric; -} - -function moonSummary(chart: Record) { - const planets = chart.planets && typeof chart.planets === "object" ? chart.planets as Record : {}; - const moon = planets.Moon && typeof planets.Moon === "object" ? planets.Moon as Record : {}; - return { - sign: moon.sign, - nakshatra: moon.nakshatra, - pada: moon.nakshatra_pada, - lord: moon.nakshatra_lord, - longitude: moonLongitude(chart), - }; -} - -function d9Summary(varga: Record) { - const result = varga.result && typeof varga.result === "object" ? varga.result as Record : {}; - const d9 = result.D9_Navamsa && typeof result.D9_Navamsa === "object" ? result.D9_Navamsa as Record : {}; - const ascendant = d9.ascendant && typeof d9.ascendant === "object" ? d9.ascendant as Record : {}; - const planets = d9.planets && typeof d9.planets === "object" ? d9.planets as Record : {}; - return { - ascendant, - moon: planets.Moon, - venus: planets.Venus, - mars: planets.Mars, - source: varga.source, - }; -} - -function planetSign(point: unknown) { - return point && typeof point === "object" && "sign" in point - ? String((point as Record).sign || "unknown") - : "unknown"; -} - -function relationshipReport(synastry: Record, selfD9: Record, partnerD9: Record) { - const total = Number(synastry.total_score ?? 0); - const max = Number(synastry.max_score ?? 36); - const ratio = max > 0 ? total / max : 0; - const band = ratio >= 0.72 ? "supportive" : ratio >= 0.5 ? "mixed" : "challenging"; - const self = d9Summary(selfD9); - const partner = d9Summary(partnerD9); - return { - status: "evidence_summary", - scoreBand: band, - headline: band === "supportive" - ? "基础匹配度偏支持,但仍需结合现实互动与长期运势。" - : band === "mixed" - ? "基础匹配度中等,适合重点观察沟通节奏、价值观与关系承诺。" - : "基础匹配度偏谨慎,需要先处理冲突模式与现实条件。", - strengths: [ - `Ashtakoot ${total}/${max}`, - `本人 D9 Moon:${planetSign(self.moon)}`, - `对方 D9 Moon:${planetSign(partner.moon)}`, - ], - risks: [ - "这不是完整婚恋结论;尚未纳入双方 Dasha、UL/DK 与长期时机。", - `D9 Venus/Mars 需要继续解释:本人 ${planetSign(self.venus)}/${planetSign(self.mars)},对方 ${planetSign(partner.venus)}/${planetSign(partner.mars)}。`, - ], - nextEvidence: ["双方 Dasha", "UL/DK", "D9 7宫/7主", "现实关系时间线"], - }; -} - -function vargaPlanetSign(varga: Record, division: string, planet: string) { - const result = varga.result && typeof varga.result === "object" ? varga.result as Record : {}; - const chart = result[division] && typeof result[division] === "object" ? result[division] as Record : {}; - const planets = chart.planets && typeof chart.planets === "object" ? chart.planets as Record : {}; - return planetSign(planet === "Ascendant" ? chart.ascendant : planets[planet]); -} - -function businessReport(selfVargas: Record, partnerVargas: Record) { - return { - status: "partial_evidence", - scoreBand: "not_scored", - headline: "已完成基础合作结构筛查;这不是合作成败、收益或契约保证。", - strengths: [ - `D10 事业轴:本人 ${vargaPlanetSign(selfVargas, "D10_Dasamsa", "Ascendant")} / 对方 ${vargaPlanetSign(partnerVargas, "D10_Dasamsa", "Ascendant")}`, - `D2 财富轴:本人 Moon ${vargaPlanetSign(selfVargas, "D2_Hora", "Moon")} / 对方 Moon ${vargaPlanetSign(partnerVargas, "D2_Hora", "Moon")}`, - `D11 收益轴:本人 Sun ${vargaPlanetSign(selfVargas, "D11_Rudramsa", "Sun")} / 对方 Sun ${vargaPlanetSign(partnerVargas, "D11_Rudramsa", "Sun")}`, - ], - risks: [ - "尚未完成 A10、功能吉凶、双方 Vimshottari + Narayana、Shadbala/AV 与外部数值一致性,不得据此断言合作结果或精确时点。", - ], - nextEvidence: ["A10", "功能吉凶", "双方 Vimshottari + Narayana", "D10/D2/D11 原始度数与外部校验"], - }; -} - -async function postPython(path: string, body: unknown) { - const response = await fetch(`${apiBase}${path}`, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(body), - signal: AbortSignal.timeout(45_000), - }); - const data = await response.json().catch(() => null); - if (!response.ok || !data || typeof data !== "object") { - throw new Error(`jyotish_api_${response.status}`); - } - return data as Record; -} - -export async function POST(request: Request) { - try { - const supabase = await createServerSupabaseClient(); - const { data: { user }, error: authError } = await supabase.auth.getUser(); - if (authError || !user) { - return NextResponse.json({ error: "请先登录" }, { status: 401 }); - } - const frozen = await refuseWhenAccountDeletionPending(user.id); - if (frozen) return frozen; - if (!await isProductEnabled("compatibility")) { - return NextResponse.json( - { error: "合盘服务暂未开放", code: "compatibility_product_disabled" }, - { status: 503 }, - ); - } - - const limited = consumeUserRequestRateLimit("synastry", user.id); - if (!limited.ok) { - return NextResponse.json({ - error: "请求过于频繁", - code: "rate_limited", - retryAfterSeconds: limited.retryAfterSeconds, - }, { status: 429, headers: { "Retry-After": String(limited.retryAfterSeconds) } }); - } - - const parsed = synastryRequestSchema.safeParse(await request.json().catch(() => null)); - if (!parsed.success) { - return NextResponse.json({ error: "请选择已保存的对方星盘" }, { status: 400 }); - } - - let selfResolved; - try { - selfResolved = await loadSubjectBirth(supabase, user.id, "self"); - } catch (error) { - if (error instanceof ConsultationSubjectError) { - return NextResponse.json({ error: "请先完成本人出生资料" }, { status: 409 }); - } - throw error; - } - if (!selfResolved.chartable) { - return NextResponse.json({ error: "请先完成本人出生资料" }, { status: 409 }); - } - let partnerResolved; - try { - partnerResolved = await loadSubjectBirth(supabase, user.id, parsed.data.partnerChartProfileId); - } catch (error) { - if (error instanceof ConsultationSubjectError && error.code === "subject_unavailable") { - return NextResponse.json({ error: "暂时无法读取对方星盘" }, { status: 503 }); - } - if (error instanceof ConsultationSubjectError) { - return NextResponse.json({ error: "请先把对方星盘保存到云端星盘库" }, { status: 404 }); - } - throw error; - } - if (!partnerResolved.chartable) { - return NextResponse.json({ error: "请先把对方星盘保存到云端星盘库" }, { status: 404 }); - } - - const [selfPayload, partnerPayload] = await Promise.all([ - synastryBirthPayload(globalBirthProfileFromAccountRow(selfResolved.row)), - synastryBirthPayload(globalBirthProfileFromAccountRow(partnerResolved.row)), - ]); - const [selfChart, partnerChart] = await Promise.all([ - postPython("/api/chart", { ...selfPayload, skip_vedastro_main_entry_overview: true }), - postPython("/api/chart", { ...partnerPayload, skip_vedastro_main_entry_overview: true }), - ]); - const relationshipType = parsed.data.relationshipType === "business" || parsed.data.relationshipType === "family" || parsed.data.relationshipType === "general" - ? parsed.data.relationshipType - : "romance"; - if (relationshipType === "business") { - const [selfVargas, partnerVargas] = await Promise.all([ - postPython("/api/varga_full", { ...selfPayload, planets: selfChart.planets, ascendant: selfChart.ascendant, divisions: ["D2", "D10", "D11"] }), - postPython("/api/varga_full", { ...partnerPayload, planets: partnerChart.planets, ascendant: partnerChart.ascendant, divisions: ["D2", "D10", "D11"] }), - ]); - return NextResponse.json({ - status: "ok", - relationshipType, - claimStatus: "partial", - method: "d2_d10_d11_business_screening_partial", - evidenceLayers: ["d2_hora", "d10_dashamsa", "d11_ekadashamsa"], - blockedLayers: ["A10", "functional_benefic_malefic", "vimshottari_narayana", "shadbala_ashtakavarga", "external_engine_parity"], - relationshipReport: businessReport(selfVargas, partnerVargas), - }); - } - if (relationshipType !== "romance") { - return NextResponse.json({ - status: "blocked", - relationshipType, - message: "该关系类型尚无可验证的专用合盘计算合同;已保留问题草稿。", - }); - } - const [selfD9, partnerD9] = await Promise.all([ - postPython("/api/varga_full", { - ...selfPayload, - planets: selfChart.planets, - ascendant: selfChart.ascendant, - divisions: ["D9"], - }), - postPython("/api/varga_full", { - ...partnerPayload, - planets: partnerChart.planets, - ascendant: partnerChart.ascendant, - divisions: ["D9"], - }), - ]); - const synastry = await postPython("/api/synastry", { - male_moon: moonLongitude(selfChart), - female_moon: moonLongitude(partnerChart), - }); - return NextResponse.json({ - status: "ok", - method: "ashtakoot_plus_moon_nakshatra_d9", - evidenceLayers: ["ashtakoot", "moon_nakshatra", "d9_navamsa"], - selfChart: { moon: moonSummary(selfChart), d9: d9Summary(selfD9) }, - partnerChart: { moon: moonSummary(partnerChart), d9: d9Summary(partnerD9) }, - synastry, - relationshipReport: relationshipReport(synastry, selfD9, partnerD9), - }); - } catch (error) { - return NextResponse.json({ - status: "blocked", - error: error instanceof Error ? error.message : "synastry_unavailable", - message: "合盘计算暂时不可用;可先保留合盘问题草稿。", - }, { status: 503 }); - } -} diff --git a/frontend/src/components/people-home-links.tsx b/frontend/src/components/people-home-links.tsx index f418c39c4..e47e86e3a 100644 --- a/frontend/src/components/people-home-links.tsx +++ b/frontend/src/components/people-home-links.tsx @@ -7,7 +7,7 @@ import { parseAccountDialogIntent, type AccountDialogIntent, } from "@/lib/account-dialog-intent"; -import type { ChartLibraryRecord, OpenAccountDialogOptions, Profile, SynastryRelationshipType } from "@/lib/home-types"; +import type { OpenAccountDialogOptions } from "@/lib/home-types"; function stripQuery(key: string) { const params = new URLSearchParams(window.location.search); @@ -17,10 +17,7 @@ function stripQuery(key: string) { window.history.replaceState(null, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`); } -export function SynastryDeepLink(props: { - profile: Profile; - draft: (record: ChartLibraryRecord, relationshipType: SynastryRelationshipType) => Promise; -}) { +export function SynastryDeepLink() { const started = useRef(false); useEffect(() => { if (started.current) return; @@ -29,7 +26,6 @@ export function SynastryDeepLink(props: { started.current = true; window.location.replace(`/synastry?with=${encodeURIComponent(id)}`); }, []); - void props; return null; } diff --git a/frontend/src/components/synastry/synastry-report-view.tsx b/frontend/src/components/synastry/synastry-report-view.tsx index 29b411f36..3e276f6ed 100644 --- a/frontend/src/components/synastry/synastry-report-view.tsx +++ b/frontend/src/components/synastry/synastry-report-view.tsx @@ -275,16 +275,19 @@ export function SynastryReportView(props: { {(snapshot.technical ?? []).map((block) => (

{block.title}

- {block.precisionAudit?.length ? ( -
- - - {block.precisionAudit.map((row) => - - )} -
方法计算在本报告中
{row.method}{row.calculation}{row.usage}
-
- ) : null} + {block.audit?.map(({ title, rows }) => ( +
+

{title}

+
+ + + {rows.map((row) => + + )} +
方法计算在本报告中
{row.method}{row.calculation}{row.usage}
+
+
+ ))}
    {block.lines.map((line) =>
  • {line}
  • )}
diff --git a/frontend/src/hooks/use-synastry.ts b/frontend/src/hooks/use-synastry.ts deleted file mode 100644 index 00c569e0f..000000000 --- a/frontend/src/hooks/use-synastry.ts +++ /dev/null @@ -1,145 +0,0 @@ -"use client"; - -import { useCallback, useState, type Dispatch, type SetStateAction } from "react"; - -import { showChatNotice as setComposerNotice } from "@/lib/chat-notice"; -import { saveCloudSynastryReport } from "@/lib/home-cloud-sync"; -import { buildSynastryQuestion } from "@/lib/home-profile"; -import { - timestamp, - type ChartLibraryRecord, - type Profile, - type SynastryRelationshipType, - type SynastryReportCard, - type Theme, -} from "@/lib/home-types"; - -export type SynastryParams = { - accountId: string | undefined; - profile: Profile; - chooseSuggestedQuestion: (question: string, theme: Theme) => void; - closeAccountDialog: () => void; - startNewChat: (options: { subjectId: "self" }) => Promise; -}; - -export type SynastryPanel = { - synastryRelationshipType: SynastryRelationshipType; - setSynastryRelationshipType: Dispatch>; - synastryPendingId: string | null; - synastryReportCard: SynastryReportCard | null; - setSynastryReportCard: Dispatch>; - synastryHistory: SynastryReportCard[]; - draftSynastryQuestionFromChart: (record: ChartLibraryRecord, relationshipType: SynastryRelationshipType) => Promise; -}; - -/** - * Owns the four synastry states that used to sit in Home(). Home keeps only the - * two stable history hooks the chart-library effect calls; everything else the - * chart-library dialog needs travels as one `synastryPanel` object. - */ -export function useSynastry(params: SynastryParams) { - const { accountId, profile, chooseSuggestedQuestion, closeAccountDialog } = params; - const [synastryRelationshipType, setSynastryRelationshipType] = useState("romance"); - const [synastryPendingId, setSynastryPendingId] = useState(null); - const [synastryReportCard, setSynastryReportCard] = useState(null); - const [synastryHistory, setSynastryHistory] = useState([]); - - // Stable across renders so Home's chart-library effect can list them in its - // dependency array without gaining a re-run. - const clearSynastryHistory = useCallback(() => { - setSynastryHistory([]); - }, []); - const applyCloudSynastryHistory = useCallback((cloudHistory: SynastryReportCard[]) => { - setSynastryHistory([...cloudHistory].sort((a, b) => b.createdAt - a.createdAt).slice(0, 10)); - }, []); - - async function draftSynastryQuestionFromChart(record: ChartLibraryRecord, relationshipType: SynastryRelationshipType) { - if (record.role !== "other") return; - if (synastryPendingId) return; - if (!await params.startNewChat({ subjectId: "self" })) return; - const baseQuestion = buildSynastryQuestion(profile, record.profile, relationshipType); - setSynastryPendingId(record.id); - setComposerNotice("正在计算基础合盘证据,请稍候。"); - try { - const response = await fetch("/api/synastry", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ partnerChartProfileId: record.id, relationshipType }), - }); - const payload = await response.json().catch(() => null) as { status?: string; claimStatus?: string; blockedLayers?: string[]; evidenceLayers?: string[]; synastry?: { total_score?: number; max_score?: number; assessment?: string }; relationshipReport?: { headline?: string; scoreBand?: string; strengths?: string[]; risks?: string[]; nextEvidence?: string[] } } | null; - if (response.ok && payload?.status === "ok") { - const score = payload.synastry?.total_score; - const max = payload.synastry?.max_score; - const assessment = payload.synastry?.assessment; - const layers = (payload.evidenceLayers || []).join(" / ") || "Ashtakoot / Moon / D9"; - const evidenceSummary = relationshipType === "business" - ? `已完成基础商业合作证据筛查:${layers};声明状态:${payload.claimStatus || "partial"};未用层:${(payload.blockedLayers || []).join(" / ") || "A10 / 双方 Dasha-Narayana / 功能吉凶"}。请勿将其表述为合作保证或精确时点。` - : `已计算基础合盘证据:${layers};Ashtakoot ${score ?? "?"}/${max ?? "?"},初步评级:${assessment || "待解释"}。请基于这个证据包继续分析。`; - const reportCard: SynastryReportCard = { - id: `${record.id}-${timestamp()}`, - partnerName: record.profile.name || "对方", - partnerChartId: record.id, - score, - maxScore: max, - assessment, - headline: payload.relationshipReport?.headline, - scoreBand: payload.relationshipReport?.scoreBand, - strengths: payload.relationshipReport?.strengths, - risks: payload.relationshipReport?.risks, - nextEvidence: payload.relationshipReport?.nextEvidence, - createdAt: timestamp(), - }; - let savedReportCard = reportCard; - let historyPersisted = !accountId; - if (accountId) { - try { - savedReportCard = await saveCloudSynastryReport(reportCard); - historyPersisted = true; - } catch { - historyPersisted = false; - } - } - setSynastryReportCard(savedReportCard); - if (accountId && historyPersisted) { - setSynastryHistory((current) => ( - [savedReportCard, ...current.filter((item) => item.id !== savedReportCard.id)].slice(0, 10) - )); - } - chooseSuggestedQuestion([ - baseQuestion, - "", - evidenceSummary, - payload.relationshipReport?.headline ? `结构化摘要:${payload.relationshipReport.headline}` : "", - ].join("\n"), relationshipType === "business" ? "career" : "marriage"); - if (accountId && !historyPersisted) { - setComposerNotice("未能存入历史"); - } - } else { - chooseSuggestedQuestion(baseQuestion, relationshipType === "business" ? "career" : "marriage"); - setComposerNotice(response.status === 404 - ? "请先把对方星盘保存到云端,再用于合盘。" - : response.status === 429 - ? "合盘请求过于频繁,请稍后再试。" - : payload?.status === "blocked" ? "合盘计算暂时不可用,已先生成问题草稿。" : "已生成合盘问题草稿。"); - } - } catch { - chooseSuggestedQuestion(baseQuestion, relationshipType === "business" ? "career" : "marriage"); - setComposerNotice("合盘计算暂时不可用,已先生成问题草稿。"); - } finally { - setSynastryPendingId(null); - } - closeAccountDialog(); - } - - const synastryPanel: SynastryPanel = { - synastryRelationshipType, - setSynastryRelationshipType, - synastryPendingId, - synastryReportCard, - setSynastryReportCard, - synastryHistory, - draftSynastryQuestionFromChart, - }; - - return { synastryPanel, clearSynastryHistory, applyCloudSynastryHistory }; -} diff --git a/frontend/src/lib/synastry-full-run.ts b/frontend/src/lib/synastry-full-run.ts index e11a24e7b..1412529ba 100644 --- a/frontend/src/lib/synastry-full-run.ts +++ b/frontend/src/lib/synastry-full-run.ts @@ -15,6 +15,7 @@ import type { PersonalReportRecord } from "@/lib/personal-report-service-core"; import { loadSynastrySubjectBirth, marriageMatchBirthBody } from "@/lib/marriage-match-service"; import { SYNASTRY_ORDER_SECTION, synastryDisplaySubjectIds } from "@/lib/synastry-display-order"; import { timelineForPair, writeSynastryLanguage, type SynastrySnapshot } from "@/lib/synastry-full-generate"; +import { currentSynastryTechnicalBlocks } from "@/lib/synastry-full-technical"; import type { TimingPeriod } from "@/lib/synastry-full-timeline"; const API_BASE = process.env.JYOTISH_API_BASE ?? "http://127.0.0.1:5200"; @@ -122,7 +123,7 @@ export function publicSynastryView(payload: unknown): SynastrySnapshot | null { sections: zh.sections as SynastrySnapshot["sections"], timeline: zh.timeline as SynastrySnapshot["timeline"], practices: zh.practices as SynastrySnapshot["practices"], - technical: zh.technical as SynastrySnapshot["technical"], + technical: currentSynastryTechnicalBlocks(zh.technical as SynastrySnapshot["technical"], row.dossier), gate: { ok: true, language: "zh" }, // 产品 2026-11-07 占星师方案:skill order marker, reading scope and the four event classes. ...(zh.structure ? { structure: zh.structure as SynastrySnapshot["structure"] } : {}), diff --git a/frontend/src/lib/synastry-full-technical.ts b/frontend/src/lib/synastry-full-technical.ts index dba060ff0..800d83075 100644 --- a/frontend/src/lib/synastry-full-technical.ts +++ b/frontend/src/lib/synastry-full-technical.ts @@ -1,7 +1,7 @@ import { AYANAMSA_OPTIONS } from "@/lib/ayanamsa"; import { signZh } from "./chart-view-labels.ts"; import { NAKSHATRA_ZH } from "./panchanga-names-zh.ts"; -import { displayTechniqueAuditLabel } from "./consultation-technique-audit.ts"; +import { displayTechniqueAuditLabel, displayTechniqueAuditNote, techniqueCalculationStatusLabel } from "./consultation-technique-audit.ts"; import { EVENT_OVERLAP_NOTE, eventClassRows } from "./synastry-full-timeline.ts"; /** @@ -12,26 +12,26 @@ export type TechnicalBlock = Readonly<{ id: "parameters" | "structures" | "contacts" | "timing" | "traditional" | "execution"; title: string; lines: readonly string[]; - precisionAudit?: readonly { method: string; calculation: string; usage: string }[]; + audit?: readonly Readonly<{ title: string; rows: readonly AuditRow[] }>[]; }>; -const STATUS_LABELS: Readonly> = { - executed: "已执行", - ready_for_comparison: "已执行", - present: "已执行", - used: "已执行", - available: "已执行", - passed: "已执行", - parameter_sensitive: "参数敏感", - partial: "参数敏感", - weak: "参数敏感", - observation_only: "参数敏感", - not_applicable: "不适用", - not_used: "不适用", - not_used_for_date_intersection: "不适用", - // E5b: a layer that could not run says so in Chinese, not as a raw code (BUG-1679). - blocked: "无法计算", - not_available: "无法计算", +type AuditRow = Readonly<{ method: string; calculation: string; usage: string }>; +const VERIFICATION_LINES = ["网上资料核对:未完成", "真实案例校准:未完成"]; + +const AUDIT_REASONS: Readonly> = { + birth_time_window_varies: "出生时间误差内会变", + solar_day_window_unavailable: "无法确定出生时刻所在的日出日落区间", + sunrise_or_sunset_unavailable_for_location_date: "出生地当日没有可用的日出或日落计算", + saham_daynight_requires_wgs84_location_and_timezone: "缺少计算日出日落所需的地点或时区", + saham_inputs_unavailable: "缺少 Saham 所需的盘面输入", + saham_calculation_failed: "Saham 计算未完成", +}; + +const NOT_APPLICABLE: Readonly> = { + "Niryaana Shoola Dasha": "此技法用于寿元,不用于关系应期", + "optional 27-nakshatra Shukuyo narrative layer": "宿曜属于单独的文化解读", + "optional Western synastry/composite/Davison layer": "本命西洋盘不能替代两人的西洋合盘", + "Prashna context when a real question chart was supplied": "本报告没有用于问卦的提问时刻盘", }; function record(value: unknown): Record | null { @@ -42,12 +42,6 @@ function text(value: unknown): string { return typeof value === "string" ? value.trim() : ""; } -function statusLabel(value: unknown): string { - const raw = text(value); - if (!raw) return "未标明"; - return STATUS_LABELS[raw.toLowerCase()] ?? raw; -} - function named(value: unknown): string { if (typeof value === "string") return value.trim(); const row = record(value); @@ -55,22 +49,69 @@ function named(value: unknown): string { return text(row.planet) || text(row.sign) || text(row.name) || text(row.lord); } -export function executionBasisLines(receipt: unknown): string[] { - const row = record(receipt) ?? {}; - return [ - ...linesOf(row.individual_technique_audit), - ...linesOf(row.pair_execution_tasks), - ]; +function reasonText(value: unknown): string { + const raw = text(value); + const label = AUDIT_REASONS[raw] ?? displayTechniqueAuditNote(raw); + return /\p{Script=Han}/u.test(label) ? label.replace(/\s*·\s*/g, ",") : ""; } -function linesOf(value: unknown): string[] { +function auditRow(method: string, item: Record): AuditRow { + const display = displayTechniqueAuditLabel(method).replaceAll("_", " ").replace(/\s*·\s*/g, ","); + const status = text(item.status).toLowerCase(); + const reasonLabel = reasonText(item.reason || item.note); + const reasons = [reasonLabel]; + if (item.reason === "birth_time_window_varies") { + return { method: display, calculation: "参数敏感", usage: `只作观察。${reasonLabel}` }; + } + if (status === "ready_for_comparison") return { method: display, calculation: "输入已齐", usage: "供写作参考" }; + if (["executed", "present", "used", "available", "passed"].includes(status)) { + return { method: display, calculation: techniqueCalculationStatusLabel("executed"), usage: "供写作参考" }; + } + if (["parameter_sensitive", "partial", "weak", "observation_only"].includes(status)) { + return { method: display, calculation: status === "partial" ? techniqueCalculationStatusLabel("partial") : "参数敏感", usage: "只作观察" }; + } + if (["not_applicable", "not_used", "not_used_for_date_intersection"].includes(status)) { + reasons.push(NOT_APPLICABLE[method] || "该技法不在本次对照范围"); + return { method: display, calculation: techniqueCalculationStatusLabel("not_applicable"), usage: `未使用。${reasons.find(Boolean)}` }; + } + if (Array.isArray(item.required_inputs)) { + for (const raw of item.required_inputs) { + const input = record(raw); + if (input?.status !== "blocked") continue; + if (input.person_a_status === "blocked") reasons.push(`甲方${reasonText(input.person_a_reason) || "缺少所需的计算结果"}`); + if (input.person_b_status === "blocked") reasons.push(`乙方${reasonText(input.person_b_reason) || "缺少所需的计算结果"}`); + } + } + const reason = [...new Set(reasons.filter(Boolean))].join(",") || "回执没有可用的计算结果"; + const calculation = status ? techniqueCalculationStatusLabel("blocked") : "未标明"; + return { method: display, calculation, usage: `未使用。${reason}` }; +} + +function receiptRows(value: unknown, side?: "person_a" | "person_b"): AuditRow[] { if (!Array.isArray(value)) return []; return value.flatMap((row) => { const item = record(row); - if (!item) return []; - const label = text(item.technique) || text(item.task) || text(item.label) || text(item.lane); - if (!label) return []; - return [`${label}:${statusLabel(item.status)}`]; + const method = text(item?.technique || item?.task || item?.label || item?.lane); + return item && method ? [auditRow(method, (side && record(item[side])) || item)] : []; + }); +} + +export function synastryExecutionAudit(receipt: unknown): NonNullable { + const source = record(receipt); + return [ + { title: "甲方", rows: receiptRows(source?.individual_technique_audit, "person_a") }, + { title: "乙方", rows: receiptRows(source?.individual_technique_audit, "person_b") }, + { title: "两盘对照", rows: receiptRows(source?.pair_execution_tasks) }, + ].filter(({ rows }) => rows.length); +} + +export function currentSynastryTechnicalBlocks(blocks: readonly TechnicalBlock[] | undefined, dossier: unknown) { + const packet = record(dossier); + if (!record(packet?.birth_precision)) return blocks; + return blocks?.map((block) => { + if (block.id !== "execution" || block.audit) return block; + const audit = synastryExecutionAudit(packet?.execution_receipt); + return audit.length ? { id: block.id, title: block.title, lines: VERIFICATION_LINES, audit } : block; }); } @@ -179,25 +220,6 @@ export function precisionEvidence(dossier: unknown, language: "zh" | "en"): stri : `${affected.join(" / ")}. These layers vary within the birth-time window.`; } -function precisionAuditRows(receipt: Record) { - const usage = "出生时间误差内会变,只作观察"; - const individual = Array.isArray(receipt.individual_technique_audit) ? receipt.individual_technique_audit : []; - const pairs = Array.isArray(receipt.pair_execution_tasks) ? receipt.pair_execution_tasks : []; - return [ - ...individual.flatMap((value) => { - const item = record(value); - const method = displayTechniqueAuditLabel(text(item?.technique)); - return [["person_a", "甲方"], ["person_b", "乙方"]].flatMap(([side, label]) => - record(item?.[side])?.reason === "birth_time_window_varies" - ? [{ method: `${label} ${method}`, calculation: "参数敏感", usage }] : []); - }), - ...pairs.flatMap((value) => { - const item = record(value); - return item?.reason === "birth_time_window_varies" ? [{ method: text(item.task), calculation: "参数敏感", usage }] : []; - }), - ]; -} - /** Seven kutas, each with its own ceiling; Varna (caste) is not scored. */ const KUTAS: ReadonlyArray = [ ["Vashya", "Vashya(相互牵引)", 2], @@ -462,14 +484,12 @@ export function buildTechnicalBasis(input: Readonly<{ ...(alignment ? [text(alignment.status) === "same_profile" ? "两盘口径:两人用同一岁差与交点" : `两盘口径:两人档案的岁差或交点不同,合盘统一用 ${text(used?.ayanamsa) || "lahiri"} / ${text(used?.node_mode) || "mean"}`] : []), - ...(scope ? [`结论范围:${text(scope.status) === "full" ? "可以写完整结论" : text(scope.status) === "limited" ? `主链对照有未闭合项,只写条件性结论(${text(scope.reason)})` : "两盘口径不一致,不出结论"}`] : []), + ...(scope ? [`结论范围:${text(scope.status) === "full" ? "可以写完整结论" : text(scope.status) === "limited" ? "主链对照有未闭合项,只写条件性结论" : "两盘口径不一致,不出结论"}`] : []), ]; const eventLines = eventClassRows(dossier, input.names).map((row) => `${row.title}:${row.status}${row.windows.length ? `;候选 ${row.windows.join("、")}` : ""};${row.people.join(";")}`); - // 原值:execution 末尾一行「外部资料与真实案例核对:未进行,本报告是计算层归纳」 - // 新值:删掉这一行;回执里的对应审计数据仍在后台 - // 原因:产品负责人 2026-11-08:用户可见文字不出现联网/外部核验字样,后台保留 - const precisionAudit = precisionAuditRows(receipt); - const execution = [...executionBasisLines(receipt)]; + // 原值:没有公开核验行。新值:在计算依据附录中分列两项未完成。 + // 原因:产品负责人 2026-11-12 决定附录照实列出,正文和追问仍沿用 BUG-1794。 + const audit = synastryExecutionAudit(receipt); return [ { id: "parameters", title: "计算参数", lines: [...parameters, ...pairLines] }, { id: "structures", title: "各自的婚恋结构", lines: structure }, @@ -479,6 +499,6 @@ export function buildTechnicalBasis(input: Readonly<{ ...(eventLines.length > 0 ? [...eventLines, EVENT_OVERLAP_NOTE.zh] : []), ] }, { id: "traditional", title: "传统配对参考", lines: [...lunarNotes, ...traditional] }, - { id: "execution", title: "技法执行情况", lines: execution, ...(precisionAudit.length ? { precisionAudit } : {}) }, + { id: "execution", title: "技法执行情况", lines: VERIFICATION_LINES, audit }, ]; } diff --git a/frontend/src/lib/synastry-report-material.ts b/frontend/src/lib/synastry-report-material.ts index 0112df9dd..fa5b26e93 100644 --- a/frontend/src/lib/synastry-report-material.ts +++ b/frontend/src/lib/synastry-report-material.ts @@ -5,6 +5,7 @@ import { type SynastryAskSectionId, type SynastrySectionId, } from "@/lib/synastry-full-sections"; +import { currentSynastryTechnicalBlocks, type TechnicalBlock } from "@/lib/synastry-full-technical"; export const SYNASTRY_CHAT_CHAR_BUDGET = 20_000; @@ -12,7 +13,7 @@ type LanguageBody = { sections?: Array<{ id?: string; title?: string; text?: string; reasons?: Array<{ plain?: string; basis?: string }> }>; timeline?: Array<{ id?: string; phase?: string; text?: string; basis?: string }>; practices?: Array<{ text?: string }>; - technical?: Array<{ id?: string; title?: string; lines?: string[] }>; + technical?: TechnicalBlock[]; events?: Array>; }; @@ -58,6 +59,22 @@ function timingLines(payload: Record): unknown { return Object.keys(picked).length > 0 ? picked : null; } +function technicalLines(block: TechnicalBlock): string[] { + if (block.id === "execution" && block.audit?.length) { + const lines: string[] = []; + const rowCount = Math.max(...block.audit.map(({ rows }) => rows.length)); + for (let index = 0; index < rowCount && lines.length < 12; index += 1) { + for (const { title, rows } of block.audit) { + const row = rows[index]; + if (row) lines.push(`${title} ${row.method}:计算 ${row.calculation},在本报告中 ${row.usage}`); + if (lines.length === 12) return lines; + } + } + return lines; + } + return (block.lines ?? []).filter((line) => !/网上资料核对|真实案例校准/.test(line)).slice(0, 12); +} + export function synastrySectionMaterial(input: { payload: unknown; sectionId: SynastrySectionId; @@ -100,10 +117,11 @@ export function synastrySectionMaterial(input: { } if (input.includeTechnical) { const blocks = (record(payload.zh)?.technical ?? body?.technical) as LanguageBody["technical"]; - material.technical = (blocks ?? []).map((block) => ({ + const current = currentSynastryTechnicalBlocks(blocks, payload.dossier); + material.technical = (current ?? []).map((block) => ({ id: block.id ?? "", title: block.title ?? "", - lines: (block.lines ?? []).slice(0, 12), + lines: technicalLines(block), })); } return fitSynastryMaterial(material, 16_000); diff --git a/frontend/tests/account-deletion.test.tsx b/frontend/tests/account-deletion.test.tsx index 5da110348..b6eeba3fd 100644 --- a/frontend/tests/account-deletion.test.tsx +++ b/frontend/tests/account-deletion.test.tsx @@ -118,7 +118,6 @@ test("every paid route refuses a frozen account before doing work", () => { for (const path of [ "../src/app/api/consult/route.ts", "../src/app/api/reports/route.ts", - "../src/app/api/synastry/route.ts", ]) { const source = read(path); assert.match(source, /refuseWhenAccountDeletionPending\(/, path); diff --git a/frontend/tests/chart-library-other-profile.test.ts b/frontend/tests/chart-library-other-profile.test.ts index 9de44c8e5..14f6c1d41 100644 --- a/frontend/tests/chart-library-other-profile.test.ts +++ b/frontend/tests/chart-library-other-profile.test.ts @@ -66,52 +66,6 @@ test("cloud save failures preserve the server error message", () => { assert.match(source, /throw new Error\(payload\?\.error \|\| "cloud_chart_profile_save_failed"\);/); }); -test("synastry selection exposes a pending state while the evidence packet is computed", () => { - assert.match(source, /const \[synastryPendingId, setSynastryPendingId\] = useState\(null\);/); - assert.match(source, /setSynastryPendingId\(record\.id\);/); - assert.match(source, /finally \{\s*setSynastryPendingId\(null\);\s*\}/); - // 原值 / 新值 / 原因:死面板 disabled/按钮 spinner / hook 重入门与既有通知 / 锁实际合盘请求入口。 - assert.match(source, /if \(synastryPendingId\) return;/); - assert.match(source, /正在计算基础合盘证据,请稍候。/); -}); - -test("relationship intent selects domain-specific evidence instead of treating every pairing as romance", () => { - const route = readFileSync(new URL("../src/app/api/synastry/route.ts", import.meta.url), "utf8"); - assert.match(source, /商业合作/); - assert.match(source, /亲友\/家庭/); - assert.match(source, /其他关系/); - assert.match(source, /relationshipType: SynastryRelationshipType/); - assert.match(source, /body: JSON\.stringify\(\{ partnerChartProfileId: record\.id, relationshipType \}\)/); - assert.doesNotMatch(source, /selfProfile: profile, partnerProfile: record\.profile/); - assert.match(route, /partnerChartProfileId/); - // 原值: the route selected profiles and the chart_profiles jsonb itself. - // 新值: both people are read by loadSubjectBirth. - // 原因: D13. The other person's birth is the typed columns. "我" stays the household profile. - assert.match(route, /loadSubjectBirth/); - assert.doesNotMatch(route, /globalBirthProfileFromStoredChart/); - assert.match(route, /consumeUserRequestRateLimit\("synastry"/); - assert.match(route, /relationshipType === "business"/); - assert.match(route, /divisions: \["D2", "D10", "D11"\]/); - assert.match(route, /"D10_Dasamsa"/); - assert.match(route, /"D11_Rudramsa"/); - assert.match(route, /blockedLayers:/); - assert.match(route, /"A10"/); - assert.match(route, /"functional_benefic_malefic"/); - assert.match(route, /"vimshottari_narayana"/); - assert.match(source, /基础商业合作证据筛查/); - assert.match(source, /relationshipType === "business"/); -}); - - -test("synastry history is replaced by the cloud list and save failures stay in page memory", () => { - // Former value: `new Map([...current, ...cloudHistory])` unioned local+cloud - // and `writeSynastryHistory(accountId, next)` on cloud save failure. - assert.doesNotMatch(source, /new Map\(\[\.\.\.current, \.\.\.cloudHistory\]/); - assert.match(source, /未能存入历史/); - assert.doesNotMatch(source, /writeSynastryHistory\(/); - assert.match(source, /discardLegacyCloudMirrorKeys\(/); -}); - test("current chart selection is local and does not overwrite the owner's profile", () => { // 原值: activeChartStorageKey and the "set as current" copy lived in the home surface. // 新值: those symbols are gone from frontend/src. The page profile is not replaced from the archive. @@ -145,7 +99,6 @@ test("other chart details own actions and self details cannot delete", () => { // 原因: D11 removes "set as default". assert.doesNotMatch(charts, /设为默认/); assert.match(charts, /和我合盘/); - assert.match(source, /startNewChat\(\{ subjectId: "self" \}\)/); + assert.match(charts, /\/synastry\?with=\$\{selected\.id\}/); assert.match(charts, /pendingDelete\?\.id === selected\.id && selected\.role === "other"/); - assert.match(source, /partnerChartId: record\.id/); }); diff --git a/frontend/tests/composer-isolation-contract.test.ts b/frontend/tests/composer-isolation-contract.test.ts index b939e035c..26a05f8c1 100644 --- a/frontend/tests/composer-isolation-contract.test.ts +++ b/frontend/tests/composer-isolation-contract.test.ts @@ -13,7 +13,6 @@ const chatOwnerSource = [ "../src/hooks/use-session-management.ts", "../src/hooks/use-consultation-run.ts", "../src/hooks/use-profile-onboarding.ts", - "../src/hooks/use-synastry.ts", ].map((path) => readFileSync(new URL(path, import.meta.url), "utf8")).join("\n"); function sourceBetween(source: string, startMarker: string, endMarker: string) { diff --git a/frontend/tests/home-surface.ts b/frontend/tests/home-surface.ts index 8c4057613..a60e83256 100644 --- a/frontend/tests/home-surface.ts +++ b/frontend/tests/home-surface.ts @@ -20,7 +20,6 @@ const optionalHomeHookFiles = [ "../src/hooks/use-session-management.ts", "../src/hooks/use-consultation-run.ts", "../src/hooks/use-profile-onboarding.ts", - "../src/hooks/use-synastry.ts", "../src/hooks/use-session-list.ts", "../src/hooks/use-home-shell-registration.ts", // issue #116:会话行的重命名、删除、收藏、转发、排序和删除确认框搬进共用外壳。 diff --git a/frontend/tests/jyotish-api-reachability-contract.test.ts b/frontend/tests/jyotish-api-reachability-contract.test.ts index b881d9bfe..655b0994e 100644 --- a/frontend/tests/jyotish-api-reachability-contract.test.ts +++ b/frontend/tests/jyotish-api-reachability-contract.test.ts @@ -7,7 +7,7 @@ const readRoot = (path: string) => readFileSync(new URL(path, root), "utf8"); const consultationWorkflow = readRoot("frontend/src/mastra/consultation-workflow.ts"); // 原值: 读 birth-time-journey-engine-model.ts,断言 /api/active_rectification_* 新值: 读 chart-choice/server.ts,断言 /api/chart_choice/* 原因: 2026-11-06 生时纠正改为选盘页 const chartChoice = readRoot("frontend/src/lib/chart-choice/server.ts"); -const synastry = readRoot("frontend/src/app/api/synastry/route.ts"); +const synastry = readRoot("frontend/src/lib/synastry-full-run.ts"); const apiServer = readRoot("scripts/jyotish_api_server.py"); test("commercial Jyotish paths resolve to a registered Python handler", () => { @@ -15,14 +15,14 @@ test("commercial Jyotish paths resolve to a registered Python handler", () => { "/api/consultation_workflow", "/api/chart_choice/packet", "/api/chart_choice/decide", - "/api/varga_full", - "/api/synastry", + "/api/synastry_full_dossier", + "/api/synastry_full_reader_gate", ]) { assert.match(apiServer, new RegExp(`['\"]${path.replaceAll("/", "\\/")}['\"]`)); } assert.match(consultationWorkflow, /\/api\/consultation_workflow/); assert.match(chartChoice, /\/api\/chart_choice\/packet/); assert.match(chartChoice, /\/api\/chart_choice\/decide/); - assert.match(synastry, /\/api\/varga_full/); - assert.match(synastry, /\/api\/synastry/); + assert.match(synastry, /"\/api\/synastry_full_dossier"/); + assert.match(synastry, /"\/api\/synastry_full_reader_gate"/); }); diff --git a/frontend/tests/people-archive-regressions.test.ts b/frontend/tests/people-archive-regressions.test.ts index e8ca79689..70bf385fa 100644 --- a/frontend/tests/people-archive-regressions.test.ts +++ b/frontend/tests/people-archive-regressions.test.ts @@ -86,7 +86,8 @@ test("people delete requires known usage and synastry never switches the global // 原因: BUG-1081——本人在星盘档案可编辑(TASK-self-edit-avatar-menu-20260928 S1) assert.match(people, /title=\{editingSelf \? "编辑我的资料" : selectedId \? "编辑人物" : "添加一个人"\}/); assert.doesNotMatch(people, /openPerson\(selected\.id,.*synastry/); - assert.match(source("hooks/use-synastry.ts"), /startNewChat\(\{ subjectId: "self" \}\)/); + assert.match(people, /\/synastry\?with=/); + assert.match(source("components/people-home-links.tsx"), /location\.replace\(`\/synastry\?with=/); }); test("daily card computes eligibility, calendar and fingerprint from selected profile", () => { diff --git a/frontend/tests/product-domain-registry.test.ts b/frontend/tests/product-domain-registry.test.ts index f61a4f83e..7d5f5340e 100644 --- a/frontend/tests/product-domain-registry.test.ts +++ b/frontend/tests/product-domain-registry.test.ts @@ -51,7 +51,7 @@ test("write and compute APIs enforce their independent product gates", async () ["src/app/api/chart-choice/route.ts", "await chartChoiceCaller("], ["src/app/api/chart-choice/packet/route.ts", "await chartChoiceCaller("], ["src/app/api/chart-choice/adopt/route.ts", "await chartChoiceCaller("], - ["src/app/api/synastry/route.ts", 'isProductEnabled("compatibility")'], + ["src/lib/synastry-full-create.ts", 'isProductEnabled("compatibility")'], ["src/app/api/synastry-reports/route.ts", 'isProductEnabled("compatibility")'], ["src/app/api/reports/route.ts", 'isProductEnabled("report_center")'], ]; diff --git a/frontend/tests/report-no-web-wording-20261109.test.ts b/frontend/tests/report-no-web-wording-20261109.test.ts index 6bba465a2..940b36a1c 100644 --- a/frontend/tests/report-no-web-wording-20261109.test.ts +++ b/frontend/tests/report-no-web-wording-20261109.test.ts @@ -73,8 +73,15 @@ test("synastry technical basis never shows web-verification wording", () => { contacts: [], timing: [], }); - assertNoWebWording(blocks.flatMap((block) => [block.title, ...block.lines]).join("\n"), "合盘技法依据"); - // 回执数据原样保留,只是不再渲染。 + // #275:11-12 允许在合盘附录列两行固定状态,其余文案仍用原契约。 + const verification = ["网上资料核对:未完成", "真实案例校准:未完成"]; + assert.deepEqual(blocks.find(({ id }) => id === "execution")?.lines, verification); + assertNoWebWording(blocks.flatMap((block) => [ + block.title, + ...block.lines.filter((line) => block.id !== "execution" || !verification.includes(line)), + ...(block.audit ?? []).flatMap(({ rows }) => rows.flatMap(({ method, calculation, usage }) => [method, calculation, usage])), + ]).join("\n"), "合盘技法依据的其他文字"); + // 后台原始核验条目照旧保留。 assert.match(JSON.stringify(dossier.execution_receipt), /MEVG/); assert.match(JSON.stringify(dossier.execution_receipt), /Real Case/); }); diff --git a/frontend/tests/server-owned-birth-profile.test.ts b/frontend/tests/server-owned-birth-profile.test.ts index 437249a35..6652904f2 100644 --- a/frontend/tests/server-owned-birth-profile.test.ts +++ b/frontend/tests/server-owned-birth-profile.test.ts @@ -80,7 +80,7 @@ test("a stored chart without a clock cannot be used for synastry", () => { test("daily and synastry routes share a literal account-birth select string", () => { const daily = readFileSync(new URL("../src/app/api/daily-starlanguage/route.ts", import.meta.url), "utf8"); - const synastry = readFileSync(new URL("../src/app/api/synastry/route.ts", import.meta.url), "utf8"); + const synastry = readFileSync(new URL("../src/lib/synastry-full-run.ts", import.meta.url), "utf8"); // 原值:…,uncertainty_after_minutes,declared_window_start,declared_window_end // 新值:uncertainty_after_minutes 后多一列 birth_time_uncertainty_known,其余列与顺序不变 // 原因:issue #144 T4,选了「不清楚误差」的本人,星盘页上升预检只按所填时间算一次,需要读这一列 diff --git a/frontend/tests/synastry-b1-20261114.test.tsx b/frontend/tests/synastry-b1-20261114.test.tsx new file mode 100644 index 000000000..0a548ad6e --- /dev/null +++ b/frontend/tests/synastry-b1-20261114.test.tsx @@ -0,0 +1,97 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { renderToStaticMarkup } from "react-dom/server"; + +import { SynastryReportView } from "../src/components/synastry/synastry-report-view"; +import { buildTechnicalBasis } from "../src/lib/synastry-full-technical"; +import { synastrySectionMaterial } from "../src/lib/synastry-report-material"; + +const oldLink = new URL("../src/components/people-home-links.tsx", import.meta.url); +const retiredRoute = new URL("../src/app/api/synastry/route.ts", import.meta.url); + +test("old links still reach the current pair picker after the scoring route is retired", () => { + assert.match(readFileSync(oldLink, "utf8"), /location\.replace\(`\/synastry\?with=/); + assert.throws(() => readFileSync(retiredRoute), { code: "ENOENT" }); +}); + +test("legacy report snapshots still render the saved appendix", () => { + const html = renderToStaticMarkup(); + assert.match(html, /旧报告正文/); + assert.match(html, /
  • 旧版技法回执<\/li>/); + assert.doesNotMatch(html, / { + const execution = buildTechnicalBasis({ + dossier: { execution_receipt: { + individual_technique_audit: [{ technique: "Tajika Yogas", person_a: { status: "partial" }, person_b: { status: "executed" } }], + pair_execution_tasks: [{ + task: "年度对照", status: "blocked", + required_inputs: [{ status: "blocked", person_a_status: "executed", person_b_status: "blocked", person_b_reason: "solar_day_window_unavailable" }], + }], + } }, + names: { a: "甲", b: "乙" }, contacts: [], timing: [], + }).find(({ id }) => id === "execution"); + assert.equal(execution?.audit?.[0].rows[0].usage, "只作观察"); + assert.equal(execution?.audit?.[1].rows[0].usage, "供写作参考"); + assert.equal(execution?.audit?.[2].rows[0].usage, "未使用。乙方无法确定出生时刻所在的日出日落区间"); +}); + +test("the audit tables distinguish comparison readiness and render verification only in the appendix", () => { + const basis = buildTechnicalBasis({ + dossier: { execution_receipt: { + individual_technique_audit: [{ + technique: "Vivah and other Sahams", + person_a: { status: "parameter_sensitive" }, + person_b: { status: "blocked", reason: "solar_day_window_unavailable" }, + }], + pair_execution_tasks: [{ task: "DK cross-comparison", status: "ready_for_comparison" }], + } }, + names: { a: "甲", b: "乙" }, contacts: [], timing: [], + }); + const execution = basis.find(({ id }) => id === "execution")!; + const html = renderToStaticMarkup(); + const [body, appendix] = html.split('
    '); + assert.match(body, /这里是报告正文/); + assert.doesNotMatch(body, /网上资料核对|真实案例校准/); + assert.match(appendix, /
    方法<\/th>计算<\/th>在本报告中<\/th>/); + assert.match(appendix, /输入已齐<\/td>供写作参考<\/td>/); + assert.match(appendix, /阻塞<\/td>未使用。无法确定出生时刻所在的日出日落区间<\/td>/); + assert.match(appendix, /网上资料核对:未完成[\s\S]*真实案例校准:未完成/); + assert.doesNotMatch(appendix, /_|·|已执行/); +}); + +test("follow-up material includes at most twelve audit rows across both people and the comparison", () => { + const saved = buildTechnicalBasis({ + dossier: { execution_receipt: { + individual_technique_audit: Array.from({ length: 14 }, (_, index) => ({ + technique: `技法 ${index + 1}`, + person_a: { status: "parameter_sensitive", reason: "birth_time_window_varies" }, + person_b: { status: "executed" }, + })), + pair_execution_tasks: [{ task: "宫位对照", status: "ready_for_comparison" }], + } }, + names: { a: "甲", b: "乙" }, contacts: [], timing: [], + }); + const result = synastrySectionMaterial({ payload: { zh: { technical: saved } }, sectionId: "climate", includeTechnical: true }); + const technical = result.technical as { id: string; lines: string[] }[]; + const execution = technical.find(({ id }) => id === "execution")!; + assert.equal(execution.lines.length, 12); + assert.ok(execution.lines.includes("甲方 技法 1:计算 参数敏感,在本报告中 只作观察。出生时间误差内会变")); + assert.ok(execution.lines.includes("乙方 技法 1:计算 已执行,在本报告中 供写作参考")); + assert.ok(execution.lines.includes("两盘对照 宫位对照:计算 输入已齐,在本报告中 供写作参考")); + assert.doesNotMatch(JSON.stringify(result), /网上资料核对|真实案例校准/); + const old = synastrySectionMaterial({ payload: { zh: { technical: [{ + id: "execution", title: "技法执行情况", lines: ["D1/Rashi:已执行", "网上资料核对:未完成", "真实案例校准:未完成"], + }] } }, sectionId: "climate", includeTechnical: true }); + assert.deepEqual(old.technical, [{ id: "execution", title: "技法执行情况", lines: ["D1/Rashi:已执行"] }]); +}); diff --git a/frontend/tests/synastry-chart-skip.test.ts b/frontend/tests/synastry-chart-skip.test.ts deleted file mode 100644 index ffc03949b..000000000 --- a/frontend/tests/synastry-chart-skip.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import assert from "node:assert/strict"; -import { spawnSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; - -const frontendRoot = fileURLToPath(new URL("../", import.meta.url)); -const partnerId = "11111111-1111-4111-8111-111111111111"; - -function runRoute(script: string): { romance: Record; business: Record; maxChart: number; maxVarga: number; chartSkip: boolean } { - const result = spawnSync(process.execPath, [ - "--experimental-test-module-mocks", - "--import", - "tsx", - "--input-type=module", - "--eval", - script, - ], { cwd: frontendRoot, encoding: "utf8", timeout: 20000 }); - assert.equal(result.status, 0, result.stderr || result.stdout); - const line = result.stdout.trim().split("\n").at(-1) ?? "{}"; - return JSON.parse(line); -} - -test("synastry charts send skip concurrently and keep the stubbed JSON", () => { - const script = String.raw` - import { mock } from "node:test"; - import { pathToFileURL } from "node:url"; - const moduleUrl = (path) => pathToFileURL(process.cwd() + "/" + path).href; - mock.module("server-only", { namedExports: {} }); - mock.module("@/lib/account-deletion-server", { namedExports: { refuseWhenAccountDeletionPending: async () => null } }); - mock.module("@/lib/product-access", { namedExports: { isProductEnabled: async () => true } }); - mock.module("@/lib/request-rate-limit", { namedExports: { consumeUserRequestRateLimit: () => ({ ok: true, retryAfterSeconds: 1 }) } }); - mock.module("@/lib/supabase/server", { namedExports: { createServerSupabaseClient: async () => ({ auth: { getUser: async () => ({ data: { user: { id: "user-1" } }, error: null }) } }) } }); - mock.module("@/lib/subject-birth", { namedExports: { - ConsultationSubjectError: class ConsultationSubjectError extends Error {}, - loadSubjectBirth: async () => ({ chartable: true, row: { name: "fixture" } }), - } }); - mock.module("@/lib/server-owned-birth-profile", { namedExports: { globalBirthProfileFromAccountRow: (row) => row } }); - mock.module("@/lib/global-birth-payloads", { namedExports: { - synastryBirthPayload: async () => ({ year: 1990, month: 1, day: 1, hour: 12, minute: 0, lat: 28.6139, lon: 77.209, tz: 5.5, ayanamsa: "lahiri" }), - } }); - const chartBodies = []; - const maxInflight = { chart: 0, varga: 0 }; - const inflight = { chart: 0, varga: 0 }; - const waiters = { chart: [], varga: [] }; - globalThis.fetch = async (inputUrl, init) => { - const url = String(inputUrl); - const body = JSON.parse(String(init.body)); - const kind = url.endsWith("/api/chart") ? "chart" : url.endsWith("/api/varga_full") ? "varga" : "other"; - if (kind === "chart") chartBodies.push(body); - if (kind === "chart" || kind === "varga") { - inflight[kind] += 1; - maxInflight[kind] = Math.max(maxInflight[kind], inflight[kind]); - await new Promise((resolve) => { - waiters[kind].push(resolve); - if (waiters[kind].length >= 2) { - const pending = waiters[kind].splice(0, 2); - pending.forEach((fn) => fn()); - } - }); - inflight[kind] -= 1; - } - if (url.endsWith("/api/chart")) { - return Response.json({ - planets: { Moon: { lon: 12.5, sign: "Aries", nakshatra: "Ashwini", nakshatra_pada: 1, nakshatra_lord: "Ketu" } }, - ascendant: { sign: "Leo" }, - }); - } - if (url.endsWith("/api/varga_full")) { - const divisions = body.divisions || []; - if (divisions.includes("D9")) { - return Response.json({ source: "engine", result: { D9_Navamsa: { ascendant: { sign: "Virgo" }, planets: { Moon: { sign: "Cancer" }, Venus: { sign: "Taurus" }, Mars: { sign: "Aries" } } } } }); - } - return Response.json({ source: "engine", result: { - D2_Hora: { planets: { Moon: { sign: "Taurus" } } }, - D10_Dasamsa: { ascendant: { sign: "Libra" } }, - D11_Rudramsa: { planets: { Sun: { sign: "Capricorn" } } }, - } }); - } - if (url.endsWith("/api/synastry")) return Response.json({ total_score: 18, max_score: 36 }); - return Response.json({}, { status: 500 }); - }; - const { POST } = await import(moduleUrl("src/app/api/synastry/route.ts")); - const romanceRes = await POST(new Request("https://example.test/api/synastry", { method: "POST", body: JSON.stringify({ partnerChartProfileId: "${partnerId}", relationshipType: "romance" }) })); - const romance = await romanceRes.json(); - const businessRes = await POST(new Request("https://example.test/api/synastry", { method: "POST", body: JSON.stringify({ partnerChartProfileId: "${partnerId}", relationshipType: "business" }) })); - const business = await businessRes.json(); - console.log(JSON.stringify({ romance, business, maxChart: maxInflight.chart, maxVarga: maxInflight.varga, chartSkip: chartBodies.every((body) => body.skip_vedastro_main_entry_overview === true) && chartBodies.length === 4 })); - `; - const got = runRoute(script); - assert.equal(got.maxChart, 2); - assert.equal(got.maxVarga, 2); - assert.equal(got.chartSkip, true); - assert.equal(got.romance.status, "ok"); - assert.equal(got.romance.method, "ashtakoot_plus_moon_nakshatra_d9"); - assert.deepEqual(got.romance.selfChart, { - moon: { sign: "Aries", nakshatra: "Ashwini", pada: 1, lord: "Ketu", longitude: 12.5 }, - d9: { ascendant: { sign: "Virgo" }, moon: { sign: "Cancer" }, venus: { sign: "Taurus" }, mars: { sign: "Aries" }, source: "engine" }, - }); - assert.equal((got.romance.relationshipReport as { scoreBand?: string }).scoreBand, "mixed"); - assert.equal(got.business.status, "ok"); - assert.equal(got.business.method, "d2_d10_d11_business_screening_partial"); - assert.equal((got.business.relationshipReport as { scoreBand?: string }).scoreBand, "not_scored"); -}); diff --git a/frontend/tests/synastry-full-report.test.ts b/frontend/tests/synastry-full-report.test.ts index ed79c0875..de9d63b14 100644 --- a/frontend/tests/synastry-full-report.test.ts +++ b/frontend/tests/synastry-full-report.test.ts @@ -156,10 +156,7 @@ test("technical appendix has six program blocks and the fixed closing line", () timing: ["甲:木星大运 2026-01 至 2028-01"], }); assert.deepEqual(blocks.map((block) => block.id), ["parameters", "structures", "contacts", "timing", "traditional", "execution"]); - // 原值:blocks[5].lines 末尾是「外部资料与真实案例核对:未进行,本报告是计算层归纳」 - // 新值:该行删除,执行情况只留回执里的技法依据 - // 原因:产品负责人 2026-11-08:用户可见文字不出现联网/外部核验字样,后台保留 - assert.equal(blocks[5]?.lines.some((line) => line.includes("外部资料")), false); + assert.deepEqual(blocks[5]?.lines, ["网上资料核对:未完成", "真实案例校准:未完成"]); assert.equal(JSON.stringify(blocks).includes("1879"), false); }); @@ -515,7 +512,9 @@ test("technical execution lines follow the receipt and raman is named", () => { contacts: [], timing: [], }); - assert.deepEqual(blocks[5]?.lines.slice(0, 2), ["Niryaana Shoola:不适用", "DK cross-comparison:已执行"]); + assert.deepEqual(blocks[5]?.audit?.map(({ title }) => title), ["甲方", "乙方", "两盘对照"]); + assert.equal(blocks[5]?.audit?.[0].rows[0].calculation, "不适用"); + assert.deepEqual(blocks[5]?.audit?.[2].rows[0], { method: "DK cross-comparison", calculation: "输入已齐", usage: "供写作参考" }); assert.match(blocks[1]?.lines[0] ?? "", /DK Venus/); // 2026-11-07 原值:/raman_muhurtha_v1/(原样显示规则 id)。新值:显示中文口径说明。 // 原因:BUG-1679,传统配对块改成读真实字段并写成中文;Raman 仍然单独点名。 @@ -581,7 +580,9 @@ test("BUG-1679: parameters and traditional matching read the dossier's real shap assert.match(traditional, /Raman 口径,甲 火星凶位/); assert.doesNotMatch(traditional, /36|百分|%/); assert.equal(JSON.stringify([blocks[0], blocks[4]]).includes("未标明"), false); - assert.deepEqual(blocks[5]?.lines.slice(0, 1), ["Vivah and other Sahams:无法计算"]); + assert.deepEqual(blocks[5]?.audit?.[1].rows[0], { + method: "Vivah and other Sahams", calculation: "阻塞", usage: "未使用。回执没有可用的计算结果", + }); }); function pythonBin(): string | null { @@ -684,40 +685,18 @@ test("a public pair dossier fills every section without birth keys", { timeout: individual_technique_audit?: Array>; pair_execution_tasks?: Array>; }; - const statusText: Record = { - executed: "已执行", - ready_for_comparison: "已执行", - present: "已执行", - used: "已执行", - available: "已执行", - passed: "已执行", - parameter_sensitive: "参数敏感", - partial: "参数敏感", - weak: "参数敏感", - observation_only: "参数敏感", - not_applicable: "不适用", - not_used: "不适用", - not_used_for_date_intersection: "不适用", - // 2026-11-07 新增:blocked / not_available 显示「无法计算」,原来露出英文原词(BUG-1679)。 - blocked: "无法计算", - not_available: "无法计算", - }; - const receiptRows = [...(receipt.individual_technique_audit ?? []), ...(receipt.pair_execution_tasks ?? [])]; - const executionLines = blocks[5]?.lines ?? []; - let namedRows = 0; - for (const row of receiptRows) { - const name = String(row.technique || row.task || row.label || row.lane || "").trim(); - const status = String(row.status || "").trim(); - if (!name || !status) continue; - const shown = statusText[status.toLowerCase()] ?? status; - assert.equal(executionLines.some((line) => line.includes(name) && line.includes(shown)), true, `${name} ${shown}`); - namedRows += 1; + const execution = blocks[5]; + const groups = execution?.audit ?? []; + assert.deepEqual(groups.map(({ title }) => title), ["甲方", "乙方", "两盘对照"]); + assert.equal(groups[0].rows.length, receipt.individual_technique_audit?.length); + assert.equal(groups[1].rows.length, receipt.individual_technique_audit?.length); + assert.equal(groups[2].rows.length, receipt.pair_execution_tasks?.length); + assert.deepEqual(execution?.lines, ["网上资料核对:未完成", "真实案例校准:未完成"]); + assert.ok(groups[2].rows.some((row) => row.calculation === "输入已齐" && row.usage === "供写作参考")); + for (const row of groups.flatMap(({ rows }) => [...rows])) { + assert.doesNotMatch(Object.values(row).join(" "), /[·_]|ready_for_comparison/); + if (["阻塞", "不适用"].includes(row.calculation)) assert.match(row.usage, /^未使用。.+/); } - assert.ok(namedRows > 0); - // 原值:executionLines 末尾是「外部资料与真实案例核对:未进行,本报告是计算层归纳」 - // 新值:该行删除 - // 原因:产品负责人 2026-11-08:用户可见文字不出现联网/外部核验字样,后台保留 - assert.equal(executionLines.some((line) => line.includes("外部资料")), false); const structures = dossier.local_structures as Record>; for (const person of ["person_a", "person_b"]) { const local = structures[person] ?? {}; diff --git a/frontend/tests/synastry-precision-20261114.test.tsx b/frontend/tests/synastry-precision-20261114.test.tsx index 3eb4d5423..c8ae694b3 100644 --- a/frontend/tests/synastry-precision-20261114.test.tsx +++ b/frontend/tests/synastry-precision-20261114.test.tsx @@ -6,7 +6,7 @@ import { renderToStaticMarkup } from "react-dom/server"; import { SynastryReportView } from "../src/components/synastry/synastry-report-view"; import { loadSynastrySubjectBirth, marriageMatchBirthBody, marriageMatchFingerprint } from "../src/lib/marriage-match-service"; import { sectionEvidence, SYNASTRY_SECTION_IDS, systemPrompt } from "../src/lib/synastry-full-sections"; -import { buildTechnicalBasis } from "../src/lib/synastry-full-technical"; +import { buildTechnicalBasis, currentSynastryTechnicalBlocks } from "../src/lib/synastry-full-technical"; const stable = { D1: { status: "stable" }, D9: { status: "stable" }, moon: { status: "stable" } }; const person = { window_label: "没有误差信息,按前后各 30 分钟", axes: stable, affected_layers: [] }; @@ -15,6 +15,9 @@ const receipt = { technique: "D1/Rashi", status: "parameter_sensitive", person_a: { status: "parameter_sensitive", reason: "birth_time_window_varies" }, person_b: { status: "executed" }, }], + pair_execution_tasks: [{ + task: "宫位对照", status: "parameter_sensitive", reason: "birth_time_window_varies", + }], }; const changed = { execution_receipt: receipt, @@ -57,8 +60,22 @@ test("the appendix renders window sources, Chinese candidates and only the affec assert.match(appendix, /甲方出生时间误差:没有误差信息,按前后各 30 分钟/); assert.match(appendix, /水瓶座(档案时刻)、双鱼座(偏晚约 12 分钟)/); assert.match(appendix, /乙方出生时间误差[^<]*本命上升误差内稳定/); - assert.match(appendix, /甲方 D1\/Rashi<\/td>参数敏感<\/td>出生时间误差内会变/); - assert.doesNotMatch(appendix, /乙方 D1|[·_]/); + assert.match(appendix, /

    甲方<\/h4>[\s\S]*?

    D1\/Rashi<\/td>参数敏感<\/td>只作观察。出生时间误差内会变<\/td>/); + assert.match(appendix, /

    乙方<\/h4>[\s\S]*?

    D1\/Rashi<\/td>已执行<\/td>供写作参考<\/td>/); + assert.match(appendix, /

    两盘对照<\/h4>[\s\S]*?

    宫位对照<\/td>参数敏感<\/td>只作观察。出生时间误差内会变<\/td>/); + assert.equal(appendix.match(/ { + const saved = { + id: "execution" as const, title: "技法执行情况", lines: ["D1/Rashi:参数敏感"], precisionAudit: [], + }; + const execution = currentSynastryTechnicalBlocks([saved], changed)?.[0]; + assert.deepEqual(execution?.audit, buildTechnicalBasis({ + dossier: changed, names: { a: "甲", b: "乙" }, contacts: [], timing: [], + }).find(({ id }) => id === "execution")?.audit); + assert.ok(execution && !Object.hasOwn(execution, "precisionAudit")); }); test("the request reuses the reported and adopted windows", () => { diff --git a/scripts/consult_full_data_cache.py b/scripts/consult_full_data_cache.py index 7439a3adf..65baa62ca 100644 --- a/scripts/consult_full_data_cache.py +++ b/scripts/consult_full_data_cache.py @@ -23,7 +23,9 @@ from typing import Any, Callable ROOT = Path(__file__).resolve().parents[1] # 原值 v2;新值 v3;原因:BUG-1601 Narayana 默认换成 Sanjay Rath,旧缓存里是旧算法默认(引擎版本号未变) # 原值 v3;新值 v4;原因:BUG-1699 全读加了 Chesta 候选、AV score_fields 与 career_analysis,旧包里没有 -CACHE_SCHEMA = "consult-full-data-cache-v4" +# v4: report reference identity without a shared schema marker for pair dossiers. +# v5: the pair dossier uses this schema and includes both calculation dates. +CACHE_SCHEMA = "consult-full-data-cache-v5" SLOW_MISS_SECONDS = 20.0 KEEP_SECONDS = 2 * 24 * 60 * 60 diff --git a/scripts/marriage_match_service/api.py b/scripts/marriage_match_service/api.py index 12857b20e..55db339e8 100644 --- a/scripts/marriage_match_service/api.py +++ b/scripts/marriage_match_service/api.py @@ -1,6 +1,6 @@ """HTTP-facing marriage match and full synastry dossier. -The dossier endpoint caches on the two birth payloads plus ``GITHUB_SHA``, +The dossier endpoint caches on both births, calculation dates and ``GITHUB_SHA``, the same scratch helper the report reference cache uses. A missing or ``unknown`` commit id skips the cache. """ @@ -73,6 +73,7 @@ def _birth_identity(body: dict[str, Any]) -> dict[str, Any]: "ayanamsa": body.get("ayanamsa", "lahiri"), "node_mode": node or "mean", "birth_precision_window": normalized_birth_window(body), + "today": body.get("today"), } @@ -104,11 +105,19 @@ def _narayana_profile_config() -> dict[str, str]: return dict(nr.DEFAULT_STEP_PROFILES) +def _calculation_date(person: dict[str, Any], fallback: str) -> str: + day = person.get("today") or person.get("current_date") + return day.strip()[:10] if isinstance(day, str) and day.strip() else fallback + + def compute_synastry_full_dossier(handler: Any, body: dict[str, Any]) -> dict[str, Any]: if not isinstance(body, dict): raise MarriageMatchInputError("request body must be an object") person_a = _birth(body.get("person_a"), "person_a") person_b = _birth(body.get("person_b"), "person_b") + pair_date = _calculation_date(person_a, "") or _calculation_date(person_b, "") or _cache.reference_date_from_body({}) + person_a = {**person_a, "today": _calculation_date(person_a, pair_date)} + person_b = {**person_b, "today": _calculation_date(person_b, pair_date)} sha = _commit_sha() def build(_identity: dict[str, Any]) -> dict[str, Any]: @@ -118,6 +127,7 @@ def compute_synastry_full_dossier(handler: Any, body: dict[str, Any]) -> dict[st return build({}) cached = _cache.get_or_build( { + "schema": _cache.CACHE_SCHEMA, "person_a": _birth_identity(person_a), "person_b": _birth_identity(person_b), "github_sha": sha, diff --git a/scripts/marriage_match_service/full_dossier.py b/scripts/marriage_match_service/full_dossier.py index 173a1b53d..136376d65 100644 --- a/scripts/marriage_match_service/full_dossier.py +++ b/scripts/marriage_match_service/full_dossier.py @@ -718,6 +718,42 @@ def reading_scope(dossier: dict[str, Any]) -> dict[str, Any]: "rule": "both chart profiles match and every primary pair lane is comparable"} +def _saham_block_reason(reading: dict[str, Any]) -> str | None: + packet = _reading_packet(reading) + modules = packet.get("modules") + module = modules.get("sahams") if isinstance(modules, dict) else None + if isinstance(module, dict) and module.get("reason"): + return str(module["reason"]) + for error in packet.get("errors") or []: + if isinstance(error, str) and error.startswith("tajika-yogas+sahams:"): + for reason in ("solar_day_window_unavailable", "sunrise_or_sunset_unavailable_for_location_date"): + if reason in error: + return reason + return "saham_calculation_failed" + if not module or (isinstance(module, dict) and module.get("warning")): + return "saham_inputs_unavailable" + return None + + +def _add_saham_receipt_reasons(dossier: dict[str, Any], readings: dict[str, Any]) -> None: + receipt = dossier.get("execution_receipt") or {} + reasons = {side: _saham_block_reason(reading) for side, reading in readings.items() if isinstance(reading, dict)} + for row in receipt.get("individual_technique_audit", []): + if row.get("technique") != "Vivah and other Sahams": + continue + for side, reason in reasons.items(): + person = row.get(side) or {} + if reason and person.get("status") == "blocked": + person["reason"] = reason + for row in receipt.get("pair_execution_tasks", []): + for item in row.get("required_inputs", []): + if item.get("source_path") != "modules.sahams": + continue + for side, reason in reasons.items(): + if reason and item.get(f"{side}_status") == "blocked": + item[f"{side}_reason"] = reason + + def build_synastry_full_dossier( handler: Any, person_a: dict[str, Any], @@ -735,6 +771,7 @@ def build_synastry_full_dossier( reading_b = future_b.result() dossier = _dossier_builder()(reading_a, reading_b) if isinstance(dossier, dict): + _add_saham_receipt_reasons(dossier, {"person_a": reading_a, "person_b": reading_b}) dossier["local_structures"] = { "person_a": relationship_structure(reading_a if isinstance(reading_a, dict) else {}), "person_b": relationship_structure(reading_b if isinstance(reading_b, dict) else {}), diff --git a/tests/test_supabase_user_data_contract.py b/tests/test_supabase_user_data_contract.py index 620fd217c..f4c6333a1 100644 --- a/tests/test_supabase_user_data_contract.py +++ b/tests/test_supabase_user_data_contract.py @@ -66,7 +66,6 @@ OPTIONAL_HOME_HOOKS = ( # 状态下沉把合盘从 page.tsx 搬进了自己的 hook(2026-09-16)。首页表面是这 # 些文件的并集,新 hook 不进这张白名单,下面的合盘断言就会在代码完全正确 # 的情况下变红。新增 Home 级 hook 时必须同步加进来。 - _FRONTEND_SRC / "hooks" / "use-synastry.ts", _FRONTEND_SRC / "hooks" / "use-session-list.ts", _FRONTEND_SRC / "hooks" / "use-home-shell-registration.ts", _FRONTEND_SRC / "lib" / "session-list-context.tsx", @@ -85,7 +84,6 @@ SESSION_ITEM_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / ACCOUNT_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / "app" / "api" / "account" / "route.ts" CHART_PROFILE_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / "app" / "api" / "chart-profiles" / "route.ts" CHART_PROFILE_DELETE_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / "app" / "api" / "chart-profiles" / "[id]" / "route.ts" -SYNASTRY_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / "app" / "api" / "synastry" / "route.ts" SYNASTRY_REPORT_ROUTE = Path(__file__).resolve().parents[1] / "frontend" / "src" / "app" / "api" / "synastry-reports" / "route.ts" @@ -271,16 +269,10 @@ def test_chart_profile_library_has_cloud_table_api_and_local_fallback() -> None: "fetchCloudChartLibrary", "saveCloudChartProfile", "deleteCloudChartProfile", - "buildSynastryQuestion", - "draftSynastryQuestionFromChart", - "synastryReportCard", - "synastryHistory", "discardLegacyCloudMirrorKeys", # 原值 / 新值 / 原因:退役面板样式 / 人物详情与带用量的删除 / 锁实际 /people 入口。 "people-archive-detail", "pendingDelete", - 'fetch("/api/synastry"', - "Ashtakoot", "jyotisha_chart_library", "保存失败,请重试", # 原值:首页相关源码必须出现「星盘库」。 @@ -304,35 +296,10 @@ def test_chart_profile_library_has_cloud_table_api_and_local_fallback() -> None: assert "ayanam-sessions" not in page -def test_synastry_route_orchestrates_python_chart_and_ashtakoot() -> None: - route = SYNASTRY_ROUTE.read_text(encoding="utf-8") - for token in ( - 'const apiBase = process.env.JYOTISH_API_BASE ?? "http://127.0.0.1:5200"', - # 原值: postPython("/api/chart", selfPayload) 与 postPython("/api/chart", partnerPayload) - # 新值: 两次调用都展开对应 payload,并带 skip_vedastro_main_entry_overview: true - # 原因: 合盘改为同时排本人和对方两张盘,并关掉用不上的外部概览。断言仍锁住这两次 /api/chart,同时锁住这个开关,不放宽。 - 'postPython("/api/chart", { ...selfPayload, skip_vedastro_main_entry_overview: true })', - 'postPython("/api/chart", { ...partnerPayload, skip_vedastro_main_entry_overview: true })', - 'postPython("/api/varga_full"', - 'postPython("/api/synastry"', - "moonLongitude(selfChart)", - "moonSummary(selfChart)", - "d9Summary(selfD9)", - "relationshipReport", - "scoreBand", - "nextEvidence", - "ashtakoot_plus_moon_nakshatra_d9", - 'evidenceLayers: ["ashtakoot", "moon_nakshatra", "d9_navamsa"]', - 'status: "blocked"', - "synastryBirthPayload", - ): - assert token in route - - def test_synastry_reports_are_cloud_persisted_per_user() -> None: sql = re.sub(r"\s+", " ", SYNASTRY_REPORT_MIGRATION.read_text(encoding="utf-8").lower()).strip() route = SYNASTRY_REPORT_ROUTE.read_text(encoding="utf-8") - page = _home_surface() + source = (_FRONTEND_SRC / "lib" / "home-cloud-sync.ts").read_text(encoding="utf-8") for token in ( "create table if not exists public.synastry_reports", @@ -362,14 +329,12 @@ def test_synastry_reports_are_cloud_persisted_per_user() -> None: "fetchCloudSynastryHistory", "saveCloudSynastryReport", 'fetch("/api/synastry-reports"', - "未能存入历史", "cloud_synastry_history_unavailable", "cloud_synastry_report_save_failed", ): - assert token in page - # Former value: writeSynastryHistory(accountId, next) wrote a local - # history copy when cloud save failed. - assert "writeSynastryHistory(accountId, next)" not in page + assert token in source + # Legacy synastry records still persist on the guarded server route. + assert "writeSynastryHistory(accountId, next)" not in _home_surface() def test_consultation_credit_lifecycle_is_idempotent_and_server_only() -> None: diff --git a/tests/test_synastry_b1_20261114.py b/tests/test_synastry_b1_20261114.py new file mode 100644 index 000000000..751633547 --- /dev/null +++ b/tests/test_synastry_b1_20261114.py @@ -0,0 +1,45 @@ +"""Synastry dossier date identity and the Saham reason in the upstream receipt.""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) + +from marriage_match_service import api, full_dossier + + +def test_dossier_cache_changes_each_day_and_keeps_dates_used_by_native_calculation(monkeypatch): + birth = {"year": 1990, "month": 6, "day": 15, "hour": 12, "minute": 0, "lat": 40, "lon": 116, "tz": 8} + keys = [] + + def cache(identity, build, *, cache_name): + keys.append(identity) + return {"packet": build(identity)} + + monkeypatch.setattr(api, "_commit_sha", lambda: "example-commit") + monkeypatch.setattr(api._cache, "get_or_build", cache) + monkeypatch.setattr(api, "build_synastry_full_dossier", lambda _, a, b: {"dates": [a["today"], b["today"]]}) + for day in ("2026-11-14", "2026-11-15"): + result = api.compute_synastry_full_dossier(None, {"person_a": {**birth, "today": day}, "person_b": birth}) + assert keys[-1]["schema"] == api._cache.CACHE_SCHEMA + assert [keys[-1][side]["today"] for side in ("person_a", "person_b")] == result["dates"] == [day, day] + assert keys[0] != keys[1] + + +def test_native_saham_failure_stays_blocked_and_keeps_its_reason_on_the_affected_side(): + # The upstream validator emits per-person and pair states but drops the calculation error. + receipt = { + "individual_technique_audit": [{ + "technique": "Vivah and other Sahams", "person_a": {"status": "parameter_sensitive"}, "person_b": {"status": "blocked"}, + }], + "pair_execution_tasks": [{"required_inputs": [{ + "source_path": "modules.sahams", "status": "blocked", "person_a_status": "parameter_sensitive", "person_b_status": "blocked", + }]}], + } + a = {"modules": {"sahams": {"status": "partial", "vivah_saham": {"sign": "Aries"}}}} + b = {"modules": {}, "errors": ["tajika-yogas+sahams: solar_day_window_unavailable"]} + full_dossier._add_saham_receipt_reasons({"execution_receipt": receipt}, {"person_a": a, "person_b": b}) + row = receipt["individual_technique_audit"][0] + assert row["person_a"] == {"status": "parameter_sensitive"} + assert row["person_b"] == {"status": "blocked", "reason": "solar_day_window_unavailable"} + assert receipt["pair_execution_tasks"][0]["required_inputs"][0]["person_b_reason"] == "solar_day_window_unavailable" diff --git a/tests/test_synastry_full_dossier.py b/tests/test_synastry_full_dossier.py index b7162a18e..7166c8e06 100644 --- a/tests/test_synastry_full_dossier.py +++ b/tests/test_synastry_full_dossier.py @@ -18,15 +18,16 @@ from marriage_match_service.full_dossier import build_synastry_full_dossier, rel FIXTURE = ROOT / "frontend" / "tests" / "fixtures" / "synastry-full-dossier-truncated.json" # Public Rodden-rated charts already used by tests/verify_jyotish_v6_1.py. -# Times are the UT hours stored there, passed with tz 0. +# The first time uses UT. For the second chart use the same instant in local +# civil time so the native Saham sunrise function can bracket the local day. EINSTEIN = { "year": 1879, "month": 3, "day": 14, "hour": 10, "minute": 30, "second": 0, "lat": 48.4, "lon": 10.0, "tz": 0, "ayanamsa": "lahiri", "node_mode": "mean", "today": "2026-10-18", } JOBS = { - "year": 1955, "month": 2, "day": 25, "hour": 3, "minute": 15, "second": 0, - "lat": 37.77, "lon": -122.42, "tz": 0, "ayanamsa": "lahiri", "node_mode": "mean", + "year": 1955, "month": 2, "day": 24, "hour": 19, "minute": 15, "second": 0, + "lat": 37.77, "lon": -122.42, "tz": -8, "ayanamsa": "lahiri", "node_mode": "mean", "today": "2026-10-18", } @@ -143,6 +144,12 @@ def test_public_pair_dossier_reading_scope_follows_upstream_readiness(): "person_a": ["stable", "varies", "stable"], "person_b": ["varies", "varies", "stable"], } assert tasks[timing] == "parameter_sensitive" + + sahams = next(row for row in dossier["execution_receipt"]["individual_technique_audit"] + if row["technique"] == "Vivah and other Sahams") + for side in ("person_a", "person_b"): + assert sahams[side]["source_path"] == "modules.sahams" + assert sahams[side]["status"] == "parameter_sensitive" assert dossier["delivery_readiness"] == "ready_for_narrative" assert dossier["reading_scope"]["status"] == "full" assert dossier["ayanamsa_alignment"]["status"] == "same_profile"