#313 报告标示出生输入变化与自选情景 #319

Merged
Claude merged 6 commits from codex/rect-artifact-marking-20261117 into staging 2026-11-17 16:37:34 +08:00
34 changed files with 803 additions and 46 deletions
+4
View File
@@ -1,5 +1,9 @@
# 印度占星 Skill 更新日志
## 2026-11-17 · 报告标示出生时间变化与自选情景
- 个人报告、年运和合盘的正文顶部及 Markdown 导出显示相关说明。生成中出生资料变化时提示点数已返还。占星 Skill 版本沿用(BUG-1959)。
## 2026-11-17 · 聊天保留旧回答并标明出生依据变化
- 下一轮按当前出生输入判断,旧回答的判断依据只在页面保留。Skill 版本沿用(BUG-1960)。
+11
View File
@@ -26322,6 +26322,17 @@
- 关联记录:BUG-1936、BUG-1952、BUG-1956。
- 修复版本:`codex/rect-self-choice-scenario-20261117`。
## BUG-1959 | 历史报告和导出缺少出生输入标示,合盘写入前没有复核双方版本
- 状态:fixed-pending-verify,待独立验收。
- 首次发现 / 最近更新:2026-11-17 / 2026-11-17。
- 触发与现象:改过出生输入后打开或导出长报告、年运或合盘,读者看不到历史依据。自选情景生成的产物没有留下选边和变化领域。完整合盘写作途中任一方改资料,启动时的复核无法阻挡最终快照写入。
- 根因:版本状态停在接口和导出块元数据,生成数据缺少情景和当时范围的公开摘要;合盘只在计算开始前读取双方版本。
- 修复:三种报告详情和 Markdown 使用保存的版本、情景与范围摘要;详情的重新生成文字链接复用现有入口。合盘写入前核对双方,变化时沿用一次性失败和返还路径。没有绑定版本的旧任务沿用原路径。
- 验证与防复发:合成回归覆盖三类详情与导出、旧导出字节保持、三种选边、两方说明、写入顺序与返还。见 [#313 进度](tasks/PROGRESS-rect-artifact-marking-20261117.md)。
- 关联记录:#310、#312、#313、BUG-1936、BUG-1956、BUG-1958。
- 修复版本:`codex/rect-artifact-marking-20261117`。
## BUG-1960 | 出生输入改动后,聊天继续沿用旧回答的盘面依据
- 状态:fixed-pending-verify,待独立验收。
@@ -23,10 +23,10 @@
- 首页暖启动和已交付历史聊天内容可能保留上一次投影或当时的计算依据。
- 星盘缓存按有效计算输入复用,来源撤回而有效时刻相同时缺少专门的回归证据。
## 11-17 之后(#310)
## 11-17 之后(#310、#313、#314)
1. 长报告、年运及完整合盘的新增快照保存生成版本,详情与报告列表核对当前投影。旧产物返回 `unknown`,页面如何标示待定。
1. 长报告、年运及完整合盘的新增快照保存生成版本,详情与报告列表核对当前投影。详情在出生输入变化时提示重新生成,自选情景单独说明。旧产物返回 `unknown`,保持原有展示。
2. 同主体同周期年运仅复用同版本的在途任务。续跑或提交时发现版本变化的长报告和年运进入原有失败及返还流程。年运可继续阅读历史结果并查到核对状态。
3. 未绑定的旧独立合盘记录返回 `unknown`。长报告、年运及合盘输出携带核对元数据。导出正文标示、聊天导出和已下载文件仍有缺口。
3. 未绑定的旧独立合盘记录返回 `unknown`。长报告、年运及合盘输出携带核对元数据。三类报告的 Markdown 正文已标示变化与自选情景。出生时间范围只使用产物保存的值。已下载文件无法回收,聊天导出另有任务。
4. 首页暖启动和今日卡按版本核对,较晚回来的已失效请求不能覆盖新档案。历史聊天原文和旧取数卡保留。BUG-1960 已给新回答绑定出生输入版本;下一轮读取到已知过期回答时仅保留带说明的正文,不将旧「判断依据」交给模型。历史页面按读时版本显示分隔。旧聊天导出和真实模型抽查仍待处理。
5. 星盘沿用数值盘体缓存,状态、范围及来源取当前投影,客户端按版本替换数据。同分钟撤回及再次自选有合成回归,真实浏览器走查待验收。
@@ -0,0 +1,33 @@
# #313 报告出生输入标示
- 任务书 [TASK-rect-artifact-marking-20261117.md](TASK-rect-artifact-marking-20261117.md)
- 分支 `codex/rect-artifact-marking-20261117`,代码基线 `origin/staging` 的 `f8d9e0dc1`。
## 实现
- 个人报告、年运和完整合盘在标题下方说明历史出生输入变化与自选情景,重新生成文字链接指向原有入口。
- 导出在一级标题之后插入说明。个人报告和年运只使用生成时随产物保存的时刻和范围。完整合盘按已存展示顺序分别说明双方的情景。
- 合盘在写最终快照前重新读取并核对双方的版本,匹配才写入;旧任务没有版本时沿用现有路径。资料变化复用原有失败及点数返还路径,页面说明具体原因。
## 验证
- 仓库跟踪文件的 Linux 容器运行 Python 快速门(`--profile quick --skip-frontend-runtime`)通过。隐私标记测试 62 项通过。
- 定向套件 161 项通过,另复跑个人报告 API、版本绑定和新标示三组测试共 81 项通过。覆盖三类详情与导出、旧产物字节保持、三种自选情景及领域、合盘最终写入与点数返还。
- TypeScript 检查通过,ESLint 0 错误、63 条既有警告。前端全量在测试进程内禁用 Docker 自动探测,以同样条件对照 Windows 的 `origin/staging`。基线 3976 项,47 失败、40 跳过。变更后 3982 项,46 失败、40 跳过,取消 0 项,无新增失败或丢失的用例。少一个失败为聊天回答时限用例,此单没有修改该用例。
- Next.js 生产构建通过,`/` 保持静态。首页脚本 gzip 合计 529067 字节,与基线一致。
- Docker 隔离 PostgreSQL 的合盘、租约过期与点数返还测试 4 项通过。
- 三类报告页面的有标示与无标示真人走查留给独立验收。
### 既有断言变更
| 原值 | 新值 | 原因 |
| --- | --- | --- |
| `changed` 的导出拼接结果与原 Markdown 完全相同 | 原正文块仍逐字相同,拼接结果只在标题后多一段精确的变化说明 | #313 要求导出显示历史依据。无标示的产物仍按字节比较。 |
| 报告生成合同要求写入输入版本后通过规范服务端校验 | 合同要求写入输入版本及可选自选情景后通过同一个规范服务端校验 | 两类元数据同位置保存,保留同一校验边界。 |
## 已知边界
- 用户已下载的文件由用户保存,服务器无法更改。
- 聊天导出由 #314 独立处理。
- 报告正文仍按生成时采用的时刻写作。自选情景和变化领域集中在顶部说明。
- 历史产物缺少版本时返回 `unknown`,页面和导出保持原样。按任务书,生产尚无这批新标示的存量,无需回填。
+1
View File
@@ -7,6 +7,7 @@
- 被环境或依赖挡住的事项写进根目录 `BLOCKED.md`;Bug 事实写进 `docs/BUG_HISTORY.md`;两者不在这里重复。
- 纯文档改动不触发 staging 门禁(见 `deploy/gated-paths.txt`)。
- [报告出生输入标示(#313)](PROGRESS-rect-artifact-marking-20261117.md) — 详情、Markdown 导出、合盘写入复核及返还。
- [旧聊天出生依据过期(#314)](PROGRESS-rect-stale-chat-evidence-20261117.md) — 历史上下文、摘要与聊天分隔。
- [生时纠正用户自选情景(#312)](PROGRESS-rect-self-choice-scenario-20261117.md) — 换座列表、保存重放校验及聊天口径。
- [出生输入版本与报告核对(#310)](PROGRESS-rect-birth-input-revision-20261117.md) — 生成、读取、导出元数据及缓存验证。
@@ -0,0 +1,116 @@
# 生时纠正 P0:出生时间变过的报告和合盘加一行标示,自选情景的报告加一句说明(2026-11-17,Claude)
Bug 编号:BUG-1959。关联 BUG-1956(#310)、BUG-1958(#312)、BUG-1936。
## 背景
#310 已经让报告、年运、合盘记录生成时的出生输入版本,并在读取时给出 `birthInputState`(`current` / `changed` / `unknown`)。页面和导出还没有用它。#312 已经把自选保存成「用户自选情景」,并提供 `isSelfSelectedScenario`、`selfSelectedScenarioSide`(`frontend/src/lib/chart-choice/self-selected-scenario.ts`)。
产品负责人 11-17 的决定:
1. 出生时间变过(`changed`)的报告,打开时显示一行:`这份报告按当时的出生时间生成,可重新生成。` 原文照常能看。
2. **老报告一律不动。** 生产上从没上线过 11 月这套生时纠正,没有存量问题。`unknown`(没有记录版本的旧产物)不显示任何东西。
3. 按用户自选情景生成的报告、年运、导出,开头加一句说明,只出现一次。
4. 自选功能在本单和 #314 验收前不上生产。
## 一、`changed` 的标示
只在 `birthInputState === "changed"` 时显示;`current`、`unknown`、字段缺失都不显示。
| 位置 | 文案 |
|---|---|
| 长报告页(`personal-report-page.tsx`) | `这份报告按当时的出生时间生成,可重新生成。` |
| 年运页(`annual-report-page.tsx`) | `这份年运按当时的出生时间生成,可重新生成。` |
| 完整合盘(`synastry-report-view.tsx`) | `这份合盘按当时两个人的出生时间生成,其中有人的出生时间后来改过,可重新生成。` |
| 报告中心 / 过往列表里的每一项 | 不加文字,不加徽标(列表保持干净;打开后才看到那一行) |
要求:
- 放在报告正文上方、标题下方,普通正文段落,用页面已有的说明段落样式(看该页现有的提示/说明用的类名,沿用,不新造样式、不加图标、不加颜色块)。
- 「可重新生成」不做成新按钮:长报告和年运页上已有回到报告中心重新生成的入口(`返回报告中心重新生成` 等),这一行里的「重新生成」做成指向同一入口的文字链接;合盘同理指向现有的再次生成入口。没有现成入口的页面只显示文字。
- 英文版报告视图给对应英文句子:`This report was generated from the birth time on file at that time. You can generate it again.`(年运、合盘同理改主语)。
## 二、导出
`report-export-blocks.ts`、`annual-report-export.ts`、`synastry-report-export.ts`:#310 已把 `birthInputState` 放进导出块的 `metadata`。本单在导出的 Markdown 正文最前面(标题之后)加一段,仅 `changed` 时:
`> 这份报告按当时的出生时间生成,之后出生时间改过。`
快照里存有当时的出生时间范围时(年运快照的 `birth_window`、长报告的出生时间载荷),再加一行 `> 生成时使用的出生时间:HH:MM(范围 HH:MM–HH:MM)`;没有存就不加,不去读当前档案来补。
聊天导出(`consultation-report-export.ts`)不在本单。已经下载到用户手里的文件无法更改,在 PROGRESS「已知边界」登记。
## 三、自选情景下生成的报告、年运、合盘
### 生成时记录
生成报告时,如果主体当前来源是自选情景(`isSelfSelectedScenario(active_birth_provenance)`),在产物里记录(与 `birthInputRevision` 同位置):
```
birthScenario: {
kind: "self_selected",
side: "before" | "after" | "unsure", // selfSelectedScenarioSide
differingDomains: string[] // 见下
}
```
`differingDomains`:从来源里的 `scenarios` 取主情景和其他情景,六张盘中上升星座不同的那些盘对应的领域名(用页面已有的盘名:主盘、婚恋、事业、钱财、日常、突变)。只有一个情景时为空数组。合盘记录双方各一份(`birthScenarios: { a, b }`,不是自选的一方为 `null`)。
不是自选的主体不写这个字段。旧产物没有这个字段。
### 显示
产物带 `birthScenario` 时,在正文上方显示一段(与第一节同样的位置和样式;两者都有时 `changed` 那行在上):
- 选了一侧:`这份报告按你自己选的线后情景写成,不是出生时间已核实;你填的时间和范围都还保留着。`(「线后」按 `side` 换成「线前」;年运、合盘把「这份报告」换成「这份年运」「这份合盘」,合盘写明是哪一位:`其中 A 的出生时间按自己选的线后情景`,A 用报告里已有的称呼。)
- `side` 为 `unsure`:`你没有选定线前还是线后,这份报告按你填的时间写成;你填的时间和范围都还保留着。`
- `differingDomains` 非空时再接一句:`另一种情景下,婚恋、事业的分盘上升星座不同,报告里这两方面的判断只适用于你选的这一侧。`(领域名按实际列出;一个领域时写「这方面」。)
导出正文开头带同样的话(引用块)。只出现这一次:**报告正文、章节、提示词都不因为自选而加任何别的保留语气**。这是产品负责人批准的唯一例外。
报告生成的提示词和渲染代码(`scripts/report_render/`、报告写作提示词)不改:报告仍然只按采用时刻写。本单不做报告内的分情景写作。
## 四、`birth_input_changed` 失败的说法
#310 之后,生成期间出生资料变了的任务会失败并返还点数,接口带 `failureReason: "birth_input_changed"`。现在页面显示的是通用失败文案。改成:
`生成期间出生资料改过,这次没有扣点。请重新生成。`
用现有的失败提示位置和样式。
## 五、合盘 worker 提交前再核对一次
`frontend/src/lib/synastry-full-run.ts` 现在只在开始时核对双方版本。在写最终快照之前再读一次双方档案并比对,不一致则抛 `birth_input_changed`(与长报告、年运一致),走现有失败与返还路径。没有记录版本的旧任务不核对(与 #310 验收时的修改一致)。
## 六、不做的事
- `unknown` 不显示任何东西;不回填、不改写旧产物。
- 不改报告正文的生成、不做分情景写作、不改 `scripts/`。
- 不动聊天(#314)、不动自选流程(#312)。
- 不新造按钮、徽标、颜色块;不在列表上加标记。
## 七、测试
新文件 `frontend/tests/report-birth-marking-20261117.test.tsx`(合成数据):
1. 三种页面:`changed` 显示对应那一行且含指向现有入口的链接;`current`、`unknown`、缺失都不显示。
2. 导出:`changed` 时正文开头有那段引用,有存范围时带时间行,没有存时不带;`current`/`unknown` 时导出正文与现在逐字相同。
3. 自选情景:生成时写入 `birthScenario`(before / after / unsure 三种;`differingDomains` 空与非空;合盘一方自选一方不是);非自选不写。
4. 显示:三种 `side` 的句子;`differingDomains` 一个与多个;与 `changed` 同时出现时的先后;整份报告正文里这句话只出现一次。
5. 页面任何位置不出现「无法确认」「未核对」「没有通过核对」「已校正」「已确认」。
6. `birth_input_changed` 的失败文案;其他失败原因的文案不变。
7. 合盘 worker:提交前一方档案变化 → 不写最终快照,原因 `birth_input_changed`,返还路径与现有失败用例相同;旧任务(无记录)照常完成。
8. 既有测试不删断言:`annual-md-export-20261113.test.tsx`、`birth-input-revision-20261117.test.ts`、`report-birth-binding.test.ts`、`chart-choice-self-choice-scenario-20261117.test.tsx`、合盘与长报告的页面测试。
## 八、文档
- `docs/BUG_HISTORY.md` 新增 BUG-1959(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID)。
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-artifact-marking-20261117.md`,含「已知边界」:已下载文件、聊天导出、报告内不分情景写作、`unknown` 不标示及其理由(生产无存量)。
- `docs/research/rect-p0-artifact-checklist-20261116.md` 的「11-17 之后」一节更新缺口 1、3 的状态。
- `frontend/DESIGN.md` 相应位置补一句这两段说明的位置和样式约定。
## 验收
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
- `cd frontend && npx tsc --noEmit` 通过;`npx eslint .` 0 错误;新测试与第七节第 8 条的测试通过;前端全量不新增失败;
- 验收时会在本地构建上看三种页面各一次(有标示 / 无标示),核对样式与现有说明段落一致。
+2
View File
@@ -19,6 +19,8 @@
婚恋合盘技术依据的计算参数按甲乙各占一段。段首写出生时间误差来源,复用年运横向滚动表格,分「项目」「档案时刻」「候选时刻」三列。候选按相对档案的偏早或偏晚分钟数分行,表格只列会变或缺计算结果的项目。没有变化的项目汇成一句。个人报告、年运和合盘在误差来源一行说明默认前后各 30 分钟只是试算,同一页或导出只说明一次。甲方、乙方及两盘的技法回执沿用同一表格。只在受影响的行标参数敏感或写明阻塞原因。
个人报告、年运及完整合盘在标题下方复用各页现有说明段落。出生时间变化时先显示重新生成的文字链接,自选情景说明紧接其后。
### Palette
| Role | Token | Value | Usage |
@@ -1,4 +1,6 @@
import { NextResponse } from "next/server";
import { asRecord } from "@/lib/guards";
import { readReportBirthScenario, readReportBirthWindow } from "@/lib/report-birth-marking";
import { readReportBirthInputSection, REPORT_BIRTH_INPUT_SECTION } from "@/lib/report-birth-revision";
import { ownedReportBirthInputReader } from "@/lib/report-birth-revision-server";
import { REPORT_STABLE_CODES } from "@/lib/personal-report-codes";
@@ -206,8 +208,13 @@ export async function GET(request: Request, context: RouteContext) {
const failure = owned.status === "failed" && jobs
? await jobs.getOwnedByRequestId(owned.userId, owned.requestId).catch(() => null)
: null;
const subject = owned.status === "ready" ? asRecord(asRecord(owned.reportDocument)?.subject) : null;
const birthScenario = readReportBirthScenario(subject?.birthScenario);
const artifactBirthWindow = readReportBirthWindow(subject?.artifactBirthWindow);
response = { ...response, body: {
...response.body,
...(birthScenario ? { birthScenario } : {}),
...(artifactBirthWindow ? { artifactBirthWindow } : {}),
birthInputState: await inputState(binding),
...(failure?.lastErrorCode === "birth_input_changed" ? { failureReason: "birth_input_changed" } : {}),
} };
@@ -21,6 +21,8 @@ import { accountDialogHref } from "@/lib/account-dialog-intent";
import { readCurrentSubjectId, useCurrentSubjectReady, useCurrentSubjectScope } from "@/lib/current-subject";
import { dragScroll } from "@/lib/drag-scroll";
import { ANNUAL_PRAVESHA_NOTE, ANNUAL_PRAVESHA_TITLE, annualAppendixDisplayLines, type AnnualSnapshot } from "@/lib/annual-report-generate";
import { ReportBirthNotices } from "@/components/personal-report/report-birth-notices";
import { REPORT_BIRTH_CHANGED_FAILURE, readReportBirthScenario } from "@/lib/report-birth-marking";
import { buildAnnualExportBlocks, hasAnnualTimeline } from "@/lib/annual-report-export";
import { annualGradeLine, remainingTableGrade } from "@/lib/annual-report-grade";
import {
@@ -53,6 +55,7 @@ type ReportState = Readonly<{
id: string;
status: "generating" | "ready" | "failed";
annual: AnnualSnapshot | null;
failureReason?: "birth_input_changed";
/** The worker's stage: queued → computing_annual → writing_report. */
phase?: string;
createdAt?: string;
@@ -668,6 +671,16 @@ export function AnnualReportView({ snapshot, generating, failed = false }: Reado
<header className="annual-report-head">
<p className="annual-range">{snapshot.range.label},{snapshot.range.span}</p>
<h2>{snapshot.subject.name}的这一年</h2>
{!generating && !failed ? (
<ReportBirthNotices
kind="annual"
language="zh"
state={snapshot.birthInputState}
scenario={readReportBirthScenario(snapshot.birthScenario)}
regenerateHref="/reports"
className="annual-quiet"
/>
) : null}
</header>
<AnnualPageNotes title="这一年从哪天算到哪天" notes={snapshot.solarReturns} variant="solar" />
{snapshot.plan.map((entry) => {
@@ -800,6 +813,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR
const status = view.status === "ready" || view.status === "failed" ? view.status : "generating";
setReport({
id, status, annual: (json.annual as AnnualSnapshot | null) ?? null,
...(json.failureReason === "birth_input_changed" ? { failureReason: json.failureReason } : {}),
...(typeof view.progressPhase === "string" ? { phase: view.progressPhase } : {}),
...(typeof view.createdAt === "string" ? { createdAt: view.createdAt } : {}),
...(typeof record(json.queue).line === "string" ? { queueLine: record(json.queue).line as string } : {}),
@@ -871,7 +885,7 @@ export function AnnualReportPage({ initialReportId = null }: Readonly<{ initialR
)}
{failed ? (
<div className="annual-failed" role="alert">
<p>这一次没写完,没有扣点。</p>
<p>{report?.failureReason === "birth_input_changed" ? REPORT_BIRTH_CHANGED_FAILURE : "这一次没写完,没有扣点。"}</p>
<Button type="button" variant="outline" onClick={() => { setReport(null); setReportId(null); }}>重新开始</Button>
</div>
) : null}
@@ -109,6 +109,7 @@ function markdownComponents(
subjectName?: string,
createdAt?: string,
birth?: string | null,
birthNotices?: ReactNode,
): Components {
const cursor = { h2: 0, h3: 0 };
const byline = { shown: false };
@@ -152,6 +153,7 @@ function markdownComponents(
<header className="personal-report-md-cover">
<span className="personal-report-md-cover-kicker">{zh ? "印度占星,完整本命报告" : "Vedic astrology, Full natal report"}</span>
<h1>{heading}</h1>
{birthNotices}
{facts ? <p className="personal-report-md-byline">{facts}</p> : null}
<p className="personal-report-ai-notice">{reportAiNotice(language)}</p>
</header>
@@ -207,10 +209,11 @@ function renderMarkdown(
subjectName?: string,
createdAt?: string,
birth?: string | null,
birthNotices?: ReactNode,
) {
return (
<ReactMarkdown
components={markdownComponents(headings, language, subjectName, createdAt, birth)}
components={markdownComponents(headings, language, subjectName, createdAt, birth, birthNotices)}
disallowedElements={["script", "iframe", "object", "embed", "img"]}
rehypePlugins={[reportChartGrid]}
remarkPlugins={remarkPlugins}
@@ -407,10 +410,12 @@ export function PersonalReportMarkdownView({
createdAt,
reading = null,
appendix = null,
birthNotices,
}: {
markdown: string;
/** Charts and fact tables; they close the article column instead of running under the rail. */
appendix?: ReactNode;
birthNotices?: ReactNode;
/** Model-written reading (issue #113 R1). Chinese only; shown after the lead, before the engine chapters. */
reading?: ReportReading | null;
language?: ReportLanguage;
@@ -456,12 +461,13 @@ export function PersonalReportMarkdownView({
reveal.revealed = true;
for (const listener of reveal.listeners) listener();
}), [chapters.length, paged, reveal]);
const lead = useMemo(
() => (outline.leadMarkdown
? renderMarkdown(outline.leadMarkdown, outline.headings, language, subjectName, createdAt, reportBirthLine(markdown))
: null),
[outline, language, subjectName, createdAt, markdown],
);
const lead = useMemo(() => {
const hasTitle = /^#[ \t]+\S/m.test(outline.leadMarkdown);
const content = outline.leadMarkdown
? renderMarkdown(outline.leadMarkdown, outline.headings, language, subjectName, createdAt, reportBirthLine(markdown), hasTitle ? birthNotices : null)
: null;
return hasTitle || !birthNotices ? content : <>{birthNotices}{content}</>;
}, [outline, language, subjectName, createdAt, markdown, birthNotices]);
const safeChapter = Math.min(chapter, Math.max(chapters.length - 1, 0));
const currentChapter = chapters[safeChapter];
const pagedChapter = useMemo(() => (
@@ -23,6 +23,8 @@ import { ChartDrawLoader } from "@/components/chart-draw-loader";
import { SecondaryHeader } from "@/components/secondary-header";
import { SynastryReportView } from "@/components/synastry/synastry-report-view";
import { SynastryWait } from "@/components/synastry/synastry-wait";
import { REPORT_BIRTH_CHANGED_FAILURE, readReportBirthScenario, readReportBirthWindow, type ReportBirthScenario, type ReportBirthWindow } from "@/lib/report-birth-marking";
import { ReportBirthNotices } from "./report-birth-notices";
import { ReportActions } from "./report-actions";
import { ReportFactTables } from "./report-fact-tables";
import { ReportCalculationCharts } from "./report-calculation-charts";
@@ -63,7 +65,7 @@ export type ReportLoadState =
queueLine?: string;
}
| { phase: "timed-out" }
| { phase: "failed"; failureCode: string | null; failureSummary?: string | null; appendixLastErrorCode?: string | null; reportType?: string }
| { phase: "failed"; failureCode: string | null; failureReason?: "birth_input_changed"; failureSummary?: string | null; appendixLastErrorCode?: string | null; reportType?: string }
| { phase: "invalid"; message: string }
| { phase: "network-error" }
| {
@@ -82,6 +84,8 @@ export type ReportLoadState =
/** Model-written reading in front of the report (issue #113 R1); absent on older or failed readings. */
reading?: ReportReading;
birthInputState?: BirthInputState;
birthScenario?: ReportBirthScenario;
artifactBirthWindow?: ReportBirthWindow;
}
| { phase: "legacy-unavailable" }
| { phase: "synastry-ready"; reportId: string; synastry: unknown; createdAt?: string };
@@ -179,6 +183,8 @@ export function classifyReportEnvelope(statusCode: number, json: unknown): Repor
phase: "markdown-ready",
...(json.birthInputState === "current" || json.birthInputState === "changed" || json.birthInputState === "unknown"
? { birthInputState: json.birthInputState } : {}),
birthScenario: readReportBirthScenario(json.birthScenario),
artifactBirthWindow: readReportBirthWindow(json.artifactBirthWindow),
markdown,
reportId: typeof view.id === "string" ? view.id : "",
createdAt: typeof view.createdAt === "string" ? view.createdAt : "",
@@ -216,6 +222,7 @@ export function classifyReportEnvelope(statusCode: number, json: unknown): Repor
return {
phase: "failed",
failureCode: appendixLastErrorCode ?? code,
...(json.failureReason === "birth_input_changed" ? { failureReason: json.failureReason } : {}),
...(typeof view.reportType === "string" ? { reportType: view.reportType } : {}),
...(summary ? { failureSummary: summary } : {}),
...(appendixLastErrorCode ? { appendixLastErrorCode } : {}),
@@ -597,7 +604,9 @@ export function PersonalReportPage({
<div className="personal-report-state">
<TriangleAlert aria-hidden="true" className="size-8 text-warning" />
<h1>报告生成失败</h1>
<p>{state.failureSummary ?? "生成过程中出现问题,未产出可用报告。请稍后重试。"}</p>
<p>{state.failureReason === "birth_input_changed"
? REPORT_BIRTH_CHANGED_FAILURE
: state.failureSummary ?? "生成过程中出现问题,未产出可用报告。请稍后重试。"}</p>
{state.failureCode && (
<p>错误码:{state.failureCode}</p>
)}
@@ -692,6 +701,8 @@ export function PersonalReportPage({
factTables={state.factTables}
reading={state.reading}
birthInputState={state.birthInputState}
birthScenario={state.birthScenario}
artifactBirthWindow={state.artifactBirthWindow}
english={state.englishEdition === "ready" && state.markdownEn ? { markdown: state.markdownEn, factTables: state.factTablesEn } : null}
reportDate={state.createdAt}
language={shown}
@@ -713,6 +724,16 @@ export function PersonalReportPage({
markdown={markdown}
reading={state.reading ?? null}
subjectName={state.subjectDisplayName}
birthNotices={state.birthInputState === "changed" || state.birthScenario ? (
<ReportBirthNotices
kind="personal"
language={shown}
state={state.birthInputState}
scenario={state.birthScenario}
regenerateHref="/reports"
className="personal-report-ai-notice"
/>
) : null}
appendix={(
<>
{state.calculationCharts && <ReportCalculationCharts charts={state.calculationCharts} markdown={markdown} language={shown} />}
@@ -9,6 +9,7 @@ import Link from "next/link";
import { ArrowLeft, Download } from "lucide-react";
import type { BirthInputState } from "@/lib/birth-input-revision";
import type { ReportBirthScenario, ReportBirthWindow } from "@/lib/report-birth-marking";
import { buildReportExportBlocks } from "@/lib/report-export-blocks";
import type { ReportDocumentV2 } from "@/lib/personal-report-contract";
import type { ReportReading } from "@/lib/personal-report-reading-contract";
@@ -23,6 +24,8 @@ interface ReportActionsProps {
charts?: ReportDocumentV2["charts"];
factTables?: readonly ReportFactTable[];
birthInputState?: BirthInputState;
birthScenario?: ReportBirthScenario;
artifactBirthWindow?: ReportBirthWindow;
reading?: ReportReading | null;
reportDate?: string | null;
/** The English edition, when the report has one; `markdown` / `factTables` are always Chinese. */
@@ -49,6 +52,8 @@ export function ReportActions({
factTables,
reading,
birthInputState,
birthScenario,
artifactBirthWindow,
reportDate,
english = null,
language = "zh",
@@ -59,9 +64,9 @@ export function ReportActions({
const [exportOpen, setExportOpen] = useState(false);
// Built only while the sheet is open; each edition labels its own blocks.
const editions = useMemo(() => (exportOpen ? {
zh: buildReportExportBlocks({ markdown, charts, factTables, language: "zh", reading, birthInputState }),
...(english ? { en: buildReportExportBlocks({ markdown: english.markdown, charts, factTables: english.factTables, language: "en", birthInputState }) } : {}),
} : null), [exportOpen, markdown, charts, factTables, english, reading, birthInputState]);
zh: buildReportExportBlocks({ markdown, charts, factTables, language: "zh", reading, birthInputState, birthScenario, artifactBirthWindow }),
...(english ? { en: buildReportExportBlocks({ markdown: english.markdown, charts, factTables: english.factTables, language: "en", birthInputState, birthScenario, artifactBirthWindow }) } : {}),
} : null), [exportOpen, markdown, charts, factTables, english, reading, birthInputState, birthScenario, artifactBirthWindow]);
const canSwitch = englishEdition === "ready" && onLanguageChange !== undefined;
const controls = (
@@ -0,0 +1,44 @@
import Link from "next/link";
import type { BirthInputState } from "@/lib/birth-input-revision";
import {
reportBirthChangedCopy,
reportBirthScenarioCopy,
type ArtifactKind,
type ReportBirthScenario,
type ReportBirthScenarios,
} from "@/lib/report-birth-marking";
export function ReportBirthNotices({
kind, language, state, scenario, scenarios, names, regenerateHref, className,
}: Readonly<{
kind: ArtifactKind;
language: "zh" | "en";
state?: BirthInputState;
scenario?: ReportBirthScenario;
scenarios?: ReportBirthScenarios;
names?: Readonly<{ a: string; b: string }>;
regenerateHref?: string;
className?: string;
}>) {
const changed = state === "changed" ? reportBirthChangedCopy(kind, language) : null;
const notes = [];
if (scenario) notes.push(reportBirthScenarioCopy(scenario, kind, language));
if (scenarios && names) {
if (scenarios.a) notes.push(reportBirthScenarioCopy(scenarios.a, kind, language, names.a));
if (scenarios.b) notes.push(reportBirthScenarioCopy(scenarios.b, kind, language, names.b));
}
return (
<>
{changed ? (
<p className={className}>
{changed.lead}
{regenerateHref ? (
<Link href={regenerateHref} className="underline underline-offset-2">{changed.action}</Link>
) : changed.action}
{changed.end}
</p>
) : null}
{notes.length ? <p className={className}>{notes.join(language === "en" ? " " : "")}</p> : null}
</>
);
}
@@ -1,5 +1,7 @@
"use client";
import { ReportBirthNotices } from "@/components/personal-report/report-birth-notices";
import { readReportBirthScenarios } from "@/lib/report-birth-marking";
import { buildSynastryExportBlocks, synastryParagraphs } from "@/lib/synastry-report-export";
import { ReportExportButton } from "@/components/personal-report/report-actions";
import { ReportExportDrawer } from "@/components/personal-report/report-export-drawer";
@@ -41,6 +43,7 @@ type LanguageBody = {
type Snapshot = {
birthInputState?: import("@/lib/birth-input-revision").BirthInputState;
birthScenarios?: unknown;
names?: { a?: string; b?: string };
matching_profiles?: unknown;
sections?: Prose[];
@@ -154,6 +157,8 @@ export function SynastryReportView(props: {
const body: LanguageBody | null = language === "en" && english ? english : snapshot;
if (!body) return null;
const names = snapshot.names ?? {};
const reportNames = { a: names.a || "甲", b: names.b || "乙" };
const birthScenarios = readReportBirthScenarios(snapshot.birthScenarios);
const structure = body.structure ?? snapshot.structure;
const order = synastrySectionOrder(structure);
const events = currentSynastryEvents(body.events, undefined, { a: names.a ?? "", b: names.b ?? "" }, language);
@@ -182,6 +187,8 @@ export function SynastryReportView(props: {
practices: source.practices,
technical: snapshot?.technical,
birthInputState: snapshot?.birthInputState,
birthScenarios,
names: reportNames,
});
}
@@ -248,6 +255,15 @@ export function SynastryReportView(props: {
<Link className="synastry-report-back" href="/synastry"><ChevronLeft aria-hidden="true" /> 婚恋合盘</Link>
<header className="synastry-report-heading">
<h1>{title}</h1>
<ReportBirthNotices
kind="synastry"
language={language}
state={snapshot.birthInputState}
scenarios={birthScenarios}
names={reportNames}
regenerateHref="/synastry"
className="synastry-footnote"
/>
<div className="synastry-report-meta">
<span>{savedLine(props.createdAt)}</span>
<Tabs className="synastry-lang" value={language} onValueChange={(next) => { if (next === "en") showEnglish(); else setLanguage("zh"); }}>
+8 -1
View File
@@ -1,4 +1,5 @@
import { ANNUAL_PRAVESHA_NOTE, ANNUAL_PRAVESHA_TITLE, annualAppendixDisplayLines, annualAppendixMarkdown, type AnnualSnapshot } from "./annual-report-generate";
import { readReportBirthScenario, readReportBirthWindow, reportBirthExportPreamble } from "./report-birth-marking.ts";
import { withExportBirthInputState, type ReportExportBlock } from "./report-export-blocks";
import { projectOrdinaryReportMarkdown } from "./report-public-projection";
import { annualGradeLine, remainingTableGrade } from "./annual-report-grade";
@@ -185,5 +186,11 @@ export function buildAnnualExportBlocks(snapshot: AnnualSnapshot): ReportExportB
// Each subheading stays individually addressable; the drawer selects the group together.
add(`table:${block.id}`, "table", title, index === 0 ? appendix : appendix.replace(/^# 计算依据\n\n/, ""));
}
return withExportBirthInputState(blocks, snapshot.birthInputState);
return withExportBirthInputState(blocks, snapshot.birthInputState, reportBirthExportPreamble({
kind: "annual",
language: "zh",
state: snapshot.birthInputState,
scenario: readReportBirthScenario(snapshot.birthScenario),
window: readReportBirthWindow(snapshot.artifactBirthWindow),
}));
}
@@ -67,6 +67,8 @@ export const ANNUAL_PRAVESHA_NOTE =
type AnnualSnapshotBody = Readonly<{
kind: "annual_report_snapshot";
birthInputRevision?: string;
birthScenario?: import("./report-birth-marking").ReportBirthScenario;
artifactBirthWindow?: import("./report-birth-marking").ReportBirthWindow;
birthInputState?: import("./birth-input-revision").BirthInputState;
status: "writing" | "ready";
subject: Readonly<{ name: string; isSelf: boolean }>;
+14 -7
View File
@@ -2,6 +2,7 @@ import "server-only";
import { createHash, randomUUID } from "node:crypto";
import { birthInputRevision, type BirthInputState } from "@/lib/birth-input-revision";
import { recordReportBirthWindow, reportBirthScenario } from "@/lib/report-birth-marking";
import { bindReportBirthInput, findReusableAnnualReport, readReportBirthInput, type ReportBirthInput } from "@/lib/report-birth-revision";
import { createAnnualSectionWriter } from "@/mastra/annual-report";
@@ -407,21 +408,27 @@ export async function runAnnualReport(input: Readonly<{
if (!resolved.chartable) throw new PersonalReportWorkerError("profile_incomplete", false);
const row = resolved.row as Row;
const birthTime = annualBirthTime(row);
const birthWindow = annualBirthWindowBody(birthTime);
const birthScenario = reportBirthScenario(row.active_birth_provenance);
let artifactBirthWindow: ReturnType<typeof recordReportBirthWindow>;
await input.onProgress?.({ phase: "computing_annual", completed: 0, total: 10 });
let facts: Row;
try {
const kind = stored.rangeKind as AnnualRangeKind;
const year = typeof stored.rangeYear === "number" ? stored.rangeYear : undefined;
const response = await postEngine("/api/annual/report_facts", {
...annualEngineBody(row, { kind, ...(year ? { year } : {}) }, text(stored.observationDate) || annualObservationDate(row),
situation.success ? situation.data : null),
birth_window: annualBirthWindowBody(birthTime),
}, input.signal);
const birth = annualEngineBody(row, { kind, ...(year ? { year } : {}) }, text(stored.observationDate) || annualObservationDate(row),
situation.success ? situation.data : null);
artifactBirthWindow = recordReportBirthWindow(birth.hour, birth.minute, birthWindow);
const response = await postEngine("/api/annual/report_facts", { ...birth, birth_window: birthWindow }, input.signal);
facts = record(response.facts);
} catch (error) {
if (input.signal.aborted) throw error;
throw new PersonalReportWorkerError("calculation_unavailable", true);
}
const birthMarking = {
...(birthScenario ? { birthScenario } : {}),
...(artifactBirthWindow ? { artifactBirthWindow } : {}),
};
if (record(facts.cards).status !== "computed") throw new PersonalReportWorkerError("calculation_unavailable", false);
const catalog = await loadLanguageModelCatalog();
const model = catalog.models.find((entry) => entry.id === catalog.defaultModelId) ?? null;
@@ -432,7 +439,7 @@ export async function runAnnualReport(input: Readonly<{
request_id: input.report.requestId,
section_id: ANNUAL_SNAPSHOT_SECTION,
status: "ready",
payload: { ...snapshot, birthInputRevision: revision },
payload: { ...snapshot, birthInputRevision: revision, ...birthMarking },
attempt_count: 1,
max_attempts: 2,
});
@@ -478,7 +485,7 @@ export async function runAnnualReport(input: Readonly<{
modelConfigVersion: model.configVersion,
},
ready: {
reportDocument: { schemaVersion: ANNUAL_REPORT_SCHEMA, reportId: input.report.id, sectionId: ANNUAL_SNAPSHOT_SECTION, birthInputRevision: revision },
reportDocument: { schemaVersion: ANNUAL_REPORT_SCHEMA, reportId: input.report.id, sectionId: ANNUAL_SNAPSHOT_SECTION, birthInputRevision: revision, ...birthMarking },
calculationHash: sha256(facts),
evidenceHash: sha256(written.snapshot),
cardSummary: `${subject.name}的这一年,${written.snapshot.range.span}`.slice(0, 500),
@@ -14,6 +14,7 @@
*/
import { z } from "zod";
import { reportBirthScenarioSchema, reportBirthWindowSchema } from "./report-birth-marking";
import { reportFactTablesSchema } from "./report-fact-table-schema";
import { REPORT_DEPTHS, type ReportDepth } from "./contracts/personal-report-request";
@@ -185,6 +186,8 @@ const subjectSchema = z.strictObject({
// never show a cover. Server-only; the reader never receives the subject.
birthFingerprint: z.string().regex(/^[0-9a-f]{32}$/, "invalid birth fingerprint").optional(),
birthInputRevision: z.string().regex(/^[0-9a-f]{64}$/).optional(),
birthScenario: reportBirthScenarioSchema.optional(),
artifactBirthWindow: reportBirthWindowSchema.optional(),
});
const provenanceV1Schema = z.strictObject({
@@ -61,6 +61,7 @@ import {
type ReportSectionPlanEntry,
} from "./personal-report-plan.ts";
import type { PersonalReportSectionRecord, PersonalReportSectionService } from "./personal-report-section-service-core.ts";
import type { ReportBirthScenario } from "./report-birth-marking.ts";
import { withReportBirthFingerprint, withReportBirthInputRevision } from "./report-birth-binding.ts";
import { asRecord as record, finiteNumberOrNull as finiteNumber } from "@/lib/guards";
// Compatibility re-export: prefer importing from ./personal-report-codes.ts
@@ -3315,6 +3316,7 @@ export type GeneratePersonalReportDeps = GeneratePersonalReportBaseDeps & Readon
/** Stored-row birth fingerprint; written to `subject.birthFingerprint`, never into the bundle the model reads. */
birthFingerprint?: string;
birthInputRevision?: string;
birthScenario?: ReportBirthScenario;
}>;
export type ReportSchemaInnerReason = string;
@@ -3631,7 +3633,7 @@ async function generateSectionedPersonalReport(
});
const guarded = applyReportGuard(withReportBirthFingerprint(candidate, deps.birthFingerprint), buildLegacyPacketFromBundle(bundle));
if (!guarded.ok) return { status: "failed", failureCode: "report_guard_rejected" };
const parsed = safeParseServerReportDocument(withReportBirthInputRevision(guarded.document, deps.birthInputRevision));
const parsed = safeParseServerReportDocument(withReportBirthInputRevision(guarded.document, deps.birthInputRevision, deps.birthScenario));
if (!parsed.ok || parsed.document.schemaVersion !== "report_document.v2") return failFinalParse(parsed);
return { status: "ready", document: parsed.document, evidenceHash: computeEvidenceHash(parsed.document.evidenceAppendix), usage: deps.agent.getUsage?.() };
} catch (error) {
@@ -3732,7 +3734,7 @@ export async function generatePersonalReport(
if (!guarded.ok) {
return { status: "failed", failureCode: "report_guard_rejected" };
}
const parsed = safeParseServerReportDocument(withReportBirthInputRevision(guarded.document, deps.birthInputRevision));
const parsed = safeParseServerReportDocument(withReportBirthInputRevision(guarded.document, deps.birthInputRevision, deps.birthScenario));
if (!parsed.ok || parsed.document.schemaVersion !== "report_document.v2") {
return failFinalParse(parsed);
}
@@ -44,6 +44,8 @@ export type LongformCoverInput = Readonly<{
/** Stored-row birth fingerprint (report cover binding); absent → no `subject.birthFingerprint`. */
birthFingerprint?: string;
birthInputRevision?: string;
birthScenario?: import("./report-birth-marking").ReportBirthScenario;
artifactBirthWindow?: import("./report-birth-marking").ReportBirthWindow;
markdown: string;
factTables?: ReportDocumentV2["factTables"];
charts?: ReportDocumentV2["charts"];
@@ -95,6 +97,8 @@ export function buildLongformCoverDocument(input: LongformCoverInput): ReportDoc
...input.subject,
...(input.birthFingerprint ? { birthFingerprint: input.birthFingerprint } : {}),
...(input.birthInputRevision ? { birthInputRevision: input.birthInputRevision } : {}),
...(input.birthScenario ? { birthScenario: input.birthScenario } : {}),
...(input.artifactBirthWindow ? { artifactBirthWindow: input.artifactBirthWindow } : {}),
},
provenance: {
skillName,
@@ -16,6 +16,7 @@ import {
type LongformAppendixRow,
} from "./personal-report-longform-appendix";
import { buildLongformBirthPayload, utcToday } from "./personal-report-longform-birth";
import { recordReportBirthWindow, reportBirthScenario } from "./report-birth-marking";
import { buildLongformCoverDocument } from "./personal-report-longform-cover";
import { readReportBirthFingerprint, readReportProfileBirthInputRevision } from "./report-birth-binding";
import { assembleLongformCharts, type GeneratePersonalReportResult } from "./personal-report-generation";
@@ -270,9 +271,13 @@ export async function generatePersonalReportLongform(
contentSha256: hashLongformMarkdown(annotateUnreliableChartSections(engine.english.markdown, unreliable, "en")),
} } : {}),
} : engine;
const birthScenario = reportBirthScenario(profile.active_birth_provenance);
const artifactBirthWindow = recordReportBirthWindow(payload.hour, payload.minute, payload.birth_time_window);
snapshot = validateLongformSnapshot({
...annotated, ...identity, kind: "longform_calculation_snapshot", version: 2,
...(birthInputRevision ? { birthInputRevision } : {}),
...(birthScenario ? { birthScenario } : {}),
...(artifactBirthWindow ? { artifactBirthWindow } : {}),
...(reading?.reading ? { reading: reading.reading } : {}),
...(reading && !reading.reading ? { readingUnavailable: reading.unavailable ?? "model_failed" } : {}),
contentSha256: hashLongformMarkdown(annotated.markdown),
@@ -308,6 +313,8 @@ export async function generatePersonalReportLongform(
},
birthFingerprint: readReportBirthFingerprint(profile),
birthInputRevision,
birthScenario: snapshot?.birthScenario,
artifactBirthWindow: snapshot?.artifactBirthWindow,
markdown,
factTables,
charts,
@@ -1,4 +1,5 @@
import { z } from "zod";
import { reportBirthScenarioSchema, reportBirthWindowSchema } from "./report-birth-marking";
import { hashLongformMarkdown } from "./personal-report-longform-appendix";
import { CHART_IDS, reportDocumentV2Schema } from "./personal-report-contract";
import { reportFactTablesSchema } from "./report-fact-table-schema";
@@ -11,6 +12,8 @@ export const LONGFORM_SNAPSHOT_TABLE = "personal_report_sections";
export type LongformSnapshotIdentity = { reportId: string; userId: string; requestId: string };
const snapshotFields = {
birthInputRevision: z.string().regex(/^[0-9a-f]{64}$/).optional(),
birthScenario: reportBirthScenarioSchema.optional(),
artifactBirthWindow: reportBirthWindowSchema.optional(),
kind: z.literal("longform_calculation_snapshot"),
reportId: z.string().uuid(), userId: z.string().uuid(), requestId: z.string().uuid(),
markdown: z.string().min(1), contentSha256: z.string().regex(/^[a-f0-9]{64}$/),
@@ -18,6 +18,7 @@ import { parseReportCandidateRange, type ReportCandidateClockRange } from "./rep
*/
import { effectiveBirthDate } from "./effective-birth-date";
import { reportBirthScenario } from "./report-birth-marking.ts";
import { asRecord as record, finiteNumberOrNull as finiteNumber } from "@/lib/guards";
import { isSelfSelectedScenario } from "./chart-choice/self-selected-scenario";
import {
@@ -580,6 +581,7 @@ export async function resolveReportCreate(deps: ReportCreateCoreDeps): Promise<R
now: deps.now,
birthFingerprint: readReportBirthFingerprint(profile),
birthInputRevision: readReportProfileBirthInputRevision(profile),
birthScenario: reportBirthScenario(record(profile)?.active_birth_provenance),
});
if (result.status === "failed") {
@@ -1,6 +1,7 @@
import type { ReportCandidateClockRange } from "./report-candidate-range";
import "server-only";
import { effectiveBirthDate } from "./effective-birth-date";
import { reportBirthScenario } from "./report-birth-marking.ts";
import { asRecord as record, finiteNumberOrNull as finiteNumber } from "@/lib/guards";
import { runConsultationWorkflow } from "@/mastra";
@@ -189,6 +190,7 @@ async function generateWriterReport(
onProgress: context.onProgress,
birthFingerprint: readReportBirthFingerprint(profile),
birthInputRevision: readReportProfileBirthInputRevision(profile),
birthScenario: reportBirthScenario(record(profile)?.active_birth_provenance),
});
if (result.status !== "ready") return result;
return {
+8 -3
View File
@@ -1,3 +1,4 @@
import type { ReportBirthScenario } from "./report-birth-marking.ts";
import { resolveServerOwnedChartBirth } from "./chart-birth-truth.ts";
import { asRecord as record } from "@/lib/guards";
@@ -56,9 +57,13 @@ export function readReportProfileBirthInputRevision(profile: unknown): string |
return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? value : undefined;
}
export function withReportBirthInputRevision<T>(document: T, revision: string | undefined): T {
export function withReportBirthInputRevision<T>(document: T, revision: string | undefined, birthScenario?: ReportBirthScenario): T {
const source = record(document);
const subject = record(source?.subject);
if (!source || !subject || !revision) return document;
return { ...source, subject: { ...subject, birthInputRevision: revision } } as T;
if (!source || !subject || (!revision && !birthScenario)) return document;
return { ...source, subject: {
...subject,
...(revision ? { birthInputRevision: revision } : {}),
...(birthScenario ? { birthScenario } : {}),
} } as T;
}
+180
View File
@@ -0,0 +1,180 @@
import { z } from "zod";
import { asRecord } from "./guards.ts";
import { selfSelectedScenarioSide } from "./chart-choice/self-selected-scenario.ts";
import type { BirthInputState } from "./birth-input-revision.ts";
const DOMAINS = [
["D1", "主盘", "the main chart"],
["D9", "婚恋", "relationships"],
["D10", "事业", "career"],
["D2", "钱财", "finances"],
["D6", "日常", "daily life"],
["D8", "突变", "sudden changes"],
] as const;
const [mainChart, ...divisionalCharts] = DOMAINS;
const domainNames = [mainChart[1], ...divisionalCharts.map(([, label]) => label)] as const;
export const reportBirthScenarioSchema = z.strictObject({
kind: z.literal("self_selected"),
side: z.enum(["before", "after", "unsure"]),
differingDomains: z.array(z.enum(domainNames)).max(DOMAINS.length),
});
export type ReportBirthScenario = z.infer<typeof reportBirthScenarioSchema>;
export type ReportBirthScenarios = Readonly<{ a: ReportBirthScenario | null; b: ReportBirthScenario | null }>;
export function reportBirthScenario(provenance: unknown): ReportBirthScenario | undefined {
const side = selfSelectedScenarioSide(provenance);
if (!side) return undefined;
const possible = asRecord(provenance)?.scenarios;
const scenarios = Array.isArray(possible) ? possible.map(asRecord) : [];
const primary = scenarios.find((scenario) => scenario?.is_primary === true);
const sign = (scenario: ReturnType<typeof asRecord>, chart: string) => {
const rows = scenario?.key_charts;
const value = Array.isArray(rows) ? asRecord(rows.find((row) => asRecord(row)?.chart === chart))?.sign : null;
return typeof value === "string" && value.length > 0 ? value : null;
};
const differingDomains = DOMAINS.flatMap(([chart, label]) => {
const primarySign = sign(primary ?? null, chart);
return primarySign && scenarios.some((scenario) => {
const alternative = sign(scenario, chart);
return scenario !== primary && alternative !== null && alternative !== primarySign;
}) ? [label] : [];
});
return { kind: "self_selected", side, differingDomains };
}
export function readReportBirthScenario(value: unknown): ReportBirthScenario | undefined {
const parsed = reportBirthScenarioSchema.safeParse(value);
return parsed.success ? parsed.data : undefined;
}
export function readReportBirthScenarios(value: unknown): ReportBirthScenarios | undefined {
const row = asRecord(value);
const a = readReportBirthScenario(row?.a);
const b = readReportBirthScenario(row?.b);
return a || b ? { a: a ?? null, b: b ?? null } : undefined;
}
const clockSchema = z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
export const reportBirthWindowSchema = z.strictObject({ time: clockSchema, start: clockSchema, end: clockSchema });
export type ReportBirthWindow = z.infer<typeof reportBirthWindowSchema>;
export function readReportBirthWindow(value: unknown): ReportBirthWindow | undefined {
const parsed = reportBirthWindowSchema.safeParse(value);
return parsed.success ? parsed.data : undefined;
}
function windowClock(minute: number) {
const clock = ((minute % 1440) + 1440) % 1440;
return `${String(Math.floor(clock / 60)).padStart(2, "0")}:${String(clock % 60).padStart(2, "0")}`;
}
/** Record only the window actually used. Never infer a missing range on read. */
export function recordReportBirthWindow(hour: unknown, minute: unknown, value: unknown): ReportBirthWindow | undefined {
const window = asRecord(value);
const before = window?.before_minutes;
const after = window?.after_minutes;
if (typeof hour !== "number" || !Number.isInteger(hour) || hour < 0 || hour > 23
|| typeof minute !== "number" || !Number.isInteger(minute) || minute < 0 || minute > 59
|| window?.known === false
|| window?.source === "default_unknown_30" || typeof before !== "number" || typeof after !== "number"
|| !Number.isFinite(before) || !Number.isFinite(after) || before < 0 || after < 0 || before + after > 2880) return undefined;
const used = hour * 60 + minute;
return readReportBirthWindow({
time: windowClock(used),
start: typeof window?.start_at === "string" ? window.start_at.slice(11, 16) : windowClock(used - Math.round(before)),
end: typeof window?.end_at === "string" ? window.end_at.slice(11, 16) : windowClock(used + Math.round(after)),
});
}
export type ArtifactKind = "personal" | "annual" | "synastry";
type Language = "zh" | "en";
const NOMINAL = {
personal: { zh: "报告", en: "report" },
annual: { zh: "年运", en: "annual report" },
synastry: { zh: "合盘", en: "synastry report" },
} as const;
export function reportBirthChangedCopy(kind: ArtifactKind, language: Language) {
const noun = NOMINAL[kind];
if (language === "en") {
return {
lead: kind === "synastry"
? "This synastry report was generated from both birth times on file at that time. At least one of them has since changed. You can "
: `This ${noun.en} was generated from the birth time on file at that time. You can `,
action: "generate it again", end: ".",
};
}
return {
lead: kind === "synastry"
? "这份合盘按当时两个人的出生时间生成,其中有人的出生时间后来改过,可"
: `这份${noun.zh}按当时的出生时间生成,可`,
action: "重新生成", end: "。",
};
}
function differingCopy(scenario: ReportBirthScenario, language: Language) {
const labels = scenario.differingDomains;
if (!labels.length) return "";
if (language === "en") {
const domains = labels.map((label) => DOMAINS.find(([, zh]) => zh === label)?.[2] ?? label);
return `The ascendant differs in the charts for ${domains.join(", ")} in another scenario. Those conclusions apply only to the scenario used here.`;
}
const aspects = labels.length === 1 ? "这方面" : labels.length === 2 ? "这两方面" : "这些方面";
const boundary = scenario.side === "unsure" ? "这份报告所用的情景" : "你选的这一侧";
return `另一种情景下,${labels.join("、")}的分盘上升星座不同,报告里${aspects}的判断只适用于${boundary}。`;
}
export function reportBirthScenarioCopy(scenario: ReportBirthScenario, kind: ArtifactKind, language: Language, person?: string) {
const noun = NOMINAL[kind];
if (language === "en") {
const side = scenario.side === "before" ? "before" : "after";
const statement = person
? scenario.side === "unsure"
? `For ${person}, this ${noun.en} uses the birth time they entered. They did not pick a side, and the time and range they entered are still kept.`
: `For ${person}, this ${noun.en} uses the time from their chosen scenario ${side} the transition. Their birth time has not been verified, and the time and range they entered are still kept.`
: scenario.side === "unsure"
? `You did not pick a side of the transition. This ${noun.en} uses the birth time you entered. Your entered time and range are still kept.`
: `This ${noun.en} uses the scenario you chose ${side} the transition. Your birth time has not been verified, and your entered time and range are still kept.`;
return [statement, differingCopy(scenario, language)].filter(Boolean).join(" ");
}
const side = scenario.side === "before" ? "线前" : "线后";
const statement = person
? scenario.side === "unsure"
? `这份合盘其中 ${person} 没有选定线前还是线后,按其填写的出生时间写成;填写的时间和范围都还保留着。`
: `这份合盘其中 ${person} 的出生时间按自己选的${side}情景写成,不是出生时间已核实;填写的时间和范围都还保留着。`
: scenario.side === "unsure"
? `你没有选定线前还是线后,这份${noun.zh}按你填的时间写成;你填的时间和范围都还保留着。`
: `这份${noun.zh}按你自己选的${side}情景写成,不是出生时间已核实;你填的时间和范围都还保留着。`;
return statement + differingCopy(scenario, language);
}
function markdownName(value: string) {
return value.replace(/\s+/g, " ").replace(/[\\`*_[\]<>&#]/g, "\\$&");
}
export function reportBirthExportPreamble(input: Readonly<{
kind: ArtifactKind; language: Language; state?: BirthInputState;
scenario?: ReportBirthScenario; scenarios?: ReportBirthScenarios;
names?: Readonly<{ a: string; b: string }>; window?: ReportBirthWindow;
}>): string | undefined {
const { language, state, kind, scenario, scenarios, names, window } = input;
const lines: string[] = [];
if (state === "changed") {
lines.push(language === "zh"
? "这份报告按当时的出生时间生成,之后出生时间改过。"
: kind === "synastry"
? "This synastry report was generated from both birth times on file at that time. At least one of them has since changed."
: `This ${NOMINAL[kind].en} was generated from the birth time on file at that time. The birth time has since changed.`);
if (window) lines.push(language === "zh"
? `生成时使用的出生时间:${window.time}(范围 ${window.start}–${window.end})`
: `Birth time used: ${window.time} (range ${window.start}–${window.end})`);
}
if (scenario) lines.push(reportBirthScenarioCopy(scenario, kind, language));
if (scenarios && names) {
if (scenarios.a) lines.push(reportBirthScenarioCopy(scenarios.a, kind, language, markdownName(names.a)));
if (scenarios.b) lines.push(reportBirthScenarioCopy(scenarios.b, kind, language, markdownName(names.b)));
}
return lines.length ? lines.map((line) => `> ${line}`).join("\n>\n") : undefined;
}
export const REPORT_BIRTH_CHANGED_FAILURE = "生成期间出生资料改过,这次没有扣点。请重新生成。";
+27 -6
View File
@@ -1,3 +1,4 @@
import { reportBirthExportPreamble, type ReportBirthScenario, type ReportBirthWindow } from "./report-birth-marking.ts";
import type { BirthInputState } from "./birth-input-revision";
import type { ReportDocumentV2 } from "./personal-report-contract";
import { reportChartExportSvg } from "./report-chart-export";
@@ -23,11 +24,20 @@ export type ReportExportBlock = Readonly<{
title: string;
text: string;
chars: number;
metadata?: Readonly<{ birthInputState: BirthInputState }>;
metadata?: Readonly<{ birthInputState?: BirthInputState; preambleMarkdown?: string }>;
}>;
export function withExportBirthInputState(blocks: ReportExportBlock[], birthInputState?: BirthInputState): ReportExportBlock[] {
return birthInputState ? blocks.map((block) => ({ ...block, metadata: { birthInputState } })) : blocks;
export function withExportBirthInputState(
blocks: ReportExportBlock[],
birthInputState?: BirthInputState,
preambleMarkdown?: string,
): ReportExportBlock[] {
if (!birthInputState && !preambleMarkdown) return blocks;
const metadata = {
...(birthInputState ? { birthInputState } : {}),
...(preambleMarkdown ? { preambleMarkdown } : {}),
};
return blocks.map((block) => ({ ...block, metadata }));
}
export type ReportExportPreset = "common" | "charts" | "tables";
@@ -73,12 +83,14 @@ export function factTableToMarkdown(group: ReportFactTable, language: ReportLang
].filter(Boolean).join("\n\n"), language);
}
export function buildReportExportBlocks({ markdown, charts = [], factTables = [], language = "zh", reading, birthInputState }: {
export function buildReportExportBlocks({ markdown, charts = [], factTables = [], language = "zh", reading, birthInputState, birthScenario, artifactBirthWindow }: {
markdown: string;
charts?: ReportDocumentV2["charts"];
factTables?: readonly ReportFactTable[];
reading?: ReportReading | null;
birthInputState?: BirthInputState;
birthScenario?: ReportBirthScenario;
artifactBirthWindow?: ReportBirthWindow;
/** Which edition `markdown` and `factTables` are; labels added here follow it. */
language?: ReportLanguage;
}): ReportExportBlock[] {
@@ -136,7 +148,9 @@ export function buildReportExportBlocks({ markdown, charts = [], factTables = []
add(`chart:${chart.id}`, "chart", title, projectOrdinaryReportMarkdown(`${text}\n\n${reportChartExportSvg(chart, title, language)}`, language));
}
for (const table of factTables) add(`table:${table.id}`, "table", table.title, factTableToMarkdown(table, language));
return withExportBirthInputState(blocks, birthInputState);
return withExportBirthInputState(blocks, birthInputState, reportBirthExportPreamble({
kind: "personal", language, state: birthInputState, scenario: birthScenario, window: artifactBirthWindow,
}));
}
export function joinExportBlocks(blocks: readonly ReportExportBlock[]): string {
@@ -153,7 +167,14 @@ export function joinExportBlocks(blocks: readonly ReportExportBlock[]): string {
joinSource(bodyBlocks.slice(readingIndex + 1)).replace(/^(?:\r?\n)+/, ""),
].filter(Boolean).join("\n\n");
const added = blocks.filter(block => block.group !== "body").map(block => block.text).join("\n\n");
return body && added ? `${body}\n\n${added}` : body || added;
const markdown = body && added ? `${body}\n\n${added}` : body || added;
const preamble = blocks.find((block) => block.metadata?.preambleMarkdown)?.metadata?.preambleMarkdown;
if (!preamble) return markdown;
const title = /^(\ufeff?[ \t]*#[ \t]+[^\r\n]+)(\r?\n|$)/.exec(markdown);
if (!title) return `${preamble}\n\n${markdown}`;
const eol = title[2] || "\n";
const rest = markdown.slice(title[0].length).replace(/^(?:[ \t]*\r?\n)+/, "");
return `${title[1]}${eol}${eol}${preamble.replaceAll("\n", eol)}${rest ? eol + eol + rest : ""}`;
}
export function presetSelection(preset: ReportExportPreset, blocks: readonly ReportExportBlock[]): Set<string> {
@@ -32,6 +32,7 @@ export type SynastryDelivery = Readonly<{
export type SynastrySnapshot = Readonly<{
birthInputState?: import("./birth-input-revision").BirthInputState;
birthScenarios?: import("./report-birth-marking").ReportBirthScenarios;
names: Readonly<{ a: string; b: string }>;
matching_profiles?: SynastryMatchingProfiles;
sections: ReadonlyArray<Readonly<{ id: SynastrySectionId; title: string; text: string; reasons: readonly SynastryReason[] }>>;
+28 -8
View File
@@ -1,6 +1,9 @@
import "server-only";
import { birthInputRevision, birthInputState } from "@/lib/birth-input-revision";
import { birthInputRevision } from "@/lib/birth-input-revision";
import { readReportBirthScenarios, reportBirthScenario } from "@/lib/report-birth-marking";
import { assertSynastryBirthInputs, persistSynastrySnapshotWithBirthCheck } from "@/lib/synastry-snapshot-birth-check";
import { ConsultationSubjectError } from "@/lib/subject-birth";
import { createHash } from "node:crypto";
import { createSynastrySectionWriter } from "@/mastra/synastry-report";
@@ -134,7 +137,9 @@ export function publicSynastryView(payload: unknown): SynastrySnapshot | null {
const zh = asRecord(row?.zh);
if (!row || !names || typeof names.a !== "string" || typeof names.b !== "string" || !zh) return null;
const matchingProfiles = synastryMatchingProfiles(hasRamanMatchingProfile(row.matching_profiles));
const birthScenarios = readReportBirthScenarios(row.birthScenarios);
const view: SynastrySnapshot = {
...(birthScenarios ? { birthScenarios } : {}),
names: { a: names.a, b: names.b },
matching_profiles: matchingProfiles,
sections: zh.sections as SynastrySnapshot["sections"],
@@ -197,17 +202,22 @@ export async function runSynastryFullReport(input: Readonly<{
input.report.subjectHigh,
orderPayload,
);
const [personA, personB] = await Promise.all([
const loadPair = () => Promise.all([
loadSynastrySubjectBirth(input.admin, input.admin, input.report.userId, firstId),
loadSynastrySubjectBirth(input.admin, input.admin, input.report.userId, secondId),
]);
const [personA, personB] = await loadPair();
const birthInputRevisions = { a: birthInputRevision(personA.row), b: birthInputRevision(personB.row) };
const scenarioA = reportBirthScenario(personA.row.active_birth_provenance);
const scenarioB = reportBirthScenario(personB.row.active_birth_provenance);
const birthMarking = scenarioA || scenarioB ? { birthScenarios: { a: scenarioA ?? null, b: scenarioB ?? null } } : {};
const birthInputSubjects = { a: firstId, b: secondId };
const expected = asRecord(asRecord(orderPayload)?.birthInputRevisions);
if (expected && birthInputState({
a: typeof expected.a === "string" ? expected.a : undefined,
b: typeof expected.b === "string" ? expected.b : undefined,
}, birthInputRevisions) !== "current") throw new PersonalReportWorkerError("birth_input_changed", false);
const storedRevisions = asRecord(asRecord(orderPayload)?.birthInputRevisions);
const expected = storedRevisions ? {
a: typeof storedRevisions.a === "string" ? storedRevisions.a : undefined,
b: typeof storedRevisions.b === "string" ? storedRevisions.b : undefined,
} : null;
assertSynastryBirthInputs(expected, birthInputRevisions);
// The report row saves the choice before the worker starts. Its engine version may change before a retry.
const compareRamanKuja = input.report.synastryRulesVersion?.endsWith(`:${RAMAN_MATCHING_PROFILE}`) === true;
const matchingProfiles = synastryMatchingProfiles(compareRamanKuja);
@@ -276,9 +286,18 @@ export async function runSynastryFullReport(input: Readonly<{
zh: written.snapshotParts,
birthInputRevisions,
birthInputSubjects,
...birthMarking,
};
await input.onProgress?.({ phase: "persisting_report", completed: SYNASTRY_V3_ORDER.length, total: SYNASTRY_V3_ORDER.length });
await writeSnapshot(input.admin, input.report, payload);
await persistSynastrySnapshotWithBirthCheck(expected, async () => {
try {
const [currentA, currentB] = await loadPair();
return { a: birthInputRevision(currentA.row), b: birthInputRevision(currentB.row) };
} catch (error) {
if (error instanceof ConsultationSubjectError) return {};
throw error;
}
}, () => writeSnapshot(input.admin, input.report, payload));
const storedMatch = await input.admin.from("synastry_reports")
.select("id")
.eq("user_id", input.report.userId)
@@ -307,6 +326,7 @@ export async function runSynastryFullReport(input: Readonly<{
schemaVersion: "synastry_report.v1", reportId: input.report.id, names,
sectionId: SNAPSHOT_SECTION, structure: written.snapshotParts.structure,
birthInputRevisions,
...birthMarking,
matching_profiles: matchingProfiles,
},
calculationHash: sha256(dossier),
+7 -1
View File
@@ -1,5 +1,6 @@
// 2026-11-16 owner: the synastry report gets the same plain-text .md export as the annual report.
import type { BirthInputState } from "./birth-input-revision";
import { reportBirthExportPreamble, type ReportBirthScenarios } from "./report-birth-marking.ts";
import { withExportBirthInputState, type ReportExportBlock } from "./report-export-blocks";
type Row = Record<string, unknown>;
@@ -43,6 +44,8 @@ export type SynastryExportInput = Readonly<{
practices: unknown;
technical: unknown;
birthInputState?: BirthInputState;
birthScenarios?: ReportBirthScenarios;
names?: Readonly<{ a: string; b: string }>;
}>;
export function buildSynastryExportBlocks(input: SynastryExportInput): ReportExportBlock[] {
@@ -87,5 +90,8 @@ export function buildSynastryExportBlocks(input: SynastryExportInput): ReportExp
if (!text(source.title) || lines.length === 0) continue;
blocks.push(block(`table:${text(item.id)}`, "table", text(source.title), [lines.join("\n")]));
}
return withExportBirthInputState(blocks, input.birthInputState);
return withExportBirthInputState(blocks, input.birthInputState, reportBirthExportPreamble({
kind: "synastry", language: input.language, state: input.birthInputState,
scenarios: input.birthScenarios, names: input.names,
}));
}
@@ -0,0 +1,17 @@
import { birthInputState, type BirthInputPair } from "./birth-input-revision.ts";
import { PersonalReportWorkerError } from "./personal-report-worker-core.ts";
export function assertSynastryBirthInputs(expected: BirthInputPair | null, current: BirthInputPair): void {
if (expected && birthInputState(expected, current) !== "current") {
throw new PersonalReportWorkerError("birth_input_changed", false);
}
}
export async function persistSynastrySnapshotWithBirthCheck(
expected: BirthInputPair | null,
readCurrent: () => Promise<BirthInputPair>,
persist: () => Promise<void>,
): Promise<void> {
if (expected) assertSynastryBirthInputs(expected, await readCurrent());
await persist();
}
@@ -261,7 +261,10 @@ test("export blocks attach input state without changing the Markdown body", () =
const oldBlocks = buildReportExportBlocks(input);
const newBlocks = buildReportExportBlocks({ ...input, birthInputState: "changed" });
assert.deepEqual(newBlocks.map((block) => block.metadata?.birthInputState), oldBlocks.map(() => "changed"));
assert.equal(joinExportBlocks(newBlocks), joinExportBlocks(oldBlocks));
assert.deepEqual(newBlocks.map((block) => block.text), oldBlocks.map((block) => block.text));
assert.equal(joinExportBlocks(newBlocks), joinExportBlocks(oldBlocks).replace(
"# Synthetic report\n\n", "# Synthetic report\n\n> 这份报告按当时的出生时间生成,之后出生时间改过。\n\n",
));
});
test("annual reuse ignores changed and legacy generating rows while preserving ready history", async () => {
+1 -1
View File
@@ -1444,7 +1444,7 @@ test("GET route imports codes from the pure module, never the generation module"
});
test("generation pipeline re-validates with the canonical server parse after the guard", () => {
assert.match(generationSource, /safeParseServerReportDocument\(withReportBirthInputRevision\(guarded\.document, deps\.birthInputRevision\)\)/);
assert.match(generationSource, /safeParseServerReportDocument\(withReportBirthInputRevision\(guarded\.document, deps\.birthInputRevision, deps\.birthScenario\)\)/);
assert.match(generationSource, /assembleReportDocument/);
});
@@ -0,0 +1,185 @@
import "./install-test-document";
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { AnnualReportView } from "../src/components/annual/annual-report-page";
import { PersonalReportMarkdownView } from "../src/components/personal-report/personal-report-markdown-view";
import { classifyReportEnvelope } from "../src/components/personal-report/personal-report-page";
import { ReportBirthNotices } from "../src/components/personal-report/report-birth-notices";
import { SynastryReportView } from "../src/components/synastry/synastry-report-view";
import { buildAnnualExportBlocks } from "../src/lib/annual-report-export";
import type { AnnualSnapshot } from "../src/lib/annual-report-generate";
import type { BirthInputState } from "../src/lib/birth-input-revision";
import type { PersonalReportJobRecord } from "../src/lib/personal-report-job-service-core";
import type { PersonalReportRecord } from "../src/lib/personal-report-service-core";
import { createPersonalReportWorker } from "../src/lib/personal-report-worker-core";
import { withReportBirthInputRevision } from "../src/lib/report-birth-binding";
import {
recordReportBirthWindow, reportBirthScenario, readReportBirthScenarios, REPORT_BIRTH_CHANGED_FAILURE, type ReportBirthScenario,
} from "../src/lib/report-birth-marking";
import { buildReportExportBlocks, joinExportBlocks } from "../src/lib/report-export-blocks";
import { buildSynastryExportBlocks } from "../src/lib/synastry-report-export";
import { persistSynastrySnapshotWithBirthCheck } from "../src/lib/synastry-snapshot-birth-check";
Object.assign(globalThis, { React });
const markdown = "# 测试报告\n\n一段正文。\n";
const exportCopy = "这份报告按当时的出生时间生成,之后出生时间改过。";
const annual: AnnualSnapshot = {
kind: "annual_report_snapshot", version: 1, status: "ready", subject: { name: "虚构甲", isSelf: false },
range: { kind: "birthday_year", key: "synthetic", label: "测试年度", span: "", crossesBirthday: false, birthdays: [] },
factsSha256: "synthetic", appendix: [], plan: [], sections: {}, windows: [], remaining: [],
};
const names = { a: "虚构甲", b: "虚构乙" };
const pair = {
title: "测试合盘", savedLine: "", language: "zh" as const, order: [], headings: {}, sections: [],
timeline: [], events: [], eventNote: "", practices: [], technical: [],
};
const window = recordReportBirthWindow(23, 58, { before_minutes: 8, after_minutes: 7 });
const before: ReportBirthScenario = { kind: "self_selected", side: "before", differingDomains: ["婚恋"] };
const after: ReportBirthScenario = { kind: "self_selected", side: "after", differingDomains: ["婚恋", "事业"] };
const unsure: ReportBirthScenario = { kind: "self_selected", side: "unsure", differingDomains: [] };
const forbidden = /无法确认|未核对|没有通过核对|已校正|已确认/;
function viewPersonal(state?: BirthInputState, scenario?: ReturnType<typeof reportBirthScenario>, language: "zh" | "en" = "zh") {
return renderToStaticMarkup(<PersonalReportMarkdownView markdown={markdown} language={language} birthNotices={
<ReportBirthNotices kind="personal" language={language} state={state} scenario={scenario} regenerateHref="/reports" />
} />);
}
test("the three report readers put changed birth input below the title with their existing regeneration links", () => {
const views = [
{ render: viewPersonal, before: "这份报告按当时的出生时间生成,可", href: "/reports" },
{
render: (birthInputState?: BirthInputState) => renderToStaticMarkup(<AnnualReportView snapshot={{ ...annual, birthInputState }} generating={false} />),
before: "这份年运按当时的出生时间生成,可", href: "/reports",
},
{
render: (birthInputState?: BirthInputState) => renderToStaticMarkup(<SynastryReportView reportId="synthetic" snapshot={{ names, birthInputState }} />),
before: "这份合盘按当时两个人的出生时间生成,其中有人的出生时间后来改过,可", href: "/synastry",
},
];
for (const { render, before, href } of views) {
const marked = render("changed");
assert.match(marked, new RegExp(`</h[12]><p[^>]*>${before}<a[^>]*href="${href}"[^>]*>重新生成</a>。</p>`));
assert.doesNotMatch(marked, forbidden);
for (const state of ["current", "unknown", undefined] as const) {
assert.ok(!render(state).includes(before));
}
}
assert.match(viewPersonal("changed", undefined, "en"),
/This report was generated from the birth time on file at that time\. You can <a[^>]*>generate it again<\/a>\./);
});
test("each export inserts its quote after the heading and leaves all unmarked bytes intact", () => {
const exports = [
{ build: (birthInputState?: BirthInputState) => buildReportExportBlocks({ markdown, birthInputState, artifactBirthWindow: window }), hasRange: true },
{ build: (birthInputState?: BirthInputState) => buildAnnualExportBlocks({ ...annual, birthInputState, artifactBirthWindow: window }), hasRange: true },
{ build: (birthInputState?: BirthInputState) => buildSynastryExportBlocks({ ...pair, birthInputState }), hasRange: false },
];
for (const { build, hasRange } of exports) {
const plain = joinExportBlocks(build());
assert.equal(joinExportBlocks(build("current")), plain);
assert.equal(joinExportBlocks(build("unknown")), plain);
const changed = joinExportBlocks(build("changed"));
assert.match(changed, new RegExp(`^# [^\n]+\n\n> ${exportCopy}`));
assert.equal(changed.includes("生成时使用的出生时间:23:58(范围 23:50–00:05)"), hasRange);
assert.equal(changed.split(exportCopy).length, 2);
}
assert.equal(joinExportBlocks(buildReportExportBlocks({ markdown })), markdown);
assert.doesNotMatch(joinExportBlocks(buildReportExportBlocks({ markdown, birthInputState: "changed" })), /生成时使用的出生时间/);
assert.equal(recordReportBirthWindow(12, 0, { before_minutes: 30, after_minutes: 30, source: "default_unknown_30" }), undefined);
});
test("report metadata freezes the chosen side and only the differing ascendants", () => {
const main = { is_primary: true, key_charts: [{ chart: "D9", sign: "Aries" }, { chart: "D10", sign: "Leo" }, { chart: "D2", sign: "Cancer" }] };
const different = { key_charts: [{ chart: "D9", sign: "Taurus" }, { chart: "D10", sign: "Virgo" }, { chart: "D2", sign: "Cancer" }] };
const provenance = { selection_kind: "self_selected_scenario", scenarios: [main, different] };
const document = { subject: { name: "虚构甲" } };
for (const side of ["before", "after", "unsure"] as const) {
const scenario = reportBirthScenario({ ...provenance, choices: [{ side }] });
assert.deepEqual(scenario, { ...after, side });
assert.deepEqual(withReportBirthInputRevision(document, "synthetic", scenario), {
subject: { ...document.subject, birthInputRevision: "synthetic", birthScenario: { ...after, side } },
});
}
assert.deepEqual(reportBirthScenario({ ...provenance, scenarios: [main] }), unsure);
assert.equal(reportBirthScenario({ scenarios: [main, different] }), undefined);
assert.deepEqual(withReportBirthInputRevision(document, "synthetic"), { subject: { ...document.subject, birthInputRevision: "synthetic" } });
assert.deepEqual(readReportBirthScenarios({ a: before, b: null }), { a: before, b: null });
});
test("scenario wording appears once, with actual domains and the changed notice ahead of it", () => {
for (const [input, copy] of [
[before, "线前情景"], [after, "线后情景"], [unsure, "你没有选定线前还是线后"],
] as const) {
const scenario = { ...input, differingDomains: [...input.differingDomains] };
const html = viewPersonal("changed", scenario);
assert.ok(html.indexOf("按当时的出生时间生成") < html.indexOf(copy));
assert.equal(html.split(copy).length, 2);
const exported = joinExportBlocks(buildReportExportBlocks({ markdown, birthScenario: scenario, birthInputState: "changed" }));
assert.ok(exported.indexOf(exportCopy) < exported.indexOf(copy));
assert.equal(exported.split(copy).length, 2);
assert.doesNotMatch(html + exported, forbidden);
}
assert.match(viewPersonal(undefined, { ...before, differingDomains: ["婚恋"] }), /婚恋的分盘上升星座不同,报告里这方面/);
assert.match(viewPersonal(undefined, { ...after, differingDomains: ["婚恋", "事业"] }), /婚恋、事业的分盘上升星座不同,报告里这两方面/);
const one = renderToStaticMarkup(<SynastryReportView reportId="synthetic" snapshot={{ names, birthScenarios: { a: before, b: null } }} />);
assert.match(one, /其中 虚构甲 的出生时间按自己选的线前情景/);
assert.doesNotMatch(one, /其中 虚构乙/);
const both = joinExportBlocks(buildSynastryExportBlocks({ ...pair, names, birthScenarios: { a: before, b: after } }));
assert.match(both, /其中 虚构甲[^\n]+\n>\n> .*其中 虚构乙/);
});
test("failed report envelopes retain the typed birth input reason and other failure summaries", () => {
const report = { status: "failed", failureSummary: "原有提示" };
assert.deepEqual(classifyReportEnvelope(200, { report, failureReason: "birth_input_changed" }), {
phase: "failed", failureCode: null, failureSummary: report.failureSummary, failureReason: "birth_input_changed",
});
assert.deepEqual(classifyReportEnvelope(200, { report, failureReason: "other" }), {
phase: "failed", failureCode: null, failureSummary: report.failureSummary,
});
assert.equal(REPORT_BIRTH_CHANGED_FAILURE, "生成期间出生资料改过,这次没有扣点。请重新生成。");
});
test("a changed pair cannot write the snapshot and the worker releases the existing reservation", async () => {
const job = {
id: "job", leaseToken: "lease", userId: "owner", requestId: "request", requestFingerprint: "intent", attemptCount: 1, maxAttempts: 3,
} as PersonalReportJobRecord;
const report = {
userId: job.userId, requestId: job.requestId, requestFingerprint: job.requestFingerprint, reportType: "synastry_full", status: "generating",
} as PersonalReportRecord;
const calls: string[] = [];
const expected = { a: "one", b: "two" };
const worker = createPersonalReportWorker({
workerId: "worker",
reports: { getByUserAndRequestId: async () => report },
jobs: {
recoverExpiredLeases: async () => ({ retryingCount: 0, failedCount: 0 }),
claimLease: async () => job, updateProgress: async () => job, heartbeatLease: async () => job,
completeReportReady: async () => { assert.fail("must not publish"); },
completeReportFailed: async ({ errorCode }) => { calls.push(`failed:${errorCode}`); return job; },
markReady: async () => { assert.fail("must not publish"); },
markFailed: async () => { assert.fail("must close report and job together"); },
scheduleRetry: async () => { assert.fail("must not retry a changed revision"); },
},
loadProfile: async () => ({}),
generate: async () => {
await persistSynastrySnapshotWithBirthCheck(expected, async () => ({ ...expected, b: "new" }), async () => {
assert.fail("must not write the final snapshot");
});
assert.fail("must fail before returning a generated report");
},
billing: {
reserve: async () => { assert.fail("must not reserve twice"); },
complete: async () => { assert.fail("must not charge"); },
release: async ({ reason }) => { calls.push(`released:${reason}`); return true; },
},
});
assert.equal((await worker.tick()).outcome, "failed");
assert.deepEqual(calls, ["released:birth_input_changed", "failed:birth_input_changed"]);
await persistSynastrySnapshotWithBirthCheck(expected, async () => { calls.push("read"); return expected; }, async () => { calls.push("write"); });
await persistSynastrySnapshotWithBirthCheck(null, async () => { assert.fail("legacy jobs must skip the recheck"); }, async () => { calls.push("legacy-write"); });
assert.deepEqual(calls.slice(2), ["read", "write", "legacy-write"]);
});