feat(report): birth-sky report cover bound to the report's birth fingerprint (F1–F3)
Product decision A (TASK-birth-sky-followup-20260928): - every generation path writes subject.birthFingerprint (stored-row fingerprint, same function as the chart page's profileFingerprint); never into the evidence bundle the model reads - GET /api/reports/:id compares on the server and returns only report.coverSubject (subject id or null); legacy reports never get one - report page shows the night cover above the body, paper cover alone on the first printed A4 page; silent on any failure, no waiting state - TS / JSON schema / Python contract accept the optional field - BLOCKED T5 struck through; DESIGN §17, CHANGELOG, checklist, PROGRESS Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01N4f2nya58RoRu4yEmJgRGE
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
14ef18ac24
commit
a9a917d50c
+11
-10
@@ -1,17 +1,18 @@
|
||||
# BLOCKED
|
||||
|
||||
## TASK-birth-sky-cover T5:报告封面没有可靠的出生资料绑定(2026-09-28)
|
||||
## ~~TASK-birth-sky-cover T5:报告封面没有可靠的出生资料绑定(2026-09-28)~~ → 已解除:产品 2026-09-28 选 A
|
||||
|
||||
- 任务书要求「只有报告生成时的出生资料与现在一致时才显示封面」。逐项查过,报告侧**没有任何出生资料指纹**:
|
||||
- `personal_reports` 表列(`20260806010000_personal_reports.sql` 及其后 `add column`):`chart_profile_id`、`request_fingerprint`、`calculation_hash`、`evidence_hash` 等,没有出生资料快照或 `profileFingerprint`。
|
||||
- `request_fingerprint` 只哈希 `reportType / presentationMode / depth / themes / sessionId / chartProfileId`(`personal-report-route-core.ts` `computeRequestFingerprint`),不含出生资料。
|
||||
- `calculation_hash`:普通报告取引擎 `result_hash`(含计算结果,不是出生资料指纹,且 BUG-693/694 记过哈希含墙钟);长报告取 markdown 全文的 sha256(`personal-report-longform-cover.ts`)。两者都不能和当前 `profileFingerprint` 比。
|
||||
- 报告文档 `subject` 只有 `displayName / birthTimeStatus / birthPlaceLabel`;`personal_report_jobs`、`personal_report_sections`、`personal_report_longform_appendices` 也没有出生资料。
|
||||
- 仓库里 `result_binding` 只出现在 Python 的 `calculation_profile_contract.py` / `full_report_quality_gate.py`,不进报告行。
|
||||
- 按任务书:本单**不显示**报告封面,不拿当前资料冒充当时资料;`reportView` 未改、报告页未改、打印样式未改,旧报告不补算不补写库。
|
||||
- 解除需要一个产品决定(二选一,都不改表结构):① 生成报告时把当时的 `profileFingerprint`(`resolveServerOwnedChartBirth(...).fingerprint`)写进报告文档(如 `subject.birthFingerprint`,v2 schema 加可选字段),只对新报告生效,旧报告永远无封面;② 接受「当前资料」作为封面依据并在封面上说明——与任务书红线冲突,需产品推翻。
|
||||
- `draw.ts` 的 `paper` palette 已实现并有单测(打印用),解除后报告封面可直接复用。
|
||||
- ~~任务书要求「只有报告生成时的出生资料与现在一致时才显示封面」。逐项查过,报告侧**没有任何出生资料指纹**:~~
|
||||
- ~~`personal_reports` 表列(`20260806010000_personal_reports.sql` 及其后 `add column`):`chart_profile_id`、`request_fingerprint`、`calculation_hash`、`evidence_hash` 等,没有出生资料快照或 `profileFingerprint`。~~
|
||||
- ~~`request_fingerprint` 只哈希 `reportType / presentationMode / depth / themes / sessionId / chartProfileId`(`personal-report-route-core.ts` `computeRequestFingerprint`),不含出生资料。~~
|
||||
- ~~`calculation_hash`:普通报告取引擎 `result_hash`(含计算结果,不是出生资料指纹,且 BUG-693/694 记过哈希含墙钟);长报告取 markdown 全文的 sha256(`personal-report-longform-cover.ts`)。两者都不能和当前 `profileFingerprint` 比。~~
|
||||
- ~~报告文档 `subject` 只有 `displayName / birthTimeStatus / birthPlaceLabel`;`personal_report_jobs`、`personal_report_sections`、`personal_report_longform_appendices` 也没有出生资料。~~
|
||||
- ~~仓库里 `result_binding` 只出现在 Python 的 `calculation_profile_contract.py` / `full_report_quality_gate.py`,不进报告行。~~
|
||||
- ~~按任务书:本单**不显示**报告封面,不拿当前资料冒充当时资料;`reportView` 未改、报告页未改、打印样式未改,旧报告不补算不补写库。~~
|
||||
- ~~解除需要一个产品决定(二选一,都不改表结构):① 生成报告时把当时的 `profileFingerprint`(`resolveServerOwnedChartBirth(...).fingerprint`)写进报告文档(如 `subject.birthFingerprint`,v2 schema 加可选字段),只对新报告生效,旧报告永远无封面;② 接受「当前资料」作为封面依据并在封面上说明——与任务书红线冲突,需产品推翻。~~
|
||||
- ~~`draw.ts` 的 `paper` palette 已实现并有单测(打印用),解除后报告封面可直接复用。~~
|
||||
- 同单其余环境缺口:无登录态与真机(星盘页按钮、保存 / 分享、首次揭幕按 `docs/testing/birth-sky-cover-checklist.md` 走);无 Docker(24 条 DB / 部署套件失败与基线逐条同名)。未推送、未部署。
|
||||
- **已解除(2026-09-28,TASK-birth-sky-followup-20260928 F1–F3)**:产品选方案 A。新生成的报告在 `subject.birthFingerprint` 写入生成时的出生资料指纹(与星盘页 `profileFingerprint` 同一算法、同取存储行);`GET /api/reports/:id` 在服务端比对当前指纹,只下发 `coverSubject`(人物 id 或 null),不下发指纹与出生资料。旧报告没有该字段,永远不显示封面,不补算不回填;不改表结构。
|
||||
|
||||
## TASK-site-button-contrast(BUG-1079):真机、登录态与两条待决发现(2026-09-28)
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-09-28 — 「那一刻的天空」追加:报告封面上线(待验收)
|
||||
|
||||
- 从这次起,新生成的报告会记下生成时用的是哪一套出生资料;打开报告时,只要这套资料和现在一致,正文最上方就有一张「那一刻的天空」封面(深色,和星盘页那张同一种画法)。打印或存 PDF 时封面换成浅色纸面版,单独占第一页。
|
||||
- 以前生成的报告没有这份记录,永远不显示封面;改过出生时间或出生地之后,改之前生成的报告也不再显示封面。
|
||||
- 封面拿不到就不显示,不留空白、不转圈,报告正文不受影响。浏览器拿不到出生资料和指纹,只知道「要不要画、画谁」。
|
||||
- Skill 版本不 bump(Skill 文本未改)。不改数据库结构。
|
||||
|
||||
## 2026-09-28 — 星盘页新增「那一刻的天空」(待验收)
|
||||
|
||||
- 星盘页顶栏右侧多一个按钮「那一刻的天空」:出生地、出生那一刻头顶的真实天空,画成一张 3:4 的图。天顶在圆心、东在左,地平线以上的行星和亮星(北斗、仙后、猎户连线)照实画。
|
||||
|
||||
@@ -295,6 +295,10 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"birthFingerprint": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{32}$"
|
||||
}
|
||||
},
|
||||
"required": ["displayName", "birthTimeStatus", "birthPlaceLabel"]
|
||||
|
||||
@@ -704,6 +704,10 @@
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"birthFingerprint": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9a-f]{32}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -109,3 +109,38 @@ JS 的 +773 B 是首页为 T6 引入的 `useBirthSkyReveal`、`startBirthSkyReve
|
||||
- 无 `.venv`:Python 用系统 `python3`。
|
||||
- 无头 Chrome 的 `--screenshot` 在本机对这页时好时坏(挂起),海报改用 `canvas.toDataURL` + `--dump-dom` 取出,是导出 PNG 的真实像素。
|
||||
- 未推送、未部署。
|
||||
|
||||
---
|
||||
|
||||
## 追加单(`TASK-birth-sky-followup-20260928`)
|
||||
|
||||
- 任务书:`docs/tasks/TASK-birth-sky-followup-20260928.md`(staging-docs)。产品授权直接执行(Claude 子代理)。
|
||||
- 基线:开工 `git fetch origin --prune` 后 `origin/staging` 仍是 `d670521f`,无需 rebase;本分支在前三个提交(`d277cbd8`、`028aef27`、`14ef18ac`)之上再加两个提交。
|
||||
- BUG 编号:开工时最大 BUG-1079;新功能,未开 BUG。
|
||||
|
||||
### F1 · 报告写入出生资料指纹
|
||||
|
||||
- 新模块 `frontend/src/lib/report-birth-binding.ts`:`subjectBirthFingerprint(row)` = `resolveServerOwnedChartBirth(row).fingerprint`。
|
||||
- **与星盘页同一种算法、同一种输入**:星盘页的 `profileFingerprint` 来自 `prepareChartViewProfile`,它取的是**存储行**的指纹(`stored.fingerprint`,在内存补全时区之前)。报告两处加载点(`POST /api/reports` 与 worker 的 `loadReportWorkerProfile`)都先 `loadSubjectBirth` 取存储行、再补时区,所以在补全之前用 `stampReportBirthFingerprint(resolved.row, filled)` 把指纹挂在内存行的 `report_birth_fingerprint` 上(只在服务端内存里,不落库、不进引擎输入)。测试证明:缺时区的行,补全前后指纹不同,补全前的等于星盘页。
|
||||
- 三条生成路径都写 `subject.birthFingerprint`:
|
||||
- 路由内联生成(`resolveReportCreate` → `generatePersonalReport`);
|
||||
- worker writer 路径(`generateWriterReport` → `generatePersonalReport`,单次调用与分章两种组装都在 guard 之前写入);
|
||||
- worker 长报告路径(`generatePersonalReportLongform` → `buildLongformCoverDocument`)。
|
||||
- 指纹**不进证据包**(bundle 会被发给模型),只在组装后的文档上写:`generatePersonalReport` 新增可选 `birthFingerprint`,在 `applyReportGuard` 之前写到候选文档上,随后照常走最终 server parse。
|
||||
- Schema:TS `subjectSchema`(v1/v2 共用)、`contracts/personal-report/report-document.v1|v2.schema.json`、Python `scripts/personal_report_contract.py` 都加可选 `birthFingerprint`(`^[0-9a-f]{32}$`)。旧文档不含该字段照常解析;格式不对的拒绝。
|
||||
- 测试:`frontend/tests/report-birth-binding.test.ts`(7 条:同算法 / 补时区前取;worker 加载器写入;三条路径接线;长报告写入与缺省;旧文档解析与坏格式;coverSubject 判定;GET 路由在服务端比对)、`personal-report-api.test.ts` 追加「inline generation writes subject.birthFingerprint」、`personal-report-generation-v2.test.ts` 追加「single-call and sectioned generation write subject.birthFingerprint only when given」(并断言分章调用发给模型的 bundle 不含指纹)、`tests/test_personal_report_contract.py` 追加 1 条。
|
||||
|
||||
### F2 · 服务端比对
|
||||
|
||||
- `reportView(row, job, failure, sections, coverSubject?)`:新增第 5 个可选参数,传入时输出 `coverSubject`。`resolveReportRead` 只在 `ready` 分支计算:读 `row.reportDocument.subject.birthFingerprint` → 没有就直接 `null`(不查库)→ 有则调新依赖 `loadCurrentBirthFingerprint(userId, subjectId)`(`subjectId` = `chart_profile_id ?? "self"`)→ 相等给 subject id,否则 `null`;加载器抛错(不是自己的人物、已删除、读不到)一律 `null`。
|
||||
- `GET /api/reports/:id` 用 `loadSubjectBirth(supabase, userId, subjectId)`(与星盘页同一个人物加载器,按 `user_id` 限定)取存储行再算指纹。
|
||||
- 响应里不含指纹:`reportDocument` 走 `projectOrdinaryReportDocument`,本来就不带 `subject`。
|
||||
- 测试(`personal-report-api.test.ts` 追加 4 条):一致(本人 `self`、家人给人物 id,序列化响应不含指纹、出生日期、经纬度、时区、地名);不一致;缺字段(且不查库);非本人(加载器抛错 / 返回空)。
|
||||
|
||||
### F3 · 报告封面
|
||||
|
||||
- `classifyReportEnvelope` 在 ready 态读 `report.coverSubject`(非空字符串才带上);`PersonalReportPage` 在 `.personal-report-reader-body` 正文最上方渲染 `<ReportSkyCover subjectId=…/>`(`next/dynamic`,`ssr: false`)。
|
||||
- `components/birth-sky/report-sky-cover.tsx` + `report-sky-cover.css`:挂载后(正文已上屏)才取数;`lib/birth-sky/report-cover.ts` `loadReportSkyCover` 取天空并用同一个 `renderBirthSkyPng` 画 `night`(屏幕)与 `paper`(打印)两张;任何失败返回 `null`,组件什么也不渲染。无按钮、无占位、无等待态。
|
||||
- 打印:`.report-sky-cover-screen` 隐藏、`.report-sky-cover-print` 显示;`.report-sky-cover { break-after: page }`,图高 246mm 居中(A4 减报告 `@page` 边距后版心 186 × 270mm,3:4 在 186mm 宽时 248mm 高)。
|
||||
- `BLOCKED.md` 的 T5 条目已划掉并注明「→ 已解除:产品 2026-09-28 选 A」。
|
||||
- 测试:`frontend/tests/report-sky-cover.test.ts`(5 条:coverSubject 有 / 无;封面在正文之上且懒加载、无按钮无等待;night + paper 两张;取数失败 / 空 / 画图失败 / abort 都返回 null;打印 CSS 的 paper 与分页)。
|
||||
|
||||
@@ -27,12 +27,18 @@
|
||||
|
||||
## 报告封面
|
||||
|
||||
本期**未上线**(报告与出生资料没有可靠绑定,见 `BLOCKED.md`)。验收时确认:打开任何报告,正文最上方**没有**天空封面、也没有空白占位;打印 PDF 第一页仍是原来的报告封面。
|
||||
~~本期**未上线**(报告与出生资料没有可靠绑定,见 `BLOCKED.md`)。验收时确认:打开任何报告,正文最上方**没有**天空封面、也没有空白占位;打印 PDF 第一页仍是原来的报告封面。~~ → 追加单(`TASK-birth-sky-followup-20260928`)已上线报告封面,原 11、12 条作废,改按下表。
|
||||
|
||||
| # | 设备 / 浏览器 | 操作 | 期望 | 结果 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 11 | 桌面 Chrome | 打开「我的报告」任一份 | 没有天空封面,没有占位 | |
|
||||
| 12 | 桌面 Chrome | 该报告「打印 → 存为 PDF」 | 第一页与上线前相同 | |
|
||||
| ~~11~~ | ~~桌面 Chrome~~ | ~~打开「我的报告」任一份~~ | ~~没有天空封面,没有占位~~ | 作废 |
|
||||
| ~~12~~ | ~~桌面 Chrome~~ | ~~该报告「打印 → 存为 PDF」~~ | ~~第一页与上线前相同~~ | 作废 |
|
||||
| 18 | 桌面 Chrome | 部署后**新生成**一份报告,打开 | 正文最上方一张深色 3:4 天空封面,宽与正文一致,下面没有按钮;正文先出来,封面随后出现,其间没有占位或转圈 | |
|
||||
| 19 | 桌面 Chrome | 该报告「打印 → 存为 PDF」 | 第一页只有一张浅色纸面版天空封面;正文从第二页开始 | |
|
||||
| 20 | 桌面 Chrome | 打开部署**之前**生成的旧报告 | 没有封面,没有空白占位 | |
|
||||
| 21 | 任一 | 新生成一份报告 → 设置里改自己的出生时间(或出生地)→ 回来打开那份报告 | 没有封面;改完后再新生成的报告有封面 | |
|
||||
| 22 | 桌面 Chrome | 打开有封面的报告,DevTools → Network 看 `/api/reports/<id>` 的响应 | 响应里只有 `coverSubject`(`"self"` 或人物 id),没有 `birthFingerprint`、没有出生日期 / 时刻 / 经纬度 / 地名 | |
|
||||
| 23 | 桌面 Chrome | 打开有封面的报告前,在 Request blocking 加一条 `*api/birth-sky*` | 报告正文照常显示,没有封面,也没有报错 | |
|
||||
|
||||
## 首次建盘揭幕
|
||||
|
||||
|
||||
+8
-2
@@ -1150,9 +1150,15 @@ D40 / D45 / D60 的表格上方,出生时间不是「已校正」时多一句
|
||||
- 弹层、画布与导出代码都在懒加载 chunk 里(`next/dynamic` + 动态 `import()`),首页 `/` 不带它们。按钮本身是星盘页里的一个普通 `<Button>`(只在数据就绪时渲染)。
|
||||
- 等待:没有等待态。按钮出现时图已就绪;弹层打开就是图。
|
||||
|
||||
### 位置二:报告封面(blocked)
|
||||
### 位置二:报告封面(2026-09-28 追加,TASK-birth-sky-followup-20260928 F1–F3)
|
||||
|
||||
本期不上线。报告行与报告文档里都没有生成时的出生资料指纹,封面「对得上报告」无从判定;按任务书不拿当前资料冒充当时资料(`BLOCKED.md`)。报告页、打印样式、`reportView` 都未改:没有封面、没有占位。解除后按原设计:ready 态正文最上方,屏幕用 `night`、宽随正文列、3:4;打印改 `paper` 并独占 A4 第一页(`break-after: page`);取数在正文出现之后,失败不显示;封面下不加按钮。
|
||||
产品选方案 A:报告只在「生成时的出生资料」与「现在的出生资料」一致时才有封面。
|
||||
|
||||
- **绑定:** 新生成的报告在文档 `subject.birthFingerprint` 里记下生成时的出生资料指纹(与星盘页 `profileFingerprint` 同一个函数、同取存储行、在时区补全之前取)。普通报告、分章报告、长报告三条生成路径都写;指纹不进给模型的证据包。旧报告没有这个字段,**永远没有封面**,不补算、不回填;不改表结构。
|
||||
- **比对在服务端:** `GET /api/reports/:id` 读当前人物的指纹,一致时 `report.coverSubject` = 人物 id(本人为 `"self"`),其余一律 `null`(不一致、缺字段、人物不是自己的、已删除、读不到)。浏览器拿不到指纹,也拿不到任何出生资料。
|
||||
- **屏幕:** ready 态正文最上方一块 `<figure>`:`night` palette,宽随正文列,3:4,圆角 `--radius-md`,下接正文 `--space-6`。封面下没有按钮。
|
||||
- **打印 / PDF:** 同一次取数同时画一张 `paper` palette 的图,只在打印时显示;封面独占 A4 第一页(`break-after: page`,高 246mm 居中,恰好放进报告 `@page` 的 186 × 270mm 版心)。不新增打印入口,仍是报告原来的「打印」。
|
||||
- **取数与等待:** 组件与正文同一次渲染挂载,副作用在正文上屏之后才发请求;两张图都画好才出现。取数、画图任一失败就不显示封面,不留占位、不加等待态,正文不受影响。组件与样式在懒加载 chunk 里(`components/birth-sky/report-sky-cover.tsx`),首页不带。
|
||||
|
||||
### 位置三:首次建盘揭幕
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ import { createSupabasePersonalReportJobService } from "@/lib/personal-report-jo
|
||||
import { createPersonalReportSectionService } from "@/lib/personal-report-section-service";
|
||||
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import { subjectBirthFingerprint } from "@/lib/report-birth-binding";
|
||||
import { loadSubjectBirth } from "@/lib/subject-birth";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -49,6 +51,7 @@ async function resolvePersistenceForUser() {
|
||||
jobs: null,
|
||||
listSections: undefined,
|
||||
loadLongformAppendix: undefined,
|
||||
loadCurrentBirthFingerprint: undefined,
|
||||
};
|
||||
}
|
||||
const persistence = createSupabasePersonalReportService(supabase);
|
||||
@@ -84,12 +87,17 @@ async function resolvePersistenceForUser() {
|
||||
markdown: row.markdown,
|
||||
};
|
||||
},
|
||||
// Report cover binding: the same stored-row fingerprint the chart page uses.
|
||||
// A foreign, deleted or unreadable subject throws and resolves to no cover.
|
||||
loadCurrentBirthFingerprint: async (ownerId: string, subjectId: string) => (
|
||||
subjectBirthFingerprint((await loadSubjectBirth(supabase, ownerId, subjectId)).row)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET(request: Request, context: RouteContext) {
|
||||
try {
|
||||
const { userId, persistence, jobs, listSections, loadLongformAppendix } = await resolvePersistenceForUser();
|
||||
const { userId, persistence, jobs, listSections, loadLongformAppendix, loadCurrentBirthFingerprint } = await resolvePersistenceForUser();
|
||||
const { reportId } = await context.params;
|
||||
if (!uuidPattern.test(reportId)) {
|
||||
return NextResponse.json(
|
||||
@@ -116,6 +124,7 @@ export async function GET(request: Request, context: RouteContext) {
|
||||
jobs: jobs ?? undefined,
|
||||
listSections,
|
||||
loadLongformAppendix,
|
||||
loadCurrentBirthFingerprint,
|
||||
validateReadyDocument: (document) => {
|
||||
const parsed = safeParseServerReportDocument(document);
|
||||
return parsed.ok
|
||||
|
||||
@@ -2,6 +2,7 @@ import { normalizeReportSubjectRequest } from "@/lib/report-subject-request";
|
||||
import { NextResponse } from "next/server";
|
||||
import { LONGFORM_SNAPSHOT_SECTION_ID } from "@/lib/personal-report-longform-snapshot";
|
||||
import { resolveMissingBirthTimezoneOffset } from "@/lib/birth-profile-timezone";
|
||||
import { stampReportBirthFingerprint } from "@/lib/report-birth-binding";
|
||||
import { runConsultationWorkflow } from "@/mastra";
|
||||
import { createPersonalReportAgent } from "@/mastra/personal-report";
|
||||
import { loadLanguageModelCatalog } from "@/lib/model-catalog";
|
||||
@@ -201,7 +202,11 @@ export async function POST(request: Request) {
|
||||
code: REPORT_STABLE_CODES.profileIncomplete,
|
||||
}, { status: 422 });
|
||||
}
|
||||
profile = await resolveMissingBirthTimezoneOffset(resolved.row, { useActiveDate: true });
|
||||
// The cover binding fingerprint is taken from the stored row, before the fill.
|
||||
profile = stampReportBirthFingerprint(
|
||||
resolved.row,
|
||||
await resolveMissingBirthTimezoneOffset(resolved.row, { useActiveDate: true }),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof ConsultationSubjectError) {
|
||||
const failure = consultationSubjectFailureResponse(error);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/* Report cover (TASK-birth-sky-followup-20260928 F3). Loaded with the lazy
|
||||
cover chunk on the report page only. Screen: night palette, as wide as the
|
||||
reading column, 3:4. Print: paper palette, alone on the first A4 page. */
|
||||
.report-sky-cover { margin: 0 0 var(--space-6); }
|
||||
.report-sky-cover img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 3 / 4;
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
.report-sky-cover-print { display: none !important; }
|
||||
@media print {
|
||||
.report-sky-cover {
|
||||
margin: 0;
|
||||
break-after: page;
|
||||
page-break-after: always;
|
||||
break-inside: avoid-page;
|
||||
}
|
||||
.report-sky-cover-screen { display: none !important; }
|
||||
.report-sky-cover-print {
|
||||
display: block !important;
|
||||
/* A4 inside the report's @page margins is 186mm × 270mm; 3:4 at 186mm
|
||||
wide is 248mm tall, so 246mm keeps it on one page. */
|
||||
width: auto !important;
|
||||
max-width: 100%;
|
||||
height: 246mm !important;
|
||||
margin: 0 auto;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import "./report-sky-cover.css";
|
||||
|
||||
import { loadReportSkyCover } from "@/lib/birth-sky/report-cover";
|
||||
|
||||
type ReportSkyCoverImages = Readonly<{ screen: string; print: string; description: string }>;
|
||||
|
||||
/**
|
||||
* 「那一刻的天空」 as the report cover (TASK-birth-sky-followup-20260928 F3).
|
||||
*
|
||||
* Mounted only after the report body is on screen and only when the server
|
||||
* said the report's birth data still matches (`coverSubject`). It fetches the
|
||||
* sky and paints two PNGs with the same `drawBirthSky`: `night` for the screen,
|
||||
* `paper` for print. Until both are painted, and on any failure, it renders
|
||||
* nothing — no placeholder, no waiting state (DESIGN §9).
|
||||
*/
|
||||
export function ReportSkyCover({ subjectId }: { subjectId: string }) {
|
||||
const [images, setImages] = useState<ReportSkyCoverImages | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const urls: string[] = [];
|
||||
void loadReportSkyCover(subjectId, controller.signal).then((pngs) => {
|
||||
if (!pngs || controller.signal.aborted) return;
|
||||
urls.push(URL.createObjectURL(pngs.screen), URL.createObjectURL(pngs.print));
|
||||
setImages({ screen: urls[0], print: urls[1], description: pngs.description });
|
||||
});
|
||||
return () => {
|
||||
controller.abort();
|
||||
for (const url of urls) URL.revokeObjectURL(url);
|
||||
};
|
||||
}, [subjectId]);
|
||||
|
||||
if (!images) return null;
|
||||
return (
|
||||
<figure className="report-sky-cover">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- blob: URL of the painted cover */}
|
||||
<img className="report-sky-cover-screen" src={images.screen} alt={images.description} width={1080} height={1440} />
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- blob: URL of the painted cover, paper palette */}
|
||||
<img className="report-sky-cover-print" src={images.print} alt="" width={1080} height={1440} />
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import Link from "next/link";
|
||||
|
||||
import { Clock3, TriangleAlert } from "lucide-react";
|
||||
@@ -40,6 +41,12 @@ import {
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useVisibilityAwarePoll } from "@/hooks/use-visibility-aware-poll";
|
||||
|
||||
// Mounted with the body, so the sky is only fetched once the report is on screen.
|
||||
const ReportSkyCover = dynamic(
|
||||
() => import("@/components/birth-sky/report-sky-cover").then((module) => module.ReportSkyCover),
|
||||
{ ssr: false },
|
||||
);
|
||||
|
||||
export type ReportLoadState =
|
||||
| { phase: "loading" }
|
||||
| { phase: "unauthorized" }
|
||||
@@ -54,7 +61,7 @@ export type ReportLoadState =
|
||||
| { phase: "failed"; failureCode: string | null; failureSummary?: string | null; appendixLastErrorCode?: string | null }
|
||||
| { phase: "invalid"; message: string }
|
||||
| { phase: "network-error" }
|
||||
| { phase: "markdown-ready"; markdown: string; reportId: string; createdAt: string; factTables?: ReportFactTable[]; calculationCharts?: ReportDocumentV2["charts"] }
|
||||
| { phase: "markdown-ready"; markdown: string; reportId: string; createdAt: string; factTables?: ReportFactTable[]; calculationCharts?: ReportDocumentV2["charts"]; coverSubject?: string }
|
||||
| { phase: "legacy-unavailable" };
|
||||
|
||||
/** GET /api/reports/:id envelope view (mirrors the API route's reportView). */
|
||||
@@ -72,6 +79,8 @@ export interface ReportEnvelopeView {
|
||||
progressPercent?: number;
|
||||
progressPhase?: string;
|
||||
sections?: readonly ReportSectionProgress[];
|
||||
/** Report cover: set by the server only when the report's birth data still matches. */
|
||||
coverSubject?: string | null;
|
||||
}
|
||||
|
||||
const SECTION_PROGRESS_STATES: readonly ReportSectionProgressState[] = [
|
||||
@@ -131,9 +140,11 @@ export function classifyReportEnvelope(statusCode: number, json: unknown): Repor
|
||||
if (markdown.length > 0) {
|
||||
const facts = reportFactTablesSchema.safeParse(json.factTables);
|
||||
const charts = reportDocumentV2Schema.shape.charts.safeParse(json.calculationCharts);
|
||||
const coverSubject = typeof view.coverSubject === "string" && view.coverSubject.length > 0 ? view.coverSubject : null;
|
||||
return {
|
||||
...(facts.success && facts.data.length ? { factTables: facts.data } : {}),
|
||||
...(charts.success ? { calculationCharts: charts.data } : {}),
|
||||
...(coverSubject ? { coverSubject } : {}),
|
||||
phase: "markdown-ready",
|
||||
markdown,
|
||||
reportId: typeof view.id === "string" ? view.id : "",
|
||||
@@ -482,6 +493,7 @@ export function PersonalReportPage({ reportId }: { reportId: string }) {
|
||||
reportDate={state.createdAt}
|
||||
/>
|
||||
<div className="personal-report-reader-body">
|
||||
{state.coverSubject ? <ReportSkyCover subjectId={state.coverSubject} /> : null}
|
||||
<PersonalReportMarkdownView markdown={state.markdown} />
|
||||
{state.calculationCharts && <ReportCalculationCharts charts={state.calculationCharts} />}
|
||||
{state.factTables && <ReportFactTables tables={state.factTables} />}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { BirthSkyOk } from "./contract.ts";
|
||||
import { fetchBirthSky } from "./cover.ts";
|
||||
import type { BirthSkyPaletteName } from "./draw.ts";
|
||||
import { birthSkyFactLine, birthSkyHeadline } from "./sentence.ts";
|
||||
|
||||
/** Screen (`night`) and print (`paper`) pictures of one report cover, painted by the same `drawBirthSky`. */
|
||||
export type ReportSkyCoverPngs = Readonly<{ screen: Blob; print: Blob; description: string }>;
|
||||
|
||||
export type ReportSkyCoverDeps = Readonly<{
|
||||
fetchSky: (subjectId: string, signal?: AbortSignal) => Promise<BirthSkyOk | null>;
|
||||
render: (sky: BirthSkyOk, palette: BirthSkyPaletteName) => Promise<Blob>;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Report cover loader (TASK-birth-sky-followup-20260928 F3). Resolves null on
|
||||
* any failure or abort; the report shows no cover and nothing else changes.
|
||||
*/
|
||||
export async function loadReportSkyCover(
|
||||
subjectId: string,
|
||||
signal: AbortSignal,
|
||||
deps?: ReportSkyCoverDeps,
|
||||
): Promise<ReportSkyCoverPngs | null> {
|
||||
try {
|
||||
const fetchSky = deps?.fetchSky ?? fetchBirthSky;
|
||||
const render = deps?.render ?? (await import("./render.ts")).renderBirthSkyPng;
|
||||
const sky = await fetchSky(subjectId, signal);
|
||||
if (!sky || signal.aborted) return null;
|
||||
const [screen, print] = await Promise.all([render(sky, "night"), render(sky, "paper")]);
|
||||
if (signal.aborted) return null;
|
||||
return { screen, print, description: `${birthSkyHeadline(sky)}${birthSkyFactLine(sky)}。` };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -179,6 +179,10 @@ const subjectSchema = z.strictObject({
|
||||
displayName: text(120),
|
||||
birthTimeStatus: z.enum(BIRTH_TIME_STATUSES),
|
||||
birthPlaceLabel: text(200),
|
||||
// Fingerprint of the birth data the report was generated from (report cover
|
||||
// binding). Optional: reports generated before it existed stay readable and
|
||||
// never show a cover. Server-only; the reader never receives the subject.
|
||||
birthFingerprint: z.string().regex(/^[0-9a-f]{32}$/, "invalid birth fingerprint").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 { withReportBirthFingerprint } from "./report-birth-binding.ts";
|
||||
// Compatibility re-export: prefer importing from ./personal-report-codes.ts
|
||||
// directly (the pure, dependency-free codes module).
|
||||
export { REPORT_STABLE_CODES } from "./personal-report-codes.ts";
|
||||
@@ -3275,6 +3276,8 @@ export type GeneratePersonalReportDeps = GeneratePersonalReportBaseDeps & Readon
|
||||
requestId?: string;
|
||||
sectionService?: PersonalReportSectionService;
|
||||
onProgress?: (progress: Readonly<{ phase: string; completed: number; total: number }>) => Promise<void> | void;
|
||||
/** Stored-row birth fingerprint; written to `subject.birthFingerprint`, never into the bundle the model reads. */
|
||||
birthFingerprint?: string;
|
||||
}>;
|
||||
|
||||
export type ReportSchemaInnerReason = string;
|
||||
@@ -3588,7 +3591,7 @@ async function generateSectionedPersonalReport(
|
||||
depth: deps.depth, bundle, plan, agentOutput, allowIncompleteThematic: true,
|
||||
additionalBlockedSections: blockedDisclosures,
|
||||
});
|
||||
const guarded = applyReportGuard(candidate, buildLegacyPacketFromBundle(bundle));
|
||||
const guarded = applyReportGuard(withReportBirthFingerprint(candidate, deps.birthFingerprint), buildLegacyPacketFromBundle(bundle));
|
||||
if (!guarded.ok) return { status: "failed", failureCode: "report_guard_rejected" };
|
||||
const parsed = safeParseServerReportDocument(guarded.document);
|
||||
if (!parsed.ok || parsed.document.schemaVersion !== "report_document.v2") return failFinalParse(parsed);
|
||||
@@ -3687,7 +3690,7 @@ export async function generatePersonalReport(
|
||||
: classifyReportSchemaInnerReason(error),
|
||||
);
|
||||
}
|
||||
const guarded = applyReportGuard(candidate, packet);
|
||||
const guarded = applyReportGuard(withReportBirthFingerprint(candidate, deps.birthFingerprint), packet);
|
||||
if (!guarded.ok) {
|
||||
return { status: "failed", failureCode: "report_guard_rejected" };
|
||||
}
|
||||
|
||||
@@ -41,6 +41,8 @@ export type LongformCoverInput = Readonly<{
|
||||
birthTimeStatus: ReportDocumentV2["subject"]["birthTimeStatus"];
|
||||
birthPlaceLabel: string;
|
||||
}>;
|
||||
/** Stored-row birth fingerprint (report cover binding); absent → no `subject.birthFingerprint`. */
|
||||
birthFingerprint?: string;
|
||||
markdown: string;
|
||||
factTables?: ReportDocumentV2["factTables"];
|
||||
charts?: ReportDocumentV2["charts"];
|
||||
@@ -88,7 +90,7 @@ export function buildLongformCoverDocument(input: LongformCoverInput): ReportDoc
|
||||
depth: input.report.depth,
|
||||
requestedThemes: [...input.report.requestedThemes],
|
||||
generatedAt: input.generatedAt ?? new Date().toISOString(),
|
||||
subject: input.subject,
|
||||
subject: input.birthFingerprint ? { ...input.subject, birthFingerprint: input.birthFingerprint } : input.subject,
|
||||
provenance: {
|
||||
skillName,
|
||||
skillVersion,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "./personal-report-longform-appendix";
|
||||
import { buildLongformBirthPayload, utcToday } from "./personal-report-longform-birth";
|
||||
import { buildLongformCoverDocument } from "./personal-report-longform-cover";
|
||||
import { readReportBirthFingerprint } from "./report-birth-binding";
|
||||
import { assembleLongformCharts, type GeneratePersonalReportResult } from "./personal-report-generation";
|
||||
import type { PersonalReportRecord } from "./personal-report-service-core";
|
||||
import type { ReportDocumentV2 } from "./personal-report-contract";
|
||||
@@ -261,6 +262,7 @@ export async function generatePersonalReportLongform(
|
||||
birthTimeStatus: deps.birthTimeStatus,
|
||||
birthPlaceLabel: text(profile.birth_place_label) ?? "未知出生地",
|
||||
},
|
||||
birthFingerprint: readReportBirthFingerprint(profile),
|
||||
markdown,
|
||||
factTables,
|
||||
charts,
|
||||
|
||||
@@ -27,6 +27,12 @@ import {
|
||||
type SkillSnapshot,
|
||||
} from "./personal-report-generation";
|
||||
import { REPORT_STABLE_CODES } from "./personal-report-codes";
|
||||
import {
|
||||
readReportBirthFingerprint,
|
||||
reportCoverSubject,
|
||||
reportDocumentBirthFingerprint,
|
||||
reportSubjectId,
|
||||
} from "./report-birth-binding";
|
||||
import { summarizePersonalReportFailure } from "./personal-report-failure-summary";
|
||||
import {
|
||||
deriveSectionProgressState,
|
||||
@@ -149,6 +155,7 @@ export function reportView(
|
||||
job?: PersonalReportJobRecord | null,
|
||||
failure?: ReturnType<typeof summarizePersonalReportFailure> | null,
|
||||
sections?: readonly ReportSectionProgress[] | null,
|
||||
coverSubject?: string | null,
|
||||
) {
|
||||
return {
|
||||
id: row.id,
|
||||
@@ -166,6 +173,8 @@ export function reportView(
|
||||
...(failure?.innerReason ? { innerReason: failure.innerReason } : {}),
|
||||
...(failure && failure.lastErrorCodes.length > 0 ? { sectionErrorCodes: failure.lastErrorCodes } : {}),
|
||||
...(failure?.appendixLastErrorCode ? { appendixLastErrorCode: failure.appendixLastErrorCode } : {}),
|
||||
// Report cover binding: a subject id or null, never the fingerprint itself.
|
||||
...(coverSubject !== undefined ? { coverSubject } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -551,6 +560,7 @@ export async function resolveReportCreate(deps: ReportCreateCoreDeps): Promise<R
|
||||
depth: payload.depth,
|
||||
agent: deps.createAgent(selectedModel),
|
||||
now: deps.now,
|
||||
birthFingerprint: readReportBirthFingerprint(profile),
|
||||
});
|
||||
|
||||
if (result.status === "failed") {
|
||||
@@ -678,8 +688,30 @@ export type ReportReadCoreDeps = Readonly<{
|
||||
lastErrorCode: string | null;
|
||||
markdown: string | null;
|
||||
} | null>;
|
||||
/**
|
||||
* Current birth fingerprint of one of the reader's own subjects (`"self"` or
|
||||
* a chart profile id), read on the server. Null or a throw means no cover.
|
||||
*/
|
||||
loadCurrentBirthFingerprint?: (userId: string, subjectId: string) => Promise<string | null>;
|
||||
}>;
|
||||
|
||||
/** Server-side comparison for the report cover; only its verdict leaves the server. */
|
||||
async function readyReportCoverSubject(
|
||||
deps: ReportReadCoreDeps,
|
||||
userId: string,
|
||||
row: PersonalReportRecord,
|
||||
): Promise<string | null> {
|
||||
const storedFingerprint = reportDocumentBirthFingerprint(row.reportDocument);
|
||||
if (!storedFingerprint || !deps.loadCurrentBirthFingerprint) return null;
|
||||
let currentFingerprint: string | null = null;
|
||||
try {
|
||||
currentFingerprint = await deps.loadCurrentBirthFingerprint(userId, reportSubjectId(row.chartProfileId));
|
||||
} catch {
|
||||
currentFingerprint = null;
|
||||
}
|
||||
return reportCoverSubject({ chartProfileId: row.chartProfileId, storedFingerprint, currentFingerprint });
|
||||
}
|
||||
|
||||
export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<ReportRouteResponse> {
|
||||
const originDecision = checkSameOrigin(deps.requestUrl, deps.origin, deps.allowedOrigins, deps.requestHeaders);
|
||||
if (!originDecision.ok) {
|
||||
@@ -727,6 +759,7 @@ export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<Repor
|
||||
))
|
||||
: null;
|
||||
if (row.status === "ready") {
|
||||
const coverSubject = await readyReportCoverSubject(deps, deps.userId, row);
|
||||
const markdownFromAppendix = appendix?.status === "ready" && appendix.markdown?.trim()
|
||||
? appendix.markdown
|
||||
: null;
|
||||
@@ -739,7 +772,7 @@ export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<Repor
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
report: reportView(row, job),
|
||||
report: reportView(row, job, null, null, coverSubject),
|
||||
longformMarkdown: projectOrdinaryReportMarkdown(markdown),
|
||||
...(validated.ok && validated.document && typeof validated.document === "object" && "charts" in validated.document
|
||||
? { calculationCharts: validated.document.charts } : {}),
|
||||
@@ -759,7 +792,7 @@ export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<Repor
|
||||
if (deps.loadLongformMarkdown || deps.loadLongformAppendix) {
|
||||
return {
|
||||
status: 200,
|
||||
body: { report: reportView(row, job), longformMarkdown: null },
|
||||
body: { report: reportView(row, job, null, null, coverSubject), longformMarkdown: null },
|
||||
};
|
||||
}
|
||||
if (!validated.ok) {
|
||||
@@ -768,13 +801,13 @@ export async function resolveReportRead(deps: ReportReadCoreDeps): Promise<Repor
|
||||
body: {
|
||||
error: "报告内容未通过合同校验",
|
||||
code: REPORT_STABLE_CODES.schemaInvalid,
|
||||
report: reportView(row, job),
|
||||
report: reportView(row, job, null, null, coverSubject),
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: 200,
|
||||
body: { report: reportView(row, job), reportDocument: projectOrdinaryReportDocument(validated.document) },
|
||||
body: { report: reportView(row, job, null, null, coverSubject), reportDocument: projectOrdinaryReportDocument(validated.document) },
|
||||
};
|
||||
}
|
||||
return { status: 200, body: { report: reportView(row, job, failure, sectionProgress) } };
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { resolveMissingBirthTimezoneOffset } from "./birth-profile-timezone.ts";
|
||||
import { resolveReportBirthClock } from "./personal-report-route-core.ts";
|
||||
import { PersonalReportWorkerError } from "./personal-report-worker-core.ts";
|
||||
import { stampReportBirthFingerprint } from "./report-birth-binding.ts";
|
||||
import { ConsultationSubjectError, loadSubjectBirth } from "./subject-birth.ts";
|
||||
|
||||
export async function loadReportWorkerProfile(client: unknown, userId: string, subjectId: string): Promise<unknown> {
|
||||
@@ -20,7 +21,8 @@ export async function loadReportWorkerProfile(client: unknown, userId: string, s
|
||||
if (error) throw new PersonalReportWorkerError("profile_incomplete", true);
|
||||
row = { ...row, rectification_case_id: data?.rectification_case_id ?? null };
|
||||
}
|
||||
return await resolveMissingBirthTimezoneOffset(row, { useActiveDate: true });
|
||||
// The cover binding fingerprint is taken from the stored row, before the fill.
|
||||
return stampReportBirthFingerprint(resolved.row, await resolveMissingBirthTimezoneOffset(row, { useActiveDate: true }));
|
||||
} catch (error) {
|
||||
if (error instanceof ConsultationSubjectError) {
|
||||
// Missing/deleted/foreign subjects are terminal and release the existing
|
||||
|
||||
@@ -36,6 +36,7 @@ import type { ConsultationInput } from "@/mastra/consultation-workflow";
|
||||
import { resolveAyanamsa } from "@/lib/ayanamsa";
|
||||
|
||||
import { loadReportWorkerProfile, reportWorkerUsesCandidateRange } from "@/lib/personal-report-worker-subject";
|
||||
import { readReportBirthFingerprint } from "@/lib/report-birth-binding";
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
type WorkerGlobal = typeof globalThis & {
|
||||
@@ -183,6 +184,7 @@ async function generateWriterReport(
|
||||
requestId: context.report.requestId,
|
||||
sectionService: context.sectionService,
|
||||
onProgress: context.onProgress,
|
||||
birthFingerprint: readReportBirthFingerprint(profile),
|
||||
});
|
||||
if (result.status !== "ready") return result;
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { resolveServerOwnedChartBirth } from "./chart-birth-truth.ts";
|
||||
|
||||
/**
|
||||
* Report ↔ birth-data binding for the report cover (TASK-birth-sky-followup-20260928,
|
||||
* product decision A).
|
||||
*
|
||||
* A report records the fingerprint of the birth data it was generated from, in
|
||||
* `subject.birthFingerprint`. The fingerprint is the chart page's
|
||||
* `profileFingerprint`: `resolveServerOwnedChartBirth` over the **stored** row,
|
||||
* before any in-memory timezone fill. Reports generated before this field
|
||||
* existed never get one and never show a cover. Neither the fingerprint nor
|
||||
* any birth field leaves the server; the reader only receives `coverSubject`.
|
||||
*/
|
||||
|
||||
/** Server-only key stamped on the loaded profile row; never persisted, never serialized to a client. */
|
||||
export const REPORT_BIRTH_FINGERPRINT_KEY = "report_birth_fingerprint";
|
||||
|
||||
const FINGERPRINT_PATTERN = /^[0-9a-f]{32}$/;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Same algorithm and same input (the stored row) as the chart page's `profileFingerprint`. */
|
||||
export function subjectBirthFingerprint(storedRow: unknown): string {
|
||||
return resolveServerOwnedChartBirth(storedRow).fingerprint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carries the stored row's fingerprint on the timezone-filled row the
|
||||
* generators read. Filling a missing offset changes the fingerprint, so it
|
||||
* must be taken before the fill.
|
||||
*/
|
||||
export function stampReportBirthFingerprint(storedRow: unknown, filledRow: unknown): unknown {
|
||||
const filled = record(filledRow);
|
||||
if (!filled) return filledRow;
|
||||
return { ...filled, [REPORT_BIRTH_FINGERPRINT_KEY]: subjectBirthFingerprint(storedRow) };
|
||||
}
|
||||
|
||||
export function readReportBirthFingerprint(profile: unknown): string | undefined {
|
||||
const value = record(profile)?.[REPORT_BIRTH_FINGERPRINT_KEY];
|
||||
return typeof value === "string" && FINGERPRINT_PATTERN.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
/** Writes `subject.birthFingerprint` on a report document; a missing fingerprint leaves it untouched. */
|
||||
export function withReportBirthFingerprint<T>(document: T, fingerprint: string | undefined): T {
|
||||
const source = record(document);
|
||||
const subject = record(source?.subject);
|
||||
if (!source || !subject || !fingerprint) return document;
|
||||
return { ...source, subject: { ...subject, birthFingerprint: fingerprint } } as T;
|
||||
}
|
||||
|
||||
export function reportDocumentBirthFingerprint(document: unknown): string | null {
|
||||
const value = record(record(document)?.subject)?.birthFingerprint;
|
||||
return typeof value === "string" && FINGERPRINT_PATTERN.test(value) ? value : null;
|
||||
}
|
||||
|
||||
/** The subject id the reader may ask `/api/birth-sky` for; `"self"` when the report has no chart profile. */
|
||||
export function reportSubjectId(chartProfileId: string | null): string {
|
||||
return chartProfileId && chartProfileId.trim() ? chartProfileId.trim() : "self";
|
||||
}
|
||||
|
||||
/**
|
||||
* `coverSubject` for `reportView`: the subject id only when the stored
|
||||
* fingerprint equals the subject's current one; null otherwise (mismatch,
|
||||
* legacy report without the field, foreign or deleted person, lookup failure).
|
||||
*/
|
||||
export function reportCoverSubject(input: Readonly<{
|
||||
chartProfileId: string | null;
|
||||
storedFingerprint: string | null;
|
||||
currentFingerprint: string | null;
|
||||
}>): string | null {
|
||||
if (!input.storedFingerprint || !input.currentFingerprint) return null;
|
||||
return input.storedFingerprint === input.currentFingerprint ? reportSubjectId(input.chartProfileId) : null;
|
||||
}
|
||||
@@ -1447,3 +1447,98 @@ test("failed report reads aggregate existing section error codes without importi
|
||||
assert.match(createRoute, /row\.section_id === LONGFORM_SNAPSHOT_SECTION_ID\) continue/);
|
||||
assert.doesNotMatch(itemRoute, /personal-report-generation/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Report cover binding (TASK-birth-sky-followup-20260928 F1/F2, decision A)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const BIRTH_FP = "0123456789abcdef0123456789abcdef";
|
||||
const OTHER_FP = "fedcba9876543210fedcba9876543210";
|
||||
|
||||
test("core create: inline generation writes subject.birthFingerprint from the stamped profile", async () => {
|
||||
const persistence = new MemoryPersistence();
|
||||
const stamped = await resolveReportCreate(baseDeps({
|
||||
persistence,
|
||||
profile: { ...profileFixture(), report_birth_fingerprint: BIRTH_FP },
|
||||
}));
|
||||
assert.equal(stamped.status, 201);
|
||||
assert.equal(persistence.rows.get(REPORT_ID)?.reportDocument?.subject.birthFingerprint, BIRTH_FP);
|
||||
// The browser-facing projection carries no subject at all.
|
||||
assert.doesNotMatch(JSON.stringify(stamped.body), new RegExp(BIRTH_FP));
|
||||
|
||||
const unstamped = new MemoryPersistence();
|
||||
await resolveReportCreate(baseDeps({ persistence: unstamped }));
|
||||
assert.equal("birthFingerprint" in (unstamped.rows.get(REPORT_ID)?.reportDocument?.subject ?? {}), false);
|
||||
});
|
||||
|
||||
async function readWithCover(input: Readonly<{
|
||||
storedFingerprint: string | null;
|
||||
chartProfileId?: string | null;
|
||||
current: (userId: string, subjectId: string) => Promise<string | null>;
|
||||
}>) {
|
||||
const persistence = new MemoryPersistence();
|
||||
const subject = {
|
||||
displayName: "测试用户",
|
||||
birthTimeStatus: "confirmed",
|
||||
birthPlaceLabel: "北京",
|
||||
...(input.storedFingerprint ? { birthFingerprint: input.storedFingerprint } : {}),
|
||||
};
|
||||
persistence.rows.set(REPORT_ID, {
|
||||
...seedRecord(),
|
||||
chartProfileId: input.chartProfileId ?? null,
|
||||
reportDocument: { schemaVersion: "report_document.v2", subject } as unknown as PersonalReportRecord["reportDocument"],
|
||||
});
|
||||
const asked: string[] = [];
|
||||
const response = await resolveReportRead({
|
||||
requestUrl: "https://jyotisha.chat/api/reports/x",
|
||||
origin: null,
|
||||
allowedOrigins: [],
|
||||
userId: UUID_A,
|
||||
reportId: REPORT_ID,
|
||||
persistence,
|
||||
validateReadyDocument: acceptAnyDocument,
|
||||
loadLongformAppendix: async () => ({ status: "ready", lastErrorCode: null, markdown: "# 报告\n\n正文。" }),
|
||||
loadCurrentBirthFingerprint: async (userId, subjectId) => {
|
||||
asked.push(`${userId}:${subjectId}`);
|
||||
return input.current(userId, subjectId);
|
||||
},
|
||||
});
|
||||
assert.equal(response.status, 200);
|
||||
return { response, asked, report: response.body.report as Record<string, unknown> };
|
||||
}
|
||||
|
||||
test("core read: coverSubject is the subject id when the stored fingerprint matches the current one", async () => {
|
||||
const self = await readWithCover({ storedFingerprint: BIRTH_FP, current: async () => BIRTH_FP });
|
||||
assert.equal(self.report.coverSubject, "self");
|
||||
assert.deepEqual(self.asked, [`${UUID_A}:self`]);
|
||||
const person = await readWithCover({ storedFingerprint: BIRTH_FP, chartProfileId: SESSION_ID, current: async () => BIRTH_FP });
|
||||
assert.equal(person.report.coverSubject, SESSION_ID);
|
||||
assert.deepEqual(person.asked, [`${UUID_A}:${SESSION_ID}`]);
|
||||
// Serialized response: no fingerprint, no birth fields.
|
||||
const body = JSON.stringify(self.response.body);
|
||||
assert.doesNotMatch(body, new RegExp(BIRTH_FP));
|
||||
assert.doesNotMatch(body, /birthFingerprint|birth_date|latitude|longitude|timezone|birthPlaceLabel|北京/);
|
||||
});
|
||||
|
||||
test("core read: coverSubject is null when the birth data changed since the report", async () => {
|
||||
const { report, response } = await readWithCover({ storedFingerprint: BIRTH_FP, current: async () => OTHER_FP });
|
||||
assert.equal(report.coverSubject, null);
|
||||
assert.doesNotMatch(JSON.stringify(response.body), new RegExp(`${BIRTH_FP}|${OTHER_FP}`));
|
||||
});
|
||||
|
||||
test("core read: coverSubject is null for a legacy report without the field, and nothing is looked up", async () => {
|
||||
const { report, asked } = await readWithCover({ storedFingerprint: null, current: async () => BIRTH_FP });
|
||||
assert.equal(report.coverSubject, null);
|
||||
assert.deepEqual(asked, []);
|
||||
});
|
||||
|
||||
test("core read: coverSubject is null for a subject that is not the reader's (foreign, deleted, unreadable)", async () => {
|
||||
const foreign = await readWithCover({
|
||||
storedFingerprint: BIRTH_FP,
|
||||
chartProfileId: SESSION_ID,
|
||||
current: async () => { throw new Error("subject_not_found"); },
|
||||
});
|
||||
assert.equal(foreign.report.coverSubject, null);
|
||||
const missing = await readWithCover({ storedFingerprint: BIRTH_FP, current: async () => null });
|
||||
assert.equal(missing.report.coverSubject, null);
|
||||
});
|
||||
|
||||
@@ -1031,3 +1031,45 @@ test("sectioned generation never uses English character-halving for output token
|
||||
assert.match(generationSource, /sectionOutputTokenBudget\(entry\.targetCharacters\.max\)/);
|
||||
assert.doesNotMatch(generationSource, /targetCharacters\.max\s*\/\s*2/);
|
||||
});
|
||||
|
||||
// Report cover binding (TASK-birth-sky-followup-20260928 F1): both assemblies
|
||||
// write subject.birthFingerprint; the model-facing bundle never carries it.
|
||||
test("single-call and sectioned generation write subject.birthFingerprint only when given", async () => {
|
||||
const fingerprint = "0123456789abcdef0123456789abcdef";
|
||||
const bundle = makeBundle({ themes: fullThemes.slice(0, 3), charts: [chart("D1"), chart("D2", 1), chart("D9", 2), chart("D10", 3), chart("D11", 4)] });
|
||||
const seen: string[] = [];
|
||||
const agent = sectionedAgent({});
|
||||
const watching: ReportAgentPort = {
|
||||
...agent,
|
||||
async generateSection(sectionBundle, section, titles, options) {
|
||||
seen.push(JSON.stringify(sectionBundle));
|
||||
return agent.generateSection!(sectionBundle, section, titles, options);
|
||||
},
|
||||
};
|
||||
const sectioned = readyV2(await generatePersonalReport({
|
||||
reportId: REPORT_ID,
|
||||
userId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
requestId: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb",
|
||||
bundle,
|
||||
depth: "research",
|
||||
agent: watching,
|
||||
sectionService: inMemorySectionService(),
|
||||
now: () => new Date(GENERATED_AT),
|
||||
birthFingerprint: fingerprint,
|
||||
}));
|
||||
assert.equal(sectioned.subject.birthFingerprint, fingerprint);
|
||||
assert.ok(seen.length > 0);
|
||||
for (const payload of seen) assert.doesNotMatch(payload, new RegExp(fingerprint));
|
||||
|
||||
const single = readyV2(await generatePersonalReport({
|
||||
reportId: REPORT_ID,
|
||||
bundle,
|
||||
depth: "research",
|
||||
agent: fakeWriter(writerOutputFor),
|
||||
now: () => new Date(GENERATED_AT),
|
||||
birthFingerprint: fingerprint,
|
||||
}));
|
||||
assert.equal(single.subject.birthFingerprint, fingerprint);
|
||||
const legacy = readyV2(await run(bundle, fakeWriter(writerOutputFor)));
|
||||
assert.equal("birthFingerprint" in legacy.subject, false);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { resolveServerOwnedChartBirth } from "../src/lib/chart-birth-truth.ts";
|
||||
import { prepareChartViewProfile } from "../src/lib/chart-view-profile-read.ts";
|
||||
import { safeParseReportDocument } from "../src/lib/personal-report-contract.ts";
|
||||
import { buildLongformCoverDocument } from "../src/lib/personal-report-longform-cover.ts";
|
||||
import { loadReportWorkerProfile } from "../src/lib/personal-report-worker-subject.ts";
|
||||
import {
|
||||
REPORT_BIRTH_FINGERPRINT_KEY,
|
||||
readReportBirthFingerprint,
|
||||
reportCoverSubject,
|
||||
reportDocumentBirthFingerprint,
|
||||
stampReportBirthFingerprint,
|
||||
subjectBirthFingerprint,
|
||||
withReportBirthFingerprint,
|
||||
} from "../src/lib/report-birth-binding.ts";
|
||||
|
||||
// Report cover binding, product decision A (TASK-birth-sky-followup-20260928 F1/F2).
|
||||
// Fictional sample birth only: 1994-05-18 07:40 UTC+8, 30.27N 120.15E.
|
||||
|
||||
const storedSelf = {
|
||||
name: "虚构甲",
|
||||
birth_date: "1994-05-18",
|
||||
reported_birth_time: "07:40:00",
|
||||
birth_time_source: "family_exact",
|
||||
birth_time_status: "reported",
|
||||
birth_place_label: "虚构城",
|
||||
latitude: 30.27,
|
||||
longitude: 120.15,
|
||||
timezone_offset: 8,
|
||||
timezone_id: "Asia/Shanghai",
|
||||
ayanamsa: "lahiri",
|
||||
};
|
||||
|
||||
const routeSource = readFileSync(new URL("../src/app/api/reports/route.ts", import.meta.url), "utf8");
|
||||
const itemRouteSource = readFileSync(new URL("../src/app/api/reports/[reportId]/route.ts", import.meta.url), "utf8");
|
||||
const workerSource = readFileSync(new URL("../src/lib/personal-report-worker.ts", import.meta.url), "utf8");
|
||||
const longformSource = readFileSync(new URL("../src/lib/personal-report-longform-generate.ts", import.meta.url), "utf8");
|
||||
const routeCoreSource = readFileSync(new URL("../src/lib/personal-report-route-core.ts", import.meta.url), "utf8");
|
||||
const generationSource = readFileSync(new URL("../src/lib/personal-report-generation.ts", import.meta.url), "utf8");
|
||||
|
||||
function fakeSupabase(rows: Readonly<{ profiles?: Record<string, unknown> | null }>) {
|
||||
return {
|
||||
from(table: string) {
|
||||
const query = {
|
||||
select: () => query,
|
||||
eq: () => query,
|
||||
maybeSingle: async () => ({
|
||||
data: table === "profiles" ? (rows.profiles ?? null) : { rectification_case_id: null },
|
||||
error: null,
|
||||
}),
|
||||
};
|
||||
return query;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("the report fingerprint is the chart page's profileFingerprint (same function, stored row)", async () => {
|
||||
const withoutOffset = { ...storedSelf, timezone_offset: null };
|
||||
const filled = { ...withoutOffset, timezone_offset: 8 };
|
||||
const chartView = await prepareChartViewProfile({ row: withoutOffset, resolveTimezone: async () => filled });
|
||||
assert.equal(chartView.ok, true);
|
||||
assert.equal(subjectBirthFingerprint(withoutOffset), chartView.birth.fingerprint);
|
||||
// The in-memory timezone fill changes the fingerprint, so it must be taken before the fill.
|
||||
assert.notEqual(resolveServerOwnedChartBirth(filled).fingerprint, chartView.birth.fingerprint);
|
||||
const stamped = stampReportBirthFingerprint(withoutOffset, filled);
|
||||
assert.equal(readReportBirthFingerprint(stamped), chartView.birth.fingerprint);
|
||||
assert.match(String((stamped as Record<string, unknown>)[REPORT_BIRTH_FINGERPRINT_KEY]), /^[0-9a-f]{32}$/);
|
||||
});
|
||||
|
||||
test("worker profile loader stamps the stored-row fingerprint before the timezone fill", async () => {
|
||||
const profile = await loadReportWorkerProfile(fakeSupabase({ profiles: storedSelf }), "user-1", "self");
|
||||
assert.equal(readReportBirthFingerprint(profile), subjectBirthFingerprint(storedSelf));
|
||||
assert.equal((profile as Record<string, unknown>).latitude, 30.27, "the generators still read the same row");
|
||||
});
|
||||
|
||||
test("every generation path writes subject.birthFingerprint from the stamped profile", () => {
|
||||
// POST /api/reports (inline and queued create) stamps before the timezone fill.
|
||||
assert.match(routeSource, /profile = stampReportBirthFingerprint\(\s*resolved\.row,\s*await resolveMissingBirthTimezoneOffset\(resolved\.row/);
|
||||
// Inline route-core generation, the queued writer and the queued longform all pass it on.
|
||||
assert.match(routeCoreSource, /birthFingerprint: readReportBirthFingerprint\(profile\),/);
|
||||
assert.match(workerSource, /birthFingerprint: readReportBirthFingerprint\(profile\),/);
|
||||
assert.match(longformSource, /birthFingerprint: readReportBirthFingerprint\(profile\),/);
|
||||
// Both document assemblies (single-call and sectioned) stamp before the guard and the final parse.
|
||||
assert.equal(generationSource.match(/applyReportGuard\(withReportBirthFingerprint\(candidate, deps\.birthFingerprint\)/g)?.length, 2);
|
||||
// Never into the evidence bundle the model reads.
|
||||
assert.doesNotMatch(generationSource, /bundle[^\n]*birthFingerprint/);
|
||||
});
|
||||
|
||||
test("longform cover document carries the fingerprint and still parses; without it nothing is added", () => {
|
||||
const input = {
|
||||
report: {
|
||||
id: "123e4567-e89b-12d3-a456-426614174000",
|
||||
reportType: "personal_full" as const,
|
||||
presentationMode: "default" as const,
|
||||
depth: "standard" as const,
|
||||
requestedThemes: ["career"],
|
||||
skillName: "jyotish-vedic-astrology",
|
||||
skillVersion: "6.9.14",
|
||||
skillSourceCommit: null,
|
||||
skillSnapshotSha256: "ab".repeat(32),
|
||||
},
|
||||
subject: { displayName: "虚构甲", birthTimeStatus: "reported" as const, birthPlaceLabel: "虚构城" },
|
||||
markdown: "# 个人长报告\n\n## 摘要\n\n事业方向保持观察。\n",
|
||||
generatedAt: "2026-09-28T00:00:00.000Z",
|
||||
};
|
||||
const fingerprint = subjectBirthFingerprint(storedSelf);
|
||||
const bound = buildLongformCoverDocument({ ...input, birthFingerprint: fingerprint });
|
||||
assert.equal(bound.subject.birthFingerprint, fingerprint);
|
||||
assert.equal(reportDocumentBirthFingerprint(bound), fingerprint);
|
||||
const legacy = buildLongformCoverDocument(input);
|
||||
assert.equal("birthFingerprint" in legacy.subject, false);
|
||||
assert.equal(reportDocumentBirthFingerprint(legacy), null);
|
||||
});
|
||||
|
||||
test("documents without the field (old reports) still parse; a malformed fingerprint does not", () => {
|
||||
const document = buildLongformCoverDocument({
|
||||
report: {
|
||||
id: "123e4567-e89b-12d3-a456-426614174000",
|
||||
reportType: "personal_full",
|
||||
presentationMode: "default",
|
||||
depth: "standard",
|
||||
requestedThemes: ["career"],
|
||||
skillName: "jyotish-vedic-astrology",
|
||||
skillVersion: "6.9.14",
|
||||
skillSourceCommit: null,
|
||||
skillSnapshotSha256: "ab".repeat(32),
|
||||
},
|
||||
subject: { displayName: "虚构甲", birthTimeStatus: "reported", birthPlaceLabel: "虚构城" },
|
||||
markdown: "# 个人长报告\n\n## 摘要\n\n事业方向保持观察。\n",
|
||||
generatedAt: "2026-09-28T00:00:00.000Z",
|
||||
});
|
||||
assert.equal(safeParseReportDocument(document).ok, true);
|
||||
assert.equal(safeParseReportDocument(withReportBirthFingerprint(document, "a".repeat(32))).ok, true);
|
||||
assert.equal(safeParseReportDocument({ ...document, subject: { ...document.subject, birthFingerprint: "1994-05-18" } }).ok, false);
|
||||
assert.equal(withReportBirthFingerprint(document, undefined), document, "no fingerprint → untouched");
|
||||
});
|
||||
|
||||
test("coverSubject: only a matching fingerprint yields the subject id, self when chart_profile_id is null", () => {
|
||||
const fp = "a".repeat(32);
|
||||
assert.equal(reportCoverSubject({ chartProfileId: null, storedFingerprint: fp, currentFingerprint: fp }), "self");
|
||||
assert.equal(reportCoverSubject({ chartProfileId: "11111111-1111-4111-8111-111111111111", storedFingerprint: fp, currentFingerprint: fp }), "11111111-1111-4111-8111-111111111111");
|
||||
assert.equal(reportCoverSubject({ chartProfileId: null, storedFingerprint: fp, currentFingerprint: "b".repeat(32) }), null);
|
||||
assert.equal(reportCoverSubject({ chartProfileId: null, storedFingerprint: null, currentFingerprint: fp }), null);
|
||||
assert.equal(reportCoverSubject({ chartProfileId: null, storedFingerprint: fp, currentFingerprint: null }), null);
|
||||
});
|
||||
|
||||
test("GET /api/reports/:id compares on the server through the chart page's subject loader", () => {
|
||||
assert.match(itemRouteSource, /loadCurrentBirthFingerprint: async \(ownerId: string, subjectId: string\) => \(\s*subjectBirthFingerprint\(\(await loadSubjectBirth\(supabase, ownerId, subjectId\)\)\.row\)/);
|
||||
assert.match(routeCoreSource, /reportDocumentBirthFingerprint\(row\.reportDocument\)/);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { classifyReportEnvelope } from "../src/components/personal-report/personal-report-page.tsx";
|
||||
import type { BirthSkyPaletteName } from "../src/lib/birth-sky/draw.ts";
|
||||
import { loadReportSkyCover } from "../src/lib/birth-sky/report-cover.ts";
|
||||
import { goldenSky } from "./birth-sky-test-support.ts";
|
||||
|
||||
// Report cover (TASK-birth-sky-followup-20260928 F3).
|
||||
|
||||
const page = readFileSync(new URL("../src/components/personal-report/personal-report-page.tsx", import.meta.url), "utf8");
|
||||
const component = readFileSync(new URL("../src/components/birth-sky/report-sky-cover.tsx", import.meta.url), "utf8");
|
||||
const css = readFileSync(new URL("../src/components/birth-sky/report-sky-cover.css", import.meta.url), "utf8");
|
||||
|
||||
function readyEnvelope(coverSubject?: unknown) {
|
||||
return {
|
||||
report: {
|
||||
id: "11111111-1111-4111-8111-111111111111",
|
||||
status: "ready",
|
||||
createdAt: "2026-09-28T00:00:00.000Z",
|
||||
...(coverSubject === undefined ? {} : { coverSubject }),
|
||||
},
|
||||
longformMarkdown: "# 报告\n\n正文。",
|
||||
};
|
||||
}
|
||||
|
||||
test("matching fingerprint → the ready state carries coverSubject; mismatch or legacy → no cover", () => {
|
||||
const bound = classifyReportEnvelope(200, readyEnvelope("self"));
|
||||
assert.equal(bound.phase, "markdown-ready");
|
||||
assert.equal(bound.phase === "markdown-ready" && bound.coverSubject, "self");
|
||||
for (const value of [null, undefined, "", 42]) {
|
||||
const state = classifyReportEnvelope(200, readyEnvelope(value));
|
||||
assert.equal(state.phase, "markdown-ready");
|
||||
assert.equal("coverSubject" in state, false, `coverSubject=${String(value)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the cover sits above the body, lazy, and only when coverSubject is set", () => {
|
||||
assert.match(page, /\{state\.coverSubject \? <ReportSkyCover subjectId=\{state\.coverSubject\} \/> : null\}\s*<PersonalReportMarkdownView/);
|
||||
assert.match(page, /const ReportSkyCover = dynamic\(\s*\(\) => import\("@\/components\/birth-sky\/report-sky-cover"\)/);
|
||||
// No buttons, no placeholder, no waiting state.
|
||||
assert.doesNotMatch(component, /<Button|<button|Spinner|skeleton|正在/i);
|
||||
assert.match(component, /if \(!images\) return null;/, "nothing renders before both pictures are painted");
|
||||
});
|
||||
|
||||
test("loader paints night for the screen and paper for print with the same sky", async () => {
|
||||
const sky = goldenSky("day");
|
||||
const painted: BirthSkyPaletteName[] = [];
|
||||
const asked: string[] = [];
|
||||
const pngs = await loadReportSkyCover("self", new AbortController().signal, {
|
||||
fetchSky: async (subjectId) => { asked.push(subjectId); return sky; },
|
||||
render: async (_sky, palette) => { painted.push(palette); return new Blob([palette]); },
|
||||
});
|
||||
assert.deepEqual(asked, ["self"]);
|
||||
assert.deepEqual(painted.sort(), ["night", "paper"]);
|
||||
assert.equal(await pngs?.screen.text(), "night");
|
||||
assert.equal(await pngs?.print.text(), "paper");
|
||||
assert.match(pngs?.description ?? "", /^星星都在,只是还看不见。|太阳/);
|
||||
});
|
||||
|
||||
test("fetch failure, an empty sky or an abort → no cover, and nothing throws into the report", async () => {
|
||||
const signal = new AbortController().signal;
|
||||
const render = async () => new Blob(["x"]);
|
||||
assert.equal(await loadReportSkyCover("self", signal, { fetchSky: async () => { throw new Error("offline"); }, render }), null);
|
||||
assert.equal(await loadReportSkyCover("self", signal, { fetchSky: async () => null, render }), null);
|
||||
assert.equal(await loadReportSkyCover("self", signal, { fetchSky: async () => goldenSky("day"), render: async () => { throw new Error("canvas"); } }), null);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
assert.equal(await loadReportSkyCover("self", aborted.signal, { fetchSky: async () => goldenSky("day"), render }), null);
|
||||
});
|
||||
|
||||
test("print: paper picture alone on the first A4 page; the screen picture is hidden", () => {
|
||||
assert.match(component, /className="report-sky-cover-print" src=\{images\.print\}/);
|
||||
assert.match(css, /\.report-sky-cover-print \{ display: none !important; \}/);
|
||||
const print = css.slice(css.indexOf("@media print"));
|
||||
assert.match(print, /\.report-sky-cover \{[^}]*break-after: page;/);
|
||||
assert.match(print, /\.report-sky-cover-screen \{ display: none !important; \}/);
|
||||
assert.match(print, /\.report-sky-cover-print \{[^}]*display: block !important;/);
|
||||
assert.match(css, /aspect-ratio: 3 \/ 4;/);
|
||||
});
|
||||
@@ -61,6 +61,7 @@ FAILURE_CODES = (
|
||||
UUID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
||||
SHA256_PATTERN = re.compile(r"^[0-9a-f]{64}$")
|
||||
SHA1_PATTERN = re.compile(r"^[0-9a-f]{40}$")
|
||||
BIRTH_FINGERPRINT_PATTERN = re.compile(r"^[0-9a-f]{32}$")
|
||||
SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$")
|
||||
SKILL_VERSION_PATTERN = re.compile(
|
||||
r"^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)"
|
||||
@@ -301,7 +302,9 @@ def _validate_subject(result: ValidationResult, value: Any) -> None:
|
||||
if subject is None:
|
||||
return
|
||||
required = ("displayName", "birthTimeStatus", "birthPlaceLabel")
|
||||
_check_keys(result, "subject", subject, required)
|
||||
_check_keys(result, "subject", subject, required, (*required, "birthFingerprint"))
|
||||
if "birthFingerprint" in subject:
|
||||
_check_pattern(result, "subject.birthFingerprint", subject.get("birthFingerprint"), BIRTH_FINGERPRINT_PATTERN, "birth fingerprint")
|
||||
_check_text(result, "subject.displayName", subject.get("displayName"), TEXT_LIMITS["displayName"])
|
||||
_check_enum(result, "subject.birthTimeStatus", subject.get("birthTimeStatus"), BIRTH_TIME_STATUSES)
|
||||
_check_text(result, "subject.birthPlaceLabel", subject.get("birthPlaceLabel"), TEXT_LIMITS["birthPlaceLabel"])
|
||||
|
||||
@@ -229,6 +229,19 @@ def test_strict_keys_missing_and_extra(fixture: dict) -> None:
|
||||
assert any("unexpected keys" in error for error in result.errors)
|
||||
|
||||
|
||||
def test_subject_birth_fingerprint_is_optional_and_pattern_checked(fixture: dict) -> None:
|
||||
# Report cover binding (TASK-birth-sky-followup-20260928): old documents
|
||||
# have no fingerprint; new ones carry a 32-hex stored-row fingerprint.
|
||||
assert "birthFingerprint" not in fixture["subject"]
|
||||
bound = json.loads(json.dumps(fixture))
|
||||
bound["subject"]["birthFingerprint"] = "0123456789abcdef0123456789abcdef"
|
||||
assert validate_report_document(bound).valid
|
||||
bound["subject"]["birthFingerprint"] = "1994-05-18"
|
||||
result = validate_report_document(bound)
|
||||
assert not result.valid
|
||||
assert any("subject.birthFingerprint" in str(error) for error in result.errors)
|
||||
|
||||
|
||||
def test_json_object_key_order_is_not_validated(fixture: dict) -> None:
|
||||
# JSON objects are unordered; fixed reader order is a display contract of
|
||||
# the typed fields, never a key-order condition.
|
||||
|
||||
Reference in New Issue
Block a user