Merge pull request '#314 生时纠正:下轮对话按当前出生输入读取历史' (#318) from codex/rect-stale-chat-evidence-20261117 into staging
This commit was merged in pull request #318.
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
# BLOCKED
|
||||
|
||||
## #314 聊天旧依据独立验收
|
||||
|
||||
- 合成会话的真实模型抽查和登录后真机走查未执行。定向测试检查模型投影、闲聊提交、摘要过滤、合盘版本与折叠分隔。见 [#314 进度](docs/tasks/PROGRESS-rect-stale-chat-evidence-20261117.md)。
|
||||
|
||||
## #312 自选情景独立验收
|
||||
|
||||
- 登录后浏览器走查与真实模型回答待独立验收。本机已用虚构档案、原生引擎、React 流程和隔离 PostgreSQL 提供替代证据。Windows 预检的工作台镜像路径断言失败,远端和外部引擎适配器检查通过。见 [#312 进度](docs/tasks/PROGRESS-rect-self-choice-scenario-20261117.md)。
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# 印度占星 Skill 更新日志
|
||||
|
||||
## 2026-11-17 · 聊天保留旧回答并标明出生依据变化
|
||||
|
||||
- 下一轮按当前出生输入判断,旧回答的判断依据只在页面保留。Skill 版本沿用(BUG-1960)。
|
||||
|
||||
## 2026-11-17 · 生时纠正自选保存为用户情景
|
||||
|
||||
- 结果页可展开全部换座,聊天区分自选情景与时间核实,旧预览遇到资料或当前记录变化会重新加载。占星 Skill 版本不变(BUG-1958)。
|
||||
|
||||
@@ -26321,3 +26321,14 @@
|
||||
- 验证与防复发:原生引擎分段、真实 PostgreSQL 并发与声明变化、接口重放及页面恢复均有定向回归。见 [#312 进度](tasks/PROGRESS-rect-self-choice-scenario-20261117.md)。
|
||||
- 关联记录:BUG-1936、BUG-1952、BUG-1956。
|
||||
- 修复版本:`codex/rect-self-choice-scenario-20261117`。
|
||||
|
||||
## BUG-1960 | 出生输入改动后,聊天继续沿用旧回答的盘面依据
|
||||
|
||||
- 状态:fixed-pending-verify,待独立验收。
|
||||
- 首次发现 / 最近更新:2026-11-17 / 2026-11-17。
|
||||
- 触发与现象:在生时纠正页面自选、恢复申报或修改档案后,回到旧会话追问,下一轮仍能把旧回答的盘面结论和判断依据当作当前依据。
|
||||
- 根因:BUG-1251 只依赖聊天内的返回分隔,历史回答未记录读取时的出生输入版本,无法识别会话外的变化。
|
||||
- 修复:给新回答绑定主体版本,合盘按双方核对。旧答案和覆盖它的摘要在模型上下文中标明过期,旧判断依据段仅保留在历史页面;新摘要排除过期回答,页面在分界处复用生时纠正分隔。
|
||||
- 验证与防复发:合成用例覆盖四种判定、双方独立变化、原文保留、摘要排除、分隔去重、寒暄与历史水合。见 [#314 进度](tasks/PROGRESS-rect-stale-chat-evidence-20261117.md)。
|
||||
- 关联记录:BUG-1251、BUG-1890、BUG-1948、BUG-1956。
|
||||
- 修复版本:`codex/rect-stale-chat-evidence-20261117`。
|
||||
|
||||
@@ -28,5 +28,5 @@
|
||||
1. 长报告、年运及完整合盘的新增快照保存生成版本,详情与报告列表核对当前投影。旧产物返回 `unknown`,页面如何标示待定。
|
||||
2. 同主体同周期年运仅复用同版本的在途任务。续跑或提交时发现版本变化的长报告和年运进入原有失败及返还流程。年运可继续阅读历史结果并查到核对状态。
|
||||
3. 未绑定的旧独立合盘记录返回 `unknown`。长报告、年运及合盘输出携带核对元数据。导出正文标示、聊天导出和已下载文件仍有缺口。
|
||||
4. 首页暖启动和今日卡按版本核对,较晚回来的已失效请求不能覆盖新档案。已交付的聊天历史、旧取数卡和旧模型证据待另单处理。
|
||||
4. 首页暖启动和今日卡按版本核对,较晚回来的已失效请求不能覆盖新档案。历史聊天原文和旧取数卡保留。BUG-1960 已给新回答绑定出生输入版本;下一轮读取到已知过期回答时仅保留带说明的正文,不将旧「判断依据」交给模型。历史页面按读时版本显示分隔。旧聊天导出和真实模型抽查仍待处理。
|
||||
5. 星盘沿用数值盘体缓存,状态、范围及来源取当前投影,客户端按版本替换数据。同分钟撤回及再次自选有合成回归,真实浏览器走查待验收。
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# #314 旧聊天依据过期后按当前出生输入回答
|
||||
|
||||
执行者 Codex。开工基线 `f8e0db21f`,交付分支已并入 `f8d9e0dc1`,任务书 [BUG-1960](TASK-rect-stale-chat-evidence-20261117.md)。
|
||||
|
||||
## 实现
|
||||
|
||||
- 普通咨询复用本轮已加载并用于读盘的档案投影,写入出生输入版本。新前端声明支持扩展流事件后才接收版本字段,旧页面继续使用原事件格式。流式、回退、直达提示、寒暄和审核替换走同一个绑定。合盘追问读取两位会话主体的当前版本以筛选历史;有绑定版本的报告以实际取用的报告材料版本保存,按会话主体顺序记录。合盘追问的普通咨询路由本来不加载档案,双方核对用所有者范围内的档案读取。报告页面、生成与导出不在本单。
|
||||
- 旧回答判定复用聊天内校正的返回分隔,并核对单主体版本、双方版本、停用采用投影或晚于旧消息的采用时间。无版本且无其他证据的历史仍可继续;无消息时间时不按采用时间推断。
|
||||
- 仅在发给模型的文本里提示依据过期,复用 `splitJudgmentBasis` 移除旧「判断依据」。旧摘要覆盖过期回答时加同一说明。新摘要排除已知过期助手回答,已有摘要含过期回答时,下次生成从现有消息重建。原有摘要阈值与受控写入条件沿用。
|
||||
- 页面按当前主体档案和聊天版本计算分隔,保留聊天内已有分隔;旧原文、折叠依据和证据卡照原样读取。新分隔不持久化,正文内容的内部词检查和事实复查沿用。
|
||||
|
||||
## 断言调整
|
||||
|
||||
| 原值 | 新值 | 原因 |
|
||||
| --- | --- | --- |
|
||||
| 寒暄分支调用 `completeSmalltalk(turn.reply)` | `completeSmalltalk(turn.reply, birthFields)` | 保留原分类与付费门禁,同时写同轮的出生输入版本。两处合同同步。 |
|
||||
| 预留前回调解构到 `subject` | 追加 `birthHistory`,数据卡预热仍是第一句、计划仍在预留前生成 | 在同一回调保存已经读取的档案投影。两处合同保留原调用顺序。 |
|
||||
| 消息外层结束 `</div>` 之后立即结束返回 | `</div>` 后渲染可选分隔,同时按原顺序断言正文、操作、追问和分隔 | 依据变化的分隔属于两个消息之间,保留原回复与操作顺序。 |
|
||||
|
||||
## 验收
|
||||
|
||||
- 过期判定、旧摘要、真实 PostgreSQL 合盘授权、寒暄和内部词回归一组 85 项通过。合入 staging 后,包含流式顺序、滚动和资料预热合同的定向一组 112 项通过。补上浏览器流协议兼容后,再跑 59 项定向,全部通过。并入 #312 后复验咨询、账户和自选情景,135 项通过。
|
||||
- 两个 Windows 全量对照进程临时从 PATH 移除 Docker。最终基线 3,976 项(3,889 通过、47 失败、40 跳过),本分支 3,983 项(3,896 通过、47 失败、40 跳过)。均无取消,失败名称逐条一致,未删用例。
|
||||
- 带 Git 索引的 Linux 快照通过 Python 快速门(`--profile quick --skip-frontend-runtime`)。无 Git 索引那次的三项隐私检查在带索引快照独立复验通过。并入 #312 后,原生自选、隐私和会话入口 126 项通过。Windows 原生快速门另有三条上游技法测试失败,已在最终 staging 基线复现同样的 `seed` 缺失与路径参数错误。
|
||||
- TypeScript、ESLint(0 错误,63 条警告)和生产构建通过。`/` 保持 Static。基线与本分支的首屏压缩脚本分别为 529,067、530,113 字节(+0.20%)。
|
||||
- 用合成会话实跑一次真实模型并确认无旧依据转述或多段历史说明,未执行。登录后真机分隔与折叠走查留待独立验收。合盘追问仍使用绑定报告的材料,旧报告本身的版本提示与导出范围归 BUG-1959。
|
||||
@@ -7,6 +7,7 @@
|
||||
- 被环境或依赖挡住的事项写进根目录 `BLOCKED.md`;Bug 事实写进 `docs/BUG_HISTORY.md`;两者不在这里重复。
|
||||
- 纯文档改动不触发 staging 门禁(见 `deploy/gated-paths.txt`)。
|
||||
|
||||
- [旧聊天出生依据过期(#314)](PROGRESS-rect-stale-chat-evidence-20261117.md) — 历史上下文、摘要与聊天分隔。
|
||||
- [生时纠正用户自选情景(#312)](PROGRESS-rect-self-choice-scenario-20261117.md) — 换座列表、保存重放校验及聊天口径。
|
||||
- [出生输入版本与报告核对(#310)](PROGRESS-rect-birth-input-revision-20261117.md) — 生成、读取、导出元数据及缓存验证。
|
||||
- [生时纠正 P0 聚合统计 v3(#311)](PROGRESS-rect-p0-aggregate-v3-20261117.md) — 输出段、绑定行为及 PostgreSQL 验证。
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# 生时纠正 P0:出生输入变过之后,旧回答不再被下一轮当作依据(2026-11-17,Claude)
|
||||
|
||||
Bug 编号:BUG-1960。关联 BUG-1956(#310)、BUG-1251、BUG-1890、BUG-1948。
|
||||
|
||||
## 背景
|
||||
|
||||
占星师 11-17 裁定(缺口 4 的聊天部分):历史聊天可以保留,但出生时间的依据变过之后,旧回答要标明依据已过期,下一轮不得把旧回答里的盘面结论当作可信事实接着推理。不要求改写历史聊天。
|
||||
|
||||
现状(`frontend/src/lib/consultation-session-history.ts`,BUG-1251 的 C7):只有一种情况被处理——在聊天里走完生时纠正并采用(消息里有 `rectificationReturn.adopted` 的分隔记录)。这之前的助手回答在交给模型时前面加一句 `BIRTH_TIME_CHANGED_HISTORY_NOTE`,会话摘要同样处理。
|
||||
|
||||
没处理的情况:出生输入是在别处变的——生时纠正页面上自选线前线后或改回原时间、旧采用被停用(BUG-1890 的读取投影)、在档案里改了时间或范围。这些变化在消息里没有任何记录,旧回答原样进入下一轮。
|
||||
|
||||
#310 已提供 `birthInputRevision(projectedRow)`。本单用它把上面的机制补全。
|
||||
|
||||
## 一、回答存下来时记录版本
|
||||
|
||||
助手回答写入会话 `messages` 时,在消息对象上加 `birthInputRevision`(本轮所用主体的当前版本;合盘会话存双方 `birthInputRevisions: { a, b }`)。只加字段,不改其他字段。闲聊快路径(`responseKind: "smalltalk"`)和没有用到星盘的回答也照样记录,逻辑保持一处。
|
||||
|
||||
本轮开始时用于装配上下文的「当前版本」:`/api/consult` 已经读取当前主体的档案行,在同一处算出版本,往下传;不另加查询。
|
||||
|
||||
## 二、哪些旧回答算过期
|
||||
|
||||
`storedConsultationTurns` 增加入参:当前版本(合盘为双方)和当前档案投影里判断所需的少量信息。一条助手回答满足下面任一条即为过期:
|
||||
|
||||
1. 现有规则:位于最后一次 `rectificationReturn.adopted` 之前(保留,不改)。
|
||||
2. 消息带 `birthInputRevision` 且与当前版本不同(合盘:任一侧不同)。
|
||||
3. 消息不带版本(本单上线前的旧消息),并且当前档案是被停用采用的读取投影(`active_birth_provenance.retired_reason === "BUG-1890"`)。这类主体的旧回答可能是按已停用的时间写的。
|
||||
4. 消息不带版本,当前来源有 `adopted_at`,且消息的时间早于它(消息对象上有时间字段才比;没有时间字段的不按这条判)。
|
||||
|
||||
其余不带版本的旧消息不算过期(没有证据表明依据变过,不能把所有老会话都判掉)。在 PROGRESS 里把这条边界写明。
|
||||
|
||||
会话摘要 `context_summary`:摘要覆盖到 `throughMessageIndex`。只要它覆盖范围内有任何一条过期的助手回答,摘要按过期处理(现有 C7 的做法推广)。新生成摘要时(看摘要生成处),过期的回答不参与摘要,或者摘要重新生成;二选一,以改动小的为准,写进 PROGRESS。
|
||||
|
||||
## 三、过期的回答怎么交给模型
|
||||
|
||||
保留现有做法的骨架(前面加一句说明、正文仍给模型看),因为用户可能追问「你刚才说的 X 是什么意思」,模型需要看得到原话。在此基础上改三点:
|
||||
|
||||
1. 说明句换掉。现有 `(以下回答按校正前的出生时间,不要沿用其中的盘面判断)` 只适用于聊天内校正。新句子(两种情况共用一句):
|
||||
|
||||
`(这条回答按之前的出生时间写成,里面的盘面判断不能当作现在的依据;需要时按现在的盘重新看。这句只给你看,不要在回答里转述或解释。)`
|
||||
|
||||
2. 过期回答里的 `## 判断依据` 一节不交给模型(那是逐行的数据依据,最容易被当成事实沿用)。切分**必须复用** `frontend/src/lib/consult-judgment-basis.ts` 的 `splitJudgmentBasis`,不另写一套。只影响交给模型的文本;存储的原文和页面显示不变。
|
||||
3. 在咨询提示词里加一条对应的规则(放在现有处理历史的那段附近,`frontend/src/mastra/` 下,改动前看 `product-voice.ts` 的现有措辞,不与之重复):用户追问一条被标了上面那句的旧回答时,按现在的盘重新回答这个问题;可以用一句话说明「出生时间后来改过,所以我按现在的重新看了」,不讲技术细节,不逐条对比新旧,不向用户复述那句括号里的话。
|
||||
|
||||
产品负责人 11-16 的规则照旧:正文不出现讲解读本身的话。除上面允许的那一句外,新回答不得因为历史过期而加任何额外说明。
|
||||
|
||||
## 四、页面上标一处
|
||||
|
||||
会话页面在「依据变化的位置」显示一条分隔,复用聊天内校正返回时已有的那条分隔的样式和组件(`rectificationReturn` 的分隔,不新造样式):
|
||||
|
||||
`出生时间在这之后改过,上面的回答按之前的时间写成。`
|
||||
|
||||
规则:按消息顺序,从过期变为不过期的交界处显示一条;整段会话只有过期回答、后面还没有新回答时,显示在最后一条过期回答之后。已有 `rectificationReturn` 分隔的位置不重复显示。旧回答原文、折叠的「判断依据」、取数卡照常显示,不置灰、不隐藏。
|
||||
|
||||
这条分隔是读取时算出来的,不写进 `messages`。
|
||||
|
||||
## 五、不做的事
|
||||
|
||||
- 不改写、不删除任何已存消息;不改 `## 判断依据` 的存储和页面折叠显示;不改 BUG-1948 的内部词检查与重写(`consultation-internal-words.ts`、`consultation-internal-word-rewrite.ts`)、`consultation-answer-fact-guard.ts`。
|
||||
- 不改取数工具和证据卡(`consultation-tools.ts`、`consultation-evidence-card.ts`)。
|
||||
- 不处理聊天导出文件(已导出的收不回;再次导出时带不带分隔,归 BUG-1959)。
|
||||
- 不改报告。
|
||||
|
||||
## 六、测试
|
||||
|
||||
新文件 `frontend/tests/consult-stale-history-20261117.test.ts`(合成消息,不用真实对话):
|
||||
|
||||
1. 第二节四条规则各一条命中、各一条不命中;不带版本且无任何证据的旧消息不过期。
|
||||
2. 合盘会话任一侧版本变化即过期。
|
||||
3. 过期回答交给模型的文本:以新说明句开头、不含 `## 判断依据` 及其后的内容、正文其余部分保留;未过期回答原样。存储的消息对象未被修改(深比较)。
|
||||
4. 摘要:覆盖范围内有过期回答时摘要带说明句;没有时不带。
|
||||
5. 页面分隔:交界处一条;只有过期回答时在末尾一条;与 `rectificationReturn` 分隔不重复;旧回答的折叠依据仍可展开(现有 `consult-judgment-basis` 的测试照旧通过)。
|
||||
6. 新回答写入时消息带版本;闲聊快路径也带。
|
||||
7. 提示词含第三节第 3 点的规则;说明句里有「只给你看」的要求。
|
||||
8. 既有测试不删断言、照旧通过:BUG-1251 C7 相关用例(说明句文字变了的断言改成新句子,逐条在 PROGRESS 说明)、`rectification-in-chat` 系列、BUG-1948 的测试。
|
||||
|
||||
人工核对项(写进 PROGRESS,验收时抽查):用合成会话实跑一轮模型(一次即可,控制成本),确认新回答没有复述括号里的说明句,也没有多出解释历史的段落。跑不了就写「未执行」。
|
||||
|
||||
## 七、文档
|
||||
|
||||
- `docs/BUG_HISTORY.md` 新增 BUG-1960,关联 BUG-1251、BUG-1956(只在自己那一节内编辑;不写姓名、出生资料、邮箱、ID、对话原文)。
|
||||
- `CHANGELOG.md` 一行;`docs/tasks/PROGRESS-rect-stale-chat-evidence-20261117.md`。
|
||||
- `docs/research/rect-p0-artifact-checklist-20261116.md` 的「11-17 之后」一节补上聊天这一项做到哪。
|
||||
|
||||
## 验收
|
||||
|
||||
- `PATH=<venv>/bin:$PATH python scripts/run_quality_gate.py --profile quick --skip-frontend-runtime` 通过;
|
||||
- `cd frontend && npx tsc --noEmit` 通过;`npx eslint .` 0 错误;新测试和第六节第 8 条的测试通过;前端全量不新增失败;
|
||||
- diff 不含第五节列出的文件。
|
||||
@@ -11,6 +11,8 @@
|
||||
|
||||
### 用户可见分隔符
|
||||
|
||||
聊天的出生输入依据改过时,沿用生时纠正返回分隔的样式。在最后一条过期回答之后显示「出生时间在这之后改过,上面的回答按之前的时间写成。」若已有返回分隔,同位置只显示原分隔。旧回答正文、折叠的判断依据和取数卡照常显示。
|
||||
|
||||
页面标签标题用带空格的连字符。中文日期、状态和来源用中文逗号,名称并列用顿号,英文并列用逗号。宫位和星座之间使用对应语言的括号。卡片上的日期、地点和计算口径各占一个元素,用已有间距令牌分开,窄屏允许换行。无值时沿用破折号。
|
||||
|
||||
代号与中文释义用括号,如「AK(自我)」「D9(婚姻)」。运期层级沿用「›」,Yogini 运名后的主星用括号。Saham 公式以「白天:」或「夜晚:」开头。
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { loadBillingPanel } from "@/lib/billing-panel-loader";
|
||||
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
|
||||
import type { BirthHistorySubject, ConsultationBirthHistory } from "@/lib/consultation-birth-history";
|
||||
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import type { FormEvent, KeyboardEvent } from "react";
|
||||
import { AccountDialogOverlay, type AccountOverlayModel } from "@/components/account-dialog-overlay";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -358,6 +359,18 @@ export default function Home() {
|
||||
const activeSession = sessions.find((session) => session.id === activeSessionId)
|
||||
?? pendingWarmLandingSession(activeSessionId)
|
||||
?? sessions.find((session) => !isRetiredRectificationSession(session) && sessionMatchesSubject(session, readCurrentSubjectId()));
|
||||
const chatSubjectA = activeSession?.chartProfileId ?? "self";
|
||||
const chatSubjectB = activeSession?.synastryPartnerSubjectId;
|
||||
const chatSessionType = activeSession?.sessionType;
|
||||
const currentBirth = useMemo<ConsultationBirthHistory | undefined>(() => {
|
||||
function birthOf(id: string): BirthHistorySubject | undefined {
|
||||
const subject = id === "self" ? account : chartLibrary.find((record) => record.id === id);
|
||||
return subject?.birthHistory ?? (subject?.birthInputRevision ? { revision: subject.birthInputRevision } : undefined);
|
||||
}
|
||||
if (chatSessionType === "synastry_report") return { pair: true, a: birthOf(chatSubjectA), b: chatSubjectB ? birthOf(chatSubjectB) : undefined };
|
||||
if (chatSessionType === "consultation") return { a: birthOf(chatSubjectA) };
|
||||
return undefined;
|
||||
}, [account, chartLibrary, chatSessionType, chatSubjectA, chatSubjectB]);
|
||||
useReplyRatingsSync(activeSession, setMessageFeedback);
|
||||
const retiredRectificationSession = isRetiredRectificationSession(activeSession);
|
||||
const activeError = requestError && requestError.sessionId === activeSession?.id ? requestError.message : "";
|
||||
@@ -1155,6 +1168,7 @@ export default function Home() {
|
||||
<div className="message-list" aria-busy={isLoading}>
|
||||
<ChatStreamingTranscript
|
||||
messages={activeSession.messages}
|
||||
currentBirth={currentBirth}
|
||||
loading={isLoading}
|
||||
sessionId={activeSession.id}
|
||||
sessionType={activeSession.sessionType}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
resolveAccountBirthTimeApplicationPatch,
|
||||
resolveAppliedAccountBirthTime,
|
||||
} from "@/lib/account-profile-patch";
|
||||
import { birthInputRevision } from "@/lib/birth-input-revision";
|
||||
import { birthInputRevision, consultationBirthSubject } from "@/lib/birth-input-revision";
|
||||
import { readBirthRow } from "@/lib/retired-birth-window";
|
||||
import { chartBirthAfterAccountWrite, resolveServerOwnedChartBirth } from "@/lib/chart-birth-truth";
|
||||
import { scheduleConsultPacketWarm } from "@/lib/consult-packet-warm";
|
||||
@@ -164,6 +164,7 @@ export async function GET() {
|
||||
} = profileRow as typeof profileRow & Partial<Record<"avatar_seed" | "avatar_palette" | "avatar_renderer_version", unknown>>;
|
||||
|
||||
const profile = await readBirthRow(storedProfile, admin, userId, "self");
|
||||
const birthHistory = consultationBirthSubject(profile);
|
||||
let avatar = null;
|
||||
if (selfHosted) {
|
||||
let avatarProfile: Record<string, unknown> = {
|
||||
@@ -230,7 +231,8 @@ export async function GET() {
|
||||
longitude: profile.longitude ?? null,
|
||||
},
|
||||
chartBirth: resolveServerOwnedChartBirth(profile),
|
||||
birthInputRevision: birthInputRevision(profile),
|
||||
birthInputRevision: birthHistory.revision,
|
||||
birthHistory,
|
||||
compatibility,
|
||||
rectification,
|
||||
firstConsultFree: firstConsultFreeFromProfile(profile),
|
||||
|
||||
@@ -8,7 +8,7 @@ import { sortByArchiveOrder } from "@/lib/people-archive-order";
|
||||
import { CHART_SUBJECT_API_SELECT, MAX_SAVED_SUBJECTS } from "@/lib/subject-birth";
|
||||
import { scheduleConsultPacketWarm } from "@/lib/consult-packet-warm";
|
||||
import { createAdminSupabaseClient } from "@/lib/supabase/admin";
|
||||
import { birthInputRevision } from "@/lib/birth-input-revision";
|
||||
import { consultationBirthSubject } from "@/lib/birth-input-revision";
|
||||
import { readBirthRow } from "@/lib/retired-birth-window";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import { isSupabaseConfigurationError } from "@/lib/supabase/config";
|
||||
@@ -38,11 +38,13 @@ function databaseFailure(error: unknown): NextResponse | null {
|
||||
}
|
||||
|
||||
function toClientProfile(row: Record<string, unknown>) {
|
||||
const birthHistory = consultationBirthSubject(row);
|
||||
return {
|
||||
id: row.id,
|
||||
role: "other",
|
||||
profile: libraryProfileFromSubjectRow(row),
|
||||
birthInputRevision: birthInputRevision(row),
|
||||
birthInputRevision: birthHistory.revision,
|
||||
birthHistory,
|
||||
updated_at: row.updated_at,
|
||||
created_at: row.created_at,
|
||||
archive_order: typeof row.archive_order === "number" ? row.archive_order : null,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
runConsultationWorkflow,
|
||||
} from "@/mastra";
|
||||
import { blocksPromptExtraction } from "@/lib/consult-safety";
|
||||
import { consultationBirthFields, publicConsultationBirthFields, type ConsultationBirthHistory } from "@/lib/consultation-birth-history";
|
||||
import { selfSelectedScenarioOpening } from "@/mastra/consultation-workflow";
|
||||
import { consultDomainConcurrency, consultPrepParallelEnabled, modelVersionCacheTtlMs } from "@/lib/consult/prep-flags";
|
||||
import {
|
||||
@@ -440,14 +441,14 @@ export async function POST(request: Request) {
|
||||
|
||||
// Client `history` stays in the request schema for old bundles and is not read.
|
||||
const contextSummary = parseSessionContextSummary(chatSession.context_summary);
|
||||
const historyWindow = consultationHistoryWindow(chatSession.messages, contextSummary, {
|
||||
let currentBirth: ConsultationBirthHistory | undefined;
|
||||
let historyWindow = consultationHistoryWindow(chatSession.messages, contextSummary, {
|
||||
contextWindow: sessionContextWindow,
|
||||
});
|
||||
const storedHistory = historyWindow.tail;
|
||||
const userControlledPrompt = [
|
||||
parsed.data.question,
|
||||
historyWindow.summaryText,
|
||||
...storedHistory.filter((message) => message.role === "user").map((message) => message.text),
|
||||
...historyWindow.tail.filter((message) => message.role === "user").map((message) => message.text),
|
||||
].filter(Boolean).join("\n");
|
||||
if (blocksPromptExtraction(userControlledPrompt)) {
|
||||
return NextResponse.json(
|
||||
@@ -569,6 +570,7 @@ export async function POST(request: Request) {
|
||||
model: sessionModel,
|
||||
question: visibleQuestion,
|
||||
history: chatSession.messages,
|
||||
currentBirth,
|
||||
name,
|
||||
signal: request.signal,
|
||||
onObservation(observation) {
|
||||
@@ -627,15 +629,22 @@ export async function POST(request: Request) {
|
||||
async loadProfile(profileUserId) {
|
||||
const { data, error } = await supabase
|
||||
.from("profiles")
|
||||
.select("name,birth_date,active_birth_date,active_birth_timezone_offset,active_birth_provenance,reported_birth_time,active_birth_time,birth_time_source,birth_time_period,declared_window_start,declared_window_end,birth_time_status,country_code,province_code,city_code,district_code,latitude,longitude,timezone_offset,birth_place_label,birth_place_type,birth_place_provider,birth_place_provider_id,timezone_id,timezone_source,ayanamsa,gender,uncertainty_before_minutes,uncertainty_after_minutes,birth_time_uncertainty_known,birth_time_clue,birth_time_shichen")
|
||||
.select("name,birth_date,active_birth_date,active_birth_timezone_offset,active_birth_provenance,reported_birth_time,active_birth_time,birth_time_source,birth_time_period,declared_window_start,declared_window_end,birth_time_status,country_code,province_code,city_code,district_code,latitude,longitude,timezone_offset,birth_place_label,birth_place_type,birth_place_provider,birth_place_provider_id,timezone_id,timezone_source,ayanamsa,gender,uncertainty_before_minutes,uncertainty_after_minutes,birth_time_uncertainty_known,birth_time_clue,birth_time_shichen,birth_time")
|
||||
.eq("id", profileUserId)
|
||||
.single();
|
||||
if (error || !data) throw new ConsultationProfileTruthError("profile_unavailable");
|
||||
return readBirthRow(data, accounting, profileUserId, "self");
|
||||
},
|
||||
loadCandidateRange: (profileUserId) => loadReportCandidateRange(accounting, { userId: profileUserId }),
|
||||
beforeReserve: async ({ consultationMode, serverChart, declaredWindow, subject }) => {
|
||||
beforeReserve: async ({ consultationMode, serverChart, declaredWindow, subject, birthHistory }) => {
|
||||
if (serverChart && consultationMode !== "declared_birth_window") prewarmConsultPacketForTurn(serverChart.toolInput);
|
||||
if (birthHistory) {
|
||||
currentBirth = { a: birthHistory };
|
||||
historyWindow = consultationHistoryWindow(chatSession.messages, contextSummary, {
|
||||
contextWindow: sessionContextWindow,
|
||||
currentBirth,
|
||||
});
|
||||
}
|
||||
prepPhases.push({
|
||||
phase: "prep.subject",
|
||||
durationMs: Math.max(0, Date.now() - prepareStarted),
|
||||
@@ -774,6 +783,9 @@ export async function POST(request: Request) {
|
||||
return consultSettlement.cancel();
|
||||
}
|
||||
|
||||
const storedHistory = historyWindow.tail;
|
||||
const birthFields = consultationBirthFields(currentBirth);
|
||||
const publicBirthFields = publicConsultationBirthFields(request.headers, birthFields);
|
||||
const appended = await consultSettlement.appendQuestion();
|
||||
if (appended) return appended;
|
||||
|
||||
@@ -804,8 +816,9 @@ export async function POST(request: Request) {
|
||||
return streamSmalltalkResponse({
|
||||
requestId,
|
||||
reply: turn.reply,
|
||||
birthFields: publicBirthFields,
|
||||
async complete() {
|
||||
await consultSettlement.completeSmalltalk(turn.reply);
|
||||
await consultSettlement.completeSmalltalk(turn.reply, birthFields);
|
||||
},
|
||||
async onError() {
|
||||
await cancel();
|
||||
@@ -841,6 +854,7 @@ export async function POST(request: Request) {
|
||||
messages: sessionRow.messages,
|
||||
summary: sessionRow.context_summary,
|
||||
contextWindow: sessionContextWindow,
|
||||
currentBirth,
|
||||
generateText: (prompt, signal) => generateSessionContextSummaryText(summaryModel, prompt, signal),
|
||||
update: async (summary, seenUpdatedAt) => {
|
||||
let query = supabase.from("chat_sessions")
|
||||
@@ -883,7 +897,7 @@ export async function POST(request: Request) {
|
||||
p_user_id: userId,
|
||||
p_request_id: requestId,
|
||||
p_session_id: sessionId,
|
||||
p_response_message: { role: "assistant", text: MODERATION_OUTPUT_REPLACED_COPY, responseKind: "moderated" },
|
||||
p_response_message: { role: "assistant", text: MODERATION_OUTPUT_REPLACED_COPY, responseKind: "moderated", ...birthFields },
|
||||
p_actual_usage: actualUsage,
|
||||
});
|
||||
const result = consultationCompletionSchema.safeParse(first(data ?? []));
|
||||
@@ -926,6 +940,7 @@ export async function POST(request: Request) {
|
||||
const responseMessage = {
|
||||
role: "assistant" as const,
|
||||
text: reply.text,
|
||||
...birthFields,
|
||||
...(followUps.length > 0 ? { suggestions: followUps } : {}),
|
||||
...(persistedThinking ? { thinkingText: persistedThinking } : {}),
|
||||
...(thinkingSections?.length ? { thinkingSections } : {}),
|
||||
@@ -975,7 +990,7 @@ export async function POST(request: Request) {
|
||||
if (!entry) throw new Error("direct_entry_missing");
|
||||
try {
|
||||
const actualUsage = await usagePayload(usage);
|
||||
const responseMessage = { role: "assistant" as const, text: entry.sentence, responseKind: "smalltalk" as const };
|
||||
const responseMessage = { role: "assistant" as const, text: entry.sentence, responseKind: "smalltalk" as const, ...birthFields };
|
||||
const completion = await retryDetachedSettlement(async () => {
|
||||
const { data, error } = await accounting.rpc("complete_consultation_free", {
|
||||
p_user_id: userId,
|
||||
@@ -1410,6 +1425,7 @@ export async function POST(request: Request) {
|
||||
pass4Mode: generalDailyContext ? "general_no_birth_time" : consultationMode,
|
||||
toolStatus: () => "ready",
|
||||
receipt: executionReceipt,
|
||||
birthFields: publicBirthFields,
|
||||
headers: { "x-jyotish-birth-time-mode": consultationMode },
|
||||
onFirstActivity: markFirstActivity,
|
||||
onFirstOutput: markFirstText,
|
||||
@@ -1546,6 +1562,7 @@ export async function POST(request: Request) {
|
||||
pass4Mode: consultationMode,
|
||||
toolStatus: () => workflowStatus(state.workflowReceipt?.status),
|
||||
receipt: executionReceipt,
|
||||
birthFields: publicBirthFields,
|
||||
headers: { "x-jyotish-birth-time-mode": consultationMode },
|
||||
onFirstActivity: markFirstActivity,
|
||||
onFirstOutput: markFirstText,
|
||||
@@ -1720,6 +1737,7 @@ export async function POST(request: Request) {
|
||||
continueAfterDisconnect: true,
|
||||
toolStatus: () => workflowStatus(state.workflowReceipt?.status),
|
||||
receipt: executionReceipt,
|
||||
birthFields: publicBirthFields,
|
||||
headers: { "x-jyotish-birth-time-mode": consultationMode },
|
||||
onFirstActivity: markFirstActivity,
|
||||
onFirstOutput: markFirstText,
|
||||
@@ -1803,6 +1821,7 @@ export async function POST(request: Request) {
|
||||
"x-jyotish-precise-timing": workflowReceipt.preciseTiming,
|
||||
"x-jyotish-missing-layers": workflowReceipt.missingLayers.join(","),
|
||||
"x-jyotish-birth-time-mode": consultationMode,
|
||||
...(publicBirthFields.birthInputRevision ? { "x-jyotish-birth-input-revision": publicBirthFields.birthInputRevision } : {}),
|
||||
},
|
||||
onComplete: (rawTransformedText) => settle(() => completeResponse(
|
||||
rawTransformedText,
|
||||
@@ -1921,6 +1940,7 @@ export async function POST(request: Request) {
|
||||
"x-jyotish-precise-timing": workflowReceipt.preciseTiming,
|
||||
"x-jyotish-missing-layers": workflowReceipt.missingLayers,
|
||||
"x-jyotish-birth-time-mode": consultationMode,
|
||||
...(publicBirthFields.birthInputRevision ? { "x-jyotish-birth-input-revision": publicBirthFields.birthInputRevision } : {}),
|
||||
},
|
||||
onComplete: (rawTransformedText) => settle(() => completeResponse(
|
||||
rawTransformedText,
|
||||
|
||||
@@ -26,13 +26,14 @@ import {
|
||||
noteUnsplitListRender,
|
||||
} from "@/lib/home-streaming-render-probe";
|
||||
import { AnswerChartLinkScope } from "@/components/answer-chart-link-scope";
|
||||
import { memo, useEffect, useState, type MutableRefObject } from "react";
|
||||
import { memo, useEffect, useMemo, useState, type MutableRefObject } from "react";
|
||||
import {
|
||||
BeforeBirthTimeChangeLabel,
|
||||
RectificationOfferCard,
|
||||
RectificationReturnDivider,
|
||||
} from "@/components/rectification-in-chat-cards";
|
||||
import { lastBirthTimeChangeIndex } from "@/lib/rectification-in-chat";
|
||||
import { consultationBirthDividerIndices, type ConsultationBirthHistory } from "@/lib/consultation-birth-history";
|
||||
|
||||
export type ChatTranscriptActions = Readonly<{
|
||||
onFeedback: (feedbackKey: string, requested: ChatMessageFeedback) => void;
|
||||
@@ -45,6 +46,7 @@ export type ChatTranscriptActions = Readonly<{
|
||||
|
||||
export type ChatTranscriptProps = Readonly<{
|
||||
messages: readonly ChatMessage[];
|
||||
currentBirth?: ConsultationBirthHistory;
|
||||
loading: boolean;
|
||||
streamingText: string;
|
||||
streamingActivity?: AgentActivityView;
|
||||
@@ -66,6 +68,7 @@ type MessageEntryProps = Readonly<{
|
||||
message: ChatMessageView;
|
||||
views: readonly ChatMessageView[];
|
||||
index: number;
|
||||
birthDividerAfter?: boolean;
|
||||
sessionId: string;
|
||||
sessionType: "consultation" | "birth_time_rectification" | "synastry_report";
|
||||
theme?: ConsultationDomain;
|
||||
@@ -86,6 +89,7 @@ function MessageEntry({
|
||||
message,
|
||||
views,
|
||||
index,
|
||||
birthDividerAfter,
|
||||
sessionId,
|
||||
sessionType,
|
||||
theme,
|
||||
@@ -146,6 +150,7 @@ function MessageEntry({
|
||||
const beforeBirthTimeChange = message.role === "assistant" && lastBirthTimeChangeIndex(views) > index;
|
||||
const offer = sessionType === "consultation" && message.state === "settled" ? message.rectificationOffer : undefined;
|
||||
return (
|
||||
<>
|
||||
<div className={`message-entry${latestAnswer ? " is-latest-answer" : ""}`}>
|
||||
{beforeBirthTimeChange ? <BeforeBirthTimeChangeLabel /> : null}
|
||||
<ChatMessageRow message={message} stepsInFooter={stepsInFooter} />
|
||||
@@ -183,6 +188,10 @@ function MessageEntry({
|
||||
onSelect={(question) => actionsRef.current.onFollowUp(question)}
|
||||
/>
|
||||
</div>
|
||||
{birthDividerAfter ? (
|
||||
<div className="message-entry message-entry--divider"><RectificationReturnDivider /></div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -199,6 +208,7 @@ const HistoryMessageEntry = memo(function HistoryMessageEntry(props: MessageEntr
|
||||
export const SettledMessageList = memo(function SettledMessageList({
|
||||
messages,
|
||||
excludeLatestAssistant = false,
|
||||
birthDividers,
|
||||
sessionId,
|
||||
sessionType,
|
||||
theme,
|
||||
@@ -210,6 +220,7 @@ export const SettledMessageList = memo(function SettledMessageList({
|
||||
actionsRef,
|
||||
}: Omit<ChatTranscriptProps, "streamingText" | "streamingActivity" | "streamingThinking" | "streamingSections" | "streamingTimeline"> & {
|
||||
excludeLatestAssistant?: boolean;
|
||||
birthDividers?: readonly number[];
|
||||
}) {
|
||||
noteSettledListRender();
|
||||
const views = settledChatMessageViews(messages);
|
||||
@@ -222,6 +233,7 @@ export const SettledMessageList = memo(function SettledMessageList({
|
||||
message={message}
|
||||
views={views}
|
||||
index={index}
|
||||
birthDividerAfter={birthDividers?.includes(index)}
|
||||
sessionId={sessionId}
|
||||
sessionType={sessionType}
|
||||
theme={theme}
|
||||
@@ -247,7 +259,7 @@ export const LatestAssistantEntry = memo(function LatestAssistantEntry(props: Me
|
||||
});
|
||||
|
||||
export const ChatTranscript = memo(function ChatTranscript({
|
||||
messages,
|
||||
messages, currentBirth,
|
||||
loading,
|
||||
streamingText,
|
||||
streamingActivity,
|
||||
@@ -264,6 +276,7 @@ export const ChatTranscript = memo(function ChatTranscript({
|
||||
productEntrypointsDisabled,
|
||||
actionsRef,
|
||||
}: ChatTranscriptProps) {
|
||||
const birthDividers = useMemo(() => consultationBirthDividerIndices(messages, currentBirth), [messages, currentBirth]);
|
||||
const latest = latestAssistantView(
|
||||
messages,
|
||||
loading,
|
||||
@@ -279,6 +292,7 @@ export const ChatTranscript = memo(function ChatTranscript({
|
||||
<AnswerChartLinkScope sessionId={sessionId} enabled={sessionType === "consultation"}>
|
||||
<SettledMessageList
|
||||
messages={messages}
|
||||
birthDividers={birthDividers}
|
||||
excludeLatestAssistant
|
||||
loading={loading}
|
||||
sessionId={sessionId}
|
||||
@@ -296,6 +310,7 @@ export const ChatTranscript = memo(function ChatTranscript({
|
||||
message={latest.view}
|
||||
views={latest.views}
|
||||
index={latest.views.length - 1}
|
||||
birthDividerAfter={birthDividers.includes(latest.views.length - 1)}
|
||||
sessionId={sessionId}
|
||||
sessionType={sessionType}
|
||||
theme={theme}
|
||||
@@ -312,7 +327,7 @@ export const ChatTranscript = memo(function ChatTranscript({
|
||||
});
|
||||
|
||||
export function UnsplitChatTranscript({
|
||||
messages,
|
||||
messages, currentBirth,
|
||||
loading,
|
||||
streamingText,
|
||||
streamingActivity,
|
||||
@@ -330,6 +345,7 @@ export function UnsplitChatTranscript({
|
||||
actionsRef,
|
||||
}: ChatTranscriptProps) {
|
||||
noteUnsplitListRender();
|
||||
const birthDividers = useMemo(() => consultationBirthDividerIndices(messages, currentBirth), [messages, currentBirth]);
|
||||
const views = chatMessageViews(
|
||||
messages,
|
||||
loading,
|
||||
@@ -351,6 +367,7 @@ export function UnsplitChatTranscript({
|
||||
message={message}
|
||||
views={views}
|
||||
index={index}
|
||||
birthDividerAfter={birthDividers.includes(index)}
|
||||
sessionId={sessionId}
|
||||
sessionType={sessionType}
|
||||
theme={theme}
|
||||
|
||||
@@ -48,17 +48,21 @@ export function RectificationOfferCard({
|
||||
* new time is a button and an ordinary consultation turn: nothing is sent, and
|
||||
* nothing is charged, until it is clicked.
|
||||
*/
|
||||
export function RectificationReturnDivider({
|
||||
record,
|
||||
disabled,
|
||||
onRevisit,
|
||||
}: Readonly<{ record: RectificationReturnRecord; disabled: boolean; onRevisit: (question: string) => void }>) {
|
||||
type RectificationDividerProps = Readonly<
|
||||
{ record: RectificationReturnRecord; disabled: boolean; onRevisit: (question: string) => void }
|
||||
| { record?: undefined }
|
||||
>;
|
||||
|
||||
export function RectificationReturnDivider(props: RectificationDividerProps) {
|
||||
const record = props.record;
|
||||
return (
|
||||
<div className="rectification-return-divider" role="note">
|
||||
<p className="rectification-return-divider__line">{rectificationReturnDividerText(record)}</p>
|
||||
{record.adopted ? (
|
||||
<Button type="button" variant="outline" size="sm" disabled={disabled} onClick={() => onRevisit(record.sourceQuestion)}>
|
||||
{rectificationRevisitLabel(record.sourceQuestion)}
|
||||
<p className="rectification-return-divider__line">{record
|
||||
? rectificationReturnDividerText(record)
|
||||
: "出生时间在这之后改过,上面的回答按之前的时间写成。"}</p>
|
||||
{props.record?.adopted ? (
|
||||
<Button type="button" variant="outline" size="sm" disabled={props.disabled} onClick={() => props.onRevisit(props.record.sourceQuestion)}>
|
||||
{rectificationRevisitLabel(props.record.sourceQuestion)}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { CONSULTATION_BIRTH_HISTORY_HEADER, readStoredConsultationBirth } from "@/lib/consultation-birth-history";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import type { Dispatch, MutableRefObject, RefObject, SetStateAction } from "react";
|
||||
|
||||
@@ -895,7 +897,7 @@ export function useConsultationRun(params: ConsultationRunParams) {
|
||||
try {
|
||||
const response = await fetch("/api/consult", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
headers: { "content-type": "application/json", [CONSULTATION_BIRTH_HISTORY_HEADER]: "1" },
|
||||
body: JSON.stringify(synastryTurn ? {
|
||||
requestId,
|
||||
sessionId: currentSession.id,
|
||||
@@ -956,6 +958,7 @@ export function useConsultationRun(params: ConsultationRunParams) {
|
||||
// Whether the reply was smalltalk is only known once the server has
|
||||
// classified the turn, which now happens inside the stream (BUG-1074):
|
||||
// the run.completed event says so; there is no response header for it.
|
||||
let birthFields = readStoredConsultationBirth({ birthInputRevision: response.headers.get("x-jyotish-birth-input-revision") });
|
||||
let techniqueTruth = response.headers.get("x-jyotish-technique-truth") ?? "unknown";
|
||||
let workflowReceipt: AgentExecutionReceipt["workflow"] = {
|
||||
route: response.headers.get("x-jyotish-workflow-route") ?? "unknown",
|
||||
@@ -1048,6 +1051,7 @@ export function useConsultationRun(params: ConsultationRunParams) {
|
||||
}
|
||||
if (event.type === "run.completed") {
|
||||
runCompleted = true;
|
||||
birthFields = { ...birthFields, ...readStoredConsultationBirth(event) };
|
||||
rectificationOffer = event.rectificationOffer;
|
||||
followUps = event.suggestions ?? [];
|
||||
rectificationDirectOpen = event.rectificationDirectOpen;
|
||||
@@ -1152,6 +1156,7 @@ export function useConsultationRun(params: ConsultationRunParams) {
|
||||
messages: [...userSession.messages, {
|
||||
role: "assistant",
|
||||
text: reply.text,
|
||||
...birthFields,
|
||||
...(responseKind === "smalltalk" ? {
|
||||
responseKind,
|
||||
...(rectificationOffer ? { rectificationOffer } : {}),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { resolveAyanamsa } from "./ayanamsa.ts";
|
||||
import { effectiveBirthDate } from "./effective-birth-date.ts";
|
||||
import { asRecord } from "./guards.ts";
|
||||
import { declaredBirthWindow } from "./lagna-precheck.ts";
|
||||
import type { BirthHistorySubject } from "./consultation-birth-history.ts";
|
||||
|
||||
// The chart and marriage fingerprints still identify reusable numeric calculations.
|
||||
// This revision identifies the evidence behind conclusions, status, ranges and permissions.
|
||||
@@ -63,6 +64,16 @@ export function birthInputRevision(projectedRow: Readonly<Record<string, unknown
|
||||
return createHash("sha256").update(JSON.stringify(parts)).digest("hex");
|
||||
}
|
||||
|
||||
export function consultationBirthSubject(row: Readonly<Record<string, unknown>>): BirthHistorySubject {
|
||||
const provenance = asRecord(row.active_birth_provenance);
|
||||
const adoptedAt = text(provenance?.adopted_at);
|
||||
return {
|
||||
revision: birthInputRevision(row),
|
||||
...(provenance?.retired_reason === "BUG-1890" ? { retired: true as const } : {}),
|
||||
...(adoptedAt && Number.isFinite(Date.parse(adoptedAt)) ? { adoptedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export type BirthInputState = "current" | "changed" | "unknown";
|
||||
export type BirthInputPair = Readonly<{ a?: string; b?: string }>;
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ export function activityElapsedLabel(startedAt: number, now: number): string | n
|
||||
return `已用时 ${Math.floor(elapsedMs / 1000)} 秒`;
|
||||
}
|
||||
|
||||
export type ChatMessage = {
|
||||
export type ChatMessage = import("./consultation-birth-history.ts").StoredConsultationBirth & {
|
||||
readonly role: "user" | "assistant";
|
||||
readonly text: string;
|
||||
readonly responseKind?: "smalltalk";
|
||||
|
||||
@@ -213,14 +213,14 @@ export function createConsultSettlement(ctx: ConsultSettlementContext) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function completeSmalltalk(reply: string): Promise<void> {
|
||||
async function completeSmalltalk(reply: string, birthFields: import("../consultation-birth-history.ts").ConsultationBirthFields = {}): Promise<void> {
|
||||
const actualUsage = await usagePayload(Promise.resolve({}));
|
||||
const completion = await retryDetachedSettlement(async () => {
|
||||
const { data, error } = await accounting.rpc("complete_consultation_free", {
|
||||
p_user_id: userId,
|
||||
p_request_id: requestId,
|
||||
p_session_id: sessionId,
|
||||
p_response_message: { role: "assistant", text: reply, responseKind: "smalltalk" },
|
||||
p_response_message: { role: "assistant", text: reply, responseKind: "smalltalk", ...birthFields },
|
||||
p_actual_usage: actualUsage,
|
||||
});
|
||||
const result = consultationCompletionSchema.safeParse(first(data ?? []));
|
||||
|
||||
@@ -196,8 +196,11 @@ const rectificationDirectOpenSchema = z.object({
|
||||
resumeSessionId: z.string().uuid().optional(),
|
||||
}).strict();
|
||||
|
||||
const birthInputRevisionSchema = z.string().regex(/^[0-9a-f]{64}$/);
|
||||
const runCompletedSchema = z.object({
|
||||
type: z.literal("run.completed"),
|
||||
birthInputRevision: birthInputRevisionSchema.optional(),
|
||||
birthInputRevisions: z.object({ a: birthInputRevisionSchema.optional(), b: birthInputRevisionSchema.optional() }).strict().optional(),
|
||||
receipt: agentExecutionReceiptSchema.optional(),
|
||||
responseKind: z.literal("smalltalk").optional(),
|
||||
/** The answer offered birth-time rectification (BUG-1248); the card hangs under it. */
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { asRecord } from "./guards.ts";
|
||||
import { isRectificationReturnMessage, lastBirthTimeChangeIndex } from "./rectification-in-chat.ts";
|
||||
|
||||
export const CONSULTATION_BIRTH_HISTORY_HEADER = "x-jyotish-birth-history";
|
||||
|
||||
export type BirthHistorySubject = Readonly<{ revision: string; retired?: true; adoptedAt?: string }>;
|
||||
export type ConsultationBirthHistory = Readonly<{ a?: BirthHistorySubject; b?: BirthHistorySubject; pair?: true }>;
|
||||
export type ConsultationBirthFields = Readonly<{ birthInputRevision?: string; birthInputRevisions?: Readonly<{ a?: string; b?: string }> }>;
|
||||
export type StoredConsultationBirth = ConsultationBirthFields & Readonly<{
|
||||
createdAt?: number;
|
||||
}>;
|
||||
|
||||
function revision(value: unknown): string | undefined {
|
||||
return typeof value === "string" && /^[0-9a-f]{64}$/.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function messageTime(value: unknown): number | undefined {
|
||||
const time = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : NaN;
|
||||
return Number.isFinite(time) && time > 0 ? time : undefined;
|
||||
}
|
||||
|
||||
export function readStoredConsultationBirth(message: Record<string, unknown>): StoredConsultationBirth {
|
||||
const single = revision(message.birthInputRevision);
|
||||
const pair = asRecord(message.birthInputRevisions);
|
||||
const a = revision(pair?.a);
|
||||
const b = revision(pair?.b);
|
||||
const createdAt = messageTime(message.createdAt ?? message.created_at ?? message.timestamp);
|
||||
return {
|
||||
...(single ? { birthInputRevision: single } : {}),
|
||||
...(a || b ? { birthInputRevisions: { a, b } } : {}),
|
||||
...(createdAt === undefined ? {} : { createdAt }),
|
||||
};
|
||||
}
|
||||
|
||||
export function consultationBirthFields(current?: ConsultationBirthHistory): ConsultationBirthFields {
|
||||
const a = current?.a?.revision;
|
||||
const b = current?.b?.revision;
|
||||
if (current?.pair) return a || b ? { birthInputRevisions: { a, b } } : {};
|
||||
return a ? { birthInputRevision: a } : {};
|
||||
}
|
||||
|
||||
export function publicConsultationBirthFields(headers: Headers, fields: ConsultationBirthFields): ConsultationBirthFields {
|
||||
return headers.get(CONSULTATION_BIRTH_HISTORY_HEADER) === "1" ? fields : {};
|
||||
}
|
||||
|
||||
export function staleConsultationAnswerIndices(
|
||||
messages: readonly unknown[], current?: ConsultationBirthHistory,
|
||||
): ReadonlySet<number> {
|
||||
const changedAt = lastBirthTimeChangeIndex(messages);
|
||||
const stale = new Set<number>();
|
||||
messages.forEach((message, index) => {
|
||||
const row = asRecord(message);
|
||||
if (row?.role !== "assistant" || typeof row.text !== "string" || !row.text || isRectificationReturnMessage(row)) return;
|
||||
if (index < changedAt) {
|
||||
stale.add(index);
|
||||
return;
|
||||
}
|
||||
if (!current) return;
|
||||
const { birthInputRevision, birthInputRevisions, createdAt } = readStoredConsultationBirth(row);
|
||||
if (birthInputRevision || birthInputRevisions) {
|
||||
const changed = current.pair
|
||||
? [current.a?.revision && birthInputRevisions?.a && current.a.revision !== birthInputRevisions.a,
|
||||
current.b?.revision && birthInputRevisions?.b && current.b.revision !== birthInputRevisions.b].some(Boolean)
|
||||
: current.a?.revision && birthInputRevision && current.a.revision !== birthInputRevision;
|
||||
if (changed) stale.add(index);
|
||||
return;
|
||||
}
|
||||
if ([current.a, current.b].some((subject) => {
|
||||
const adoptedAt = messageTime(subject?.adoptedAt);
|
||||
return subject?.retired || (createdAt !== undefined && adoptedAt !== undefined && createdAt < adoptedAt);
|
||||
})) stale.add(index);
|
||||
});
|
||||
return stale;
|
||||
}
|
||||
|
||||
export function consultationBirthDividerIndices(
|
||||
messages: readonly unknown[], current?: ConsultationBirthHistory,
|
||||
): readonly number[] {
|
||||
if (!current) return [];
|
||||
const stale = staleConsultationAnswerIndices(messages, current);
|
||||
const dividers: number[] = [];
|
||||
let pending: number | undefined;
|
||||
messages.forEach((message, index) => {
|
||||
const row = asRecord(message);
|
||||
if (isRectificationReturnMessage(row)) pending = undefined;
|
||||
else if (row?.role === "assistant" && typeof row.text === "string" && row.text) {
|
||||
if (stale.has(index)) pending = index;
|
||||
else if (pending !== undefined) {
|
||||
dividers.push(pending);
|
||||
pending = undefined;
|
||||
}
|
||||
}
|
||||
});
|
||||
if (pending !== undefined) dividers.push(pending);
|
||||
return dividers;
|
||||
}
|
||||
@@ -145,7 +145,11 @@ export type DeclaredBirthWindowConsultation = Readonly<{
|
||||
}>;
|
||||
}>;
|
||||
|
||||
import { consultationBirthSubject } from "./birth-input-revision.ts";
|
||||
import type { BirthHistorySubject } from "./consultation-birth-history.ts";
|
||||
|
||||
type ConsultationPreReserveContext = Readonly<{
|
||||
birthHistory?: BirthHistorySubject;
|
||||
consultationMode: ConsultationBirthTimeMode;
|
||||
serverChart: ServerChartConsultation | null;
|
||||
declaredWindow: DeclaredBirthWindowConsultation | null;
|
||||
@@ -586,7 +590,8 @@ export async function prepareConsultationRoute<Reservation, GuardResult>(
|
||||
}
|
||||
|
||||
const storedProfile = record(profile);
|
||||
if (storedProfile) profile = birthRowForReading(storedProfile);
|
||||
const projected = storedProfile ? birthRowForReading(storedProfile) : null;
|
||||
if (projected) profile = projected;
|
||||
const consultationMode = reconcileConsultationMode(input.mode, profile);
|
||||
let serverChart: ServerChartConsultation | null = null;
|
||||
let declaredWindow: DeclaredBirthWindowConsultation | null = null;
|
||||
@@ -664,6 +669,7 @@ export async function prepareConsultationRoute<Reservation, GuardResult>(
|
||||
}
|
||||
const preReserveResult = input.beforeReserve
|
||||
? await input.beforeReserve({
|
||||
...(projected ? { birthHistory: consultationBirthSubject(projected) } : {}),
|
||||
consultationMode,
|
||||
serverChart,
|
||||
declaredWindow,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { BIRTH_TIME_CHANGED_HISTORY_NOTE, isRectificationReturnMessage, lastBirthTimeChangeIndex } from "./rectification-in-chat.ts";
|
||||
import { splitJudgmentBasis } from "./consult-judgment-basis.ts";
|
||||
import { staleConsultationAnswerIndices, type ConsultationBirthHistory } from "./consultation-birth-history.ts";
|
||||
|
||||
export const CONSULTATION_HISTORY_LIMIT = 12;
|
||||
export const CONSULTATION_HISTORY_MESSAGE_CHARS = 12_000;
|
||||
@@ -42,6 +44,7 @@ type StoredTurn = Readonly<{
|
||||
text: string;
|
||||
requestId: string | null;
|
||||
responseKind?: "smalltalk";
|
||||
staleBirthEvidence?: true;
|
||||
}>;
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
@@ -106,13 +109,13 @@ export function clipConsultationHistoryText(text: string): string {
|
||||
|
||||
export function storedConsultationTurns(
|
||||
messages: unknown,
|
||||
options: { excludeRequestId?: string } = {},
|
||||
options: { excludeRequestId?: string; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): StoredTurn[] {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
const rows: StoredTurn[] = [];
|
||||
// C7 (BUG-1251): answers written before the birth time changed are read
|
||||
// with a note, and the return divider itself is never a model turn.
|
||||
const changedAt = lastBirthTimeChangeIndex(messages);
|
||||
const stale = staleConsultationAnswerIndices(messages, options.currentBirth);
|
||||
messages.forEach((message, index) => {
|
||||
if (!message || typeof message !== "object") return;
|
||||
if (isRectificationReturnMessage(message)) return;
|
||||
@@ -123,9 +126,8 @@ export function storedConsultationTurns(
|
||||
rows.push({
|
||||
index,
|
||||
role: stored.role,
|
||||
text: stored.role === "assistant" && index < changedAt
|
||||
? `${BIRTH_TIME_CHANGED_HISTORY_NOTE}\n${stored.text}`
|
||||
: stored.text,
|
||||
text: stale.has(index) ? `${BIRTH_TIME_CHANGED_HISTORY_NOTE}\n${splitJudgmentBasis(stored.text).body}` : stored.text,
|
||||
...(stale.has(index) ? { staleBirthEvidence: true as const } : {}),
|
||||
requestId: typeof stored.requestId === "string" ? stored.requestId : null,
|
||||
...(stored.responseKind === "smalltalk" ? { responseKind: "smalltalk" as const } : {}),
|
||||
});
|
||||
@@ -160,9 +162,10 @@ export function consultationHistoryWindow(
|
||||
contextWindow?: number | null;
|
||||
excludeRequestId?: string;
|
||||
overflow?: boolean;
|
||||
currentBirth?: ConsultationBirthHistory;
|
||||
} = {},
|
||||
): ConsultationHistoryWindow {
|
||||
const turns = storedConsultationTurns(messages, { excludeRequestId: options.excludeRequestId });
|
||||
const turns = storedConsultationTurns(messages, options);
|
||||
const afterSummary = turnsAfterSummary(turns, summary);
|
||||
const selected = options.overflow ? lastConsultationPair(afterSummary) : afterSummary;
|
||||
const clipped = selected.map((turn) => ({
|
||||
@@ -181,7 +184,8 @@ export function consultationHistoryWindow(
|
||||
// The summary only covers turns up to its index; when the birth time changed
|
||||
// after that, its conclusions came from the earlier time too (C7).
|
||||
const summaryBeforeChange = summary && Array.isArray(messages)
|
||||
&& summary.throughMessageIndex < lastBirthTimeChangeIndex(messages);
|
||||
&& (summary.throughMessageIndex < lastBirthTimeChangeIndex(messages)
|
||||
|| turns.some((turn) => turn.staleBirthEvidence && turn.index <= summary.throughMessageIndex));
|
||||
return {
|
||||
tail: kept,
|
||||
summaryText: summaryText && summaryBeforeChange ? `${BIRTH_TIME_CHANGED_HISTORY_NOTE}\n${summaryText}` : summaryText,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { noopLogger } from "@mastra/core/logger";
|
||||
import { z } from "zod";
|
||||
import { agentGenerationSettings, promptCacheUsage } from "./agent-generation-settings.ts";
|
||||
import { storedConsultationTurns } from "./consultation-session-history.ts";
|
||||
import type { ConsultationBirthHistory } from "./consultation-birth-history.ts";
|
||||
import type { ResolvedLanguageModel } from "../mastra/model.ts";
|
||||
|
||||
export const SMALLTALK_TIMEOUT_MS = 3_000;
|
||||
@@ -31,8 +32,8 @@ reply 只用一句简体中文白话,最多20字,不以句号结尾;称你
|
||||
只输出符合 schema 的 JSON,不解释分类过程。`;
|
||||
|
||||
/** Last *complete* adjacent pair, not last two rows or a context summary. */
|
||||
export function smalltalkHistoryPair(messages: unknown) {
|
||||
const rows = storedConsultationTurns(messages);
|
||||
export function smalltalkHistoryPair(messages: unknown, currentBirth?: ConsultationBirthHistory) {
|
||||
const rows = storedConsultationTurns(messages, { currentBirth });
|
||||
for (let index = rows.length - 1; index > 0; index -= 1) {
|
||||
const assistant = rows[index]!;
|
||||
const user = rows[index - 1]!;
|
||||
@@ -49,6 +50,7 @@ export async function classifyConsultationTurn(input: {
|
||||
model: ResolvedLanguageModel;
|
||||
question: string;
|
||||
history: unknown;
|
||||
currentBirth?: ConsultationBirthHistory;
|
||||
name?: string;
|
||||
signal?: AbortSignal;
|
||||
onObservation?: (observation: SmalltalkObservation) => void;
|
||||
@@ -101,7 +103,7 @@ export async function classifyConsultationTurn(input: {
|
||||
if (controller.signal.aborted) throw new Error("classification_aborted");
|
||||
const pending = generate(JSON.stringify({
|
||||
question: input.question,
|
||||
history: smalltalkHistoryPair(input.history),
|
||||
history: smalltalkHistoryPair(input.history, input.currentBirth),
|
||||
name: input.name ?? "",
|
||||
}), controller.signal).then((result) => {
|
||||
// Some providers ignore abort. Never delay fail-open; still observe a late bill.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readStoredConsultationBirth } from "@/lib/consultation-birth-history";
|
||||
import { parseRectificationOfferRecord, parseRectificationReturnRecord } from "@/lib/rectification-in-chat";
|
||||
import { BOOT_CHART_PROFILES_PATH, BOOT_MODELS_PATH, BOOT_READ_INIT, takeBootSessionDetailRead, withBootFallback } from "@/lib/boot-early-reads";
|
||||
import { writeChatSession } from "@/lib/chat-session-write-contract";
|
||||
@@ -171,6 +172,7 @@ export function normalizeChartLibraryApiRecord(record: ChartLibraryApiRecord): C
|
||||
role: record.role,
|
||||
profile: { ...emptyProfile, ...record.profile, chartRelationship: relationship },
|
||||
...(record.birthInputRevision ? { birthInputRevision: record.birthInputRevision } : {}),
|
||||
...(record.birthHistory ? { birthHistory: record.birthHistory } : {}),
|
||||
relationship,
|
||||
updatedAt: Date.parse(record.updated_at || "") || timestamp(),
|
||||
};
|
||||
@@ -284,6 +286,7 @@ export function readSessions(value: unknown, catalog: PublicLanguageModelCatalog
|
||||
return [{
|
||||
role: stored.role,
|
||||
text: stored.text.slice(0, 12000),
|
||||
...readStoredConsultationBirth(stored),
|
||||
...(stored.role === "assistant" && stored.responseKind === "smalltalk" ? { responseKind: "smalltalk" as const } : {}),
|
||||
...(thinkingText ? { thinkingText } : {}),
|
||||
...(thinkingSections.length ? { thinkingSections } : {}),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { BirthHistorySubject } from "@/lib/consultation-birth-history";
|
||||
import type { BeamAvatar } from "@/lib/beam-avatar";
|
||||
import type { ConsultationEntrypoint } from "@/lib/consultation-entrypoint";
|
||||
import type { BirthTimeDraft } from "@/lib/birth-time-intake-model";
|
||||
@@ -46,6 +47,7 @@ export type ChartLibraryRecord = {
|
||||
role: "self" | "other";
|
||||
profile: Profile;
|
||||
birthInputRevision?: string;
|
||||
birthHistory?: BirthHistorySubject;
|
||||
relationship: ChartRelationship;
|
||||
updatedAt: number;
|
||||
};
|
||||
@@ -55,6 +57,7 @@ export type ChartLibraryApiRecord = {
|
||||
role: "self" | "other";
|
||||
profile: Profile;
|
||||
birthInputRevision?: string;
|
||||
birthHistory?: BirthHistorySubject;
|
||||
updated_at?: string;
|
||||
};
|
||||
export type SynastryReportCard = {
|
||||
@@ -157,6 +160,7 @@ export type Account = {
|
||||
profile: unknown;
|
||||
chartBirth?: { fingerprint?: string | null } | null;
|
||||
birthInputRevision?: string;
|
||||
birthHistory?: BirthHistorySubject;
|
||||
compatibility?: boolean;
|
||||
/** Product flag for the /rectification entry (issue #145). Missing: the sidebar row follows the registry default (BUG-1526); the page itself stays closed. */
|
||||
rectification?: boolean;
|
||||
|
||||
@@ -114,7 +114,7 @@ export function rectificationRevisitLabel(question: string): string {
|
||||
}
|
||||
|
||||
/** C7: the note the model reads in front of answers written with the earlier birth time. */
|
||||
export const BIRTH_TIME_CHANGED_HISTORY_NOTE = "(以下回答按校正前的出生时间,不要沿用其中的盘面判断)";
|
||||
export const BIRTH_TIME_CHANGED_HISTORY_NOTE = "(这条回答按之前的出生时间写成,里面的盘面判断不能当作现在的依据;需要时按现在的盘重新看。这句只给你看,不要在回答里转述或解释。)";
|
||||
|
||||
// ---- pure helpers over a stored messages array ----
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type SessionContextSummaryV1,
|
||||
} from "@/lib/consultation-session-history";
|
||||
import type { ResolvedLanguageModel } from "@/mastra/model";
|
||||
import { staleConsultationAnswerIndices, type ConsultationBirthHistory } from "./consultation-birth-history.ts";
|
||||
|
||||
export const SESSION_CONTEXT_SUMMARY_TIMEOUT_MS = 15_000;
|
||||
export const SESSION_CONTEXT_SUMMARY_MAX_HAN = 800;
|
||||
@@ -98,9 +99,9 @@ export function sanitizeSessionContextSummary(raw: string): string | null {
|
||||
export function tailCharCount(
|
||||
messages: unknown,
|
||||
summary: SessionContextSummaryV1 | null,
|
||||
options: { excludeRequestId?: string; contextWindow?: number | null } = {},
|
||||
options: { excludeRequestId?: string; contextWindow?: number | null; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): number {
|
||||
const turns = storedConsultationTurns(messages, { excludeRequestId: options.excludeRequestId });
|
||||
const turns = storedConsultationTurns(messages, options);
|
||||
const tail = summary
|
||||
? turns.filter((turn) => turn.index > summary.throughMessageIndex)
|
||||
: turns;
|
||||
@@ -110,7 +111,7 @@ export function tailCharCount(
|
||||
export function shouldCheckpoint(
|
||||
messages: unknown,
|
||||
summary: SessionContextSummaryV1 | null,
|
||||
options: { excludeRequestId?: string; contextWindow?: number | null } = {},
|
||||
options: { excludeRequestId?: string; contextWindow?: number | null; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): boolean {
|
||||
return tailCharCount(messages, summary, options)
|
||||
> consultationHistoryCheckpointChars(options.contextWindow);
|
||||
@@ -119,22 +120,22 @@ export function shouldCheckpoint(
|
||||
export function messagesForSummaryInput(
|
||||
messages: unknown,
|
||||
summary: SessionContextSummaryV1 | null,
|
||||
options: { excludeRequestId?: string } = {},
|
||||
options: { excludeRequestId?: string; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): Array<{ role: "user" | "assistant"; text: string; index: number; requestId: string | null }> {
|
||||
const turns = storedConsultationTurns(messages, { excludeRequestId: options.excludeRequestId });
|
||||
const turns = storedConsultationTurns(messages, options);
|
||||
const tail = summary
|
||||
? turns.filter((turn) => turn.index > summary.throughMessageIndex)
|
||||
: turns;
|
||||
const lastPair = lastConsultationPair(tail);
|
||||
const pairStart = lastPair[0];
|
||||
if (!pairStart) return [];
|
||||
return tail.filter((turn) => turn.index < pairStart.index);
|
||||
return tail.filter((turn) => turn.index < pairStart.index && !turn.staleBirthEvidence);
|
||||
}
|
||||
|
||||
export function buildSummaryPrompt(
|
||||
previous: SessionContextSummaryV1 | null,
|
||||
messages: unknown,
|
||||
options: { excludeRequestId?: string } = {},
|
||||
options: { excludeRequestId?: string; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): string {
|
||||
const input = messagesForSummaryInput(messages, previous, options);
|
||||
const lines = input.map((turn) => `${turn.role === "user" ? "用户" : "助手"}:${turn.text}`);
|
||||
@@ -168,12 +169,14 @@ export async function generateSessionContextSummary(input: {
|
||||
previous: SessionContextSummaryV1 | null;
|
||||
messages: unknown;
|
||||
excludeRequestId?: string;
|
||||
currentBirth?: ConsultationBirthHistory;
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
generateText?: (prompt: string, signal?: AbortSignal) => Promise<string>;
|
||||
}): Promise<string | null> {
|
||||
const prompt = buildSummaryPrompt(input.previous, input.messages, {
|
||||
excludeRequestId: input.excludeRequestId,
|
||||
currentBirth: input.currentBirth,
|
||||
});
|
||||
const generate = input.generateText ?? (input.model
|
||||
? (nextPrompt: string, signal?: AbortSignal) => generateSessionContextSummaryText(
|
||||
@@ -201,7 +204,7 @@ export function nextSessionContextSummary(
|
||||
previous: SessionContextSummaryV1 | null,
|
||||
text: string,
|
||||
updatedAt: string,
|
||||
options: { excludeRequestId?: string } = {},
|
||||
options: { excludeRequestId?: string; currentBirth?: ConsultationBirthHistory } = {},
|
||||
): SessionContextSummaryV1 | null {
|
||||
const covered = messagesForSummaryInput(messages, previous, options);
|
||||
const last = covered.at(-1);
|
||||
@@ -243,6 +246,7 @@ export async function checkpointSessionContextSummary(input: {
|
||||
summary: unknown;
|
||||
excludeRequestId?: string;
|
||||
contextWindow?: number | null;
|
||||
currentBirth?: ConsultationBirthHistory;
|
||||
now?: () => Date;
|
||||
generateText: (prompt: string, signal?: AbortSignal) => Promise<string>;
|
||||
update: (summary: SessionContextSummaryV1, seenUpdatedAt: string | null) => Promise<boolean>;
|
||||
@@ -252,24 +256,29 @@ export async function checkpointSessionContextSummary(input: {
|
||||
if (!shouldCheckpoint(input.messages, previous, {
|
||||
excludeRequestId: input.excludeRequestId,
|
||||
contextWindow: input.contextWindow,
|
||||
currentBirth: input.currentBirth,
|
||||
})) {
|
||||
return "skipped";
|
||||
}
|
||||
const stale = Array.isArray(input.messages) ? staleConsultationAnswerIndices(input.messages, input.currentBirth) : new Set<number>();
|
||||
const rebuild = previous && [...stale].some((index) => index <= previous.throughMessageIndex);
|
||||
const basis = rebuild ? null : previous;
|
||||
try {
|
||||
const text = await generateSessionContextSummary({
|
||||
previous,
|
||||
previous: basis,
|
||||
messages: input.messages,
|
||||
excludeRequestId: input.excludeRequestId,
|
||||
currentBirth: input.currentBirth,
|
||||
generateText: input.generateText,
|
||||
timeoutMs: input.timeoutMs,
|
||||
});
|
||||
if (!text) return "failed";
|
||||
const next = nextSessionContextSummary(
|
||||
input.messages,
|
||||
previous,
|
||||
basis,
|
||||
text,
|
||||
(input.now ?? (() => new Date()))().toISOString(),
|
||||
{ excludeRequestId: input.excludeRequestId },
|
||||
{ excludeRequestId: input.excludeRequestId, currentBirth: input.currentBirth },
|
||||
);
|
||||
if (!next) return "skipped";
|
||||
return writeSessionContextSummary({
|
||||
|
||||
@@ -338,6 +338,7 @@ async function resolveAgentStream(stream: AgentStreamSource): Promise<ChunkStrea
|
||||
}
|
||||
|
||||
type StreamAgentResponseOptions = EventOptions & {
|
||||
birthFields?: import("./consultation-birth-history.ts").ConsultationBirthFields;
|
||||
state: ConsultationRuntimeState;
|
||||
stream: AgentStreamSource;
|
||||
warmup?: (send: (event: ConsultationAgentPublicEvent) => void) => Promise<void>;
|
||||
@@ -583,7 +584,8 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
|
||||
firstActivity = true;
|
||||
void Promise.resolve(options.onFirstActivity?.()).catch(() => {});
|
||||
}
|
||||
if (!disconnected && controller) controller.enqueue(encoder.encode(`${JSON.stringify(consultationAgentPublicEventSchema.parse(event))}\n`));
|
||||
const publicEvent = event.type === "run.completed" ? { ...event, ...options.birthFields } : event;
|
||||
if (!disconnected && controller) controller.enqueue(encoder.encode(`${JSON.stringify(consultationAgentPublicEventSchema.parse(publicEvent))}\n`));
|
||||
};
|
||||
const flushThinkingPlan = (controller: ReadableStreamDefaultController<Uint8Array> | undefined) => {
|
||||
if (planSent) return;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { consultationAgentPublicEventSchema, type ConsultationAgentPublicEvent } from "./consultation-agent-events.ts";
|
||||
import type { ConsultationBirthFields } from "./consultation-birth-history.ts";
|
||||
|
||||
/** Same NDJSON public envelope as consultation; no fake workflow or skill receipt. */
|
||||
export function streamSmalltalkResponse(input: {
|
||||
requestId: string;
|
||||
reply: string;
|
||||
birthFields?: ConsultationBirthFields;
|
||||
complete: () => Promise<void>;
|
||||
onError: () => Promise<void>;
|
||||
}) {
|
||||
@@ -18,7 +20,7 @@ export function streamSmalltalkResponse(input: {
|
||||
// Persist/refund before emitting success or text; a rejected/failed RPC is not a reply.
|
||||
await input.complete();
|
||||
send({ type: "answer.delta", text: input.reply });
|
||||
send({ type: "run.completed", responseKind: "smalltalk" });
|
||||
send({ type: "run.completed", responseKind: "smalltalk", ...input.birthFields });
|
||||
} catch {
|
||||
await input.onError().catch(() => {});
|
||||
send({ type: "run.failed", code: "calculation_failed", message: "这次回复没能保存,请重试。" });
|
||||
|
||||
@@ -4,6 +4,10 @@ import { NextResponse } from "next/server";
|
||||
|
||||
import { logAgentObservability } from "@/lib/agent-observability";
|
||||
import { blocksPromptExtraction } from "@/lib/consult-safety";
|
||||
import { consultationBirthFields, publicConsultationBirthFields, readStoredConsultationBirth, type ConsultationBirthFields } from "@/lib/consultation-birth-history";
|
||||
import { consultationBirthSubject } from "@/lib/birth-input-revision";
|
||||
import { loadSubjectBirth } from "@/lib/subject-birth";
|
||||
import { storedConsultationTurns } from "@/lib/consultation-session-history";
|
||||
import { consultationCompletionSchema, createConsultSettlement, first, retryDetachedSettlement } from "@/lib/consult/settlement";
|
||||
import { CreditRpcError } from "@/lib/consultation-billing";
|
||||
import { consultationAgentPublicEventSchema, type ConsultationAgentPublicEvent } from "@/lib/consultation-agent-events";
|
||||
@@ -40,7 +44,7 @@ function answerLanguage(question: string): "zh" | "en" {
|
||||
return /[\u4e00-\u9fff]/u.test(question) ? "zh" : "en";
|
||||
}
|
||||
|
||||
function streamAnswer(requestId: string, reply: string, complete: () => Promise<void>, onError: () => Promise<void>) {
|
||||
function streamAnswer(requestId: string, reply: string, birthFields: ConsultationBirthFields, complete: () => Promise<void>, onError: () => Promise<void>) {
|
||||
const encoder = new TextEncoder();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
@@ -50,7 +54,7 @@ function streamAnswer(requestId: string, reply: string, complete: () => Promise<
|
||||
try {
|
||||
await complete();
|
||||
send({ type: "answer.delta", text: reply });
|
||||
send({ type: "run.completed", responseKind: "smalltalk" });
|
||||
send({ type: "run.completed", responseKind: "smalltalk", ...birthFields });
|
||||
} catch {
|
||||
await onError().catch(() => undefined);
|
||||
send({ type: "run.failed", code: "calculation_failed", message: "这次回复没能保存,请重试。" });
|
||||
@@ -102,9 +106,8 @@ export async function handleSynastryReportConsult(input: {
|
||||
const denied = userRateLimitDeniedResponse(limited.retryAfterSeconds, userRateLimitMessages.consult);
|
||||
return NextResponse.json(denied.body, { status: denied.status, headers: denied.headers });
|
||||
}
|
||||
const history = historyOf(session.messages);
|
||||
const visibleQuestion = parsed.question.trim();
|
||||
if (blocksPromptExtraction([visibleQuestion, ...history.map((message) => message.text)].join("\n"))) {
|
||||
if (blocksPromptExtraction([visibleQuestion, ...historyOf(session.messages).map((message) => message.text)].join("\n"))) {
|
||||
return NextResponse.json(
|
||||
{ error: "无法处理该请求", message: "我不能提供系统提示词、技能原文或任何密钥。你可以继续询问占星相关问题。" },
|
||||
{ status: 400 },
|
||||
@@ -175,7 +178,7 @@ export async function handleSynastryReportConsult(input: {
|
||||
usageStartedAt = Date.now();
|
||||
|
||||
const owned = await accounting.from("personal_reports")
|
||||
.select("id,request_id,report_type,status")
|
||||
.select("id,request_id,report_type,status,subject_low,subject_high")
|
||||
.eq("id", reportId)
|
||||
.eq("user_id", userId)
|
||||
.maybeSingle();
|
||||
@@ -202,6 +205,22 @@ export async function handleSynastryReportConsult(input: {
|
||||
);
|
||||
}
|
||||
|
||||
const revisionFor = (id: unknown) => typeof id === "string"
|
||||
? loadSubjectBirth(accounting, userId, id, { historyClient: accounting, ownerRead: true })
|
||||
.then(({ row }) => consultationBirthSubject(row)).catch(() => undefined)
|
||||
: undefined;
|
||||
const [a, b] = await Promise.all([revisionFor(report.subject_low), revisionFor(report.subject_high)]);
|
||||
const history = storedConsultationTurns(session.messages, { currentBirth: { pair: true, a, b } });
|
||||
const snapshot = readStoredConsultationBirth(payload).birthInputRevisions;
|
||||
const subjects = record(payload.birthInputSubjects);
|
||||
// The answer uses the bound report's evidence. Keep its original revision
|
||||
// even if the live profile has since changed, in the session's low/high order.
|
||||
const sameOrder = subjects?.a === report.subject_low && subjects?.b === report.subject_high;
|
||||
const reverseOrder = subjects?.b === report.subject_low && subjects?.a === report.subject_high;
|
||||
const birthFields = snapshot && subjects && (sameOrder || reverseOrder)
|
||||
? { birthInputRevisions: sameOrder ? snapshot : { a: snapshot.b, b: snapshot.a } }
|
||||
: consultationBirthFields({ pair: true, a, b });
|
||||
|
||||
const language = answerLanguage(visibleQuestion);
|
||||
let turn: Awaited<ReturnType<typeof runSynastryReportTurn>>;
|
||||
try {
|
||||
@@ -261,7 +280,8 @@ export async function handleSynastryReportConsult(input: {
|
||||
const reply = (blocked ? MODERATION_OUTPUT_REPLACED_COPY : turn.text).slice(0, 12_000);
|
||||
const usage = settlement.usagePayload(Promise.resolve({ inputTokens: turn.inputTokens, outputTokens: turn.outputTokens }));
|
||||
|
||||
return streamAnswer(parsed.requestId, reply, async () => {
|
||||
const publicBirthFields = publicConsultationBirthFields(input.request.headers, birthFields);
|
||||
return streamAnswer(parsed.requestId, reply, publicBirthFields, async () => {
|
||||
const actualUsage = await usage;
|
||||
await retryDetachedSettlement(async () => {
|
||||
const rpcName = blocked ? "complete_consultation_moderated" : "complete_consultation_response";
|
||||
@@ -272,7 +292,7 @@ export async function handleSynastryReportConsult(input: {
|
||||
p_user_id: userId,
|
||||
p_request_id: parsed.requestId,
|
||||
p_session_id: parsed.sessionId,
|
||||
p_response_message: responseMessage,
|
||||
p_response_message: { ...responseMessage, ...birthFields },
|
||||
p_actual_usage: actualUsage,
|
||||
});
|
||||
const result = consultationCompletionSchema.safeParse(first(data ?? []));
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Agent } from "@mastra/core/agent";
|
||||
import { createConsultationTools, createWindowConsultationTools, MAX_CONSULTATION_DOMAINS, type ConsultationAgentContext, type WindowConsultationAgentContext } from "./consultation-tools";
|
||||
import { toAgentConsultationContext } from "./consultation-workflow.ts";
|
||||
import type { ResolvedLanguageModel } from "./model";
|
||||
import { consultationVoiceFor, natalSpokenReportContract, productConversationVoice } from "./product-voice";
|
||||
import { consultationVoiceFor, natalSpokenReportContract, productConversationVoice, staleBirthHistoryRule } from "./product-voice";
|
||||
import {
|
||||
consultationSpokenHeadingRule,
|
||||
DEFAULT_CONSULTATION_ANSWER_MODE,
|
||||
@@ -40,7 +40,7 @@ const jyotishInstructions = productContractBlock("natal-instructions", {
|
||||
MAX_CONSULTATION_DOMAINS,
|
||||
SPOKEN_HEADING_RULE: consultationSpokenHeadingRule("natal"),
|
||||
MEVG_BLOCKED_POLICY: productContractBlock("mevg-blocked-policy"),
|
||||
});
|
||||
}) + "\n" + staleBirthHistoryRule;
|
||||
|
||||
/** How the natal instructions name this turn's answer mode. */
|
||||
function answerModeLabel(mode: ConsultationAnswerMode): string {
|
||||
@@ -88,6 +88,7 @@ ${JSON.stringify(toAgentConsultationContext(workflowContext))}
|
||||
|
||||
const generalJyotishInstructions = `You are the guide for a conversational Vedic astrology product.
|
||||
${productConversationVoice}
|
||||
${staleBirthHistoryRule}
|
||||
This request explicitly has no usable birth minute. Never calculate, infer, or claim a personal birth chart, ascendant, house, divisional chart, dasha, transit timing, or personal natal prediction. Never invent 00:00, a period midpoint, or any other substitute minute. You have no natal chart tools for this mode.
|
||||
Answer the user's actual question. Do not refuse the whole turn, and do not force a two-path choice between encyclopedia questions and birth-time rectification.
|
||||
A homepage or ordinary-session daily request may include a server-owned <public-daily-panchanga> block. When that block is present, explain today's public calendar trend, suitable actions, cautions, and one practical next step from that block only. State once that this is a public-day reference rather than a personal natal forecast.
|
||||
@@ -140,6 +141,7 @@ export function getDailyStarlanguageAgent(model: ResolvedLanguageModel) {
|
||||
|
||||
const windowJyotishInstructions = `You are the guide for a conversational Vedic astrology product.
|
||||
${productConversationVoice}
|
||||
${staleBirthHistoryRule}
|
||||
This request has a declared birth window, not a single birth minute. Never invent 00:00, a period midpoint, noon, or any probe clock as the birth time. Probe clocks in the tool result are comparison samples only.
|
||||
${jyotishSkillMethodCoreBlock}
|
||||
The bound skill method is this product's answering contract. Window answers do not use the natal Level 2 report skeleton; the window output contract below takes priority over any report-template or precise-timing language in the bound method.
|
||||
|
||||
@@ -58,6 +58,8 @@ import {
|
||||
* default is professionalConversationVoice below. The general (no birth
|
||||
* minute) and declared-window agents keep this voice.
|
||||
*/
|
||||
export const staleBirthHistoryRule = "用户追问标有旧出生时间说明的回答时,用当前星盘重新回答。可以说一次「出生时间后来改过,所以我按现在的重新看了」,不复述括号内说明,不解释技术过程,也不逐条对比新旧结论。";
|
||||
|
||||
export const productConversationVoice = `VISIBLE VOICE
|
||||
解读写法(产品 2026-11-16:只有这一种):先回答,用白话。正文只写结论和它在你日子里的样子,每个结论带一句最要紧的原因;完整的盘面依据写在最后的「## 判断依据」一节,把每个判断对到盘面事实和把握。度数表、运程表和技法清单由页面生成,回答里不写。后台方法完整执行。白话可以少用术语,不能少信息(占星师 2026-11-08 第五轮裁定 6):信息在「判断依据」里写全。
|
||||
像一个懂行、说话温和的姐姐,对着「你」说话,不叫名字(上下文里的称呼只用来知道是谁,不以「某某,」开头)。你是来给判断的:结论说到底、说清楚,语气放软但不含糊;不顺的照实说,用「可能」「这段时间会累一点」,不用「注定」「很差」「没戏」。不说教、怎么选留给对方、不卖萌,不用语气词、叠字和表情,不写客服套话。
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { ResolvedLanguageModel } from "./model.ts";
|
||||
export const SYNASTRY_CHAT_INSTRUCTIONS = [
|
||||
"你在解释一份已经写好的婚恋合盘报告。用户问的是某一节在两人盘里的依据。",
|
||||
"回答前必须先调用 readSynastrySection。没拿到材料就不要写盘面。",
|
||||
"如果用户追问标有旧出生时间说明的回答,只按工具这次返回的资料重新判断,不沿用旧回答里的盘面,不复述括号说明。",
|
||||
"只使用工具返回的内容。可以写星曜、宫位、星座、相位、大运和起止。不要重新排盘,不要补充材料里没有的盘面事实。",
|
||||
"材料没写到的,直接说「这份合盘没算到」,并建议回到各自的盘单独问。",
|
||||
"前后 30 分钟只是试算。材料说试算里没有变化,就保留试算口径,不写「稳定」「已确认」或「不会变」。",
|
||||
|
||||
@@ -259,7 +259,8 @@ test("the turn spacer trails the actions row instead of sitting between text and
|
||||
// 原值: sourceBetween(transcript, '<div className="message-entry">', "</div>")
|
||||
// 新值: 入口是 className={`message-entry…`}(最新回答加 is-latest-answer),截到整轮的收尾 </div>
|
||||
// 原因: 2026-11-05 回答底栏:动作条外包了一层 .message-footer(「已完成 N 步」入口与图标同一行),第一个 </div> 不再是整轮的结尾
|
||||
const entry = sourceBetween(transcript, "<div className={`message-entry", "\n </div>\n );");
|
||||
const entry = sourceBetween(transcript, "<div className={`message-entry", "\n </div>\n {birthDividerAfter");
|
||||
assert.ok(transcript.indexOf("<RectificationReturnDivider />") > transcript.indexOf("<ConversationFollowUps"));
|
||||
assert.ok(entry.indexOf("<ChatMessageRow") < entry.indexOf("<ChatMessageActions"));
|
||||
assert.ok(entry.indexOf("<ChatMessageActions") < entry.indexOf("<ConversationFollowUps"));
|
||||
});
|
||||
|
||||
@@ -303,7 +303,7 @@ test("the consult route opens the stream before subject reads, reservation, ques
|
||||
// 原值: 寒暄分支源码含 complete_consultation_free
|
||||
// 新值: 分支调用 consultSettlement.completeSmalltalk;RPC 与 responseKind smalltalk 在 settlement.ts
|
||||
// 原因: 寒暄结算搬进工厂,分支仍不跑 agent
|
||||
assert.match(smalltalk, /consultSettlement\.completeSmalltalk\(turn\.reply\)/);
|
||||
assert.match(smalltalk, /consultSettlement\.completeSmalltalk\(turn\.reply, birthFields\)/);
|
||||
assert.match(settlement, /complete_consultation_free[\s\S]*responseKind: "smalltalk"/);
|
||||
assert.doesNotMatch(smalltalk, /streamAgentResponse\(/);
|
||||
});
|
||||
|
||||
@@ -80,5 +80,5 @@ test("a consult turn prewarms the card packet with the same identity the card re
|
||||
// 原值: beforeReserve 只解构 consultationMode、serverChart
|
||||
// 新值: 同时解构 declaredWindow、subject;预热仍是第一句
|
||||
// 原因: issue #162 beforeReserve 多取 declaredWindow、subject,用来在审核后提前开始分类
|
||||
assert.match(route, /beforeReserve: async \(\{ consultationMode, serverChart, declaredWindow, subject \}\) => \{\n\s+if \(serverChart && consultationMode !== "declared_birth_window"\) prewarmConsultPacketForTurn\(serverChart\.toolInput\);/);
|
||||
assert.match(route, /beforeReserve: async \(\{ consultationMode, serverChart, declaredWindow, subject, birthHistory \}\) => \{\n\s+if \(serverChart && consultationMode !== "declared_birth_window"\) prewarmConsultPacketForTurn\(serverChart\.toolInput\);/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import "./install-test-document";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import React from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import {
|
||||
CONSULTATION_BIRTH_HISTORY_HEADER, consultationBirthDividerIndices, consultationBirthFields,
|
||||
publicConsultationBirthFields, readStoredConsultationBirth, staleConsultationAnswerIndices,
|
||||
} from "../src/lib/consultation-birth-history.ts";
|
||||
import { consultationBirthSubject } from "../src/lib/birth-input-revision.ts";
|
||||
import { consultationHistoryWindow, storedConsultationTurns, type SessionContextSummaryV1 } from "../src/lib/consultation-session-history.ts";
|
||||
import { buildSummaryPrompt } from "../src/lib/session-context-summary.ts";
|
||||
import { BIRTH_TIME_CHANGED_HISTORY_NOTE } from "../src/lib/rectification-in-chat.ts";
|
||||
import { ChatTranscript } from "../src/components/chat-transcript";
|
||||
import { staleBirthHistoryRule } from "../src/mastra/product-voice.ts";
|
||||
import { readSessions } from "../src/lib/home-cloud-sync";
|
||||
import { streamSmalltalkResponse } from "../src/lib/stream-smalltalk-response.ts";
|
||||
|
||||
Object.assign(globalThis, { React });
|
||||
const v1 = "a".repeat(64);
|
||||
const v2 = "b".repeat(64);
|
||||
const v3 = "c".repeat(64);
|
||||
const copy = "这是一段合成回答。";
|
||||
const evidence = "- **示例**:这是合成判断依据。";
|
||||
const answer = { role: "assistant" as const, text: copy + "\n\n## 判断依据\n" + evidence };
|
||||
const question = { role: "user" as const, text: "如何理解刚才那段话?" };
|
||||
const current = { a: { revision: v2 } };
|
||||
const summary: SessionContextSummaryV1 = {
|
||||
version: 1, text: "合成旧摘要", messageCount: 2, throughMessageIndex: 1, throughRequestId: "mock",
|
||||
updatedAt: "2026-11-17T00:00:00Z",
|
||||
};
|
||||
const returnMessage = {
|
||||
role: "assistant" as const,
|
||||
text: "旧分隔",
|
||||
rectificationReturn: {
|
||||
caseId: "12345678-1234-4234-8234-123456789abc",
|
||||
adopted: true,
|
||||
clock: "08:00",
|
||||
sourceQuestion: question.text,
|
||||
returnedAt: "2026-11-17T00:00:00Z",
|
||||
},
|
||||
};
|
||||
|
||||
test("C7 marks only assistant answers before an adopted in-chat boundary", () => {
|
||||
const rows = [question, answer, returnMessage, question, answer];
|
||||
assert.deepEqual([...staleConsultationAnswerIndices(rows)], [1]);
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([answer, {
|
||||
...returnMessage, rectificationReturn: { ...returnMessage.rectificationReturn, adopted: false, clock: null },
|
||||
}])], []);
|
||||
assert.deepEqual(consultationBirthDividerIndices(rows, current), []);
|
||||
});
|
||||
|
||||
test("mismatched and matching versions cover both ordinary and bound-pair answers", () => {
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([
|
||||
{ ...question, birthInputRevision: v1 }, { ...answer, birthInputRevision: v1 },
|
||||
{ ...answer, birthInputRevision: v2 }, answer,
|
||||
], current)], [1]);
|
||||
const pair = { pair: true as const, a: { revision: v1 }, b: { revision: v2 } };
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([
|
||||
{ ...answer, birthInputRevisions: { a: v3, b: v2 } },
|
||||
{ ...answer, birthInputRevisions: { a: v1, b: v3 } },
|
||||
{ ...answer, birthInputRevisions: { a: v1, b: v2 } },
|
||||
{ ...answer, birthInputRevisions: { a: v1 } },
|
||||
], pair)], [0, 1]);
|
||||
assert.deepEqual(consultationBirthFields(pair), { birthInputRevisions: { a: v1, b: v2 } });
|
||||
});
|
||||
|
||||
test("a retired projection or a later known adoption marks only eligible unversioned answers", () => {
|
||||
const retired = consultationBirthSubject({ active_birth_provenance: { retired_reason: "BUG-1890" } });
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([answer, { ...answer, birthInputRevision: retired.revision }], { a: retired })], [0]);
|
||||
const adoptedAt = "2026-11-17T00:00:00Z";
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([
|
||||
{ ...answer, createdAt: "2026-11-16T23:59:59Z" },
|
||||
{ ...answer, created_at: adoptedAt }, { ...answer, timestamp: "2026-11-18T00:00:00Z" },
|
||||
answer, { ...answer, createdAt: "?" },
|
||||
], { a: { revision: v2, adoptedAt } })], [0]);
|
||||
assert.deepEqual([...staleConsultationAnswerIndices([answer, { ...answer, createdAt: "2026-11-16T23:59:59Z" }], current)], []);
|
||||
});
|
||||
|
||||
test("only model history drops the obsolete basis and existing summaries disclose covered stale answers", () => {
|
||||
const rows = [question, { ...answer, birthInputRevision: v1 }, question, { ...answer, birthInputRevision: v2 }];
|
||||
const before = structuredClone(rows);
|
||||
const turns = storedConsultationTurns(rows, { currentBirth: current });
|
||||
assert.equal(turns[1]?.text, BIRTH_TIME_CHANGED_HISTORY_NOTE + "\n" + copy);
|
||||
assert.equal(turns[3]?.text, answer.text);
|
||||
assert.deepEqual(rows, before);
|
||||
assert.equal(consultationHistoryWindow(rows, summary, { currentBirth: current }).summaryText,
|
||||
BIRTH_TIME_CHANGED_HISTORY_NOTE + "\n" + summary.text);
|
||||
assert.equal(consultationHistoryWindow(rows, { ...summary, throughMessageIndex: 0 }, { currentBirth: current }).summaryText, summary.text);
|
||||
const prompt = buildSummaryPrompt(null, rows, { currentBirth: current });
|
||||
assert.match(prompt, /如何理解刚才那段话/);
|
||||
assert.doesNotMatch(prompt, /合成回答|只给你看|合成判断依据/);
|
||||
});
|
||||
|
||||
test("the transcript adds one divider at the boundary and keeps the old folded basis", () => {
|
||||
const older = { ...answer, birthInputRevision: v1 };
|
||||
const newer = { ...answer, text: "新的合成回答", birthInputRevision: v2 };
|
||||
const rows = [question, older, question, older, question, newer];
|
||||
assert.deepEqual(consultationBirthDividerIndices(rows, current), [3]);
|
||||
assert.deepEqual(consultationBirthDividerIndices(rows.slice(0, -1), current), [3]);
|
||||
assert.deepEqual(consultationBirthDividerIndices([older, returnMessage, newer], current), []);
|
||||
const noop = () => {};
|
||||
const html = renderToStaticMarkup(React.createElement(ChatTranscript, {
|
||||
messages: rows, loading: false, streamingText: "", sessionId: "mock-session", sessionType: "consultation",
|
||||
currentBirth: current, messageFeedback: {}, copiedMessageKey: null, cancellationPending: false,
|
||||
productEntrypointsDisabled: false, actionsRef: { current: {
|
||||
onFeedback: noop, onCopy: noop, onRegenerate: noop, onFollowUp: noop, onStartRectification: noop,
|
||||
} },
|
||||
}));
|
||||
assert.equal(html.match(/出生时间在这之后改过/g)?.length, 1);
|
||||
assert.ok(html.indexOf("出生时间在这之后改过") < html.indexOf("新的合成回答"));
|
||||
assert.match(html, /<details\b[^>]*>[\s\S]*?<summary[^>]*>[\s\S]*?判断依据[\s\S]*?<\/details>/);
|
||||
assert.match(html, /这是合成判断依据/);
|
||||
});
|
||||
|
||||
test("persisted and streamed replies carry server version metadata through hydration and smalltalk", async () => {
|
||||
const version = consultationBirthFields(current);
|
||||
const reply = { ...answer, ...version, created_at: "2026-11-16T00:00:00Z" };
|
||||
const hydrated = readSessions([{ id: "mock", messages: [reply] }], null).sessions[0]?.messages[0];
|
||||
assert.deepEqual(hydrated && readStoredConsultationBirth(hydrated), {
|
||||
...version, createdAt: Date.parse(reply.created_at),
|
||||
});
|
||||
const legacyHeaders = new Headers();
|
||||
const newHeaders = new Headers({ [CONSULTATION_BIRTH_HISTORY_HEADER]: "1" });
|
||||
assert.deepEqual(publicConsultationBirthFields(legacyHeaders, version), {});
|
||||
assert.deepEqual(publicConsultationBirthFields(newHeaders, version), version);
|
||||
let committed = false;
|
||||
const stream = streamSmalltalkResponse({
|
||||
requestId: "12345678-1234-4234-8234-123456789abc", reply: "你好", birthFields: publicConsultationBirthFields(newHeaders, version),
|
||||
async complete() { committed = true; }, async onError() { assert.fail("unexpected settlement failure"); },
|
||||
});
|
||||
assert.match(await stream.text(), new RegExp(v2));
|
||||
assert.equal(committed, true);
|
||||
const route = readFileSync(new URL("../src/app/api/consult/route.ts", import.meta.url), "utf-8");
|
||||
const settlement = readFileSync(new URL("../src/lib/consult/settlement.ts", import.meta.url), "utf-8");
|
||||
assert.match(route, /text: reply\.text,\s*\.\.\.birthFields/);
|
||||
assert.match(route, /completeSmalltalk\(turn\.reply, birthFields\)/);
|
||||
assert.match(settlement, /p_response_message: \{ role: "assistant", text: reply, responseKind: "smalltalk", \.\.\.birthFields/);
|
||||
});
|
||||
|
||||
test("the history note is private and redirection to the current chart has one permitted line", () => {
|
||||
assert.match(BIRTH_TIME_CHANGED_HISTORY_NOTE, /这句只给你看,不要在回答里转述或解释/);
|
||||
assert.match(staleBirthHistoryRule, /用当前星盘重新回答/);
|
||||
assert.match(staleBirthHistoryRule, /出生时间后来改过,所以我按现在的重新看了/);
|
||||
assert.match(staleBirthHistoryRule, /不复述括号内说明/);
|
||||
});
|
||||
@@ -241,7 +241,7 @@ test("route gates all special entries before a single selected-model classifier
|
||||
// 原值: 寒暄分支源码含 complete_consultation_free
|
||||
// 新值: 分支调用 consultSettlement.completeSmalltalk;RPC 在 settlement.ts
|
||||
// 原因: 寒暄结算搬进工厂,分支仍不跑 agent
|
||||
assert.match(smalltalk, /consultSettlement\.completeSmalltalk\(turn\.reply\)/);
|
||||
assert.match(smalltalk, /consultSettlement\.completeSmalltalk\(turn\.reply, birthFields\)/);
|
||||
assert.match(settlement, /complete_consultation_free/);
|
||||
assert.doesNotMatch(smalltalk, /run-jyotish-|streamAgentResponse\(/);
|
||||
});
|
||||
|
||||
@@ -178,7 +178,7 @@ test("consultation plans are server-owned and bounded", () => {
|
||||
// 原值: beforeReserve 只解构 consultationMode、serverChart
|
||||
// 新值: 同时解构 declaredWindow、subject;计划仍在 beforeReserve 里生成
|
||||
// 原因: issue #162 beforeReserve 多取 declaredWindow、subject,用来在审核后提前开始分类
|
||||
/beforeReserve:\s*async\s*\(\{\s*consultationMode,\s*serverChart,\s*declaredWindow,\s*subject\s*\}\)[\s\S]*createConsultationPlan\(\{/,
|
||||
/beforeReserve:\s*async\s*\(\{\s*consultationMode,\s*serverChart,\s*declaredWindow,\s*subject,\s*birthHistory\s*\}\)[\s\S]*createConsultationPlan\(\{/,
|
||||
);
|
||||
assert.match(
|
||||
prepareCall.slice(reserveAt),
|
||||
|
||||
Reference in New Issue
Block a user