fix(chat): a years-ahead question gets a strip over those years; text after the strip's stretches reads as body markdown; session titles turn thinking off (BUG-2433, BUG-2434, BUG-2435)
Independent Staging Quality Gate / validate-python (push) Successful in 5m4s
Independent Staging Quality Gate / validate-frontend (push) Successful in 5m53s
Independent Staging Quality Gate / publish (push) Skipped

- BUG-2433: run-jyotish-consultation takes horizon_years (the writer's own
  judgment); the program cuts the strip over those years (first year as
  before, then one stretch per Vimshottari sub-period, dasha rules only),
  names the section 「接下来N年」 and hands strip_heading to the writer.
- BUG-2434: in a time section, sub-headings and loose lines go back to the
  body as markdown (one block per line); the strip footer keeps only the
  turning-point sentence.
- BUG-2435: the session title call disables provider thinking; with
  thinking on, its 30 tokens went to reasoning and the title stayed the raw
  question.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
2026-11-27 11:47:00 +08:00
co-authored by Claude Opus 5.5
parent 5cf74d2d04
commit 54d7be828c
16 changed files with 591 additions and 39 deletions
+7
View File
@@ -1,5 +1,12 @@
# 印度占星 Skill 更新日志
## 2026-11-27 · 问往后几年时时间条照问的年数画;时间条下面不再挤正文;对话标题照常生成
- 问「未来十年」「接下来三年」这类问题时,写回答的模型在排盘工具上声明年数,程序照这个年数切时间条:第一年照旧按月细分,之后按小运分段,标题写成「接下来十年」这样;没声明时仍是接下来一年(BUG-2433)
- 时间那一节里模型接着写的小标题和段落(「### 事业」「一、……」)回到正文按标题和段落排,时间条下面只留转折点那一句(BUG-2434)
- 新对话的标题调用关掉思考,默认开思考的模型也能起出标题,不再停在问题原文(BUG-2435)
- Skill 版本不变
## 2026-11-27 · 只问西洋占星时少送印度盘时间数据;后台成本按缓存命中拆价
- 只问西洋占星时,问答不再把印度盘的运程、行运、年运等时间数据送给模型(这类回答本来就没有时间部分),每题输入少约 2.8–3 万个全价 token;印度和两边对照的问答不变
+48
View File
@@ -33248,3 +33248,51 @@
- 已知限制:非高峰时段实价是高峰的一半,估算仍按高峰;报告、合盘、年运结算的 `cost_microusd` 仍按全价(不在本次范围);已保存的其它供应商模型没有命中价。
- 关联记录:BUG-2424(缓存与成本实测)、BUG-2342(西洋问答形状)、BUG-2231 / BUG-1937 / BUG-1940(上线配置成本估算与官网价)。
- 修复版本:`claude/cost-followup`(本地,未推送)。
## BUG-2433 | 问「未来十年的事业」,有时写成「接下来十年」、有时只有「接下来一年」四段到 9 月
- 状态:fixed-pending-verify(本地分支 `claude/chat-2433`,未推送;待 staging 用公开盘复测)。
- 首次发现 / 最近更新:2026-11-27(负责人在正式站 1.5 和 staging 各问一次同一个十年事业问题)。
- 现象:正式站(1.5,`87677ca96`)的回答写「接下来十年」,时间条 8 段到 2030 年;staging(`18d17250f`)的回答写「接下来一年」,时间条 4 段到第二年 9 月。
- 触发条件:问往后几年的问题(「未来十年」「接下来三年」),首轮回答。
- 诊断(只用代码、git 历史和公开盘,没有读任何数据库行或用户对话):`87677ca96..origin/next` 之间时间条、范围、证据卡和对应提示都没有改。公开 AA 盘(Obama)同一句十年事业问题,在两个提交上用真实引擎生成的证据卡逐项相同:`horizon` 都是 10 年,行运窗口都是 4 年(2026-09 至 2030-09),`period_coverage` 都是 19 行到 2030 年 10 月,`strip_stretches` 都是 4 段到第二年 9 月(`eval-read-1116/bug-2433/live-prod`、`live-next`)。两站的差别不在代码,而在写回答的模型每次怎么选:正式站那次按 `period_coverage` 自己切了 8 段到 2030(正好是 4 年行运窗口的尽头),staging 那次照 `strip_stretches` 写了一年。本轮同题 origin/next 再跑一次,模型又选了 `period_coverage`,写成「未来十年」5 段到 2032 年。
- 根因:时间条的段由程序切,但只切接下来 12 个月(`frontend/src/lib/chat-strip-status.ts:428` `addMonths(from, 12)`,`chat-answer-timeline.ts:153` `programStretches`,BUG-2308 `2cf0e09f8` / BUG-2310 `dd6772d84` 引入);用户问了更长的范围时,提示让模型「照他的范围按 period_coverage 写」(`product-voice.ts:310`、`chat-answer-timeline.ts:234`),范围由模型逐次自己决定,同一问题有时十年、有时一年。`period_coverage` 本身也只到行运窗口的 4 年,问十年最多也只能切到第 4 年。
- 修复:
- 范围改成结构化声明:`run-jyotish-consultation` 加 `horizon_years`(写回答的模型按问题判断,「未来十年」→ 10;不看用户原话,不加新的正则路由),四舍五入并限在 2–10(`stripYearsFrom`),写到服务端卡的 `strip_years`,同时取进卡的 `horizon`(与问题本身的年数取大)。不带时仍是接下来 12 个月。
- `programStretches`:`strip_years` 大于 1 时,第一年照旧(行运、细运、KP 段界),延到当时那个小运结束(至多再 6 个月、且在行运数据以内);之后到期限每个小运一段(`dashaStretches`:只用大运和小运主星的 S1 / R1 / R2,不用行运——行运数据最多 4 年,按年读也不需要月级行运);卡上下一个大运没有小运时整段算一段;期限刚擦到的小运(不到半年)不画成一条细段;同说法相邻段照旧在超过 6 段时合并;仍超过页面能放的 8 段时整段按小运切,再超就截在第 8 段。
- 标题由程序定:覆盖约几年就写「接下来N年」(`stripHeading`,不超过问的年数),卡上给写作方 `strip_heading`;程序补写时间条时也用这个标题。`best_time` 的说明在多年时说「这段时间」。
- 提示:`STRIP_STRETCHES_READING` 和首轮结构说明各加一句——卡上有 `strip_heading` 时标题照它写、段照 `strip_stretches`,不再按 `period_coverage` 另切;原有的「照他的范围按 period_coverage 写」保留给没有声明年数的范围(例如点名某一年)。
- 验证:
- 新增 `frontend/tests/chat-strip-horizon-2433.test.ts`(9 项):`horizon_years` 的取值;三张公开盘十年期限的时间条 3–8 段、连续、覆盖 9.5–10.1 年、标题「接下来十年」、第一年以后只用大运小运规则;不声明时仍一年、标题「接下来一年」;写作方看到 `strip_heading`;程序补写的标题;大运段不重叠、越界返回空;期限擦边的小运不画。改动断言:`consultation-agentic-runtime.test.ts`(原值:工具输入字段到 `kp_only` 为止;新值:末尾加可选的 `horizon_years`;原因:本条);`chat-voice-2229.test.ts`(原值:首轮写法上限 11,250 字;新值:11,400(实测 11,312);原因:本条加了一句 `strip_heading` 的写法)。前端全量 885 个文件:856 个通过,29 个失败中 27 个与基线相同(本机没有 Docker 的数据库 / 部署类),另外 2 个就是上面改了断言的两条,改后通过。
- 真实模型(公开 AA 盘 Obama、deepseek-flash、真实引擎,同一句十年问题,前后各 1 次):origin/next 模型自己按 `period_coverage` 写「未来十年」5 段到 2032 年 11 月(没有程序的说法);本分支模型带上 `horizon_years: 10`,写「接下来十年」7 段到 2036 年 10 月(修了擦边段之前的一次;修后最后一段止于 2036 年 9 月中旬),禁句 0、must_not 0(`eval-read-1116/bug-2433/before`、`after`)。工具说明变了,第一次调用不命中缓存(本次 2,560 vs 79,616 命中 token),之后照常。
- 防复发:时间条的范围只认工具上的结构化声明;程序切段、程序定标题,模型不再在两张表之间自选。
- 已知限制:第一年以后只按 Vimshottari 小运和大运规则给说法,不叠行运和 KP;卡上没有列出的运期不画(下下个大运只有整段)。追问里写到的具体月份(`datedWindow`)仍按原逻辑最多 24 个月。
- 关联记录:BUG-1643(十年问题卡上带后续运期)、BUG-2308 / BUG-2310(时间条由程序切段)、BUG-2320、BUG-2333、BUG-2434(同一批负责人反馈)。
- 修复版本:`claude/chat-2433`(本地,未推送)。
## BUG-2434 | 时间条下面一行小灰字里挤着 「### 事业:三段路和两个转折一、……」,标题和段落都没排出来
- 状态:fixed-pending-verify(本地分支 `claude/chat-2433`,未推送)。
- 首次发现 / 最近更新:2026-11-27(负责人,正式站和 staging 同一现象)。
- 现象:时间条下面本该只有一行小灰字(「某年某月是下一个转折点」加出生时间那句),却是一大段连在一起的灰字,里面能看到原样的 `### 事业:…`、`### 财运:…`,「一、」「二、」几条连成一行;正文少了这些内容。
- 触发条件:写回答的模型在时间那一节(「## 接下来十年」)的段落下面接着写了 `###` 小标题和段落(长范围问题常见),而不是另起 `##` 一节。
- 根因:`parseTimeline` 把时间那一节里不是列表项的每一行都当作时间条的脚注,`loose.join("")` 不加分隔连成一句,再去掉 `**` 和换行,交给时间条下面的小灰字(`frontend/src/lib/chat-answer-shape.ts:518`,BUG-2281 `e0492edeb` 引入、`2b56213d3` 沿用)。脚注本来只该放 BUG-2320 定的那一句转折点。两站代码相同,所以两站一样。用本轮真实模型的两份十年回答复现:旧解析器把「### 事业」「### 财运」整段放进脚注,其中一份正文变成空的(`eval-read-1116/bug-2433/parse-before-after.txt`)。
- 修复:时间那一节从第一个 `###`–`######` 小标题起的内容,以及其它不是转折点句的散行,都还给正文,按写的位置排在时间条后面,作为 markdown 渲染;这些行每行单独成段(「一、」「二、」不再连成一段),列表项、续行和表格行保持原样。脚注只留转折点句。列表段、标题、颜色不变。
- 验证:新增 `frontend/tests/chat-strip-body-markdown-2434.test.tsx`(4 项):段落照旧、脚注只剩转折点句;小标题和「一、」行进正文且各自成段、顺序不变;非转折点散行进正文;渲染后 `###` 不再出现,`<h3>` 和分开的 `<p>` 都在,时间条脚注里没有正文内容。
- 防复发:时间条脚注只收转折点句;时间那一节里其余文字一律按正文排。
- 已知限制:正文其它节里模型若把「一、」「二、」写在相邻行、中间不空行,markdown 仍会连成一段(本次没改正文其它节)。
- 关联记录:BUG-2281(结论卡 + 时间条版式)、BUG-2305(时间节标题识别)、BUG-2320(一行脚注)、BUG-2433。
- 修复版本:`claude/chat-2433`(本地,未推送)。
## BUG-2435 | staging 上新对话的标题一直是问题原文,不再生成「事业十年阶段与转折」这类标题
- 状态:fixed-pending-verify(本地分支 `claude/chat-2433`,未推送;待 staging 复测)。
- 首次发现 / 最近更新:2026-11-27(负责人,正式站有生成标题,staging 停在问题原文)。
- 现象:首轮回答完成后,侧栏和顶栏的标题仍是问题的前十几个字,没有换成模型起的短标题。
- 触发条件:写标题用的模型默认开思考(deepseek-flash 这类)。
- 根因:标题调用只设了 `maxOutputTokens: 30`,没有关思考(`frontend/src/lib/session-title-agent.ts:105`,BUG-553 `a1956deb6` 起一直如此)。默认开思考的模型把 30 个 token 全用在思考上,正文为空,`sanitizeSessionTitle` 返回 null,标题不改。`87677ca96..origin/next` 之间标题代码、守卫和数据库函数都没有改,两站差别来自所用模型;正式站当时用的模型能直接出字(没有读两站的模型配置,这一点是推断)。同一类问题 BUG-2284 在追问建议调用上出现过并已修(`consultation-follow-up-agent.ts` 关思考),标题调用当时没有一起查。
- 修复:标题调用和追问建议、修复、闲聊这些小调用一样,`agentGenerationSettings(model, { thinking: "disabled", answerTokens: SESSION_TITLE_MAX_TOKENS })`;上限、超时、清洗和写库守卫不变。
- 验证:真实调用(deepseek-flash,同一句十年事业问题):修前返回空字符串(`""`,1.4 s),修后返回「未来十年事业阶段与转型」(0.9 s)(`eval-read-1116/bug-2433/title/`)。新增 `frontend/tests/session-title-thinking-2435.test.ts`(3 项):发出的请求里每个 provider 的 thinking 都是 disabled、上限仍是 30;生成的标题清洗后返回;空回复仍不改标题。
- 防复发:所有只要几十个 token 的小调用都必须显式关思考;本条与 BUG-2284 同类,复发原因是 BUG-2284 只修了出问题的那一处调用,没有排查同样只设上限的其它调用。
- 关联记录:BUG-553 / BUG-557(标题生成与写库守卫)、BUG-2284(追问建议同因)、BUG-2433。
- 修复版本:`claude/chat-2433`(本地,未推送)。
+47 -5
View File
@@ -501,10 +501,42 @@ function stretchLines(lines: readonly string[], streaming: boolean): { list: Arr
return { list: out, loose };
}
function parseTimeline(section: Section, streaming: boolean, now: number): AnswerShape["timeline"] {
const read = stretchLines(section.lines, streaming);
/** BUG-2434: a sub-heading (「### 事业:……」) inside the time section opens text that belongs to the body, not to the strip. */
const SUB_HEADING_LINE = /^[ \t]{0,3}#{3,6}[ \t]+\S/u;
const BLOCK_CONTINUES = /^(?:[ \t]+\S|[ \t]{0,3}(?:[-*+][ \t]|\d{1,2}[.)][ \t])|[ \t]*\|)/u;
/**
* BUG-2434: lines lifted out of the time section as body markdown. Each line that is not a list item, a list item's
* continuation or a table row starts its own paragraph: the writer's 「一、……」「二、……」 lines sit on consecutive lines, and
* markdown would join them into one run-together paragraph.
*/
function bodyBlocks(lines: readonly string[]): string {
const out: string[] = [];
for (const line of lines) {
const previous = out[out.length - 1];
if (line.trim() && previous !== undefined && previous.trim() && !BLOCK_CONTINUES.test(line)) out.push("");
out.push(line.replace(/[ \t]+$/u, ""));
}
return out.join("\n").replace(/\n{3,}/gu, "\n\n").trim();
}
/**
* The strip of a time-headed section, and what in that section is not the strip (body markdown, in place).
* BUG-2434 原值:every loose line of the section (sub-headings and numbered paragraphs included) was joined with no
* separator into the strip's note — the one small muted footer line — so 「### 事业:三段路和两个转折一、……」 showed raw and run
* together under the strip; 新值:the note keeps only the turning-point sentence (the footer's one job, BUG-2320); from the
* first sub-heading on, and any other loose line, the text goes back to the body as markdown with its line breaks; 原因:负责人
* 2026-11-27 staging 与正式站同一现象。
*/
function parseTimeline(section: Section, streaming: boolean, now: number): { timeline: NonNullable<AnswerShape["timeline"]>; rest: string } | null {
const cut = section.lines.findIndex((line) => SUB_HEADING_LINE.test(line));
const head = cut < 0 ? section.lines : section.lines.slice(0, cut);
const tail = cut < 0 ? [] : section.lines.slice(cut);
const read = stretchLines(head, streaming && cut < 0);
if (!read) return null;
const { list, loose } = read;
const { list } = read;
const loose = read.loose.filter((line) => isTurningPointSentence(line));
const restLines = [...read.loose.filter((line) => !isTurningPointSentence(line)), ...(tail.length ? ["", ...tail] : [])];
const segments: TimelineSegment[] = [];
let previousEnd: number | undefined = now;
for (const { item, stretch } of list) {
@@ -515,7 +547,10 @@ function parseTimeline(section: Section, streaming: boolean, now: number): Answe
}
if (!segments.length && !streaming) return null;
if (segments.length > MAX_TIMELINE_SEGMENTS) return null;
return { heading: section.heading, segments, note: withoutBirthTimeSentence(plain(loose.join(""))) };
return {
timeline: { heading: section.heading, segments, note: withoutBirthTimeSentence(plain(loose.join(""))) },
rest: bodyBlocks(restLines),
};
}
/** 「## 问你一句」: its lines as one sentence (list marker, quotes and bold dropped); null when empty or too long. */
@@ -642,7 +677,14 @@ export function parseAnswerShape(text: string, options: { streaming?: boolean; n
}
if (!timeline && isTimelineHeading(section.heading)) {
const parsed = parseTimeline(section, live, now);
if (parsed) { timeline = parsed; timelineAfterBody = body.some((part) => part.trim().length > 0); timelineLive = live; return; }
if (parsed) {
timeline = parsed.timeline;
timelineAfterBody = body.some((part) => part.trim().length > 0);
timelineLive = live;
// BUG-2434: what the time section holds besides the strip reads as body markdown, where it was written.
if (parsed.rest) body.push(parsed.rest);
return;
}
}
body.push(sectionMarkdown(section));
});
+90 -25
View File
@@ -13,7 +13,9 @@
* two; else 「最省力的时候」; else none); a value that pairs it with a resistance word takes the program's value.
*/
import type { EvidenceCard } from "./consultation-evidence-card.ts";
import { basisLine, plainReasonLine, saturnBackground, statusAnalysis, statusStretches, STRIP_LABEL_TEXT, stripDomain, yearBasis, yearLine, type StripLabel } from "./chat-strip-status.ts";
import { basisLine, dashaStretches, plainReasonLine, saturnBackground, statusAnalysis, statusStretches, STRIP_LABEL_TEXT, stripDomain, yearBasis, yearLine, type StatusStretch, type StripLabel } from "./chat-strip-status.ts";
import { transitWindow } from "./chat-period-coverage.ts";
import { chineseNumeral } from "./answer-markdown-sanity.ts";
import { KP_WINDOWS_READING, kpLines } from "./chat-kp-timing.ts";
import { normalizeEvidenceTags } from "./chat-evidence-tags.ts";
import { splitJudgmentBasis } from "./consult-judgment-basis.ts";
@@ -133,6 +135,13 @@ export function stretchRange(from: number, to: number, now: number): string {
}
const addDaysIso = (iso: string, n: number) => new Date(Date.parse(`${iso}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
const rec = (value: unknown): Record<string, unknown> => (value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {});
const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
const isoAfterYears = (iso: string, years: number) => {
const date = new Date(`${iso}T00:00:00Z`);
date.setUTCFullYear(date.getUTCFullYear() + years);
return date.toISOString().slice(0, 10);
};
const isoOfMonth = (index: number) => `${Math.floor(index / 12)}-${String((index % 12) + 1).padStart(2, "0")}-01`;
/**
@@ -150,27 +159,65 @@ const isoOfMonth = (index: number) => `${Math.floor(index / 12)}-${String((index
*/
export const STRIP_DISPLAY_MAX = 6;
/**
* BUG-2433: how many years ahead the strip reaches — the writer's horizon_years on the tool call (card.strip_years, a
* structured field, never a word match on the user's text), else 1. 原值:the strip was always the next 12 months and a
* ten-year question was left to the writer's choice between strip_stretches (12 months) and period_coverage; 新值:the
* program cuts the declared years; 原因:负责人 2026-11-27 — the same ten-year question got 「接下来十年」 on one site and
* 「接下来一年」 on the other.
*/
export const STRIP_HORIZON_MAX_YEARS = 10;
export function stripHorizonYears(card: EvidenceCard | null): number {
const years = Number(card?.strip_years);
return Number.isFinite(years) && years > 1 ? Math.min(STRIP_HORIZON_MAX_YEARS, Math.floor(years)) : 1;
}
/** 「接下来一年」 for the default strip; 「接下来十年」 when the stretches reach about ten years (never more than asked). */
export function stripHeading(card: EvidenceCard | null, stretches: readonly ProgramStretch[]): string {
const asked = stripHorizonYears(card);
if (asked <= 1 || !stretches.length) return DEFAULT_TIMELINE_HEADING;
const covered = Math.round((Date.parse(stretches.at(-1)!.toDay) - Date.parse(stretches[0]!.fromDay)) / (365.25 * 86_400_000));
const years = Math.min(asked, Math.max(1, covered));
return years <= 1 ? DEFAULT_TIMELINE_HEADING : `接下来${years === 2 ? "两" : chineseNumeral(years)}年`;
}
/** The first year's end: stretched to the end of the sub-period running then (at most six months more, inside the data). */
const NEAR_STRETCH_MAX_DAYS = 183;
function nearEnd(card: EvidenceCard, from: string, to: string): string {
const window = transitWindow(card);
const vim = rec(rec(rec(card.base).timing).vimshottari);
const rows = [...arr(vim.antardashas_in_mahadasha), ...arr(rec(vim.next_mahadasha).antardashas)].map((row) => arr(row).map(String));
const running = rows.find((row) => (row[1] ?? "").slice(0, 10) < to && (row[2] ?? "").slice(0, 10) > to);
const end = running?.[2]?.slice(0, 10);
if (!end || !window || end > window[1]) return to;
return Date.parse(end) - Date.parse(to) <= NEAR_STRETCH_MAX_DAYS * 86_400_000 && end > from ? end : to;
}
function statusForStrip(card: EvidenceCard, now: number, within: readonly [number, number] | undefined, wholeByDasha: boolean): StatusStretch[] {
if (within) return statusStretches(card, { from: isoOfMonth(Math.max(now, within[0])), to: isoOfMonth(within[1] + 1), now });
const years = stripHorizonYears(card);
if (years <= 1) return statusStretches(card, { now });
// BUG-2433: the first year as before (transits and sub-sub-periods), then one stretch per sub-period up to the horizon.
const year = statusAnalysis(card, { now });
if (!year.from) return [];
const end = isoAfterYears(year.from, years);
if (wholeByDasha) return dashaStretches(card, { from: year.from, to: end });
const to = nearEnd(card, year.from, year.to);
const near = to === year.to ? [...year.stretches] : statusStretches(card, { from: year.from, to, now });
return [...near, ...dashaStretches(card, { from: near.at(-1)?.to ?? to, to: end })];
}
export function programStretches(card: EvidenceCard | null, options: { now?: number; within?: readonly [number, number] } = {}): ProgramStretch[] {
if (!card) return [];
const now = options.now ?? currentMonthIndex();
const status = options.within
? statusStretches(card, { from: isoOfMonth(Math.max(now, options.within[0])), to: isoOfMonth(options.within[1] + 1), now })
: statusStretches(card, { now });
if (!status.length) return [];
const own = options.within ? null : status;
const domain = stripDomain(card);
const list = status.map((item, index) => ({ items: [item], wKeys: own ? [`W${index + 1}`] : [] as string[] }));
while (list.length > STRIP_DISPLAY_MAX) {
let best = -1;
for (let index = 0; index + 1 < list.length; index += 1) {
if (list[index]!.items[0]!.label !== list[index + 1]!.items[0]!.label) continue;
const span = Date.parse(list[index + 1]!.items.at(-1)!.to) - Date.parse(list[index]!.items[0]!.from);
if (best < 0 || span < Date.parse(list[best + 1]!.items.at(-1)!.to) - Date.parse(list[best]!.items[0]!.from)) best = index;
}
if (best < 0) break;
const [a, b] = [list[best]!, list[best + 1]!];
list.splice(best, 2, { items: [...a.items, ...b.items], wKeys: [...a.wKeys, ...b.wKeys] });
let list = joinedStretches(statusForStrip(card, now, options.within, false), !options.within);
// BUG-2433: a long horizon whose first year alone fills the strip is read by sub-periods throughout, so the page can
// hold it (MAX_TIMELINE_SEGMENTS); still too many, the strip stops at the last stretch it can hold.
if (!options.within && stripHorizonYears(card) > 1 && list.length > MAX_TIMELINE_SEGMENTS) {
list = joinedStretches(statusForStrip(card, now, undefined, true), true).slice(0, MAX_TIMELINE_SEGMENTS);
}
if (!list.length) return [];
const domain = stripDomain(card);
return list.map(({ items, wKeys }) => {
const fromDay = items[0]!.from;
const toDay = items.at(-1)!.to;
@@ -185,6 +232,23 @@ export function programStretches(card: EvidenceCard | null, options: { now?: num
});
}
/** Neighbours with the same label join beyond STRIP_DISPLAY_MAX (shortest joined span first); W keys when the strip is the program's own. */
function joinedStretches(status: readonly StatusStretch[], own: boolean): Array<{ items: StatusStretch[]; wKeys: string[] }> {
const list = status.map((item, index) => ({ items: [item], wKeys: own ? [`W${index + 1}`] : [] as string[] }));
while (list.length > STRIP_DISPLAY_MAX) {
let best = -1;
for (let index = 0; index + 1 < list.length; index += 1) {
if (list[index]!.items[0]!.label !== list[index + 1]!.items[0]!.label) continue;
const span = Date.parse(list[index + 1]!.items.at(-1)!.to) - Date.parse(list[index]!.items[0]!.from);
if (best < 0 || span < Date.parse(list[best + 1]!.items.at(-1)!.to) - Date.parse(list[best]!.items[0]!.from)) best = index;
}
if (best < 0) break;
const [a, b] = [list[best]!, list[best + 1]!];
list.splice(best, 2, { items: [...a.items, ...b.items], wKeys: [...a.wKeys, ...b.wKeys] });
}
return list;
}
/**
* BUG-2310 review: the year's background — reasons covering (nearly) the whole next 12 months — as one plain line for the
* writer and the astrological facts for its 「判断依据」 row (key YR). Empty when nothing covers the year.
@@ -231,15 +295,15 @@ export function stripStretchLines(stretches: readonly ProgramStretch[]): string[
}
export const STRIP_STRETCHES_READING =
"strip_stretches 是程序按这道题的领域切好的接下来 12 个月:每一段写了起止、这一段的说法(有机会 / 有机会,但费力 / 较费力;「不标」就是不加说法)和为什么(有利、费力、其中某几天);「但:……」是这一段次要的一面(主要的一面已经定了说法),用平常话写成那句话里的一个分句(「但推进会慢一些」),不改这一段的说法,也不用吃力、费力、机会、顺这类词;「另外:……」是不标的那一段里同时有的两件小事,照样写成分句。「这段时间:……」是这一段这件事上会更多出现的变化(各种运期在这一段启动了这件事),照样写成确定的趋势(「这段时间工作上的调整和职责变化会更多」),不写成具体事件(到账、结婚、升职这类),也不因为它改这一段的说法。首轮「## 接下来一年」就照这几段写,一段一条,段数照它(不凑数、不合并),起止和〔编号〕照抄;小标题和那句话照这一段的说法和为什么写:有机会的写清是什么机会;有机会,但费力的写清机会是什么、费力在哪;较费力的写清哪里费力;不标的写这一段最适合做什么。「其中……」那几天写进这一段的那句话里。best_time 是结论卡时间那一行的标签和值,照写;没有 best_time 就不写时间那一行。year_background 是这一整年都在的底色(整年都有的帮助和要花的力气):在结论那一句里用平常话说一次(这一年适合做什么、要付出什么),句末不写编号,「判断依据」里写一条带〔YR〕;不挂在每一段上,每段只写这一段自己的说法和为什么。saturn_background 是土星绕月亮那几年的背景:全篇最多说一次,放在「要留意的」,说清从哪一年到哪一年(只写年份)、日子里是什么样子;year_background 已经说到同样的话时不再重复;不挂在每一段上,也不用它给哪一段定说法。用户说了别的范围时,按 period_coverage 照他的范围写,说法只写 strip_stretches 里有的。";
"strip_stretches 是程序按这道题的领域切好的接下来 12 个月:每一段写了起止、这一段的说法(有机会 / 有机会,但费力 / 较费力;「不标」就是不加说法)和为什么(有利、费力、其中某几天);「但:……」是这一段次要的一面(主要的一面已经定了说法),用平常话写成那句话里的一个分句(「但推进会慢一些」),不改这一段的说法,也不用吃力、费力、机会、顺这类词;「另外:……」是不标的那一段里同时有的两件小事,照样写成分句。「这段时间:……」是这一段这件事上会更多出现的变化(各种运期在这一段启动了这件事),照样写成确定的趋势(「这段时间工作上的调整和职责变化会更多」),不写成具体事件(到账、结婚、升职这类),也不因为它改这一段的说法。首轮「## 接下来一年」就照这几段写,一段一条,段数照它(不凑数、不合并),起止和〔编号〕照抄;小标题和那句话照这一段的说法和为什么写:有机会的写清是什么机会;有机会,但费力的写清机会是什么、费力在哪;较费力的写清哪里费力;不标的写这一段最适合做什么。「其中……」那几天写进这一段的那句话里。best_time 是结论卡时间那一行的标签和值,照写;没有 best_time 就不写时间那一行。year_background 是这一整年都在的底色(整年都有的帮助和要花的力气):在结论那一句里用平常话说一次(这一年适合做什么、要付出什么),句末不写编号,「判断依据」里写一条带〔YR〕;不挂在每一段上,每段只写这一段自己的说法和为什么。saturn_background 是土星绕月亮那几年的背景:全篇最多说一次,放在「要留意的」,说清从哪一年到哪一年(只写年份)、日子里是什么样子;year_background 已经说到同样的话时不再重复;不挂在每一段上,也不用它给哪一段定说法。用户说了别的范围时,按 period_coverage 照他的范围写,说法只写 strip_stretches 里有的。卡上有 strip_heading 时,strip_stretches 已经照用户问的年数切好(第一年按月份细分,之后按小运分段):时间那一节的标题照 strip_heading 写,段照 strip_stretches 写,不再按 period_coverage 另切。";
/** The fact for the verdict's time label (timing.best_time). */
export function bestTimeFact(stretches: readonly ProgramStretch[]): string | null {
/** The fact for the verdict's time label (timing.best_time). BUG-2433: a strip over several years says 「这段时间」. */
export function bestTimeFact(stretches: readonly ProgramStretch[], span = "这一年"): string | null {
const best = bestTime(stretches);
if (!best) return null;
return best.label === BEST_TIME_LABEL
? `- **${BEST_TIME_LABEL}**:${best.value}(这一年里有明确帮助的${best.value.includes(",") ? "两段,用处不同,各说各的" : "时候"})`
: `- **${EASIEST_TIME_LABEL}**:${best.value}(这一年没有特别帮这件事的一段,这是阻力最少的;标签写「${EASIEST_TIME_LABEL}」,不写「${BEST_TIME_LABEL}」)`;
? `- **${BEST_TIME_LABEL}**:${best.value}(${span}里有明确帮助的${best.value.includes(",") ? "两段,用处不同,各说各的" : "时候"})`
: `- **${EASIEST_TIME_LABEL}**:${best.value}(${span}没有特别帮这件事的一段,这是阻力最少的;标签写「${EASIEST_TIME_LABEL}」,不写「${BEST_TIME_LABEL}」)`;
}
/**
@@ -491,7 +555,8 @@ export function claimCardsWithStripStretches<T extends { category: string; evide
let stretches: ProgramStretch[] = [];
try { stretches = programStretches(card, { now }); } catch { return [...claimCards]; }
if (!stretches.length) return [...claimCards];
const best = bestTimeFact(stretches);
const heading = stripHeading(card, stretches);
const best = bestTimeFact(stretches, heading === DEFAULT_TIMELINE_HEADING ? "这一年" : "这段时间");
const background = saturnBackground(card, stretches[0]!.fromDay, stretches.at(-1)!.toDay);
const year = programYear(card, now);
// BUG-2325: KP's narrower days inside the stretches (career, money, relationship), tied to each stretch's W key.
@@ -501,6 +566,6 @@ export function claimCardsWithStripStretches<T extends { category: string; evide
if (claim.category !== "timing") return claim;
const evidence = (claim.evidence && typeof claim.evidence === "object" ? claim.evidence : {}) as Record<string, unknown>;
const tables = (evidence.precomputed_tables && typeof evidence.precomputed_tables === "object" ? evidence.precomputed_tables : {}) as Record<string, unknown>;
return { ...claim, evidence: { ...evidence, precomputed_tables: { ...tables, strip_stretches_reading: STRIP_STRETCHES_READING, strip_stretches: stripStretchLines(stretches), ...(best ? { best_time: best } : {}), ...(background.length ? { saturn_background: background } : {}), ...(year.line ? { year_background: `〔YR〕${year.line}` } : {}), ...(kp.length ? { kp_windows_reading: KP_WINDOWS_READING, kp_windows: kp } : {}) } } };
return { ...claim, evidence: { ...evidence, precomputed_tables: { ...tables, strip_stretches_reading: STRIP_STRETCHES_READING, ...(heading === DEFAULT_TIMELINE_HEADING ? {} : { strip_heading: heading }), strip_stretches: stripStretchLines(stretches), ...(best ? { best_time: best } : {}), ...(background.length ? { saturn_background: background } : {}), ...(year.line ? { year_background: `〔YR〕${year.line}` } : {}), ...(kp.length ? { kp_windows_reading: KP_WINDOWS_READING, kp_windows: kp } : {}) } } };
});
}
+2 -1
View File
@@ -71,7 +71,8 @@ export function coverageText(coverage: Coverage): string {
// ---- card access ------------------------------------------------------------------------------------------------
export type Period = { level: "小运" | "细运"; lord: string; md: string; ad: string; start: string; end: string };
/** BUG-2433: 「大运」 only for a whole main period the card lists without its sub-periods (the long-range strip). */
export type Period = { level: "大运" | "小运" | "细运"; lord: string; md: string; ad: string; start: string; end: string };
/** The transit window the slow-planet and double-transit data cover. */
export function transitWindow(card: EvidenceCard): Span | null {
+88
View File
@@ -526,6 +526,94 @@ export function statusAnalysis(card: EvidenceCard | null, options: { from?: stri
}
}
/**
* BUG-2433: the stretches of [from, to) after the first year of a question that looks years ahead (the card's horizon,
* BUG-1643). One stretch per Vimshottari sub-period (小运) on the card — the running mahadasha's and, when the horizon
* reaches it, the next one's — read with the dasha rules only (S1 / R1 on the sub-period lord, R2 between the main and
* sub-period lords): the transit data cover four years at most, and month-level transit detail does not belong to a
* reading by years. Neighbours with the same reasons join; a piece shorter than three weeks (a clipped edge) joins its
* neighbour. Where the card lists no more sub-periods the stretches stop. Never throws.
*/
/** BUG-2433: a sub-period the horizon's end cuts to less than this is left off the long-range strip. */
export const HORIZON_EDGE_DAYS = 183;
export function dashaStretches(card: EvidenceCard | null, options: { from: string; to: string }): StatusStretch[] {
if (!card || options.from >= options.to) return [];
try {
const chart = chartOf(card);
if (!chart) return [];
const domain = stripDomain(card);
const vim = rec(rec(rec(card.base).timing).vimshottari);
const isoDay = /^\d{4}-\d{2}-\d{2}$/u;
const rows: Array<{ md: Period; ad: Period }> = [];
const collect = (mdLord: string, source: unknown) => {
if (!mdLord) return;
for (const row of arr(source)) {
const [lord, start, end] = arr(row).map((value) => String(value ?? ""));
const from = (start ?? "").slice(0, 10);
const to = (end ?? "").slice(0, 10);
if (!lord || !isoDay.test(from) || !isoDay.test(to) || from >= to) continue;
rows.push({
md: { level: "小运", lord: mdLord, md: mdLord, ad: "", start: from, end: to },
ad: { level: "小运", lord, md: mdLord, ad: lord, start: from, end: to },
});
}
};
collect(String(rec(vim.mahadasha).lord ?? ""), vim.antardashas_in_mahadasha);
const next = rec(vim.next_mahadasha);
collect(String(next.lord ?? ""), next.antardashas);
// A main period the card lists without its sub-periods (the next one when the engine sent none, the ones after it) is
// one stretch, read on its own lord.
const whole = (lord: string, start: string, end: string) => {
if (!lord || !isoDay.test(start) || !isoDay.test(end) || start >= end) return;
const period: Period = { level: "大运", lord, md: lord, ad: lord, start, end };
rows.push({ md: period, ad: period });
};
if (!arr(next.antardashas).length) whole(String(next.lord ?? ""), String(next.start ?? "").slice(0, 10), String(next.end ?? "").slice(0, 10));
for (const row of arr(vim.later_mahadashas)) {
const [lord, start, end] = arr(row).map((value) => String(value ?? ""));
whole(lord ?? "", (start ?? "").slice(0, 10), (end ?? "").slice(0, 10));
}
rows.sort((a, b) => a.ad.start.localeCompare(b.ad.start));
const pieces: Piece[] = [];
for (const { md, ad } of rows) {
const from = ad.start > options.from ? ad.start : options.from;
const to = ad.end < options.to ? ad.end : options.to;
if (from >= to) continue;
const reasons = reasonsAt(chart, { md, ad, signs: {}, double: [], cycle: null, cycleSpan: null, packet: [] }, domain);
const last = pieces[pieces.length - 1];
if (last && last.to > from) continue;
if (last && last.to === from && signature(last.reasons) === signature(reasons)) last.to = to;
else pieces.push({ from, to, reasons, partial: [] });
}
// The horizon's end falls wherever ten years from today lands: a sub-period it only grazes (under half a year) is
// left off rather than shown as a sliver (the real run's last stretch was 「2036 年 9 月中旬到 10 月」).
const tail = pieces[pieces.length - 1];
const tailPeriod = rows.find(({ ad }) => tail && ad.start <= tail.from && ad.end > tail.from);
if (tail && pieces.length > 1 && tail.to === options.to && tailPeriod && tailPeriod.ad.end > options.to && days(tail.from, tail.to) < HORIZON_EDGE_DAYS) pieces.pop();
for (;;) {
const index = pieces.length > 1 ? pieces.findIndex((piece) => days(piece.from, piece.to) < SHORT_PIECE_DAYS) : -1;
if (index < 0) break;
const short = pieces[index]!;
const host = pieces[index + 1] ?? pieces[index - 1]!;
host.from = host.from < short.from ? host.from : short.from;
host.to = host.to > short.to ? host.to : short.to;
pieces.splice(index, 1);
}
const coverage = periodCoverageRows(card);
return pieces.map((piece) => ({
from: piece.from,
to: piece.to,
label: labelOf(piece.reasons),
reasons: dedupePlain(piece.reasons),
partial: [],
keys: coverage.flatMap((row, index) => (row.period.start < piece.to && row.period.end > piece.from ? [`T${index + 1}`] : [])),
}));
} catch {
return [];
}
}
/** One reason per underlying fact (the same Saturn transit under several names is one line). */
function dedupePlain(reasons: readonly StripReason[]): StripReason[] {
const seen = new Set<string>();
@@ -771,6 +771,8 @@ export type EvidenceCard = {
day_calendar?: DayCalendar;
/** BUG-2357: the event class per domain and KP-only, as the writer declared them on the tool call; absent = defaults. */
kp_scope?: KpScope;
/** BUG-2433: the years the time strip covers, as the writer declared them on the tool call (`horizon_years`); absent = 1. */
strip_years?: number;
meta: {
backstage: typeof EVIDENCE_CARD_BACKSTAGE_LINE;
/** BUG-1976: the calculation snapshot (birth input revision, date, rule versions) the evidence ids belong to. */
@@ -816,6 +818,8 @@ export type EvidenceCardOptions = Readonly<{
question?: string | null;
/** BUG-1643: the request's server time; where a horizon of N years starts. Defaults to now. */
requestTime?: Date | null;
/** BUG-2433: the writer's horizon_years; the horizon is the larger of it and the question's. */
horizonYears?: number | null;
}>;
/**
@@ -3721,7 +3725,9 @@ export function buildEvidenceCard(
if (sources.length === 0) throw new Error("evidence_card_needs_a_domain");
const gaps: string[] = [];
const first = sources[0]!;
const horizonYears = evidenceCardTimingHorizonYears(options.question);
const asked = evidenceCardTimingHorizonYears(options.question);
const declared = typeof options.horizonYears === "number" && options.horizonYears > 0 ? options.horizonYears : null;
const horizonYears = asked === null && declared === null ? null : Math.max(asked ?? 0, declared ?? 0);
const horizon: TimingHorizon | null = horizonYears === null
? null
: { years: horizonYears, at: options.requestTime && !Number.isNaN(options.requestTime.getTime()) ? options.requestTime : new Date() };
+5 -1
View File
@@ -7,6 +7,7 @@ import {
isAutoDerivedSessionTitle,
} from "@/lib/session-title";
import type { ResolvedLanguageModel } from "@/mastra/model";
import { agentGenerationSettings } from "@/lib/agent-generation-settings";
export {
sanitizeSessionTitle,
@@ -102,7 +103,10 @@ export async function generateSessionTitleText(
].join("\n"),
}], {
abortSignal: signal,
modelSettings: { maxOutputTokens: SESSION_TITLE_MAX_TOKENS },
// BUG-2435 原值:modelSettings: { maxOutputTokens: SESSION_TITLE_MAX_TOKENS }(不关思考);
// 新值:和追问建议、修复、闲聊这些小调用一样关掉思考,上限仍是 SESSION_TITLE_MAX_TOKENS;
// 原因:deepseek-flash 默认开思考,30 个 token 全花在思考上,正文为空,标题停在问题原文(BUG-2284 同一类)。
...agentGenerationSettings(model.model, { thinking: "disabled", answerTokens: SESSION_TITLE_MAX_TOKENS }),
});
const text = typeof result.text === "string" ? result.text : "";
return text.trim();
+3 -2
View File
@@ -30,7 +30,7 @@ import { logTruncatedReasoning } from "./consultation-budget.ts";
import { basisSourcesFromCard, withCompletedBasis } from "./chat-basis-completeness.ts";
import { answerShapeData } from "./chat-answer-shape-data.ts";
import { checkDayCalendar, dayCalendarShape, dayPanelTexts } from "./chat-day-calendar.ts";
import { bodyStripDateFlags, bodyStripDisagreements, datedWindow, programStretches, serverAnswerShape, timelineRequirement, timelineSectionFromReply, timelineSectionPrompt, withProgramBestTime, withTimelineSection } from "./chat-answer-timeline.ts";
import { bodyStripDateFlags, bodyStripDisagreements, datedWindow, stripHeading, programStretches, serverAnswerShape, timelineRequirement, timelineSectionFromReply, timelineSectionPrompt, withProgramBestTime, withTimelineSection } from "./chat-answer-timeline.ts";
import { addImpliedKeys, bodyMechanismSentences, bodyTerms, checkBodyDirection, checkDirection, checkStripTone, checkTimelineEntries, expandEvidenceKeys, hasEvidenceTags, unkeyedConclusions } from "./chat-evidence-keys.ts";
import { chineseNamesAndTerms, cleanChatAnswer } from "./chat-answer-checks.ts";
import { sanitizeAnswerMarkdown } from "./answer-markdown-sanity.ts";
@@ -1342,7 +1342,8 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) {
} catch {
record.call = "failed";
}
if (section) { output = withTimelineSection(output, section); timelineSectionAdded = section; }
// BUG-2433: the section's heading follows the strip's years (「接下来十年」), the default 「接下来一年」 otherwise.
if (section) { output = withTimelineSection(output, section, window ? undefined : stripHeading(card, stretches)); timelineSectionAdded = section; }
}
appendConsultationRuntimeStep(options.state, { kind: "validation", name: "answer-timeline-section", status: record.call === "added" ? "completed" : "failed", failureCode: `${need.reason}:${String(record.call)};stretches:${stretches.length}` });
}
+18 -1
View File
@@ -1,4 +1,5 @@
import { KP_EVENT_CLASSES, kpScopeFrom } from "../lib/chat-kp-events.ts";
import { STRIP_HORIZON_MAX_YEARS } from "../lib/chat-answer-timeline.ts";
import { fetchWesternNatalFacts, westernScope, type WesternBasisFacts, type WesternGuardFacts, type WesternScope } from "../lib/chat-western-facts.ts";
import { attachFastTransits, attachKpTimingPacket, attachKpTransitLords, fetchDayCalendar } from "../lib/chat-transit-window.ts";
import { clampDayRange, DAY_CALENDAR_MAX_DAYS } from "../lib/chat-day-calendar.ts";
@@ -411,8 +412,19 @@ const consultationToolInputSchema = z.object({
// writer's own judgment, never a word match). Absent: each domain's default event, KP and Parashari together.
event_classes: z.array(z.enum(KP_EVENT_CLASSES)).max(3).optional(),
kp_only: z.boolean().optional(),
// BUG-2433: how many years ahead the question asks about (「未来十年」 → 10), the writer's own judgment, never a word match;
// the time strip is cut over those years (2 to 10; chat-answer-timeline.ts stripHorizonYears). A number, not a strict
// integer range, so an odd value never fails the call: it is rounded and clamped. Absent: the next 12 months.
horizon_years: z.number().finite().optional(),
}).strict();
/** BUG-2433: the writer's horizon_years as the strip's years (2 to STRIP_HORIZON_MAX_YEARS), else null. */
export function stripYearsFrom(value: number | undefined): number | null {
if (typeof value !== "number" || !Number.isFinite(value)) return null;
const years = Math.round(value);
return years >= 2 ? Math.min(STRIP_HORIZON_MAX_YEARS, years) : null;
}
const MAX_RECORDED_STEPS = 32;
export type ConsultationStepBudget = {
@@ -1689,7 +1701,7 @@ export function createConsultationTools(ctx: ConsultationAgentContext) {
};
const consultationTool = createTool({
id: "run-jyotish-consultation",
description: `Run one server-validated plan of personal Jyotish consultation domains. Send only question and domains (both required; choose the domains from this question, not from the conversation's first topic). The single ordered domains array is the only way to select domains: list every domain the question needs, in priority order, up to ${MAX_CONSULTATION_DOMAIN_PLAN_VALUES}. Do not drop a relevant domain to shorten the plan. Use only the ids enumerated in the schema; workflow or checklist names from the skill's methodology are not domain ids. Questions about one's parents (父母) use parents and questions about one's children (子女) use children; family is only for the household as a whole (家里、家庭氛围). Domains execute one after another and each costs about ${Math.round(CONSULTATION_DOMAIN_DURATION_MS / 1000)}s of the run's wall clock; the server executes as many as that clock can pay for (about ${MAX_CONSULTATION_DOMAINS}) and lists the rest in omitted_domains: those are not run in this request, a second call cannot run them, and the user can ask about them in a later message. Birth data is server-bound and must never be supplied. The result always carries one top-level answer contract—status, evidence_contract, claim_cards, rectification—which for several domains is the most restrictive merge of the executed ones, with each domain's own contract in consultations. claim_cards is the evidence card: the base chart (ascendant, house signs, placements, functional benefics/malefics, the D9 summary with dignities, Vargottama and D1/D9 reversals, the running Vimshottari and Narayana periods) and a section per domain; evidence_card lists what else this calculation holds. One calculation is executed per request: a repeated call returns only a short pointer to the first result (already_returned), never the card again. When the question's time scale is specific days — this week, these few days, one day, which days of a month or of the next few weeks — also send day_range {start, end} (YYYY-MM-DD, from today's date in the server time line; a week is Monday to Sunday; at most ${DAY_CALENDAR_MAX_DAYS} days): the card then carries day_calendar, this person's own day-by-day calendar for those days (the same one the 星历 page shows). Do not send day_range for questions about months, years or a period of life. When the user asks about Western astrology (西洋占星, 西方占星, the tropical Sun sign, Western elements, aspects or patterns), also send western_chart: "only" when the question asks only for the Western reading, or "both" when it asks for the Indian and the Western reading together (compare, both sides, 两边): the result then carries western_natal, this person's Western tropical chart (the same facts as the chart page's Western tab: angles, the ten planets with sign, degree, house and dignity, element / modality / hemisphere counts, stelliums, patterns, every major aspect). Every Western claim rests only on western_natal; the evidence card is the Indian sidereal chart (different signs and houses) and is never the basis of a Western claim. Do not send western_chart for a question that does not ask about Western astrology. For a relationship, career or money question also send event_classes, one per domain, naming the event the question is about: relationship first_contact_channel (how / where / through whom one meets a partner), romantic_activation (falling in love), relationship_formation (whether a relationship forms), legal_marriage (marriage itself), marital_relationship (an existing marriage); career employment (getting and keeping a job), business_clients (own business, clients, partners), job_content (what kind of work suits), promotion_change (promotion, leaving, changing job); money income (where money comes from), savings (keeping money), loans, investment, shared_funds (joint money, insurance, inheritance), foreign_funds. Send kp_only: true only when the user asks to read by KP alone.`,
description: `Run one server-validated plan of personal Jyotish consultation domains. Send only question and domains (both required; choose the domains from this question, not from the conversation's first topic). The single ordered domains array is the only way to select domains: list every domain the question needs, in priority order, up to ${MAX_CONSULTATION_DOMAIN_PLAN_VALUES}. Do not drop a relevant domain to shorten the plan. Use only the ids enumerated in the schema; workflow or checklist names from the skill's methodology are not domain ids. Questions about one's parents (父母) use parents and questions about one's children (子女) use children; family is only for the household as a whole (家里、家庭氛围). Domains execute one after another and each costs about ${Math.round(CONSULTATION_DOMAIN_DURATION_MS / 1000)}s of the run's wall clock; the server executes as many as that clock can pay for (about ${MAX_CONSULTATION_DOMAINS}) and lists the rest in omitted_domains: those are not run in this request, a second call cannot run them, and the user can ask about them in a later message. Birth data is server-bound and must never be supplied. The result always carries one top-level answer contract—status, evidence_contract, claim_cards, rectification—which for several domains is the most restrictive merge of the executed ones, with each domain's own contract in consultations. claim_cards is the evidence card: the base chart (ascendant, house signs, placements, functional benefics/malefics, the D9 summary with dignities, Vargottama and D1/D9 reversals, the running Vimshottari and Narayana periods) and a section per domain; evidence_card lists what else this calculation holds. One calculation is executed per request: a repeated call returns only a short pointer to the first result (already_returned), never the card again. When the question's time scale is specific days — this week, these few days, one day, which days of a month or of the next few weeks — also send day_range {start, end} (YYYY-MM-DD, from today's date in the server time line; a week is Monday to Sunday; at most ${DAY_CALENDAR_MAX_DAYS} days): the card then carries day_calendar, this person's own day-by-day calendar for those days (the same one the 星历 page shows). Do not send day_range for questions about months, years or a period of life. When the user asks about Western astrology (西洋占星, 西方占星, the tropical Sun sign, Western elements, aspects or patterns), also send western_chart: "only" when the question asks only for the Western reading, or "both" when it asks for the Indian and the Western reading together (compare, both sides, 两边): the result then carries western_natal, this person's Western tropical chart (the same facts as the chart page's Western tab: angles, the ten planets with sign, degree, house and dignity, element / modality / hemisphere counts, stelliums, patterns, every major aspect). Every Western claim rests only on western_natal; the evidence card is the Indian sidereal chart (different signs and houses) and is never the basis of a Western claim. Do not send western_chart for a question that does not ask about Western astrology. For a relationship, career or money question also send event_classes, one per domain, naming the event the question is about: relationship first_contact_channel (how / where / through whom one meets a partner), romantic_activation (falling in love), relationship_formation (whether a relationship forms), legal_marriage (marriage itself), marital_relationship (an existing marriage); career employment (getting and keeping a job), business_clients (own business, clients, partners), job_content (what kind of work suits), promotion_change (promotion, leaving, changing job); money income (where money comes from), savings (keeping money), loans, investment, shared_funds (joint money, insurance, inheritance), foreign_funds. Send kp_only: true only when the user asks to read by KP alone. When the question asks about a span of years ahead (未来十年, 接下来三年, 这几年, the next five years), also send horizon_years with that number of years: the time strip (strip_stretches) is then cut over those years instead of the next 12 months. Do not send horizon_years for this year, the next few months, specific days, or a when-question that names no span.`,
inputSchema: consultationToolInputSchema,
execute: async (input, context) => {
// BUG-2326: a follow-up whose route names no subject (timing / general / annual) keeps the previous answer's subject.
@@ -1905,7 +1917,12 @@ export function createConsultationTools(ctx: ConsultationAgentContext) {
// BUG-1643: a question that looks N years ahead gets the periods after the running ones.
question: userIntent,
requestTime: ctx.requestTime ?? new Date(),
// BUG-2433: the writer's horizon_years also reaches the card's horizon block (the periods it lists).
horizonYears: stripYearsFrom(input.horizon_years),
});
// BUG-2433: the strip's years (the writer's horizon_years); absent: the next 12 months.
const stripYears = stripYearsFrom(input.horizon_years);
if (stripYears) card.strip_years = stripYears;
// BUG-2357: the writer's event classes and KP-only choice, read by the KC / PC rows.
const kpScope = kpScopeFrom(input);
if (kpScope) card.kp_scope = kpScope;
+1 -1
View File
@@ -307,7 +307,7 @@ export const chatConversationVoice = `VISIBLE VOICE
第一行一句话回答这个问题,先给结论;用户问能不能、会不会、是不是的时候,第一句先答能或不能、会或不会(拿不准就说多半能、多半不会),再说条件。接着三行,按问题的领域选一组标签,标签一字不改,冒号后面写你的判断,每行 15 字以内:
${verdictLabelLines()}
## ${DEFAULT_TIMELINE_HEADING}(紧跟在结论后面写;首轮除了性格题(只问「我是什么样的人」「我的性格」,结论卡用性格那组标签)和问具体哪几天的题(卡上有 day_calendar,页面在这个位置画日历)都写这一节,「我适合做什么」「幕后还是台前」这类事业题也写:读的人会想知道什么时候动。用户说了范围就照他的范围写,标题改成「接下来两年」「2027 到 2028 年」这样)
每条一行,写成「- **小标题**(2026 年 11 月到 12 月):一句话说这一段是什么样子。该做:……。别做:……。〔W1 T3 T4〕」。小标题 2 到 4 个字(收尾、起步、最好用、守住);括号里只写起止,第一段从「现在」写起(「现在到 2026 年 12 月」),月中换段的写「5 月中旬」,照 strip_stretches 的写法。一般问题照 strip_stretches 的几段写(程序按这道题的领域切好的接下来 12 个月,段数照它,不凑数、不合并;起止、说法和〔编号〕照抄);用户说了范围就照他的范围按 period_coverage 写,最多 8 条,末尾〔〕写合并的 period_coverage 行的编号,起止从这些行来。每段的小标题和那句话照这一段的说法和为什么写:「有机会」写清是什么机会、怎么抓,不写吃力、费力,小标题也不用紧、守住、收着;「有机会,但费力」写清机会是什么、费力在哪,两样都写,不写轻松、平稳、顺;「较费力」写清哪里费力、怎么省力,不写机会、轻松、平稳、顺;「不标」写这一段最适合做什么,不写吃力,也不写平稳、顺。为什么只照 strip_stretches 写到的那几条,不自己另加好坏;没写到帮助或阻力不等于平稳,「平稳」这个词不用。「其中……」那几天写进这一段的那句话里(「其中 1 月上旬事情会多一些」)。那一句 36 字以内,该做、别做各 24 字以内。每段只说一件确定的事和怎么做,不写可能、或许、也许、不排除、视情况、有好有坏这类两头的话。出生时间会让日期移动几天这句不写进任何一段(页面在时间条下面统一写一次)。最后可以另起一行(不加「-」)写「12 个月之后,下一个转折点在某年某月,……」一句,只写在这一节。
每条一行,写成「- **小标题**(2026 年 11 月到 12 月):一句话说这一段是什么样子。该做:……。别做:……。〔W1 T3 T4〕」。小标题 2 到 4 个字(收尾、起步、最好用、守住);括号里只写起止,第一段从「现在」写起(「现在到 2026 年 12 月」),月中换段的写「5 月中旬」,照 strip_stretches 的写法。一般问题照 strip_stretches 的几段写(程序按这道题的领域切好的接下来 12 个月,段数照它,不凑数、不合并;起止、说法和〔编号〕照抄);用户说了范围就照他的范围按 period_coverage 写,最多 8 条,末尾〔〕写合并的 period_coverage 行的编号,起止从这些行来;卡上有 strip_heading 时(用户问往后几年,程序已经照他的年数切好 strip_stretches),标题照 strip_heading 写,段照 strip_stretches 写,不按 period_coverage 另切。每段的小标题和那句话照这一段的说法和为什么写:「有机会」写清是什么机会、怎么抓,不写吃力、费力,小标题也不用紧、守住、收着;「有机会,但费力」写清机会是什么、费力在哪,两样都写,不写轻松、平稳、顺;「较费力」写清哪里费力、怎么省力,不写机会、轻松、平稳、顺;「不标」写这一段最适合做什么,不写吃力,也不写平稳、顺。为什么只照 strip_stretches 写到的那几条,不自己另加好坏;没写到帮助或阻力不等于平稳,「平稳」这个词不用。「其中……」那几天写进这一段的那句话里(「其中 1 月上旬事情会多一些」)。那一句 36 字以内,该做、别做各 24 字以内。每段只说一件确定的事和怎么做,不写可能、或许、也许、不排除、视情况、有好有坏这类两头的话。出生时间会让日期移动几天这句不写进任何一段(页面在时间条下面统一写一次)。最后可以另起一行(不加「-」)写「12 个月之后,下一个转折点在某年某月,……」一句,只写在这一节。
接下来五块,标题按领域照写:
${bodyHeadingLines()}
每块两到四条。每条单独一段:先一句 **加粗** 的话,它本身就是一个结论;后面两三句短句,说它在日子里是什么样子、具体怎么做。段末写〔〕和这条判断用到的表行编号(程序会去掉,用来核对)。第二块的各条按合适程度排,加粗句开头写「一、」「二、」「三、」。「要留意的」每条写会是什么样子、怎么应对。日期只在时间条里:正文各块(「现在就可以试的」「要留意的」也一样)不写时间条里的年月和起止,要指哪一段就说「时间轴里最后那一段」「时间轴里『谈成』那一段」,说法和那一段一致;对读者只说「时间轴」。
@@ -0,0 +1,77 @@
// BUG-2434 (owner 2026-11-27, staging and production): text the writer put inside the time section after its stretches —
// sub-headings 「### 事业:……」 and numbered paragraphs 「一、……」 — was joined with no separator into the strip's one muted
// footer line, so it showed raw and run together under the strip. It now reads as body markdown, in place; the footer
// keeps only the turning-point sentence.
import "./install-test-document";
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { ChatMessageContent } from "../src/components/chat-message-content.tsx";
import { parseAnswerShape } from "../src/lib/chat-answer-shape.ts";
import { loadChatMarkdown } from "../src/lib/chat-markdown-loader.ts";
const NOW = 2026 * 12 + 10; // 2026-11
const VERDICT = [
"## 结论",
"接下来十年你的事业分三段走,前段打底,中段扩大,后段收成。",
"- **最适合**:带项目、做专业口碑",
"- **先别碰**:借钱扩张",
"- **最好的时候**:2027 年 12 月到 2030 年 6 月",
].join("\n");
const TIME = [
"## 接下来十年",
"- **打底**(现在到 2027 年 12 月):手上的事多,先把专业做扎实。该做:把手上的项目做完整。别做:别同时开两条线。",
"- **扩大**(2027 年 12 月到 2030 年 6 月):职责变大,能做的也更大。该做:主动接更大的项目。别做:别把担子一个人扛。",
"- **收成**(2030 年 6 月到 2036 年 11 月):前面攒下的口碑开始换成收入。该做:把经验整理成课程或产品。别做:别轻易换行。",
"12 个月之后,下一个转折点在 2027 年 12 月,工作的分量从那时起变重。",
"",
"### 事业:三段路和两个转折",
"一、2027 年底职责变重,从做事的人变成带事的人。",
"二、2030 年中换一套节奏,收入跟着口碑走。",
"### 财运:跟着职责走",
"钱跟着职责涨,不太有意外之财。",
].join("\n");
const BODY = [
"## 你的长处和短处",
"**你做事稳,适合把一门专业做深。** 一件事交给你,你会做到底。",
].join("\n");
const ANSWER = [VERDICT, TIME, BODY].join("\n\n");
test("BUG-2434: the strip keeps its stretches; the footer keeps only the turning-point sentence", () => {
const shape = parseAnswerShape(ANSWER, { now: NOW })!;
assert.equal(shape.timeline!.heading, "接下来十年");
assert.deepEqual(shape.timeline!.segments.map((segment) => segment.title), ["打底", "扩大", "收成"]);
assert.equal(shape.timeline!.note, "12 个月之后,下一个转折点在 2027 年 12 月,工作的分量从那时起变重。");
assert.doesNotMatch(shape.timeline!.note, /###|一、|财运/u);
});
test("BUG-2434: the sub-headings and numbered lines of the time section go to the body as markdown, one block per line", () => {
const shape = parseAnswerShape(ANSWER, { now: NOW })!;
assert.ok(shape.body.startsWith("### 事业:三段路和两个转折\n\n一、2027 年底职责变重"), shape.body.slice(0, 80));
assert.match(shape.body, /一、[^\n]+\n\n二、[^\n]+\n\n### 财运:跟着职责走\n\n钱跟着职责涨/u);
// The body's own sections follow, in the written order.
assert.ok(shape.body.indexOf("### 财运") < shape.body.indexOf("## 你的长处和短处"));
});
test("BUG-2434: a non-turning-point loose line in the time section is body text, not the footer", () => {
const text = [VERDICT, TIME.split("\n").slice(0, 4).join("\n") + "\n这十年总体是往上走的。", BODY].join("\n\n");
const shape = parseAnswerShape(text, { now: NOW })!;
assert.equal(shape.timeline!.segments.length, 3);
assert.equal(shape.timeline!.note, "");
assert.ok(shape.body.startsWith("这十年总体是往上走的。"));
});
test("BUG-2434: rendered, the lifted text has its headings and paragraphs; nothing raw is left under the strip", async () => {
await loadChatMarkdown();
const html = renderToStaticMarkup(<ChatMessageContent text={ANSWER} structured />);
assert.match(html, /<h3[^>]*>[\s\S]*?事业:三段路和两个转折[\s\S]*?<\/h3>/u);
assert.match(html, /<h3[^>]*>[\s\S]*?财运:跟着职责走[\s\S]*?<\/h3>/u);
assert.match(html, /<p>一、2027 年底职责变重,从做事的人变成带事的人。<\/p>/u);
assert.match(html, /<p>二、2030 年中换一套节奏,收入跟着口碑走。<\/p>/u);
assert.doesNotMatch(html, /###/u);
const caveat = /<p class="chat-answer-strip-caveat">([\s\S]*?)<\/p>/u.exec(html)?.[1] ?? "";
assert.doesNotMatch(caveat, /事业|财运|一、/u);
});
@@ -0,0 +1,133 @@
// BUG-2433 (owner 2026-11-27): the same ten-year career question got 「接下来十年」 with eight stretches out to 2030 on
// production and 「接下来一年」 with four stretches on staging. Same code and the same card on both (checked on a public
// chart): the program's strip was always the next 12 months, and whether a ten-year answer was cut over the years was left
// to the writer's choice between strip_stretches and period_coverage. The strip now follows the years the writer declares
// on the tool call (horizon_years → card.strip_years): the first year as before, then one stretch per sub-period.
//
// Fixture: the public AA charts of the biography backtest golden (reference date 2026-09-27), as
// consult-dasha-horizon-20261105.test.ts reads them.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { buildEvidenceCard } from "../src/lib/consultation-evidence-card.ts";
import { createConsultationPlan } from "../src/lib/consultation-plan.ts";
import { DEFAULT_TIMELINE_HEADING, MAX_TIMELINE_SEGMENTS } from "../src/lib/chat-answer-shape.ts";
import { claimCardsWithStripStretches, programStretches, STRIP_STRETCHES_READING, stripHeading, stripHorizonYears, timelineSectionFromReply, withTimelineSection } from "../src/lib/chat-answer-timeline.ts";
import { dashaStretches } from "../src/lib/chat-strip-status.ts";
import { consultationWorkflowResponseSchema, toAgentConsultationContext, toModelOutput } from "../src/mastra/consultation-workflow.ts";
import { stripYearsFrom } from "../src/mastra/consultation-tools.ts";
import { chatConversationVoice } from "../src/mastra/product-voice.ts";
type Json = Record<string, unknown>;
const REQUEST_TIME = new Date("2026-09-27T04:00:00.000Z");
const NOW = 2026 * 12 + 8; // 2026-09, the golden's reference month
const TEN_YEAR = "我想看未来十年的事业发展怎样分阶段";
const backtest = JSON.parse(readFileSync(
new URL("./fixtures/consult-biography-backtest-golden.json", import.meta.url),
"utf8",
)) as { figures: Array<{ id: string; shared_chart: Json; routes: Record<string, Json> }> };
function workflowOf(id: string, route = "career"): Json {
const figure = backtest.figures.find((item) => item.id === id)!;
const { chart: chartOverrides, chart_modules: moduleOverrides, ...rest } = structuredClone(figure.routes[route]!) as Json & { chart?: Json; chart_modules?: Json };
const shared = structuredClone(figure.shared_chart);
return { ...rest, chart: { ...shared, ...(chartOverrides ?? {}), modules: { ...(shared.modules as Json), ...(moduleOverrides ?? {}) } } };
}
function cardFor(id: string, question: string, horizonYears: number | null) {
const context = toAgentConsultationContext(consultationWorkflowResponseSchema.parse(workflowOf(id)));
const packet = toModelOutput(context, createConsultationPlan({ userIntent: question, theme: "career" }), "career");
const card = buildEvidenceCard([{ domain: "career", packet, context }], { question, requestTime: REQUEST_TIME, horizonYears });
const years = stripYearsFrom(horizonYears ?? undefined);
if (years) card.strip_years = years;
return card;
}
const years = (from: string, to: string) => (Date.parse(to) - Date.parse(from)) / (365.25 * 86_400_000);
test("BUG-2433: the writer's horizon_years is the strip's years (rounded, 2 to 10); anything else is the default year", () => {
assert.equal(stripYearsFrom(10), 10);
assert.equal(stripYearsFrom(3.4), 3);
assert.equal(stripYearsFrom(30), 10);
assert.equal(stripYearsFrom(1), null);
assert.equal(stripYearsFrom(0), null);
assert.equal(stripYearsFrom(Number.NaN), null);
assert.equal(stripYearsFrom(undefined), null);
});
for (const id of ["barack_obama", "steve_jobs", "george_w_bush"]) {
test(`BUG-2433: a ten-year horizon cuts the strip out to about ten years (${id})`, () => {
const card = cardFor(id, TEN_YEAR, 10);
assert.equal(stripHorizonYears(card), 10);
const stretches = programStretches(card, { now: NOW });
assert.ok(stretches.length >= 3 && stretches.length <= MAX_TIMELINE_SEGMENTS, `${stretches.length} stretches`);
const span = years(stretches[0]!.fromDay, stretches.at(-1)!.toDay);
assert.ok(span >= 9.5 && span <= 10.1, `span ${span.toFixed(2)} years`);
assert.equal(stripHeading(card, stretches), "接下来十年");
// Contiguous, in order, every stretch with its own W key.
for (let index = 1; index < stretches.length; index += 1) assert.equal(stretches[index]!.fromDay, stretches[index - 1]!.toDay);
// (Neighbours with the same label joined beyond the display target carry both their W keys.)
const wKeys = stretches.flatMap((item) => item.keys.filter((key) => /^W\d/u.test(key)));
assert.ok(stretches.every((item) => item.keys.some((key) => /^W\d/u.test(key))));
assert.deepEqual(wKeys, wKeys.map((_, index) => `W${index + 1}`));
// After the first year the labels rest on the dasha rules only (no transit reason from beyond the transit data).
const later = stretches.filter((item) => item.fromDay >= "2027-10-01");
assert.ok(later.length >= 2);
for (const item of later) assert.ok(item.rules.every((rule) => /^(?:S1|R1|R2)\*?$/u.test(rule)), `${item.range}: ${item.rules.join(",")}`);
});
}
test("BUG-2433: without horizon_years the strip stays the next 12 months, even when the question says 十年", () => {
const card = cardFor("barack_obama", TEN_YEAR, null);
assert.equal(stripHorizonYears(card), 1);
const stretches = programStretches(card, { now: NOW });
assert.ok(stretches.length >= 1);
assert.ok(years(stretches[0]!.fromDay, stretches.at(-1)!.toDay) <= 1.01);
assert.equal(stripHeading(card, stretches), DEFAULT_TIMELINE_HEADING);
});
test("BUG-2433: the writer sees strip_heading and the long-range stretches; the reading says to follow them", () => {
const card = cardFor("barack_obama", TEN_YEAR, 10);
const claims = claimCardsWithStripStretches([{ category: "timing", evidence: { precomputed_tables: {} } }], card, NOW);
const tables = (claims[0]!.evidence as { precomputed_tables: Record<string, unknown> }).precomputed_tables;
assert.equal(tables.strip_heading, "接下来十年");
const lines = tables.strip_stretches as string[];
assert.equal(lines.length, programStretches(card, { now: NOW }).length);
assert.match(lines.at(-1)!, /2036 年/u);
assert.match(String(tables.best_time ?? "这段时间"), /这段时间|^$/u);
assert.match(STRIP_STRETCHES_READING, /卡上有 strip_heading 时,strip_stretches 已经照用户问的年数切好/u);
assert.match(chatConversationVoice, /卡上有 strip_heading 时(用户问往后几年,程序已经照他的年数切好 strip_stretches),标题照 strip_heading 写/u);
// The default card carries no strip_heading.
const plain = claimCardsWithStripStretches([{ category: "timing", evidence: { precomputed_tables: {} } }], cardFor("barack_obama", TEN_YEAR, null), NOW);
assert.equal((plain[0]!.evidence as { precomputed_tables: Record<string, unknown> }).precomputed_tables.strip_heading, undefined);
});
test("BUG-2433: the program-written section takes the strip's heading", () => {
const card = cardFor("barack_obama", TEN_YEAR, 10);
const stretches = programStretches(card, { now: NOW });
const reply = JSON.stringify({ stretches: stretches.map(() => ({ title: "打底", sentence: "先把手上的事做扎实", do: "把手上的项目做完整", avoid: "别同时开两条线" })) });
const section = timelineSectionFromReply(reply, stretches);
assert.ok(section);
const answer = withTimelineSection("## 结论\n一句话。\n- **最适合**:带项目\n\n## 你的长处和短处\n正文。", section!, stripHeading(card, stretches));
assert.match(answer, /^## 接下来十年$/mu);
});
test("BUG-2433: dasha stretches stop where the card lists no more periods and never overlap", () => {
const card = cardFor("barack_obama", TEN_YEAR, 10);
const list = dashaStretches(card, { from: "2027-09-27", to: "2060-01-01" });
assert.ok(list.length >= 2);
for (let index = 1; index < list.length; index += 1) assert.equal(list[index]!.from, list[index - 1]!.to);
assert.deepEqual(dashaStretches(null, { from: "2027-01-01", to: "2028-01-01" }), []);
assert.deepEqual(dashaStretches(card, { from: "2028-01-01", to: "2027-01-01" }), []);
});
test("BUG-2433: a sub-period the horizon's end only grazes is left off (no 「2036 年 9 月中旬到 10 月」 sliver)", () => {
const card = cardFor("barack_obama", TEN_YEAR, 10);
// From November the ten years end on 2036-11-01; the Sun sub-period starting 2036-09-17 would be a six-week sliver.
const stretches = programStretches(card, { now: 2026 * 12 + 10 });
// The strip ends where the Venus sub-period ends (mid-September 2036 on this chart), not at the horizon's 2036-11-01.
assert.match(stretches.at(-1)!.toDay, /^2036-09-1\d$/u);
assert.ok(stretches.every((item) => (Date.parse(item.toDay) - Date.parse(item.fromDay)) / 86_400_000 >= 21));
});
+2 -1
View File
@@ -71,7 +71,8 @@ test("BUG-2229: the plain chat voice is the sectioned voice; the old plain voice
// 原值 9,850 / 新值 10,620 / 原因: BUG-2342 西洋题带 western_chart(第一轮);第二轮分 "only" / "both" 两种写法、并列的计数照并列说(实测 10,570)。
// 原值 10,620 / 新值 10,950 / 原因: BUG-2357 婚恋、事业、钱的题在工具调用里带 event_classes、只按 KP 时带 kp_only;判断由你下一条写明结论说定、正文有依据的表现用「可能」「倾向于」写出来(实测 10,890)。
// 原值 10,950 / 新值 11,250 / 原因: BUG-2420 部分满足的格局按对上的部分合起来读、帮和压一起说、几条时间依据同指一段(实测 11,192)。
assert.ok([...voice].length <= 11_250, String([...voice].length));
// 原值 11,250 / 新值 11,400 / 原因: BUG-2433 卡上有 strip_heading(用户问往后几年、程序照声明的年数切好时间条)时标题照它写、段照 strip_stretches、不按 period_coverage 另切(实测 11,312)。
assert.ok([...voice].length <= 11_400, String([...voice].length));
// A stable prefix for provider-side caching: nothing per request (no dates, no ids) in the voice.
assert.doesNotMatch(voice, /\d{4}-\d{2}-\d{2}|requestId|\$\{/u);
});
@@ -182,7 +182,9 @@ test("BUG-2287: the model must name the domains; one calculation per request", a
// 原值 ["question", "domains", "day_range"];新值加可选的 western_chart;原因:BUG-2342,西洋题由写手在工具调用里声明范围("only" / "both")。
// 原值 ["question", "domains", "day_range", "western_chart"];新值加可选的 event_classes、kp_only;原因:BUG-2357,婚恋、事业、钱的题由写手在
// 工具调用里声明问的是哪一类事件、是否只按 KP(不按用户原话匹配)。
assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains", "day_range", "western_chart", "event_classes", "kp_only"]);
// 原值 [..., "event_classes", "kp_only"];新值加可选的 horizon_years;原因:BUG-2433,问往后几年的题由写手在工具调用里声明年数,时间条照它切
// (不按用户原话匹配)。
assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains", "day_range", "western_chart", "event_classes", "kp_only", "horizon_years"]);
const execute = tool.execute!;
const context = { observe: { span: async (_n: string, fn: () => Promise<unknown>) => fn(), log() {} } } as never;
const schema = tool.inputSchema as unknown as { safeParse: (value: unknown) => { success: boolean } };
@@ -0,0 +1,60 @@
/**
* BUG-2435: the session title call turns provider thinking off. With thinking on by default (deepseek-flash) its
* 30-token budget went to thinking, the text came back empty and the conversation kept the raw question as its title.
*/
import assert from "node:assert/strict";
import test from "node:test";
import type { LanguageModelV2 } from "@ai-sdk/provider";
import { generateSessionTitle, generateSessionTitleText, SESSION_TITLE_MAX_TOKENS } from "../src/lib/session-title-agent.ts";
import type { ResolvedLanguageModel } from "../src/mastra/model.ts";
function fakeModel(text: string) {
const calls: Parameters<LanguageModelV2["doGenerate"]>[0][] = [];
const usage = { inputTokens: 40, outputTokens: 8, totalTokens: 48 };
const fake: LanguageModelV2 = {
specificationVersion: "v2", provider: "fake", modelId: "fake", supportedUrls: {},
async doGenerate(options) {
calls.push(options);
return { content: [{ type: "text", text }], finishReason: "stop", usage, warnings: [] };
},
async doStream(options) {
calls.push(options);
return { stream: new ReadableStream({ start(controller) {
controller.enqueue({ type: "stream-start", warnings: [] });
controller.enqueue({ type: "text-start", id: "1" });
controller.enqueue({ type: "text-delta", id: "1", delta: text });
controller.enqueue({ type: "text-end", id: "1" });
controller.enqueue({ type: "finish", finishReason: "stop", usage });
controller.close();
} }) };
},
};
const model = { id: "fake-model", label: "fake", description: "", creditCost: 0, isDefault: false, mode: "compatible", model: fake } as unknown as ResolvedLanguageModel;
return { model, calls };
}
const QUESTION = "我想看未来十年的事业发展怎样分阶段";
test("BUG-2435: the title call sends thinking disabled and keeps the 30-token cap", async () => {
const { model, calls } = fakeModel("事业十年阶段与转折");
const text = await generateSessionTitleText(model, { question: QUESTION, theme: "career", chartRole: "self" });
assert.equal(text, "事业十年阶段与转折");
assert.equal(calls.length, 1);
assert.equal(calls[0]?.maxOutputTokens, SESSION_TITLE_MAX_TOKENS);
const options = calls[0]?.providerOptions as Record<string, { thinking?: { type?: string } }> | undefined;
assert.ok(options, "provider options are sent");
const modes = Object.values(options).map((entry) => entry.thinking?.type);
assert.ok(modes.length > 0);
assert.ok(modes.every((mode) => mode === "disabled"), `thinking modes: ${JSON.stringify(modes)}`);
});
test("BUG-2435: a generated title reaches the caller (sanitized)", async () => {
const { model } = fakeModel("「事业十年阶段与转折」");
assert.equal(await generateSessionTitle({ model, question: QUESTION, theme: "career" }), "事业十年阶段与转折");
});
test("BUG-2435: an empty reply (all budget spent on thinking) still leaves the title alone", async () => {
const { model } = fakeModel("");
assert.equal(await generateSessionTitle({ model, question: QUESTION, theme: "career" }), null);
});