Merge remote-tracking branch 'origin/staging' into codex/annual-page-option-b-20261113
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
# BLOCKED
|
||||
|
||||
## #242 · 公开盘模型验收与 Windows 门禁
|
||||
|
||||
- 两张公开盘各两次真实模型生成由 Claude 在验收主机运行。Windows Docker 引擎返回 HTTP 500,容器用例按既有条件跳过。
|
||||
- Python 快速门的三项 Kaala / PyJHora 检查与同机基线一致,完整绿灯待可用的验收环境复核。
|
||||
- 替代证据与同配置基线结果见 [#242 进度](docs/tasks/PROGRESS-reading-rebind-repair-20261113.md)。
|
||||
|
||||
## #241 · D6、D8 事件类别待占星师定义
|
||||
|
||||
- ~~D6、D8 缺少事件评分映射,暂停 #241。~~ 修订任务书放行 D9、D10、D2 的事件题。D6、D8 照常参与选线,只使用补充题。
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-11-13 — 个人报告先修正解读标注,再重写未通过的章节
|
||||
|
||||
- 报告会自动修正可确定的依据标注,并在时限内合并重写请求。已通过核对的章节保留原文。Skill 版本沿用当前版本(BUG-1876)。
|
||||
|
||||
## 2026-11-13 — 多轮选盘按已发生的事件核对候选段
|
||||
|
||||
- 选盘接口可为感情、工作和财务提供有时段依据的事件题,逐轮保留日期与判边依据。少于三件有日期的事时,结果只给倾向。页面由 #239 接入,沿用当前 Skill 版本(BUG-1875)。
|
||||
|
||||
@@ -25282,6 +25282,21 @@
|
||||
- 验证及防复发:覆盖有与无可区分时段、D1 问题范围、日期跨轮、平分兜底、候选段内评分和三件事件门槛。见 [#241 进度](tasks/PROGRESS-chart-choice-questions-20261113.md)。
|
||||
- 关联记录:#229、#238、#241、BUG-405、BUG-1703、BUG-1759、BUG-1872。
|
||||
- 修复版本:`codex/chart-choice-questions-20261113`,待发布。
|
||||
|
||||
## BUG-1876 | 个人报告因标注遗漏或单节格式问题被拦
|
||||
|
||||
- 状态:fixed-pending-verify(合成回归通过,待独立模型验收)。
|
||||
- 首次发现 / 最近更新:2026-11-13 / 2026-11-13。
|
||||
- 影响面:个人报告的写作器、逐节复查和验收工具。
|
||||
- 现象:有效文字因缺少时间或依赖标注被拦。依据节多于六段会在结构化输出时造成整份解读失败。
|
||||
- 触发条件:模型省略可补的标注,摘要依赖被退回的结论,或者单节段数超过上限。
|
||||
- 根因:结构化输出层先执行单节段数限制。进入复查的章节没有确定性的标注修复路径。重试时会重新生成整份内容。
|
||||
- 修复:先按本节允许的结论和依据重绑,超段时合并原文,再走逐节复查。剩余失败节用一次定向重写处理,受 #240 的剩余时间约束。
|
||||
- 验收退回及复修:真实模型四稿最终平均被拦五节。补齐无标注段的确定性绑定。第二稿可用时仍保留一次重写机会,跨域提示带命中依赖。超段无法安全合并时保留其余段。验收工具用产品默认的 Raman 与平均交点重算。
|
||||
- 验证和防复发:合成回归覆盖四类标注、D8 临界状态、八段合并、定向请求、超时与摘要等级。进度与环境缺口见 [#242 进度](tasks/PROGRESS-reading-rebind-repair-20261113.md)。
|
||||
- 关联记录:#219、#220、#240、#242、BUG-1860、BUG-1862、BUG-1863、BUG-1874。
|
||||
- 修复版本:`codex/reading-rebind-repair-20261113`,待发布。
|
||||
|
||||
## BUG-1857 | 年运 Tithi Pravesha 缺现居地,本命瑜伽证据截断
|
||||
|
||||
- 状态:fixed-pending-verify(待独立验收)。
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# #242 开工前补充:格式层的一刀切也要改成可修复(2026-11-13,Claude)
|
||||
|
||||
本文件补充任务书。两者冲突时,以本文件为准。
|
||||
|
||||
## 新发现(验收主机,生产模型 deepseek-flash,#240 分支)
|
||||
|
||||
Obama 公开盘连续两次 `model_failed`,原因是:
|
||||
|
||||
```
|
||||
Structured output validation failed: sections.8.paragraphs: Array must contain at most 6 element(s)
|
||||
```
|
||||
|
||||
模型在「依据与边界」写了 7 段以上。`reportReadingDraftEnvelopeSchema` 在结构化输出这一层直接校验段数,超了就整份解读失败,后面的逐节复查和重绑都轮不到。
|
||||
|
||||
## 加做
|
||||
|
||||
1. 结构化输出层(`frontend/src/mastra/personal-report-reading.ts` 用的那个 envelope schema)只校验大结构:9 个节,每节有一个段落数组,每段有 text。段数、字数、字段齐不齐全,都挪到逐节复查里处理。
|
||||
2. 逐节复查里,段数超过 6 时由系统自动合并:多出的段,并入同一节里结论类型相同的最近一段;找不到可并的,就并进最后一段。合并后再走字数检查;合并后过长,交给重写处理。每次合并都记进 `transform_log.auto_rebound`,`rule` 写 `merge_paragraphs`。
|
||||
3. 同样的道理:envelope 层以后不得再因为单节的问题拒掉整份解读。整份拒绝只保留给「没有 9 个节」「不是 JSON」这类结构性问题。
|
||||
4. 单测:用合成稿,「依据与边界」写 8 段 → 整份不失败,这一节合并成 6 段后通过,并留下记录。
|
||||
@@ -0,0 +1,30 @@
|
||||
# #242 验收退回:真实模型 4 份稿,最后仍有平均 5 节被拦(目标 ≤ 1)(2026-11-13,Claude)
|
||||
|
||||
验收对象是 `a4087c7e`。下面这些已经通过,不要改:重绑的四条规则、等级只降不升、合并超出的段、只重写失败的节、统计字段。质量门、前端 62 项、tsc、eslint 都通过。
|
||||
|
||||
## 验收主机实测(deepseek-flash,验收工具,每张盘跑 2 次,已脱敏)
|
||||
|
||||
| 稿 | 第一轮被拦 | 重绑修好 | 重写修好 | 最后仍被拦 | 剩下的原因 |
|
||||
|---|---|---|---|---|---|
|
||||
| r1 Jobs | 7 | 0 | 0(**没有重写**) | 7 | double_transit_scope×2、ref_outside_claims×2、timing_unbound、claim_not_established、current_advice_in_replay |
|
||||
| r1 Obama | 7 | 1 | 5 | 1 | too_long(依据与边界合并后超长) |
|
||||
| r2 Jobs | 7 | 0 | 3 | 4 | sav_total_as_strength、ref_outside_claims、claim_type_section、claim_not_established |
|
||||
| r2 Obama | 8 | 0 | 0 | 8 | 全部是 claim_binding_missing:模型的段落既没有 claims,也没有 kind |
|
||||
|
||||
## 要改
|
||||
|
||||
1. **验收工具的计算参数要和产品一致。** `tools/report-reading-acceptance/cases.json` 的请求没传 `ayanamsa`,引擎默认用了 Lahiri,Jobs 的上升因此算成狮子(产品默认 Raman,算出来是处女)。请显式传入产品默认参数:ayanamsa=raman、node_mode=mean。从前端或档案的默认值读取,不要写死成另一个值。PROGRESS 里写明报告接口缺省 ayanamsa 时实际用的是哪个值,这一条可能还牵涉生产,先列出来,不改。
|
||||
2. **claim_binding_missing 也要重绑。** 段落既没有 claims 也没有 kind 时,按下面的顺序处理:
|
||||
- 正文能识别出别名或时间词,就当判断段,claims 取别名对应的类型;取不到时用本节默认类型,overview、advice 用已成立的类型。grade 取这些类型上限中最严的那个,`refs` 交给自动补全。
|
||||
- 正文没有推断词,就当事实段。
|
||||
- 每一次处理都记一条 auto_rebound,`rule` 为 `claim_binding_missing`。
|
||||
3. **重写在任何情况下都要跑。** r1 Jobs 的第一稿是 model_failed,第二稿被采用,结果没有发起重写(`repair: null`)。规则是:无论最终选中第几稿,只要还有失败的节,而且剩余时间够,就发一次重写。
|
||||
4. **ref_outside_claims 修不好的情况。** r1 Jobs 的感情节、健康节,r2 Jobs 的性格节,重绑后仍然失败。原因是正文提到的那一层,本节所有结论类型都不允许。请在 PROGRESS 里逐一列出这几段命中的别名和对应的依赖 id,判断属于以下哪一种:
|
||||
- **(a) 别名误判。** 例如「大运」这类泛词,在事实性的叙述里出现。如果是这种,就把泛词从「判断依赖」里拿掉:只出现泛词时,不要求它进 refs。
|
||||
- **(b) 真的跨了领域。** 交给重写处理。重写提示里要写明「这一节不能谈 X,请删掉或改到对应的节」。
|
||||
5. **合并超长。** 合并后的段如果超过字数上限,就不要合并。改为把超出的段截掉,记录 `rule: drop_paragraph`,被截掉的原文留在 transform_log。
|
||||
6. **重写提示要具体。** 每个失败节附上命中的句子,以及一句怎么改,例如「这句提到了 Double Transit,但本节对应的宫位不在已检查的宫位里:删掉这句」。不要只给原因代码。
|
||||
|
||||
## 验收
|
||||
|
||||
我会用修好的验收工具(Raman)重新跑 2 张盘、每张 2 次。目标是最后仍被拦的节平均每份不超过 1。剩下的节由 #243 兜底,但这里的目标先要达到。
|
||||
@@ -0,0 +1,50 @@
|
||||
# #242 报告解读重绑与逐节重写
|
||||
|
||||
- 执行者 Codex。可信放行评论 42977,补充任务书 [FIX-reading-rebind-repair-0.md](FIX-reading-rebind-repair-0.md)。从包含 #240 的 staging 开始,交付前同步已合入 #241 的 staging `d136b76a4641d227e327f961d01cef9522235006`。
|
||||
- 对判断段正文别名和显式引用,按 `REPORT_CLAIM_TYPES` 顺序添加本节允许且有对应依赖的第一个类型。时间标注使用本节允许的 `timing_window`。六个正文节的带推断事实段先按别名选类型,再用本节默认类型。总评和建议在正文复查后移除尚未成立的类型,保留仍有成立类型的段。
|
||||
- 重绑取原等级、结论上限和已成立结论等级中最严的一档。被重绑段落引用不稳定依赖时取 D。原先已绑定但等级超限的段落照常被拦。事实段没有原等级,日志记 `null`。
|
||||
- 结构化输出只检查章节容器、标识和文本类型。逐节核对先处理标注,再把超过六段的内容并入同类型的最近已保留段,没有匹配时并入最后一段。保留各段文字,同一合并段内按原顺序拼接。合并取更严格的等级与引用并集,再走原有长度和事实规则。
|
||||
- 剩余章节合成一次重写请求,携带其原 JSON、规则说明、命中句和同一事实包。原来通过的章节保留。修复段如果会让已通过的总评或建议超出证据等级,只舍弃冲突章节,其余可用修复照常接收。预留时间不足时记录 `repair_skipped_deadline`。整稿生成失败时继续沿用 #240 的完整重试。
|
||||
- `transform_log.auto_rebound`、`repair` 和 `statistics` 可审计。命中句只用于当次模型调用。验收工具在 `postcheck.json` 输出计数,`raw.json` 保留首份完整稿,有重写回复时另存 `repair_raw.json` 并写入文件哈希。既存快照可继续读回。
|
||||
|
||||
## 既有断言变更
|
||||
|
||||
| 原值 | 新值 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 事业段缺时间标注报 `timing_unbound` | 许可范围内自动补 `timing_window` 并通过 | #242 授权补标,原有缺上限或不允许的引用仍有反例 |
|
||||
| D8 可匹配另一结论时仍报 `ref_outside_claims` | 补 `health_pressure`,落在临界时取 D | #242 要求重绑 D8;预先带齐结论但高于允许等级的用例仍被拦 |
|
||||
| 第二次写作假回复为完整稿 | 假回复只含失败的感情节,原有断言保留 | 第二次请求只重写失败节 |
|
||||
| 有部分可用稿时跳过第二次请求记 `reading_retry_skipped_deadline` | `repair_skipped_deadline` | 区分章节重写与整稿重试 |
|
||||
| 新快照的 `postcheck_version` 为 1 | 2 | 逐节检查前增加重绑,快照可区分旧规则 |
|
||||
|
||||
## 验证
|
||||
|
||||
- 报告写作、事实复查、重绑、逐节重写、生成快照和离线验收包共 57 项定向测试通过。隐私检查 62 项通过。
|
||||
- Windows 前端全量 3704 项,3622 通过、45 失败、37 跳过、0 取消。最新 staging 的同机基线 3700 项,3618 通过、45 失败、37 跳过、0 取消。逐项比较,既有测试无缺失,失败清单完全一致。
|
||||
- Python 快速门运行至 pytest,1471 项通过、3 项失败、2 项跳过、29 项子测试通过。三项失败与同机 staging 基线一致,均在 Kaala / PyJHora 校验。同步最新 staging 后,另有 50 项选盘和占星师定向回归通过。
|
||||
- TypeScript、ESLint 和生产构建通过。ESLint 为 0 error、62 条既有 warning。首页保持静态,HTML 直接引用的 JS 515860 B、CSS 90906 B(gzip),同机基线一致。
|
||||
|
||||
两张公开盘各两次 DeepSeek 独立复核留给 Claude 验收,目标为每份最终被拦节数平均 ≤ 1。
|
||||
|
||||
## 第一次验收退回
|
||||
|
||||
- 可信退回评论 43032 针对 `a4087c7eed0b1c9ae96128d6dcd4f9541786e9d8`,修订任务书位于 `c8579c82d7a6e0350a782016f02907ec3db4d893`。Claude 报告四稿最终被拦 7、1、4、8 节,平均 5 节。沿用 PR #250,分支同步 staging `7e895b75ad8a0ced2f0e7cae2c5030c149bf1528`。
|
||||
- 既无 `claims` 又无 `kind` 的段按可识别别名、时间词和推断词补标。判断用本节可用结论和既有等级。纯事实补 `kind: "fact"`。显式给了无效标注的段照常复查。第二稿可用时,仍可在剩余时间内追加一次定向重写。
|
||||
- 六段以上优先合并。合并会超过段落字数上限时,保留原段,跳过新增段,并把被丢弃原文记在服务端 `auto_rebound.drop_paragraph` 记录。阅读 API 和公开交接不含该原文。验收包仍放在受控目录。
|
||||
- 验收工具原来在 `run.mts` 显式传 Lahiri。现在从前端默认常量读 Raman 与平均交点。专业报告接口的高严谨请求调用 `_request_ayanamsa(body)`,字段缺省时回到 `DEFAULT_AYANAMSA_NAME`(Raman);`node_mode` 缺省为产品的 mean。生产接口代码未改。
|
||||
- 泛称「大运」「小运」「次小运」不单独推断为 `s:vimshottari`,时间判断仍须标 `timing_window`。具名 Vimshottari 等依赖照常校验。真正跨域的段在重写提示中带上命中句、实际别名和依赖编号。验收包新增首份可用稿重绑后及最终稿的冲突字段。
|
||||
- 三个指定真实段只收到节名和原因,Gitea 无原稿、事实包或别名附件,无法逐一核实。r1 Jobs 感情节、r1 Jobs 健康节、r2 Jobs 性格节均待 Claude 从验收机原包查证。当前确认的泛称映射来自依赖目录及合成回归,未当作上述三段的实测结果。
|
||||
|
||||
| 原值 | 新值 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 无标注且无推断的段被拦 | 自动补事实标注 | 修订要求区分无标注事实与判断 |
|
||||
| 超段合并后过长,整节被拦 | 跳过超额段并记录原文 | 修订明确要求保留其余通过段 |
|
||||
| 重写记录只有是否尝试 | 已尝试时另记实际尝试序号 | 首稿失败时重写可以是第三次模型调用 |
|
||||
| 新快照的 `postcheck_version` 为 2 | 3 | 绑定和超额处理规则更新,历史快照继续可读 |
|
||||
|
||||
### 复验
|
||||
|
||||
- 报告定向 61 项、Python 定向和隐私合计 76 项、TypeScript、ESLint 和生产构建通过。ESLint 0 error。首页保持静态,HTML 直接引用的 gzip JS 515860 B、CSS 90906 B。
|
||||
- Windows 前端全量 3708 项,3625 通过、46 失败、37 跳过、0 取消。既有测试名称无缺失。45 项失败与同机基线一致,额外一项既有咨询计时测试定向复跑通过。
|
||||
- Python 快速门在隔离工作树运行。当前分支定向复现同机基线三项 Kaala / PyJHora 失败,完整门禁结果另核对。
|
||||
- 两张公开盘已通过本地报告引擎重算,事实包回读均为 Raman 与平均交点。各用同一份合成无标注稿离线回放,九节均自动补标并通过,验收包哈希核对通过。Claude 仍需在验收主机各生成两次,核对最终失败节均值。三个旧稿跨域段请用受控归档核对,回报只需章节、命中别名、依赖编号与分类。
|
||||
@@ -33,6 +33,7 @@
|
||||
|
||||
| 任务书 | 进度 | 主题 | 状态 | 落点 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [#242 任务书](TASK-reading-rebind-repair-20261113.md) | [执行进度](PROGRESS-reading-rebind-repair-20261113.md) | 报告解读重绑与逐节重写(BUG-1876) | 待验收 | `codex/reading-rebind-repair-20261113` |
|
||||
| [#241 修订任务书](FIX-chart-choice-questions-1.md) | [执行进度](PROGRESS-chart-choice-questions-20261113.md) | 多轮选盘事件题与判边(BUG-1875) | 待验收 | `codex/chart-choice-questions-20261113` |
|
||||
| [#240 任务书](TASK-reading-timeout-20261113.md) | [执行进度](PROGRESS-reading-timeout-20261113.md) | 报告解读超时与租期内重试(BUG-1874) | 待验收 | `codex/reading-timeout-20261113` |
|
||||
| [#238 任务书](TASK-chart-choice-rounds-engine-20261113.md) | [执行进度](PROGRESS-chart-choice-rounds-engine-20261113.md) | 多轮选盘与秒级采纳(BUG-1872) | 待验收 | `codex/chart-choice-rounds-engine-20261113` |
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# TASK:报告解读被拦的节先由系统修正标注,内容错误只重写这一节(2026-11-13)
|
||||
|
||||
- Gitea:#242
|
||||
- 分支:`codex/reading-rebind-repair-20261113`。**开工条件:#240(超时与剩余时间)合入 staging**,开工前先 rebase。
|
||||
- Bug 编号:BUG-1876
|
||||
- 验收:Claude(jyotisha-e6)
|
||||
|
||||
不得自行写「产品决定/裁定」,任务书没写到的取舍一律选需拍板。不得为了让测试通过而修改或删除既有断言;确需修改的,在 PROGRESS 写明原值、新值、原因。
|
||||
|
||||
## 背景(产品负责人 2026-11-13)
|
||||
|
||||
产品负责人的意见:向用户显示「这一节没有通过数据核对」不可接受。要找到被拦的原因,从根上解决。
|
||||
|
||||
验收主机统计了最近 5 份真实模型稿(DeepSeek,#219 之后的提示):一共拦了 16 节,平均每份三分之一。
|
||||
|
||||
| 原因 | 次数 | 性质 |
|
||||
|---|---|---|
|
||||
| ref_outside_claims | 4 | 标注:正文提到的层不在所标结论类型允许的依赖里,例如「留住收入」段提到 D11 |
|
||||
| timing_unbound | 3 | 标注:判断段写了年份或大运,但没标 timing_window |
|
||||
| current_advice_in_replay | 3 | 内容:已故人物写了当前建议(只出现在公开测试盘) |
|
||||
| fact_with_inference | 2 | 标注:事实段带了推断 |
|
||||
| claim_not_established | 2 | 标注:总评或建议引用了本稿被拦那一节的结论(连锁) |
|
||||
| field_name | 1 | 内容:正文里有内部编号 |
|
||||
| sav_total_as_strength | 1 | 内容:用 SAV 337 判断强弱 |
|
||||
|
||||
16 次里有 11 次只是标注不对,文字本身没有问题。
|
||||
|
||||
## 要做的(`frontend/src/lib/personal-report-reading.ts`,以及新增的 helper 文件)
|
||||
|
||||
### 1. 系统修正标注(只改标注,正文一个字不改)
|
||||
|
||||
在 `checkSection` 判定之前,对判断段和事实段先做一遍「重绑」:
|
||||
|
||||
- **ref_outside_claims**:正文提到层 X,而 X 不在所列结论类型的依赖并集里。在**本节允许的结论类型**(`claims[*].sections` 含本节)中,找一个依赖里含 X 的类型,加进 `claims`。找到多个时,按 `CLAIM_TYPES` 的顺序取第一个,规则写进 PROGRESS。本节没有任何类型允许 X,就不重绑,留给第 2 步。
|
||||
- **timing_unbound**:判断段提到时间,就把 `timing_window` 加进 `claims`。前提是 `timing_window` 允许出现在本节;不允许就留给第 2 步。
|
||||
- **fact_with_inference**:把这个事实段改成判断段。`claims` 按以下顺序取:
|
||||
1. 正文别名对应的结论类型;
|
||||
2. 取不到时,用本节的默认类型(character → character_structure,career → career_promise,wealth → wealth_earning,love → relationship_structure,health → health_pressure,now → timing_window)。
|
||||
|
||||
overview、advice、basis 三节没有默认类型,不改,留给第 2 步。
|
||||
- **claim_not_established**:先把其余各节都判完,再处理 overview 和 advice。去掉没成立的那类结论;段内还有其他已成立的结论,就保留这一段;一类都不剩了,留给第 2 步。
|
||||
- **重绑之后的等级规则:**
|
||||
- `grade` = min(模型给的等级, 所有 claims 上限里最严的那个);
|
||||
- 重绑只能降级,**不得升级**;
|
||||
- `ref_unstable` 等规则在重绑之后照常检查;
|
||||
- 每一次重绑都写进 `transform_log`:`auto_rebound: [{rule, added_claims, grade_from, grade_to}]`。
|
||||
|
||||
### 2. 只重写失败的节(内容错误)
|
||||
|
||||
重绑之后仍不通过的节,**合在一起只发一次**修改请求:
|
||||
|
||||
- 请求里只带这几节的原 JSON、每节的退回原因,以及具体到句子的说明(由复查函数返回命中的句子片段和规则说明),再附上同一份事实包。要求只返回这几节。
|
||||
- 复查规则不变;返回的节重新走「重绑 + 复查」。
|
||||
- 发请求前用 #240 的剩余时间判断:不够就跳过。原因记 `repair_skipped_deadline`。
|
||||
- 系统提示复用现有的,补一个短的修改说明块,放在产品合同的 report-reading 块里,**只加这一小段**。
|
||||
- `transform_log` 记录:`repair: {sections, reasons, attempted, passed}`。
|
||||
|
||||
### 3. 验收工具输出统计
|
||||
|
||||
`tools/report-reading-acceptance/run.mts` 的 `postcheck.json` 增加:
|
||||
|
||||
- 首轮被拦节数、重绑修好的节数、重写修好的节数、最后仍失败的节数;
|
||||
- 每种原因的计数。
|
||||
|
||||
## 验收
|
||||
|
||||
1. 单元测试(合成稿):
|
||||
- 上表 4 种标注问题,各自能被重绑修好;等级只降不升;transform_log 里有记录。
|
||||
- 正文提到边界上的 D8:重绑后等级为 D,仍然通过(`ref_unstable` 依旧生效)。
|
||||
- 内容错误(例如 field_name)会触发修改请求,用假写作器验证请求里只包含失败的节;剩余时间不足时跳过。
|
||||
2. 验收主机:我用 DeepSeek 对两张公开盘各跑 2 次。目标是最后仍失败的节平均每份 ≤ 1。
|
||||
3. 原有测试全部通过,tsc 无错误、eslint 0 个错误,Python 快速门通过。
|
||||
|
||||
## 不要碰
|
||||
|
||||
- 复查规则本身(只在前面加重绑)
|
||||
- 证据上限
|
||||
- 事实包
|
||||
- 冻结文件
|
||||
- 页面上失败节的显示方式(由 #243 负责)
|
||||
@@ -55,13 +55,45 @@ export const readingAttemptSchema = z.strictObject({
|
||||
sections: z.array(readingSectionTransformSchema),
|
||||
});
|
||||
|
||||
const referenceConflicts = z.array(z.strictObject({
|
||||
section: z.string(),
|
||||
references: z.array(z.strictObject({ alias: z.string(), ids: z.array(z.string()) })),
|
||||
}));
|
||||
|
||||
export const readingTransformLogSchema = z.strictObject({
|
||||
selected_attempt: z.number().int().positive().nullable(),
|
||||
retries: z.number().int().nonnegative(),
|
||||
attempts: z.array(readingAttemptSchema),
|
||||
auto_rebound: z.array(z.strictObject({
|
||||
section: z.string(),
|
||||
paragraph: z.number().int().positive(),
|
||||
rule: reason,
|
||||
added_claims: z.array(z.string()),
|
||||
grade_from: z.enum(["A", "B", "C", "D"]).nullable(),
|
||||
grade_to: z.enum(["A", "B", "C", "D"]).nullable(),
|
||||
dropped_text: z.string().optional(),
|
||||
})).optional(),
|
||||
repair: z.strictObject({
|
||||
sections: z.array(z.string()),
|
||||
reasons: z.record(z.string(), reason),
|
||||
attempted: z.boolean(),
|
||||
attempt: z.number().int().positive().optional(),
|
||||
passed: z.array(z.string()),
|
||||
}).optional(),
|
||||
statistics: z.strictObject({
|
||||
first_withheld: z.number().int().nonnegative(),
|
||||
rebound_fixed: z.number().int().nonnegative(),
|
||||
repair_fixed: z.number().int().nonnegative(),
|
||||
final_withheld: z.number().int().nonnegative(),
|
||||
first_reasons: z.record(reason, z.number().int().positive()),
|
||||
final_reasons: z.record(reason, z.number().int().positive()),
|
||||
}).optional(),
|
||||
first_reference_conflicts: referenceConflicts.optional(),
|
||||
final_reference_conflicts: referenceConflicts.optional(),
|
||||
});
|
||||
|
||||
export type ReadingSectionTransform = z.infer<typeof readingSectionTransformSchema>;
|
||||
export type ReadingAttempt = z.infer<typeof readingAttemptSchema>;
|
||||
export type ReadingTransformLog = z.infer<typeof readingTransformLogSchema>;
|
||||
export type ReadingRebound = NonNullable<ReadingTransformLog["auto_rebound"]>[number];
|
||||
export type ReadingSnapshot = z.infer<typeof readingSnapshotSchema>;
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { BoundReadingSection, CheckedReportReading, ReportReadingDraftSecti
|
||||
import type { ReadingSectionTransform, ReadingTransformLog } from "./personal-report-reading-audit-contract";
|
||||
|
||||
/** Bump when the report-reading post-check rules change. */
|
||||
export const REPORT_READING_POSTCHECK_VERSION = 1;
|
||||
export const REPORT_READING_POSTCHECK_VERSION = 3;
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
|
||||
@@ -82,10 +82,24 @@ export const reportReadingDraftParagraphSchema = z.union([
|
||||
factParagraph,
|
||||
]);
|
||||
export const reportReadingDraftSchema = draftSchema(reportReadingDraftParagraphSchema);
|
||||
export const reportReadingDraftEnvelopeSchema = draftSchema(z.object({ text: z.string().min(1) }).passthrough());
|
||||
const draftEnvelopeSection = z.object({
|
||||
id: z.enum(SECTION_IDS),
|
||||
paragraphs: z.array(z.object({ text: z.string() }).passthrough()),
|
||||
}).passthrough();
|
||||
export const reportReadingDraftEnvelopeSchema = z.object({
|
||||
sections: z.array(draftEnvelopeSection).length(REPORT_READING_SECTIONS.length),
|
||||
});
|
||||
export type ReportReadingDraft = z.infer<typeof reportReadingDraftSchema>;
|
||||
export type ReportReadingDraftSection = z.infer<typeof reportReadingDraftEnvelopeSchema>["sections"][number];
|
||||
|
||||
export function reportReadingRepairEnvelopeSchema(sections: readonly ReportReadingSectionId[]) {
|
||||
const [first, ...rest] = sections;
|
||||
return z.object({
|
||||
sections: z.array(first ? draftEnvelopeSection.extend({ id: z.enum([first, ...rest]) }) : draftEnvelopeSection)
|
||||
.length(sections.length),
|
||||
});
|
||||
}
|
||||
|
||||
/** What is stored in the calculation snapshot and returned by the read API. */
|
||||
const storedSection = z.strictObject({
|
||||
id: z.enum(SECTION_IDS),
|
||||
@@ -181,7 +195,7 @@ export type ReportReadingParagraph = Readonly<{ text: string; grade?: EvidenceGr
|
||||
/** Shown in place of a section that did not pass the post-check (owner 2026-11-12). */
|
||||
export const READING_SECTION_WITHHELD_TEXT = "这一节没有通过数据核对,暂不显示。";
|
||||
export const BASIS_AUDIT_INTRO = "这一节的模型文字没有通过核对,下面是由计算直接生成的依据清单。";
|
||||
const WITHHELD_REASONS: Readonly<Record<string, string>> = {
|
||||
export const READING_WITHHELD_REASONS: Readonly<Record<string, string>> = {
|
||||
field_name: "文字里混入了内部标记。",
|
||||
banned_phrase: "措辞超出了这份报告能判断的范围。",
|
||||
too_long: "有段文字超过了篇幅限制。",
|
||||
@@ -262,7 +276,7 @@ export function readingSectionView(section: ReportReading["sections"][number]):
|
||||
if (section.status === "withheld") {
|
||||
return {
|
||||
status: "withheld",
|
||||
explanation: Object.hasOwn(WITHHELD_REASONS, section.reason) ? WITHHELD_REASONS[section.reason] : undefined,
|
||||
explanation: Object.hasOwn(READING_WITHHELD_REASONS, section.reason) ? READING_WITHHELD_REASONS[section.reason] : undefined,
|
||||
...(section.id === "basis" && section.basisAudit ? { basisAudit: section.basisAudit } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import {
|
||||
EVIDENCE_GRADES, MAX_PARAGRAPH_CHARS, MAX_SECTION_PARAGRAPHS, REPORT_CLAIM_TYPES, reportReadingDraftParagraphSchema,
|
||||
type EvidenceGrade, type ReportClaimType, type ReportReadingDraftSection, type ReportReadingSectionId,
|
||||
} from "./personal-report-reading-contract";
|
||||
import type { ReadingRebound } from "./personal-report-reading-audit-contract";
|
||||
|
||||
export type Claims = Readonly<Record<string, { cap?: unknown; sections?: unknown; required?: unknown; checked?: unknown; must_disclose?: unknown }>>;
|
||||
export type Catalog = {
|
||||
states: ReadonlyMap<string, string>;
|
||||
aliases: ReadonlyMap<string, readonly string[]>;
|
||||
pattern: RegExp | null;
|
||||
};
|
||||
|
||||
export const FACT_INFERENCE = /意味着|显示出|适合|容易|有利|不利|倾向|说明你/;
|
||||
export const TIMING_TEXT = /(?<!\d)\d{4}(?!\d)|(?:\d+|[一二三四五六七八九十两]+)月|月\d+|大运|小运|窗口/;
|
||||
export const GENERIC_DASHA_ALIASES = new Set(["大运", "小运", "次小运"]);
|
||||
const DEFAULT_CLAIM: Partial<Record<ReportReadingSectionId, ReportClaimType>> = {
|
||||
character: "character_structure", career: "career_promise", wealth: "wealth_earning",
|
||||
love: "relationship_structure", health: "health_pressure", now: "timing_window",
|
||||
};
|
||||
|
||||
export function claimDependencyIds(claims: readonly Claims[string][]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const claim of claims) {
|
||||
for (const rows of [claim.required, claim.checked]) {
|
||||
for (const row of Array.isArray(rows) ? rows : []) if (typeof row?.id === "string") ids.add(row.id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function strictestGrade(grades: readonly EvidenceGrade[]): EvidenceGrade {
|
||||
return EVIDENCE_GRADES[Math.max(...grades.map((grade) => EVIDENCE_GRADES.indexOf(grade)))]!;
|
||||
}
|
||||
|
||||
export function rebindReadingSection(
|
||||
section: ReportReadingDraftSection,
|
||||
claims: Claims,
|
||||
catalog: Catalog,
|
||||
established: ReadonlyMap<string, EvidenceGrade>,
|
||||
unstable: ReadonlySet<string>,
|
||||
): { section: ReportReadingDraftSection; beforeMerge: ReportReadingDraftSection; changes: ReadingRebound[] } {
|
||||
const changes: ReadingRebound[] = [];
|
||||
const summary = section.id === "overview" || section.id === "advice";
|
||||
const candidates = REPORT_CLAIM_TYPES.filter((type) =>
|
||||
Array.isArray(claims[type]?.sections) && claims[type]!.sections.includes(section.id) && (!summary || established.has(type)));
|
||||
const establishedTypes = REPORT_CLAIM_TYPES.filter((type) => established.has(type));
|
||||
const dependencies = (types: readonly ReportClaimType[]) =>
|
||||
claimDependencyIds(types.flatMap((type) => claims[type] ? [claims[type]] : []));
|
||||
const paragraphs: ReportReadingDraftSection["paragraphs"] = section.paragraphs.map((raw, index) => {
|
||||
const parsed = reportReadingDraftParagraphSchema.safeParse(raw);
|
||||
const missing = !Object.hasOwn(raw, "kind") && !Object.hasOwn(raw, "claims");
|
||||
if (!parsed.success && !missing) return raw;
|
||||
const aliasIds = catalog.pattern ? [...raw.text.matchAll(catalog.pattern)]
|
||||
.map(([alias]) => catalog.aliases.get(alias.toLowerCase()) ?? []) : [];
|
||||
const timed = TIMING_TEXT.test(raw.text);
|
||||
const inference = FACT_INFERENCE.test(raw.text);
|
||||
const suppliedGrade = EVIDENCE_GRADES.find((grade) => grade === raw.grade) ?? null;
|
||||
if (missing && !aliasIds.length && !timed && !inference) {
|
||||
changes.push({ section: section.id, paragraph: index + 1, rule: "claim_binding_missing",
|
||||
added_claims: [], grade_from: suppliedGrade, grade_to: null });
|
||||
return { kind: "fact", text: raw.text };
|
||||
}
|
||||
const paragraph = parsed.success ? parsed.data : { kind: "fact" as const, text: raw.text };
|
||||
const fact = "kind" in paragraph;
|
||||
const fallback = DEFAULT_CLAIM[section.id];
|
||||
if (fact && !missing && (!fallback || !inference)) return raw;
|
||||
|
||||
const types = new Set<ReportClaimType>(fact ? [] : paragraph.claims);
|
||||
const originalGrade = fact ? suppliedGrade : paragraph.grade;
|
||||
const rules: { rule: string; added_claims: ReportClaimType[] }[] = [];
|
||||
const record = (rule: string, added_claims: ReportClaimType[] = []) => rules.push({ rule, added_claims });
|
||||
const namedRefs = fact ? [] : paragraph.refs ?? [];
|
||||
const available = missing && summary ? establishedTypes : candidates;
|
||||
const expand = (refGroups: readonly (readonly string[])[]) => {
|
||||
const added: ReportClaimType[] = [];
|
||||
for (const ids of refGroups) {
|
||||
const allowed = dependencies([...types]);
|
||||
if (ids.some((id) => allowed.has(id))) continue;
|
||||
const type = available.find((candidate) => ids.some((id) => dependencies([candidate]).has(id)));
|
||||
if (type && !types.has(type)) {
|
||||
types.add(type);
|
||||
added.push(type);
|
||||
}
|
||||
}
|
||||
return added;
|
||||
};
|
||||
if (fact) {
|
||||
const inferred = expand(aliasIds);
|
||||
const defaultType = missing && timed && available.includes("timing_window") ? "timing_window"
|
||||
: summary && missing ? available[0] : fallback;
|
||||
if (!types.size && defaultType && available.includes(defaultType)) {
|
||||
types.add(defaultType);
|
||||
inferred.push(defaultType);
|
||||
}
|
||||
if (!types.size) return raw;
|
||||
record(missing ? "claim_binding_missing" : "fact_with_inference", inferred);
|
||||
}
|
||||
if (summary) {
|
||||
const valid = [...types].filter((type) => established.has(type));
|
||||
if (valid.length && valid.length < types.size) {
|
||||
for (const type of types) if (!established.has(type)) types.delete(type);
|
||||
record("claim_not_established");
|
||||
}
|
||||
}
|
||||
if (timed && !types.has("timing_window") && available.includes("timing_window")) {
|
||||
types.add("timing_window");
|
||||
record("timing_unbound", ["timing_window"]);
|
||||
}
|
||||
const added = expand([...aliasIds, ...namedRefs.map((id) => [id])]);
|
||||
if (added.length) record("ref_outside_claims", added);
|
||||
if (!rules.length) return raw;
|
||||
const ceilings = [...types].flatMap((type) => [claims[type]?.cap, ...(summary ? [established.get(type)] : [])]);
|
||||
if (ceilings.some((cap) => !EVIDENCE_GRADES.includes(cap as EvidenceGrade))) return raw;
|
||||
const allowed = dependencies([...types]);
|
||||
const resolvedRefs = [...namedRefs, ...aliasIds.flatMap((ids) => ids.filter((id) => allowed.has(id)))];
|
||||
const grades = ceilings as EvidenceGrade[];
|
||||
if (originalGrade) grades.push(originalGrade);
|
||||
if (resolvedRefs.some((id) => unstable.has(catalog.states.get(id) ?? ""))) grades.push("D");
|
||||
const grade = strictestGrade(grades);
|
||||
for (const change of rules) {
|
||||
changes.push({ section: section.id, paragraph: index + 1, ...change, grade_from: originalGrade, grade_to: grade });
|
||||
}
|
||||
return { text: raw.text, claims: [...types], grade, refs: namedRefs };
|
||||
});
|
||||
|
||||
const beforeMerge = { ...section, paragraphs };
|
||||
const retained = paragraphs.slice(0, MAX_SECTION_PARAGRAPHS);
|
||||
for (const [offset, extra] of paragraphs.slice(MAX_SECTION_PARAGRAPHS).entries()) {
|
||||
const parsed = reportReadingDraftParagraphSchema.safeParse(extra);
|
||||
if (!parsed.success) return { section: beforeMerge, beforeMerge, changes };
|
||||
const incoming = parsed.data;
|
||||
const key = "kind" in incoming ? "" : [...new Set(incoming.claims)].sort().join(",");
|
||||
const match = retained.findLastIndex((item) => {
|
||||
const existing = reportReadingDraftParagraphSchema.safeParse(item);
|
||||
if (!existing.success) return false;
|
||||
return key === ("kind" in existing.data ? "" : [...new Set(existing.data.claims)].sort().join(","));
|
||||
});
|
||||
const index = match < 0 ? retained.length - 1 : match;
|
||||
const parsedTarget = reportReadingDraftParagraphSchema.safeParse(retained[index]);
|
||||
if (!parsedTarget.success) return { section: beforeMerge, beforeMerge, changes };
|
||||
const target = parsedTarget.data;
|
||||
const text = [target.text, incoming.text].join("\n\n");
|
||||
if (text.trim().length > MAX_PARAGRAPH_CHARS) {
|
||||
changes.push({
|
||||
section: section.id, paragraph: MAX_SECTION_PARAGRAPHS + offset + 1, rule: "drop_paragraph",
|
||||
added_claims: [], grade_from: "kind" in incoming ? null : incoming.grade, grade_to: null,
|
||||
dropped_text: incoming.text,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const bound = [target, incoming].flatMap((item) => "kind" in item ? [] : [item]);
|
||||
const mergedClaims = [...new Set(bound.flatMap((item) => item.claims))];
|
||||
const grade = bound.length ? strictestGrade(bound.map((item) => item.grade)) : null;
|
||||
retained[index] = grade
|
||||
? { text, claims: mergedClaims, grade, refs: [...new Set(bound.flatMap((item) => item.refs ?? []))] }
|
||||
: { kind: "fact", text };
|
||||
changes.push({
|
||||
section: section.id, paragraph: index + 1, rule: "merge_paragraphs",
|
||||
added_claims: mergedClaims.filter((type) => "kind" in target || !target.claims.includes(type)),
|
||||
grade_from: "kind" in target ? null : target.grade, grade_to: grade,
|
||||
});
|
||||
}
|
||||
return { section: { ...section, paragraphs: retained }, beforeMerge, changes };
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
* product decision 2026-10-27 「R1 C1」).
|
||||
*
|
||||
* The engine report stays as it is and moves behind this reading as the
|
||||
* calculation basis. The reading is one structured model call over the
|
||||
* calculation basis. The reading is a structured model draft over the
|
||||
* engine's own facts (`reading_facts` from /api/professional_report_reference,
|
||||
* the same leaves the chat card uses). It is optional: any failure, timeout or
|
||||
* rejected draft leaves the report without a reading, never failed.
|
||||
@@ -13,21 +13,26 @@ import {
|
||||
EVIDENCE_GRADE_CONTRACT,
|
||||
GRADED_SECTION_IDS,
|
||||
MAX_PARAGRAPH_CHARS,
|
||||
MAX_SECTION_PARAGRAPHS,
|
||||
MAX_TOTAL_CHARS,
|
||||
MIN_TOTAL_CHARS,
|
||||
REPORT_READING_SECTIONS,
|
||||
READING_WITHHELD_REASONS,
|
||||
reportReadingDraftEnvelopeSchema,
|
||||
reportReadingDraftParagraphSchema,
|
||||
reportReadingRepairEnvelopeSchema,
|
||||
type BasisAuditRow,
|
||||
type BoundReadingParagraph,
|
||||
type BoundReadingSection,
|
||||
type EvidenceGrade,
|
||||
type CheckedReportReading,
|
||||
type ReportReadingDraftSection,
|
||||
type ReportReadingSectionId,
|
||||
type SnapshottedReportReading,
|
||||
} from "./personal-report-reading-contract";
|
||||
import { bindReportReadingSnapshot, describeReadingTransform } from "./personal-report-reading-audit";
|
||||
import type { ReadingAttempt, ReadingSectionTransform, ReadingTransformLog } from "./personal-report-reading-audit-contract";
|
||||
import type { ReadingAttempt, ReadingRebound, ReadingSectionTransform, ReadingTransformLog } from "./personal-report-reading-audit-contract";
|
||||
import { claimDependencyIds, FACT_INFERENCE, GENERIC_DASHA_ALIASES, rebindReadingSection, TIMING_TEXT, type Catalog, type Claims } from "./personal-report-reading-rebind";
|
||||
import { canonicalReportReadingSha256 } from "./report-reading-canonical-json";
|
||||
import type { ReportReading } from "./personal-report-reading-contract";
|
||||
|
||||
@@ -110,8 +115,6 @@ export type ReadingRejection =
|
||||
| "claim_not_established"
|
||||
| "all_sections_withheld";
|
||||
|
||||
type Claims = Readonly<Record<string, { cap?: unknown; sections?: unknown; required?: unknown; checked?: unknown; must_disclose?: unknown }>>;
|
||||
|
||||
function claimsOf(facts: Record<string, unknown> | null): Claims {
|
||||
const grades = facts?.evidence_grades as { contract?: unknown; claims?: unknown } | undefined;
|
||||
return grades?.contract === EVIDENCE_GRADE_CONTRACT && grades.claims && typeof grades.claims === "object"
|
||||
@@ -357,14 +360,7 @@ function basisAudit(claims: Claims): BasisAuditRow[] {
|
||||
return rows;
|
||||
}
|
||||
|
||||
const FACT_INFERENCE = /意味着|显示出|适合|容易|有利|不利|倾向|说明你/;
|
||||
const TIMING_TEXT = /(?<!\d)\d{4}(?!\d)|(?:\d+|[一二三四五六七八九十两]+)月|月\d+|大运|小运|窗口/;
|
||||
const UNSTABLE_REFERENCE = new Set([...MISSING_DEPENDENCY, "not_evaluated"]);
|
||||
type Catalog = {
|
||||
states: ReadonlyMap<string, string>;
|
||||
aliases: ReadonlyMap<string, readonly string[]>;
|
||||
pattern: RegExp | null;
|
||||
};
|
||||
|
||||
function dependencyCatalog(facts: Record<string, unknown> | null): Catalog {
|
||||
const catalog = (facts?.evidence_grades as { dependency_catalog?: unknown } | undefined)?.dependency_catalog;
|
||||
@@ -377,6 +373,7 @@ function dependencyCatalog(facts: Record<string, unknown> | null): Catalog {
|
||||
for (const alias of Array.isArray(row.aliases) ? row.aliases : []) {
|
||||
if (typeof alias !== "string" || !alias.trim()) continue;
|
||||
const normalized = alias.toLowerCase();
|
||||
if (GENERIC_DASHA_ALIASES.has(normalized)) continue;
|
||||
const ids = aliases.get(normalized) ?? [];
|
||||
ids.push(id);
|
||||
aliases.set(normalized, ids);
|
||||
@@ -392,16 +389,6 @@ function dependencyCatalog(facts: Record<string, unknown> | null): Catalog {
|
||||
return { states, aliases, pattern: patterns.length ? new RegExp(patterns.join("|"), "giu") : null };
|
||||
}
|
||||
|
||||
function claimDependencyIds(claims: readonly Claims[string][]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const claim of claims) {
|
||||
for (const rows of [claim.required, claim.checked]) {
|
||||
for (const row of Array.isArray(rows) ? rows : []) if (typeof row?.id === "string") ids.add(row.id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function refsFromText(text: string, allowed: ReadonlySet<string>, catalog: Catalog): Set<string> | null {
|
||||
const refs = new Set<string>();
|
||||
if (!catalog.pattern) return refs;
|
||||
@@ -413,7 +400,21 @@ function refsFromText(text: string, allowed: ReadonlySet<string>, catalog: Catal
|
||||
return refs;
|
||||
}
|
||||
|
||||
type Checked = { section: BoundReadingSection; chars: number; inferredRefs: string[][] };
|
||||
type RefConflict = { alias: string; ids: string[] };
|
||||
|
||||
function unsupportedAliases(text: string, allowed: ReadonlySet<string>, catalog: Catalog): RefConflict[] {
|
||||
if (!catalog.pattern) return [];
|
||||
const matched = new Map([...text.matchAll(catalog.pattern)].map(([alias]) => [alias.toLowerCase(), alias]));
|
||||
return [...matched].flatMap(([normalized, alias]) => {
|
||||
const ids = catalog.aliases.get(normalized) ?? [];
|
||||
return ids.some((id) => allowed.has(id)) ? [] : [{ alias, ids: [...ids] }];
|
||||
});
|
||||
}
|
||||
|
||||
type Checked = {
|
||||
section: BoundReadingSection; chars: number; inferredRefs: string[][];
|
||||
snippet?: string; reason?: ReadingRejection; conflicts?: RefConflict[];
|
||||
};
|
||||
|
||||
function checkSection(
|
||||
section: ReportReadingDraftSection,
|
||||
@@ -424,13 +425,25 @@ function checkSection(
|
||||
facts: Record<string, unknown> | null,
|
||||
catalog: Catalog,
|
||||
established: ReadonlyMap<string, EvidenceGrade>,
|
||||
allowExtraParagraphs = false,
|
||||
): Checked {
|
||||
const inferredRefs: string[][] = [];
|
||||
const withheld = (reason: ReadingRejection): Checked => ({
|
||||
let text = "";
|
||||
const snippetFor = (matches?: (sentence: string) => boolean) => {
|
||||
if (!matches) return text.slice(0, MAX_PARAGRAPH_CHARS);
|
||||
const sentences = text.split(SENTENCE_END).map((sentence) => sentence.trim()).filter(matches);
|
||||
return (sentences.length ? sentences.join("。") : text).slice(0, MAX_PARAGRAPH_CHARS);
|
||||
};
|
||||
const withheld = (reason: ReadingRejection, matches?: (sentence: string) => boolean, conflicts?: RefConflict[]): Checked => ({
|
||||
section: { id: section.id, title, status: "withheld" as const, reason, ...(section.id === "basis" ? { basisAudit: basisAudit(claims) } : {}) },
|
||||
chars: 0,
|
||||
inferredRefs,
|
||||
reason,
|
||||
snippet: snippetFor(matches),
|
||||
conflicts,
|
||||
});
|
||||
if (!section.paragraphs.length) return withheld("too_short");
|
||||
if (!allowExtraParagraphs && section.paragraphs.length > MAX_SECTION_PARAGRAPHS) return withheld("too_long");
|
||||
const graded = GRADED_SECTION_IDS.includes(section.id);
|
||||
const summary = section.id === "overview" || section.id === "advice";
|
||||
const anyClaimMissing = Object.values(claims).some((claim) => claim?.cap === "D");
|
||||
@@ -438,34 +451,36 @@ function checkSection(
|
||||
let chars = 0;
|
||||
const paragraphs: BoundReadingParagraph[] = [];
|
||||
for (const raw of section.paragraphs) {
|
||||
const text = raw.text.trim();
|
||||
text = raw.text.trim();
|
||||
if (!text) return withheld("too_short");
|
||||
if (text.length > MAX_PARAGRAPH_CHARS) return withheld("too_long");
|
||||
if (/[_={}<>#*|`]/.test(text)) return withheld("field_name");
|
||||
if (BANNED_PHRASES.some((phrase) => text.includes(phrase)) || CERTAINTY.test(text) || text.split(SENTENCE_END).some(bannedQualifiedPhrase)) {
|
||||
return withheld("banned_phrase");
|
||||
const fieldName = (sentence: string) => /[_={}<>#*|`]/.test(sentence);
|
||||
if (fieldName(text)) return withheld("field_name", fieldName);
|
||||
const bannedPhrase = (sentence: string) => BANNED_PHRASES.some((phrase) => sentence.includes(phrase)) || CERTAINTY.test(sentence);
|
||||
if (bannedPhrase(text) || text.split(SENTENCE_END).some(bannedQualifiedPhrase)) {
|
||||
return withheld("banned_phrase", (sentence) => bannedPhrase(sentence) || bannedQualifiedPhrase(sentence));
|
||||
}
|
||||
if (dignityMismatch(text, dignities)) return withheld("dignity_mismatch");
|
||||
if (falseMissingLayer(text, computed)) return withheld("false_missing_layer");
|
||||
if (currentAdviceInReplay(text, section.id, facts)) return withheld("current_advice_in_replay");
|
||||
if (doubleTransitOutOfScope(text, section.id, facts)) return withheld("double_transit_scope");
|
||||
if (yogaStatusMismatch(text, facts)) return withheld("yoga_status_mismatch");
|
||||
if (dignityMismatch(text, dignities)) return withheld("dignity_mismatch", (sentence) => dignityMismatch(sentence, dignities));
|
||||
if (falseMissingLayer(text, computed)) return withheld("false_missing_layer", (sentence) => falseMissingLayer(sentence, computed));
|
||||
if (currentAdviceInReplay(text, section.id, facts)) return withheld("current_advice_in_replay", (sentence) => currentAdviceInReplay(sentence, section.id, facts));
|
||||
if (doubleTransitOutOfScope(text, section.id, facts)) return withheld("double_transit_scope", (sentence) => doubleTransitOutOfScope(sentence, section.id, facts));
|
||||
if (yogaStatusMismatch(text, facts)) return withheld("yoga_status_mismatch", (sentence) => yogaStatusMismatch(sentence, facts));
|
||||
const factRejection = checkedFactClaim(text, section.id, facts);
|
||||
if (factRejection) return withheld(factRejection);
|
||||
if (factRejection) return withheld(factRejection, (sentence) => checkedFactClaim(sentence, section.id, facts) === factRejection);
|
||||
disclaimers += text.match(DISCLAIMER)?.length ?? 0;
|
||||
chars += text.length;
|
||||
const parsed = reportReadingDraftParagraphSchema.safeParse(raw);
|
||||
if (!parsed.success) return withheld("claim_binding_missing");
|
||||
const paragraph = parsed.data;
|
||||
if ("kind" in paragraph) {
|
||||
if (FACT_INFERENCE.test(text)) return withheld("fact_with_inference");
|
||||
if (NO_BLOCKER.test(text) && anyClaimMissing) return withheld("false_no_blocker");
|
||||
if (FACT_INFERENCE.test(text)) return withheld("fact_with_inference", (sentence) => FACT_INFERENCE.test(sentence));
|
||||
if (NO_BLOCKER.test(text) && anyClaimMissing) return withheld("false_no_blocker", (sentence) => NO_BLOCKER.test(sentence));
|
||||
paragraphs.push({ kind: "fact", text });
|
||||
continue;
|
||||
}
|
||||
const types = [...new Set(paragraph.claims)];
|
||||
const refs = new Set(paragraph.refs);
|
||||
if (TIMING_TEXT.test(text) && !types.includes("timing_window")) return withheld("timing_unbound");
|
||||
if (TIMING_TEXT.test(text) && !types.includes("timing_window")) return withheld("timing_unbound", (sentence) => TIMING_TEXT.test(sentence));
|
||||
const bindings = types.map((type) => claims[type]).filter((claim) => claim !== undefined);
|
||||
if (bindings.length !== types.length) return withheld("claim_binding_missing");
|
||||
if (graded && bindings.some((claim) => !Array.isArray(claim.sections) || !claim.sections.includes(section.id))) {
|
||||
@@ -475,19 +490,26 @@ function checkSection(
|
||||
if (bindings.some((claim) => !gradeAtOrBelow(paragraph.grade, claim.cap)) ||
|
||||
(summary && types.some((type) => !gradeAtOrBelow(paragraph.grade, established.get(type))))) return withheld("grade_above_cap");
|
||||
const allowed = claimDependencyIds(bindings);
|
||||
if ([...refs].some((id) => !allowed.has(id) || !catalog.states.has(id))) return withheld("ref_outside_claims");
|
||||
const explicitConflicts = [...refs].filter((id) => !allowed.has(id) || !catalog.states.has(id));
|
||||
if (explicitConflicts.length) return withheld("ref_outside_claims", undefined,
|
||||
explicitConflicts.filter((id) => catalog.states.has(id)).map((id) => ({ alias: id, ids: [id] })));
|
||||
const inferred = refsFromText(text, allowed, catalog);
|
||||
if (!inferred) return withheld("ref_outside_claims");
|
||||
if (!inferred) return withheld("ref_outside_claims", (sentence) => refsFromText(sentence, allowed, catalog) === null,
|
||||
unsupportedAliases(text, allowed, catalog));
|
||||
const addedRefs = [...inferred].filter((id) => !refs.has(id));
|
||||
inferredRefs[paragraphs.length] = addedRefs;
|
||||
for (const id of addedRefs) refs.add(id);
|
||||
if (paragraph.grade !== "D" && [...refs].some((id) => UNSTABLE_REFERENCE.has(catalog.states.get(id)!))) return withheld("ref_unstable");
|
||||
if (NO_BLOCKER.test(text) && (graded ? bindings.some((claim) => claim.cap === "D") : anyClaimMissing)) {
|
||||
return withheld("false_no_blocker");
|
||||
return withheld("false_no_blocker", (sentence) => NO_BLOCKER.test(sentence));
|
||||
}
|
||||
paragraphs.push({ text, claims: types, grade: paragraph.grade, refs: [...refs], refs_from_text: addedRefs });
|
||||
}
|
||||
if (disclaimers > 1) return withheld("disclaimer");
|
||||
if (disclaimers > 1) {
|
||||
text = section.paragraphs.flatMap(({ text }) => text.split(SENTENCE_END))
|
||||
.filter((sentence) => (sentence.match(DISCLAIMER)?.length ?? 0) > 0).join("。");
|
||||
return withheld("disclaimer");
|
||||
}
|
||||
return {
|
||||
section: { id: section.id, title, status: "ok", paragraphs },
|
||||
chars,
|
||||
@@ -501,6 +523,28 @@ export type ReadingSkillMeta = Readonly<{
|
||||
loaded: ReadonlyArray<Readonly<{ path: string; sha256: string }>>;
|
||||
}>;
|
||||
|
||||
type Draft = { sections: ReportReadingDraftSection[] };
|
||||
type DraftCheck = {
|
||||
sections: ReadingSectionTransform[];
|
||||
diagnostics: { section: ReportReadingSectionId; reason: ReadingRejection; snippet?: string; conflicts?: RefConflict[] }[];
|
||||
rebound: ReadingRebound[];
|
||||
checked: Checked[];
|
||||
};
|
||||
type DraftAcceptance = DraftCheck & (
|
||||
| { ok: true; reading: CheckedReportReading; withheld: number }
|
||||
| { ok: false; reason: ReadingRejection }
|
||||
);
|
||||
|
||||
function parseReadingDraft(value: unknown): Draft | undefined {
|
||||
const parsed = reportReadingDraftEnvelopeSchema.safeParse(value);
|
||||
return parsed.success && parsed.data.sections.every(({ id }, index) => id === REPORT_READING_SECTIONS[index]!.id)
|
||||
? parsed.data : undefined;
|
||||
}
|
||||
|
||||
function invalidDraft(): DraftAcceptance {
|
||||
return { ok: false, reason: "shape", sections: [], diagnostics: [], rebound: [], checked: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft becomes the stored reading only when its shape holds and at least one
|
||||
* section passes. Each section is checked on its own: a section that breaks a rule
|
||||
@@ -512,22 +556,54 @@ export function acceptReportReadingDraft(
|
||||
facts: Record<string, unknown> | null,
|
||||
skill: ReadingSkillMeta,
|
||||
originalSections?: readonly unknown[],
|
||||
):
|
||||
| { ok: true; reading: CheckedReportReading; withheld: number; sections: ReadingSectionTransform[] }
|
||||
| { ok: false; reason: ReadingRejection; sections: ReadingSectionTransform[] } {
|
||||
const parsed = reportReadingDraftEnvelopeSchema.safeParse(value);
|
||||
if (!parsed.success) return { ok: false, reason: "shape", sections: [] };
|
||||
const sections = parsed.data.sections;
|
||||
if (sections.some((section, index) => section.id !== REPORT_READING_SECTIONS[index]!.id)) {
|
||||
return { ok: false, reason: "shape", sections: [] };
|
||||
}
|
||||
): DraftAcceptance {
|
||||
const draft = parseReadingDraft(value);
|
||||
return draft ? checkReadingDraft(draft, facts, skill, { originalSections }) : invalidDraft();
|
||||
}
|
||||
|
||||
function checkReadingDraft(
|
||||
{ sections }: Draft,
|
||||
facts: Record<string, unknown> | null,
|
||||
skill: ReadingSkillMeta,
|
||||
options: { originalSections?: readonly unknown[]; baseline?: DraftAcceptance; withoutRebind?: boolean },
|
||||
): DraftAcceptance {
|
||||
const claims = claimsOf(facts);
|
||||
const dignities = dignitiesOf(facts);
|
||||
const computed = computedPointsOf(facts);
|
||||
const catalog = dependencyCatalog(facts);
|
||||
const established = new Map<string, EvidenceGrade>();
|
||||
const check = (section: ReportReadingDraftSection, index: number) =>
|
||||
checkSection(section, REPORT_READING_SECTIONS[index]!.title, claims, dignities, computed, facts, catalog, established);
|
||||
const rebound: ReadingRebound[] = [];
|
||||
const check = (section: ReportReadingDraftSection, index: number) => {
|
||||
const previous = options.baseline?.checked[index];
|
||||
if (previous?.section.status === "ok") {
|
||||
if (section.id !== "overview" && section.id !== "advice") return previous;
|
||||
const paragraphs = previous.section.paragraphs.map((paragraph) => {
|
||||
if ("kind" in paragraph) return paragraph;
|
||||
const { text, claims, grade, refs } = paragraph;
|
||||
return { text, claims, grade, refs };
|
||||
});
|
||||
const verified = checkSection({ ...section, paragraphs }, previous.section.title, claims, dignities, computed, facts, catalog, established);
|
||||
return verified.section.status === "ok" ? previous : verified;
|
||||
}
|
||||
const title = REPORT_READING_SECTIONS[index]!.title;
|
||||
const validate = (draft: ReportReadingDraftSection, allowExtraParagraphs = false) =>
|
||||
checkSection(draft, title, claims, dignities, computed, facts, catalog, established, allowExtraParagraphs);
|
||||
if (options.withoutRebind) return validate(section);
|
||||
const prepared = rebindReadingSection(section, claims, catalog, established, UNSTABLE_REFERENCE);
|
||||
if (section.paragraphs.length > MAX_SECTION_PARAGRAPHS) {
|
||||
const dropped = new Set(prepared.changes.filter(({ rule }) => rule === "drop_paragraph").map(({ paragraph }) => paragraph));
|
||||
const source = validate({
|
||||
...prepared.beforeMerge,
|
||||
paragraphs: prepared.beforeMerge.paragraphs.filter((_, index) => !dropped.has(index + 1)),
|
||||
}, true);
|
||||
if (source.section.status === "withheld") {
|
||||
rebound.push(...prepared.changes.filter(({ rule }) => rule !== "merge_paragraphs" && rule !== "drop_paragraph"));
|
||||
return source;
|
||||
}
|
||||
}
|
||||
rebound.push(...prepared.changes);
|
||||
return validate(prepared.section);
|
||||
};
|
||||
const checked = sections.map((section, index) => section.id === "overview" || section.id === "advice" ? null : check(section, index));
|
||||
for (const entry of checked) {
|
||||
if (entry?.section.status !== "ok" || !GRADED_SECTION_IDS.includes(entry.section.id)) continue;
|
||||
@@ -540,17 +616,23 @@ export function acceptReportReadingDraft(
|
||||
}
|
||||
}
|
||||
const finalized = checked.map((entry, index) => entry ?? check(sections[index]!, index));
|
||||
const transforms = finalized.map(({ section, inferredRefs }, index) =>
|
||||
describeReadingTransform(sections[index]!, section, catalog.states, inferredRefs, originalSections?.[index]));
|
||||
const withheld = finalized.filter(({ section }) => section.status === "withheld").length;
|
||||
if (withheld === finalized.length) return { ok: false, reason: "all_sections_withheld", sections: transforms };
|
||||
const transforms = finalized.map(({ section, inferredRefs }, index) => {
|
||||
const previous = options.baseline?.sections[index];
|
||||
return previous?.status === "ok" && section.status === "ok" ? previous
|
||||
: describeReadingTransform(sections[index]!, section, catalog.states, inferredRefs, options.originalSections?.[index]);
|
||||
});
|
||||
const diagnostics = finalized.flatMap(({ section, reason, snippet, conflicts }) => reason
|
||||
? [{ section: section.id, reason, snippet, conflicts }] : []);
|
||||
const withheld = diagnostics.length;
|
||||
const details = { sections: transforms, diagnostics, rebound, checked: finalized };
|
||||
if (withheld === finalized.length) return { ok: false, reason: "all_sections_withheld", ...details };
|
||||
const total = finalized.reduce((sum, { chars }) => sum + chars, 0);
|
||||
if (total < MIN_TOTAL_CHARS) return { ok: false, reason: "too_short", sections: transforms };
|
||||
if (total > MAX_TOTAL_CHARS) return { ok: false, reason: "too_long", sections: transforms };
|
||||
if (total < MIN_TOTAL_CHARS) return { ok: false, reason: "too_short", ...details };
|
||||
if (total > MAX_TOTAL_CHARS) return { ok: false, reason: "too_long", ...details };
|
||||
return {
|
||||
ok: true,
|
||||
withheld,
|
||||
sections: transforms,
|
||||
...details,
|
||||
reading: {
|
||||
version: 4,
|
||||
language: "zh",
|
||||
@@ -592,6 +674,7 @@ export type ReportReadingWriter = ((input: Readonly<{
|
||||
system: string;
|
||||
user: string;
|
||||
signal: AbortSignal;
|
||||
repairSections?: readonly ReportReadingSectionId[];
|
||||
}>) => Promise<{
|
||||
body: unknown;
|
||||
rawResponse?: unknown;
|
||||
@@ -643,10 +726,66 @@ function timedSignal(parent: AbortSignal | undefined, timeoutMs: number) {
|
||||
};
|
||||
}
|
||||
|
||||
function countRejections(diagnostics: DraftCheck["diagnostics"]): Record<string, number> {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const { reason } of diagnostics) counts[reason] = (counts[reason] ?? 0) + 1;
|
||||
return counts;
|
||||
}
|
||||
|
||||
function referenceConflicts(diagnostics: DraftCheck["diagnostics"]) {
|
||||
return diagnostics.flatMap(({ section, conflicts }) =>
|
||||
conflicts?.length ? [{ section, references: conflicts }] : []);
|
||||
}
|
||||
|
||||
function conflictsWithAcceptedSummary(initial: DraftCheck, replacement: BoundReadingSection): boolean {
|
||||
if (replacement.status !== "ok" || !GRADED_SECTION_IDS.includes(replacement.id)) return false;
|
||||
return initial.checked.some(({ section }) => {
|
||||
if (section.status !== "ok" || (section.id !== "overview" && section.id !== "advice")) return false;
|
||||
return section.paragraphs.some((summary) => "claims" in summary && replacement.paragraphs.some((paragraph) =>
|
||||
"claims" in paragraph && paragraph.claims.some((claim) => summary.claims.includes(claim))
|
||||
&& !gradeAtOrBelow(summary.grade, paragraph.grade)));
|
||||
});
|
||||
}
|
||||
|
||||
const REPAIR_INSTRUCTIONS: Partial<Record<ReadingRejection, string>> = {
|
||||
field_name: "删掉命中句里的内部字段、编号和标记,用读者看得懂的话重述已核对的事实。",
|
||||
double_transit_scope: "这句提到双行运,但本节对应的宫位不在已检查的宫位里。删掉这句,改用本节已核对的依据。",
|
||||
current_advice_in_replay: "删掉面向当下的建议,把这段改为过去时的事实回看。",
|
||||
sav_total_as_strength: "删掉根据固定 SAV 总分推断个人强弱的句子,只保留事实包支持的分项。",
|
||||
timing_unbound: "删掉本节无时间依据的年份和窗口。有本节允许的时间依据时才标 timing_window。",
|
||||
claim_not_established: "删掉未在正文成立的结论,仅总结已通过正文支持的判断。",
|
||||
claim_type_section: "删掉其他领域的结论,只保留事实包允许在本节使用的类型。",
|
||||
claim_binding_missing: "盘面事实标 kind=fact,判断段写本节允许的 claims、证据等级和对应引用。",
|
||||
grade_above_cap: "将等级降至所列结论和已成立正文等级中最严格的一档。",
|
||||
ref_unstable: "删去对不稳定依据的依赖,或降为 D 并说明这层暂不能支持判断。",
|
||||
too_long: "缩短命中段落,每段最多七百字,每节最多六段。",
|
||||
too_short: "用事实包支持的句子补齐本节。",
|
||||
disclaimer: "将重复的边界说明合为一处。",
|
||||
banned_phrase: "删掉命中句里的确定性、医疗或其他超出报告范围的表达。",
|
||||
dignity_mismatch: "把星曜状态改为事实包里的状态,无法核对时删除该说法。",
|
||||
false_missing_layer: "删除未计算的说法,按事实包写实际有无和状态。",
|
||||
yoga_status_mismatch: "按事实包改正格局状态,并保留尚待现实验证的边界。",
|
||||
house_lord_mismatch: "按事实包纠正盘与宫主,核对不了就删除。",
|
||||
badhaka_role_mix: "区分事实包里的阻碍宫与阻碍宫主,删除混写。",
|
||||
health_outcome: "删掉对具体疾病或健康结局的推断。",
|
||||
accuracy_claim: "删掉没有证据的准确率或成功率数字。",
|
||||
false_no_blocker: "删除没有阻塞的说法,按事实包补出实际缺少的依据。",
|
||||
fact_with_inference: "删除事实段里的推断,或将其标为本节允许的判断并给出证据等级。",
|
||||
};
|
||||
|
||||
function repairInstruction(reason: ReadingRejection, conflicts: RefConflict[] | undefined): string {
|
||||
if (reason === "ref_outside_claims") {
|
||||
const topics = conflicts?.map(({ alias, ids }) => `${alias}(${ids.join("、")})`).join("、");
|
||||
return topics
|
||||
? `这一节不能谈 ${topics}。删掉命中句中的跨领域内容,或改成由本节允许的依赖支持的表达。只返回本次要求修改的节。`
|
||||
: "删掉不在本节依赖表里的引用。只用事实包列出的结论与依赖编号。";
|
||||
}
|
||||
return REPAIR_INSTRUCTIONS[reason] ?? READING_WITHHELD_REASONS[reason] ?? "按事实包修正命中句中的问题。";
|
||||
}
|
||||
|
||||
/**
|
||||
* One attempt plus one retry when the budget allows it. Keep the accepted
|
||||
* draft with the fewest withheld sections. Never throws, except when the job
|
||||
* itself is aborted.
|
||||
* Allow two draft attempts and a single section repair after a usable draft.
|
||||
* The job's remaining lease applies to all extra calls.
|
||||
*/
|
||||
export async function writeReportReading(input: Readonly<{
|
||||
facts: unknown;
|
||||
@@ -667,39 +806,124 @@ export async function writeReportReading(input: Readonly<{
|
||||
let outputTokens = 0;
|
||||
let unavailable = "model_failed";
|
||||
const attempts: ReadingAttempt[] = [];
|
||||
let best: { reading: CheckedReportReading; withheld: number; rawSha256: string; attempt: number } | null = null;
|
||||
let best: { reading: CheckedReportReading; rawSha256: string; attempt: number } | null = null;
|
||||
let initial: { draft: Draft; check: DraftAcceptance; rawSha256: string; attempt: number; originalSections?: readonly unknown[] } | undefined;
|
||||
let repair: ReadingTransformLog["repair"];
|
||||
let finalCheck: DraftAcceptance | undefined;
|
||||
let firstDiagnostics: DraftCheck["diagnostics"] | undefined;
|
||||
const autoRebound: ReadingRebound[] = [];
|
||||
let reboundFixed = 0;
|
||||
const timeoutMs = input.timeoutMs ?? REPORT_READING_TIMEOUT_MS;
|
||||
const startedAt = Date.now();
|
||||
for (let attempt = 0; attempt < Math.min(input.attempts ?? 2, 2); attempt += 1) {
|
||||
const draftAttempts = Math.min(input.attempts ?? 2, 2);
|
||||
for (let attempt = 0; attempt < draftAttempts + 1; attempt += 1) {
|
||||
input.signal?.throwIfAborted();
|
||||
const attemptStartedAt = Date.now();
|
||||
const repairSections = attempt > 0 && repair ? initial?.check.diagnostics.map(({ section }) => section) : undefined;
|
||||
if (attempt >= draftAttempts && (draftAttempts < 2 || !repairSections)) break;
|
||||
if (attempt > 0 && input.retryDeadlineMs !== undefined
|
||||
&& input.retryDeadlineMs - attemptStartedAt < timeoutMs + REPORT_READING_RETRY_RESERVE_MS) {
|
||||
const reason = "reading_retry_skipped_deadline";
|
||||
const reason = repairSections ? "repair_skipped_deadline" : "reading_retry_skipped_deadline";
|
||||
console.info(`[personal-report] reason=${reason} duration_ms=${attemptStartedAt - startedAt}`);
|
||||
attempts.push({ attempt: attempt + 1, status: "skipped", reason, sections: [] });
|
||||
break;
|
||||
}
|
||||
const timed = timedSignal(input.signal, timeoutMs);
|
||||
try {
|
||||
if (repairSections && repair) {
|
||||
repair.attempted = true;
|
||||
repair.attempt = attempt + 1;
|
||||
}
|
||||
const first = initial;
|
||||
const repairUser = repairSections && first ? JSON.stringify({
|
||||
task: "只重写以下退回的章节,按同一顺序返回,sections 只含这些章节。",
|
||||
sections: first.check.diagnostics.map(({ section, reason, snippet, conflicts }) => {
|
||||
const index = first.draft.sections.findIndex(({ id }) => id === section);
|
||||
return {
|
||||
original: first.originalSections?.[index] ?? first.draft.sections[index],
|
||||
reason,
|
||||
explanation: repairInstruction(reason, conflicts),
|
||||
...(snippet ? { snippet } : {}),
|
||||
};
|
||||
}),
|
||||
facts,
|
||||
birth_time_confirmed: input.birthTimeConfirmed,
|
||||
}) : user;
|
||||
const result = await Promise.race([
|
||||
input.write({ system, user, signal: timed.signal }),
|
||||
input.write({ system, user: repairUser, signal: timed.signal, ...(repairSections ? { repairSections } : {}) }),
|
||||
timed.lost,
|
||||
]);
|
||||
inputTokens += Math.max(0, result.inputTokens);
|
||||
outputTokens += Math.max(0, result.outputTokens);
|
||||
const rawSha256 = canonicalReportReadingSha256(result.rawResponse ?? result.body ?? null);
|
||||
const accepted = acceptReportReadingDraft(result.body, facts, skill, result.originalSections);
|
||||
if (repairSections && repair && first) {
|
||||
const response = reportReadingRepairEnvelopeSchema(repairSections).safeParse(result.body);
|
||||
if (!response.success || response.data.sections.some(({ id }, index) => id !== repairSections[index])) {
|
||||
attempts.push({ attempt: attempt + 1, raw_response_sha256: rawSha256, status: "rejected", reason: "shape", sections: [] });
|
||||
break;
|
||||
}
|
||||
const replacements = new Map(response.data.sections.map((section) => [section.id, section]));
|
||||
const combined = { sections: first.draft.sections.map((section) => replacements.get(section.id) ?? section) };
|
||||
const originalSections = combined.sections.map((section, index) => {
|
||||
const repairedIndex = repairSections.indexOf(section.id);
|
||||
return repairedIndex === -1 ? first.originalSections?.[index] ?? section : result.originalSections?.[repairedIndex] ?? section;
|
||||
});
|
||||
let checked = checkReadingDraft(combined, facts, skill, { baseline: first.check, originalSections });
|
||||
const conflicting = new Set(checked.checked.flatMap(({ section }) =>
|
||||
replacements.has(section.id) && conflictsWithAcceptedSummary(first.check, section) ? [section.id] : []));
|
||||
if (conflicting.size) {
|
||||
checked = checkReadingDraft({
|
||||
sections: combined.sections.map((section, index) => conflicting.has(section.id) ? first.draft.sections[index]! : section),
|
||||
}, facts, skill, {
|
||||
baseline: first.check,
|
||||
originalSections: originalSections.map((section, index) => conflicting.has(combined.sections[index]!.id)
|
||||
? first.originalSections?.[index] ?? first.draft.sections[index] : section),
|
||||
});
|
||||
}
|
||||
const passes = repairSections.filter((id) => checked.checked.some(({ section }) => section.id === id && section.status === "ok"));
|
||||
const regressed = first.check.checked.some(({ section }, index) =>
|
||||
section.status === "ok" && checked.checked[index]?.section.status !== "ok");
|
||||
const adopt = checked.ok && passes.length > 0 && !regressed;
|
||||
attempts.push({
|
||||
attempt: attempt + 1, raw_response_sha256: rawSha256, status: adopt ? "accepted" : "rejected",
|
||||
...(!adopt ? { reason: regressed ? "repair_regression" : checked.ok ? "repair_no_improvement" : checked.reason } : {}),
|
||||
sections: checked.sections.filter(({ id }) => repairSections.some((requested) => requested === id)),
|
||||
});
|
||||
autoRebound.push(...checked.rebound);
|
||||
if (adopt && checked.ok) {
|
||||
repair.passed = passes;
|
||||
finalCheck = checked;
|
||||
best = { reading: checked.reading, rawSha256: first.rawSha256, attempt: first.attempt };
|
||||
}
|
||||
break;
|
||||
}
|
||||
const usableDraft = parseReadingDraft(result.body);
|
||||
const accepted = usableDraft ? checkReadingDraft(usableDraft, facts, skill, { originalSections: result.originalSections })
|
||||
: invalidDraft();
|
||||
finalCheck = accepted;
|
||||
autoRebound.push(...accepted.rebound);
|
||||
if (usableDraft && !firstDiagnostics) {
|
||||
firstDiagnostics = checkReadingDraft(usableDraft, facts, skill, { withoutRebind: true }).diagnostics;
|
||||
reboundFixed = firstDiagnostics.filter(({ section }) =>
|
||||
accepted.checked.some((entry) => entry.section.id === section && entry.section.status === "ok")).length;
|
||||
}
|
||||
if (accepted.ok) {
|
||||
attempts.push({ attempt: attempt + 1, raw_response_sha256: rawSha256, status: "accepted", sections: accepted.sections });
|
||||
if (!best || accepted.withheld < best.withheld) {
|
||||
best = { reading: accepted.reading, withheld: accepted.withheld, rawSha256, attempt: attempt + 1 };
|
||||
}
|
||||
best = { reading: accepted.reading, rawSha256, attempt: attempt + 1 };
|
||||
if (accepted.withheld === 0) break;
|
||||
} else {
|
||||
unavailable = `rejected_${accepted.reason}`;
|
||||
attempts.push({ attempt: attempt + 1, raw_response_sha256: rawSha256, status: "rejected", reason: accepted.reason, sections: accepted.sections });
|
||||
}
|
||||
if (usableDraft && accepted.diagnostics.length) {
|
||||
initial = { draft: usableDraft, check: accepted, rawSha256, attempt: attempt + 1, originalSections: result.originalSections };
|
||||
repair = {
|
||||
sections: accepted.diagnostics.map(({ section }) => section),
|
||||
reasons: Object.fromEntries(accepted.diagnostics.map(({ section, reason }) => [section, reason])),
|
||||
attempted: false,
|
||||
passed: [],
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
if (input.signal?.aborted) throw input.signal.reason ?? new Error("aborted");
|
||||
unavailable = timed.signal.aborted ? "model_timeout" : "model_failed";
|
||||
@@ -707,12 +931,32 @@ export async function writeReportReading(input: Readonly<{
|
||||
console.info(`[personal-report] reason=${unavailable} duration_ms=${Date.now() - attemptStartedAt}`);
|
||||
}
|
||||
attempts.push({ attempt: attempt + 1, status: "failed", reason: unavailable, sections: [] });
|
||||
if (repairSections) break;
|
||||
} finally {
|
||||
timed.dispose();
|
||||
}
|
||||
}
|
||||
const completedAttempts = attempts.filter(({ status }) => status !== "skipped").length;
|
||||
const transformLog = { selected_attempt: best?.attempt ?? null, retries: Math.max(0, completedAttempts - 1), attempts };
|
||||
const finalDiagnostics = finalCheck?.diagnostics ?? [];
|
||||
const firstConflicts = referenceConflicts(initial?.check.diagnostics ?? []);
|
||||
const finalConflicts = referenceConflicts(finalDiagnostics);
|
||||
const transformLog: ReadingTransformLog = {
|
||||
selected_attempt: best?.attempt ?? null,
|
||||
retries: Math.max(0, completedAttempts - 1),
|
||||
attempts,
|
||||
auto_rebound: autoRebound,
|
||||
...(repair ? { repair } : {}),
|
||||
...(firstConflicts.length ? { first_reference_conflicts: firstConflicts } : {}),
|
||||
...(finalConflicts.length ? { final_reference_conflicts: finalConflicts } : {}),
|
||||
statistics: {
|
||||
first_withheld: firstDiagnostics?.length ?? 0,
|
||||
rebound_fixed: reboundFixed,
|
||||
repair_fixed: repair?.passed.length ?? 0,
|
||||
final_withheld: finalDiagnostics.length,
|
||||
first_reasons: countRejections(firstDiagnostics ?? []),
|
||||
final_reasons: countRejections(finalDiagnostics),
|
||||
},
|
||||
};
|
||||
const reading = best ? bindReportReadingSnapshot({
|
||||
reading: best.reading, rawSha256: best.rawSha256, transformLog,
|
||||
reportInput: input.reportInput, facts, system, gitCommit: input.gitCommit,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Agent } from "@mastra/core/agent";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { ResolvedLanguageModel } from "./model.ts";
|
||||
import { reportReadingDraftEnvelopeSchema } from "@/lib/personal-report-reading-contract";
|
||||
import { reportReadingDraftEnvelopeSchema, reportReadingRepairEnvelopeSchema } from "@/lib/personal-report-reading-contract";
|
||||
import type { ReportReadingWriter } from "@/lib/personal-report-reading";
|
||||
import { reportReadingPrompt } from "./report-reading-skill.ts";
|
||||
|
||||
@@ -15,6 +15,9 @@ export function createReportReadingWriter(model: ResolvedLanguageModel): ReportR
|
||||
instructions: "Follow the system message. Return only the requested JSON.",
|
||||
});
|
||||
const writeReading = async (input: Parameters<ReportReadingWriter>[0]) => {
|
||||
const schema = input.repairSections
|
||||
? reportReadingRepairEnvelopeSchema(input.repairSections)
|
||||
: reportReadingDraftEnvelopeSchema;
|
||||
const result = await agent.generate(
|
||||
[
|
||||
{ role: "system", content: input.system },
|
||||
@@ -23,7 +26,7 @@ export function createReportReadingWriter(model: ResolvedLanguageModel): ReportR
|
||||
{
|
||||
abortSignal: input.signal,
|
||||
// Validate the two paragraph forms in the post-check so a bad binding only withholds its section.
|
||||
structuredOutput: { schema: reportReadingDraftEnvelopeSchema as z.ZodType, jsonPromptInjection: "inline" },
|
||||
structuredOutput: { schema: schema as z.ZodType, jsonPromptInjection: "inline" },
|
||||
},
|
||||
);
|
||||
const usage = await Promise.resolve((result as { usage?: { inputTokens?: number; outputTokens?: number } }).usage);
|
||||
|
||||
@@ -252,7 +252,10 @@ function writer(bodies: unknown[], calls: string[] = []): ReportReadingWriter {
|
||||
// #192 原值:第一稿被退才重试;新值:第一稿有不显示的节也重试,取不显示节更少的一稿
|
||||
test("one retry after a draft with a withheld section; tokens of both attempts are counted", async () => {
|
||||
const calls: string[] = [];
|
||||
const outcome = await writeReportReading({ reportInput: {}, facts: FACTS, birthTimeConfirmed: false, write: writer([draft({ love: ["你注定晚婚。"] }), draft()], calls) });
|
||||
const outcome = await writeReportReading({
|
||||
reportInput: {}, facts: FACTS, birthTimeConfirmed: false,
|
||||
write: writer([draft({ love: ["你注定晚婚。"] }), { sections: draft().sections.filter(({ id }) => id === "love") }], calls),
|
||||
});
|
||||
assert.ok(outcome.reading && outcome.reading.version === 4);
|
||||
assert.ok(outcome.reading.sections.every((section) => "status" in section && section.status === "ok"));
|
||||
assert.deepEqual(outcome.reading.skill, SKILL);
|
||||
@@ -367,7 +370,7 @@ test("skipping the retry keeps the accepted first draft with one withheld sectio
|
||||
assert.equal(outcome.transformLog?.selected_attempt, 1);
|
||||
assert.equal(outcome.transformLog?.retries, 0);
|
||||
assert.deepEqual(outcome.reading.transform_log.attempts[1], {
|
||||
attempt: 2, status: "skipped", reason: "reading_retry_skipped_deadline", sections: [],
|
||||
attempt: 2, status: "skipped", reason: "repair_skipped_deadline", sections: [],
|
||||
});
|
||||
assert.equal(outcome.inputTokens, 1000);
|
||||
assert.equal(outcome.outputTokens, 500);
|
||||
@@ -572,7 +575,7 @@ for (const mode of ["reading", "model-down", "no-writer", "retry-skipped", "part
|
||||
assert.deepEqual(stored.snapshot.reading.sections.filter(({ status }) => status === "withheld").map(({ id }) => id), ["health"]);
|
||||
assert.equal(stored.snapshot.reading.transform_log.selected_attempt, 1);
|
||||
assert.deepEqual(stored.snapshot.reading.transform_log.attempts[1],
|
||||
{ attempt: 2, status: "skipped", reason: "reading_retry_skipped_deadline", sections: [] });
|
||||
{ attempt: 2, status: "skipped", reason: "repair_skipped_deadline", sections: [] });
|
||||
assert.deepEqual(result.usage, { inputTokens: 1200, outputTokens: 800 });
|
||||
} else {
|
||||
assert.equal(stored.snapshot.reading, undefined);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { ReportReadingSection } from "../src/components/personal-report/report-reading-section";
|
||||
import { acceptReportReadingDraft } from "../src/lib/personal-report-reading";
|
||||
import { acceptReportReadingDraft, writeReportReading, type ReportReadingWriter } from "../src/lib/personal-report-reading";
|
||||
import {
|
||||
EVIDENCE_GRADE_CONTRACT, REPORT_READING_SECTIONS, reportReadingDraftSchema, reportReadingSchema,
|
||||
type ReportReadingSectionId,
|
||||
@@ -13,6 +13,7 @@ import { buildReportExportBlocks } from "../src/lib/report-export-blocks";
|
||||
|
||||
const SKILL = { name: "reading", version: "test", loaded: [{ path: "SKILL.md", sha256: "0".repeat(64) }] };
|
||||
const NEUTRAL = "本段复述虚构记录中的顺序、参与者位置以及需要核对的几条线索。读者可对照各行说明追溯原记录。".repeat(3);
|
||||
const FACTS_ENVELOPE = { schema: "report-reading-facts-v3", planets: [], domains: {}, timing: {}, functional: {} };
|
||||
|
||||
function claim(cap: string, sections: string[], required: string[], checked: string[] = []) {
|
||||
return { cap, sections, required: required.map((id) => ({ id })), checked: checked.map((id) => ({ id })) };
|
||||
@@ -66,7 +67,7 @@ test("summary and advice only inherit claims from accepted core sections", () =>
|
||||
const career = { text: "D10 用于补充本节的判断。", claims: ["career_promise"], grade: "C", refs: ["v:D10"] };
|
||||
const summary = { ...career, text: "这一点沿用事业节的判断。", refs: [] };
|
||||
assert.equal(reportReadingDraftSchema.safeParse(draft({ career: [career], overview: [summary] })).success, true);
|
||||
assert.deepEqual(reasons(check({ overview: [{ text: "这段缺少绑定。" }] })), [["overview", "claim_binding_missing"]]);
|
||||
assert.deepEqual(reasons(check({ overview: [{ text: "这段缺少绑定。" }] })), []);
|
||||
assert.deepEqual(reasons(check({ overview: [summary], advice: [summary] })),
|
||||
[["overview", "claim_not_established"], ["advice", "claim_not_established"]]);
|
||||
assert.deepEqual(reasons(check({ career: [{ ...career, text: "D8 用于补充本节的判断。", refs: [] }], overview: [summary] })),
|
||||
@@ -81,7 +82,7 @@ test("a timing paragraph binds all named layers and uses the strictest claim cei
|
||||
text: "2025年至2028年是窗口。Vimshottari、纳拉亚纳与过境提供时间框架。",
|
||||
claims: ["career_promise"], grade: "C", refs: [],
|
||||
};
|
||||
assert.deepEqual(reasons(check({ career: [career] })), [["career", "timing_unbound"]]);
|
||||
assert.deepEqual(reasons(check({ career: [career] })), []);
|
||||
const combined = {
|
||||
...career, claims: ["career_promise", "timing_window"],
|
||||
refs: ["s:vimshottari", "s:narayana", "t:transits"],
|
||||
@@ -97,14 +98,19 @@ test("a timing paragraph binds all named layers and uses the strictest claim cei
|
||||
assert.equal([...output.matchAll(/证据等级/g)].length, 1);
|
||||
}
|
||||
for (const text of ["预计到12月。", "预计到十一月。", "这里复述次小运。"]) {
|
||||
assert.deepEqual(reasons(check({ career: [{ ...career, text }] })), [["career", "timing_unbound"]]);
|
||||
assert.deepEqual(reasons(check({ career: [{ ...career, text }] })), []);
|
||||
}
|
||||
});
|
||||
|
||||
test("a named D8 can only bind a claim that checks D8 and honors its boundary state", () => {
|
||||
const health = { text: "D8 接近换座边界。", claims: ["health_obstruction"], grade: "C", refs: [] };
|
||||
assert.deepEqual(reasons(check({ health: [health] })), [["health", "ref_outside_claims"]]);
|
||||
assert.deepEqual(reasons(check({ health: [{ ...health, refs: ["v:D8"] }] })), [["health", "ref_outside_claims"]]);
|
||||
const rebound = acceptReportReadingDraft(draft({ health: [health] }), facts(), SKILL);
|
||||
assert.ok(rebound.ok);
|
||||
assert.deepEqual(reasons(rebound.reading), []);
|
||||
assert.deepEqual(rebound.rebound, [{
|
||||
section: "health", paragraph: 3, rule: "ref_outside_claims", added_claims: ["health_pressure"], grade_from: "C", grade_to: "D",
|
||||
}]);
|
||||
assert.deepEqual(reasons(check({ health: [{ ...health, refs: ["v:D8"] }] })), []);
|
||||
const combined = { ...health, claims: ["health_obstruction", "health_pressure"] };
|
||||
assert.deepEqual(reasons(check({ health: [combined] })), [["health", "ref_unstable"]]);
|
||||
const reading = check({ health: [{ ...combined, grade: "D" }] });
|
||||
@@ -157,3 +163,202 @@ test("references named in the text bind only the ids allowed for each claim", ()
|
||||
}
|
||||
assert.equal(reportReadingSchema.safeParse(previousV4).success, true);
|
||||
});
|
||||
|
||||
test("rebind adds a permitted dependency and timing claim, converts a fact, and prunes a summary", async () => {
|
||||
const evidence = facts("D");
|
||||
const body = draft({
|
||||
career: [{ text: "D10 提供依据,2025 年是一个窗口。", claims: ["career_promise"], grade: "B" }],
|
||||
wealth: [{ text: "D11 显示出一种倾向。", kind: "fact" }],
|
||||
health: [{ text: "这显示出一种倾向。", kind: "fact" }],
|
||||
overview: [{ text: "沿用已核对的正文判断。", claims: ["career_promise", "relationship_structure"], grade: "A" }],
|
||||
advice: [{ text: "沿用已核对的正文判断。", claims: ["wealth_earning", "relationship_structure"], grade: "D" }],
|
||||
});
|
||||
const write = Object.assign(async () => ({ body, inputTokens: 1, outputTokens: 1 }), { prompt: { system: "test", skill: SKILL } });
|
||||
const outcome = await writeReportReading({
|
||||
reportInput: {}, facts: { ...evidence, ...FACTS_ENVELOPE },
|
||||
birthTimeConfirmed: true, write, attempts: 1,
|
||||
});
|
||||
assert.ok(outcome.reading);
|
||||
const { sections, transform_log: log } = outcome.reading;
|
||||
assert.ok(sections.every(({ status }) => status === "ok"));
|
||||
for (const section of sections) {
|
||||
assert.ok(section.status === "ok");
|
||||
assert.deepEqual(section.paragraphs.map(({ text }) => text), body.sections.find(({ id }) => id === section.id)!.paragraphs.map(({ text }) => text));
|
||||
}
|
||||
assert.deepEqual(log.auto_rebound?.map(({ section, rule, added_claims, grade_from, grade_to }) =>
|
||||
[section, rule, added_claims, grade_from, grade_to]), [
|
||||
["career", "timing_unbound", ["timing_window"], "B", "D"],
|
||||
["wealth", "fact_with_inference", ["wealth_earning"], null, "C"],
|
||||
["health", "fact_with_inference", ["health_pressure"], null, "C"],
|
||||
["overview", "claim_not_established", [], "A", "D"],
|
||||
["advice", "claim_not_established", [], "D", "D"],
|
||||
]);
|
||||
assert.equal(log.statistics?.first_withheld, 5);
|
||||
assert.equal(log.statistics?.rebound_fixed, 5);
|
||||
});
|
||||
|
||||
test("eight basis paragraphs pass the provider envelope and merge into six without losing prose", () => {
|
||||
const extra = Array.from({ length: 6 }, (_, index) => ({ text: `依据记录第${index + 1}项。`, kind: "fact" }));
|
||||
const body = draft({ basis: extra });
|
||||
const result = acceptReportReadingDraft(body, facts(), SKILL);
|
||||
assert.ok(result.ok);
|
||||
const basis = result.reading.sections.find(({ id }) => id === "basis");
|
||||
assert.ok(basis?.status === "ok");
|
||||
assert.equal(basis.paragraphs.length, 6);
|
||||
assert.equal(basis.paragraphs[5]?.text, extra.slice(3).map(({ text }) => text).join("\n\n"));
|
||||
assert.deepEqual(result.rebound.map(({ rule }) => rule), ["merge_paragraphs", "merge_paragraphs"]);
|
||||
|
||||
const unsafe = acceptReportReadingDraft(draft({ basis: [...extra.slice(0, -1), { text: "这是 field_id。", kind: "fact" }] }), facts(), SKILL);
|
||||
assert.ok(unsafe.ok);
|
||||
assert.deepEqual(reasons(unsafe.reading), [["basis", "field_name"]]);
|
||||
const overflow = acceptReportReadingDraft(draft({ basis: extra.map((item) => ({ ...item, text: "合成依据文字。".repeat(40) })) }), facts(), SKILL);
|
||||
assert.ok(overflow.ok);
|
||||
assert.deepEqual(reasons(overflow.reading), []);
|
||||
assert.deepEqual(overflow.rebound.filter(({ rule }) => rule === "drop_paragraph").map(({ dropped_text }) => dropped_text),
|
||||
["合成依据文字。".repeat(40)]);
|
||||
});
|
||||
|
||||
test("one repair request contains only failed sections and the matching sentences", async () => {
|
||||
const initial = draft({
|
||||
career: [{ kind: "fact", text: "第一句可以保留。这里有 field_id。第三句可以保留。" }],
|
||||
health: [{ kind: "fact", text: "正文引用下划线 id_code。" }],
|
||||
});
|
||||
const repair = draft({}).sections.filter(({ id }) => id === "career" || id === "health");
|
||||
const evidence = { ...facts(), ...FACTS_ENVELOPE };
|
||||
const calls: Parameters<ReportReadingWriter>[0][] = [];
|
||||
const write: ReportReadingWriter = Object.assign(async (request: Parameters<ReportReadingWriter>[0]) => {
|
||||
calls.push(request);
|
||||
return { body: calls.length === 1 ? initial : { sections: repair }, inputTokens: 1, outputTokens: 1 };
|
||||
}, { prompt: { system: "test", skill: SKILL } });
|
||||
const result = await writeReportReading({ reportInput: {}, facts: evidence, birthTimeConfirmed: true, write });
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[0]?.system, calls[1]?.system);
|
||||
assert.deepEqual(calls[1]?.repairSections, ["career", "health"]);
|
||||
const payload = JSON.parse(calls[1]!.user);
|
||||
assert.deepEqual(payload.facts, evidence);
|
||||
assert.deepEqual(payload.sections.map(({ original, reason, snippet }: { original: { id: string }; reason: string; snippet: string }) =>
|
||||
[original.id, reason, snippet]), [["career", "field_name", "这里有 field_id"], ["health", "field_name", "正文引用下划线 id_code"]]);
|
||||
assert.deepEqual(result.transformLog?.repair, {
|
||||
sections: ["career", "health"], reasons: { career: "field_name", health: "field_name" },
|
||||
attempted: true, attempt: 2, passed: ["career", "health"],
|
||||
});
|
||||
assert.deepEqual(result.transformLog?.statistics, {
|
||||
first_withheld: 2, rebound_fixed: 0, repair_fixed: 2, final_withheld: 0,
|
||||
first_reasons: { field_name: 2 }, final_reasons: {},
|
||||
});
|
||||
assert.ok(result.reading);
|
||||
assert.equal(reportReadingSchema.safeParse(result.reading).success, true);
|
||||
const first = acceptReportReadingDraft(initial, evidence, SKILL);
|
||||
assert.ok(first.ok);
|
||||
assert.deepEqual(result.reading.sections.filter(({ id }) => id !== "career" && id !== "health"),
|
||||
first.reading.sections.filter(({ id }) => id !== "career" && id !== "health"));
|
||||
});
|
||||
|
||||
test("a repair that weakens an established summary does not discard other valid repairs", async () => {
|
||||
const body = draft({
|
||||
overview: [{ text: "正文支持这一点。", claims: ["timing_window"], grade: "C" }],
|
||||
now: [{ text: "大运提供这项依据。", claims: ["timing_window"], grade: "C" }],
|
||||
career: [{ text: "这里有 field_id。", kind: "fact" }],
|
||||
health: [{ text: "这里有 field_id。", kind: "fact" }],
|
||||
});
|
||||
const repairs = draft({
|
||||
career: [{ text: "此窗口缺少依据。", claims: ["timing_window"], grade: "D" }],
|
||||
}).sections.filter(({ id }) => id === "career" || id === "health");
|
||||
const evidence = { ...facts(), ...FACTS_ENVELOPE };
|
||||
let calls = 0;
|
||||
const write = Object.assign(async () => ({
|
||||
body: ++calls === 1 ? body : { sections: repairs }, inputTokens: 1, outputTokens: 1,
|
||||
}), { prompt: { system: "test", skill: SKILL } });
|
||||
const result = await writeReportReading({ reportInput: {}, facts: evidence, birthTimeConfirmed: true, write });
|
||||
assert.ok(result.reading);
|
||||
assert.deepEqual(result.transformLog?.repair?.passed, ["health"]);
|
||||
assert.deepEqual(reasons(result.reading), [["career", "field_name"]]);
|
||||
const first = check({
|
||||
overview: [{ text: "正文支持这一点。", claims: ["timing_window"], grade: "C" }],
|
||||
now: [{ text: "大运提供这项依据。", claims: ["timing_window"], grade: "C" }],
|
||||
});
|
||||
assert.deepEqual(result.reading.sections[0], first.sections[0]);
|
||||
});
|
||||
|
||||
test("unmarked paragraphs use aliases, timing, established claims or a fact binding", () => {
|
||||
const draftValue = draft({
|
||||
career: [{ text: "D10 支持这项判断。" }, { text: "2025 年是一个窗口。" }, { text: "这显示出一种倾向。" }],
|
||||
overview: [{ text: "这显示出一种倾向。" }],
|
||||
advice: [{ text: "D10 支持这项判断。" }],
|
||||
basis: [{ text: "这段列出计算依据。" }],
|
||||
});
|
||||
const result = acceptReportReadingDraft(draftValue, facts("D"), SKILL);
|
||||
assert.ok(result.ok);
|
||||
assert.deepEqual(reasons(result.reading), []);
|
||||
const bindings = result.rebound.filter(({ rule }) => rule === "claim_binding_missing");
|
||||
assert.deepEqual(bindings.map(({ section, added_claims, grade_to }) => [section, added_claims, grade_to]), [
|
||||
["career", ["career_promise"], "C"],
|
||||
["career", ["timing_window"], "D"],
|
||||
["career", ["career_promise"], "C"],
|
||||
["basis", [], null],
|
||||
["overview", ["career_promise"], "C"],
|
||||
["advice", ["career_promise"], "C"],
|
||||
]);
|
||||
});
|
||||
|
||||
test("generic dasha words do not bind Vimshottari, but an explicit named technique still does", () => {
|
||||
const timed = { text: "这一段大运提供时间框架。", claims: ["timing_window"], grade: "C" };
|
||||
const result = check({ career: [timed, { ...timed, text: "Vimshottari 大运提供时间框架。" }] });
|
||||
const section = result.sections.find(({ id }) => id === "career");
|
||||
assert.ok(section?.status === "ok");
|
||||
assert.deepEqual(section.paragraphs.slice(-2).map((item) => "refs" in item ? item.refs : null), [[], ["s:vimshottari"]]);
|
||||
});
|
||||
|
||||
test("a second usable draft gets one repair with exact cross-domain names", async () => {
|
||||
const original = draft({ career: [{ text: "首句可保留。D11 用于补充判断。", claims: ["career_promise"], grade: "C" }] });
|
||||
const repaired = draft({}).sections.filter(({ id }) => id === "career");
|
||||
const calls: Parameters<ReportReadingWriter>[0][] = [];
|
||||
const write: ReportReadingWriter = Object.assign(async (request: Parameters<ReportReadingWriter>[0]) => {
|
||||
calls.push(request);
|
||||
if (calls.length === 1) throw new Error("model failed");
|
||||
return { body: calls.length === 2 ? original : { sections: repaired }, inputTokens: 1, outputTokens: 1 };
|
||||
}, { prompt: { system: "test", skill: SKILL } });
|
||||
const result = await writeReportReading({ reportInput: {}, facts: { ...facts(), ...FACTS_ENVELOPE }, birthTimeConfirmed: true, write });
|
||||
assert.equal(calls.length, 3);
|
||||
assert.deepEqual(calls[2]?.repairSections, ["career"]);
|
||||
const payload = JSON.parse(calls[2]!.user);
|
||||
assert.equal(payload.sections[0].snippet, "D11 用于补充判断");
|
||||
assert.match(payload.sections[0].explanation, /这一节不能谈 d11(v:D11、p:wealth:D11)/i);
|
||||
assert.equal(result.transformLog?.selected_attempt, 2);
|
||||
assert.equal(result.transformLog?.repair?.attempt, 3);
|
||||
assert.deepEqual(result.transformLog?.repair?.passed, ["career"]);
|
||||
assert.deepEqual(result.transformLog?.first_reference_conflicts, [{
|
||||
section: "career", references: [{ alias: "D11", ids: ["v:D11", "p:wealth:D11"] }],
|
||||
}]);
|
||||
assert.equal(result.transformLog?.final_reference_conflicts, undefined);
|
||||
assert.ok(result.reading);
|
||||
assert.deepEqual(reasons(result.reading), []);
|
||||
});
|
||||
|
||||
test("repair after the second draft preserves the accepted result when its deadline is too close", async (t) => {
|
||||
let calls = 0;
|
||||
const body = draft({ career: [{ text: "这里有 field_id。", kind: "fact" }] });
|
||||
const write = Object.assign(async () => {
|
||||
if (++calls === 1) throw new Error("model failed");
|
||||
return { body, inputTokens: 1, outputTokens: 1 };
|
||||
}, { prompt: { system: "test", skill: SKILL } });
|
||||
const start = Date.now();
|
||||
let clock = start;
|
||||
t.mock.method(Date, "now", () => clock);
|
||||
const outcome = await writeReportReading({
|
||||
reportInput: {}, facts: { ...facts(), ...FACTS_ENVELOPE }, birthTimeConfirmed: true,
|
||||
write: Object.assign(async () => {
|
||||
const result = await write();
|
||||
// The second draft takes the job past the next-call reserve threshold.
|
||||
clock = start + 10_000;
|
||||
return result;
|
||||
}, { prompt: write.prompt }),
|
||||
retryDeadlineMs: start + 305_000,
|
||||
});
|
||||
assert.equal(calls, 2);
|
||||
assert.equal(outcome.transformLog?.selected_attempt, 2);
|
||||
assert.equal(outcome.transformLog?.repair?.attempted, false);
|
||||
assert.equal(outcome.transformLog?.attempts[2]?.reason, "repair_skipped_deadline");
|
||||
assert.ok(outcome.reading);
|
||||
assert.deepEqual(reasons(outcome.reading), [["career", "field_name"]]);
|
||||
});
|
||||
|
||||
@@ -105,7 +105,7 @@ test("the stored snapshot binds the selected raw response and records a failed r
|
||||
system_prompt_sha256: reportReadingSha256("原始提示"),
|
||||
raw_response_sha256: canonicalReportReadingSha256(rawResponse),
|
||||
stored_sha256: canonicalReportReadingSha256(stored),
|
||||
rules: { evidence_grade_contract: EVIDENCE_GRADE_CONTRACT, postcheck_version: 1, git_commit: COMMIT },
|
||||
rules: { evidence_grade_contract: EVIDENCE_GRADE_CONTRACT, postcheck_version: 3, git_commit: COMMIT },
|
||||
});
|
||||
assert.equal(stored.transform_log.selected_attempt, 1);
|
||||
assert.equal(stored.transform_log.retries, 1);
|
||||
@@ -136,6 +136,9 @@ test("offline acceptance replays an archived draft and the manifest matches ever
|
||||
const manifest = JSON.parse(file("manifest.json").toString("utf8"));
|
||||
const { snapshot, ...stored } = JSON.parse(file("reading.json").toString("utf8"));
|
||||
assert.equal(manifest.mode, "replay");
|
||||
const input = JSON.parse(file("input.json").toString("utf8"));
|
||||
assert.equal(input.ayanamsa, "raman");
|
||||
assert.equal(input.node_mode, "mean");
|
||||
assert.equal(manifest.facts_sha256, snapshot.facts_sha256);
|
||||
assert.equal(manifest.stored_sha256, canonicalReportReadingSha256(stored));
|
||||
assert.equal(Object.keys(manifest.files_sha256).length, 9);
|
||||
|
||||
@@ -307,4 +307,6 @@ evidence_card.backstage records, for the backend only, that global web evidence
|
||||
可以写技法名和分盘代号(Vimshottari、Narayana、D10、A10、UL、AK、AmK、DK、KP、Shadbala、Ashtakavarga、Sade Sati),第一次出现时在括号里用半句中文说明它看什么。行星、星座用中文;交点只叫罗睺、计都。不写字段名、下划线、花括号、井号、代码,不写「本仓」「检测器」「字段」「口径」这类内部说法。审计行里网上检索和案例校准这两行只在后台记录(产品 2026-11-08 决定,BUG-1794),正文不写它们有没有做;等级由页面显示。不写病名、诊断和身体部位的疾病;不给投资指令,不点名股票、基金、币;不写「注定」「先苦后甜」「宿命」「一定会」;不预测死亡、必然离婚、怀孕与孩子性别、某天必然发财;婚姻、生死不下确定结论。每节最多一句提醒,不逐句免责。
|
||||
<!-- 产品规则,不是占星师的方法:R-08 篇幅与输出格式。 -->
|
||||
每节一到六段,每段不超过六百五十字,全篇三千到一万五千字。只输出 JSON,顶层为 {"sections":[…]}。九节的 id 依次是 overview、character、career、wealth、love、health、now、advice、basis,各节的 paragraphs 按段选择一种形态,例如 {"text":"水星落第五宫。","kind":"fact"} 或 {"text":"本命盘显示……","claims":["character_structure"],"grade":"C","refs":["v:D1"]}。claims 的每项只能取 {{CLAIM_TYPES}} 之一,grade 只能取 A、B、C、D。
|
||||
收到章节修改请求时,只按退回原因与命中片段重写指定章节。沿用同一份事实包、段落标注和证据等级规则。仍用 `sections` 数组,按请求顺序返回指定章节,各返回一次。
|
||||
|
||||
<!-- /product-block:report-reading -->
|
||||
|
||||
@@ -22,9 +22,12 @@ node --import tsx ../tools/report-reading-acceptance/run.mts \
|
||||
|
||||
在线模式复用生产报告写作器,默认模型为 `deepseek-flash`,可用 `--model` 指定。凭据依次读取 `DEEPSEEK_API_KEY`、`DS_KEY` 和 `/workspace/keys/ds_key`。
|
||||
|
||||
重新计算事实时使用前端产品默认岁差和交点(Raman、平均交点)。原样回放既有事实包时用 `--facts`。
|
||||
|
||||
## 检查输出
|
||||
|
||||
- 输出落在 `<out>/<case>/`。`input.json` 是实际计算请求。`facts.json`、`caps.json` 和 `system_prompt.txt` 是本次使用的材料。`raw.json` 保存被选中尝试的模型回复。旧草稿回放时,它保存转换前的 JSON 值。
|
||||
- `reading.json` 是存储形状,`final.md` 复用页面的 Markdown 导出。`postcheck.json` 和 `transform_log.json` 记录每次尝试和逐节结果。整份草稿被拒时,工具仍写出诊断并返回非零状态。
|
||||
- `manifest.json` 保存其他九个文件的字节哈希。JSON 使用 UTF-16 键排序和 ECMAScript 数字表示,以紧凑 UTF-8 写出。快照中的 `stored_sha256` 对 `reading.json` 去掉 `snapshot` 后的规范化 JSON 计算。其余五个快照哈希对应输入、事实、等级合同、系统提示和原始回复文件。任何快照哈希或规则不一致都会返回非零状态。
|
||||
- `reading.json` 是存储形状,`final.md` 复用页面的 Markdown 导出。`postcheck.json` 和 `transform_log.json` 记录每次尝试、逐节结果、自动重绑和重写结果。`statistics` 分别记录首轮拦截、重绑修好、重写修好、最后仍拦截的节数,以及首轮和最终的原因计数。整份草稿被拒时,工具仍写出诊断并返回非零状态。
|
||||
- 有章节重写回复时,`repair_raw.json` 保存该回复,其哈希对应 `repair.attempt`。合并后的报告以被选中的完整草稿作为 `raw.json`。仅在受控验收包与服务端转换记录保留因超长而丢弃的段落原文。
|
||||
- `manifest.json` 保存验收包各文件的字节哈希。JSON 使用 UTF-16 键排序和 ECMAScript 数字表示,以紧凑 UTF-8 写出。快照中的 `stored_sha256` 对 `reading.json` 去掉 `snapshot` 后的规范化 JSON 计算。其余五个快照哈希对应输入、事实、等级合同、系统提示和原始回复文件。任何快照哈希或规则不一致都会返回非零状态。
|
||||
- 验收包写到仓库之外,留在受控验收环境。命令结束时输出本次 Git 提交及复跑命令。
|
||||
|
||||
@@ -6,6 +6,8 @@ import { fileURLToPath } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
|
||||
import { reportReadingRules } from "../../frontend/src/lib/personal-report-reading-audit.ts";
|
||||
import { DEFAULT_AYANAMSA } from "../../frontend/src/lib/ayanamsa.ts";
|
||||
import { PRODUCT_DEFAULT_NODE_MODE } from "../../frontend/src/lib/calculation-modes.ts";
|
||||
import { acceptReadingFacts, REPORT_READING_TIMEOUT_MS, writeReportReading, type ReportReadingWriter } from "../../frontend/src/lib/personal-report-reading.ts";
|
||||
import { canonicalReportReadingJson, canonicalReportReadingSha256, reportReadingSha256 } from "../../frontend/src/lib/report-reading-canonical-json.ts";
|
||||
import { buildReportExportBlocks } from "../../frontend/src/lib/report-export-blocks.ts";
|
||||
@@ -56,7 +58,7 @@ async function main() {
|
||||
const input = {
|
||||
...sample.input, format: "markdown", packs: ["full"], edition: "full_data", languages: ["zh", "en"],
|
||||
include_fact_tables: true, include_reading_facts: true, birth_time_accuracy: "confirmed",
|
||||
ayanamsa: "lahiri", node_mode: "mean",
|
||||
ayanamsa: DEFAULT_AYANAMSA, node_mode: PRODUCT_DEFAULT_NODE_MODE,
|
||||
};
|
||||
const facts = acceptReadingFacts(values.facts ? loadJson(values.facts) : JSON.parse(execFileSync(
|
||||
values.python ?? "python3", [join(toolDir, "calculate_facts.py")], {
|
||||
@@ -86,6 +88,7 @@ async function main() {
|
||||
const { reading, transformLog } = outcome;
|
||||
const selectedSha = reading?.snapshot.raw_response_sha256 ?? [...captured.keys()].at(-1);
|
||||
const selectedRaw = selectedSha ? captured.get(selectedSha) : null;
|
||||
const repairSha = transformLog?.attempts.find(({ attempt }) => attempt === transformLog.repair?.attempt)?.raw_response_sha256;
|
||||
const caps = facts.evidence_grades;
|
||||
const final = reading ? buildReportExportBlocks({ markdown: "", reading }).find(({ id }) => id === "body:reading")?.text : "";
|
||||
const files = {
|
||||
@@ -94,6 +97,7 @@ async function main() {
|
||||
"caps.json": canonicalReportReadingJson(caps),
|
||||
"system_prompt.txt": write.prompt.system,
|
||||
"raw.json": canonicalReportReadingJson(selectedRaw ?? null),
|
||||
...(repairSha && captured.has(repairSha) ? { "repair_raw.json": canonicalReportReadingJson(captured.get(repairSha)) } : {}),
|
||||
"reading.json": canonicalReportReadingJson(reading),
|
||||
"final.md": final ?? "",
|
||||
"postcheck.json": canonicalReportReadingJson({ ok: reading !== null, unavailable: outcome.unavailable, ...transformLog }),
|
||||
|
||||
Reference in New Issue
Block a user