From 6bb596926f39733287ef521d0e4df2d3006069c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 09:59:21 +0800 Subject: [PATCH] =?UTF-8?q?fix(chat):=20Western=20answers=20clean=20by=20s?= =?UTF-8?q?tructure=20=E2=80=94=20writer-declared=20scope,=20program-enfor?= =?UTF-8?q?ced=20shape=20(BUG-2342=20round=202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit western_chart is now "only" | "both" (true = "only"), the writer's judgment. "only": no day calendar, the time section and time label removed, Indian paragraphs sent to the one repair call (dropped if they survive), the evidence box is Western rows printed from western_natal (Indian keys and items dropped and logged), no Indian method rows or chart-data table. "both": the body sits under 印度盘怎么看 / 西洋盘怎么看 (missing headings are regrouped by the same repair call, kept as written when the reply fails its checks), the verdict names both sides, rewrites keep the side they name, mixed basis items are split and the box shows 印度盘 / 西洋盘 groups. Ties in the top element / modality are given to the writer and a single-winner sentence or title goes to the repair. Backstage notes (几种方法一致 and similar) are cleaned from every answer. Non-Western cards are byte-identical. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq --- docs/BUG_HISTORY.md | 19 +- frontend/src/app/api/consult/route.ts | 6 +- frontend/src/app/globals.css | 4 + .../src/components/consult-judgment-basis.tsx | 10 +- frontend/src/lib/chat-answer-checks.ts | 22 + frontend/src/lib/chat-answer-repair.ts | 17 +- frontend/src/lib/chat-western-answer.ts | 493 ++++++++++++++++++ frontend/src/lib/chat-western-facts.ts | 121 ++++- frontend/src/lib/consult-judgment-basis.ts | 15 +- frontend/src/lib/stream-agent-response.ts | 111 +++- frontend/src/mastra/consultation-tools.ts | 22 +- frontend/src/mastra/product-voice.ts | 4 +- frontend/tests/chat-voice-2229.test.ts | 3 +- .../consult-chart-data-20261116.test.tsx | 3 +- .../consultation-agentic-runtime.test.ts | 3 +- .../tests/western-chat-2342-round2.test.ts | 378 ++++++++++++++ frontend/tests/western-chat-2342.test.ts | 10 +- 17 files changed, 1190 insertions(+), 51 deletions(-) create mode 100644 frontend/src/lib/chat-western-answer.ts create mode 100644 frontend/tests/western-chat-2342-round2.test.ts diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index 98f12f306..448448457 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -31900,7 +31900,7 @@ ## BUG-2342 | 问答里问西洋占星,回答拿印度盘作答;西洋的元素、相位等计数到不了模型 -- 状态:fixed-pending-verify(本地提交,未推送;改后的西洋题还没有用真实模型复测,待负责人批准两次调用)。 +- 状态:fixed-pending-verify(第二轮本地提交,未推送;两次真实调用:元素题通过,两边对比题结构通过,复测里发现的三处已改并有测试,没有再调用真实模型)。 - 首次发现 / 最近更新:2026-11-25(BUG-2340 抽查)/ 2026-11-25。 - 现象:公开奥巴马资料问「从西洋占星看,我的性格里哪种元素最突出?」,回答「土象最突出」,依据是印度盘(恒星黄道)的摩羯上升;西洋回归黄道实际是火 3、土 3、风 2、水 2,固定星座 5(十颗行星,不算北交点)。另见一句讲年份运势的话落在「不适合你的」里(本轮未处理,见跟进)。 - 触发条件:任何问西洋占星的问答(元素、相位、格局、太阳星座)。 @@ -31919,5 +31919,18 @@ - 真实调用(deepseek-flash,公开奥巴马资料,3 次,本地引擎):第一版只靠查卡说明和写作规则,元素题和两边对比题都没去查西洋盘(查卡 0 次),回答说这次没拿到西洋盘、不拿印度盘冒充(没有再把印度盘当西洋依据,但没答出西洋事实);事业题没碰西洋、卡片不变。因此改为排盘工具上的 `western_chart` 参数;改后的西洋题待复测。答案:`/workspace/eval-read-1116/western-chat-2342/`。 - 防复发:上面的测试;西洋判断的事实只从 `western_natal` / `western:natal` 来,卡片不加西洋数据。 - 关联记录:BUG-2340(西洋页签、十颗行星计数)、BUG-287(咨询挂西洋层)、BUG-1789(事实核对)、BUG-2281(不按字词路由用户的话)。 -- 修复版本:分支 `claude/western-chat-2342`(本地提交,未推送)。 -- 跟进:「不适合你的」里出现年份运势句,原因未核实(句式像补写调用的改写),本轮未改。 +- 修复版本:分支 `claude/western-chat-2342`(第一轮 616438cf1 与第二轮,本地提交,未推送)。 +- 第二轮(2026-11-25,复测之后): + - 复测现象(`retest-element.md`、`retest-both.md`):写手已带 `western_chart`,西洋事实正确;但元素题说「最突出的是火,土紧跟在后面」(火、土各 3 颗并列,拿太阳入庙分了高下),正文混进一段没标明的印度盘功能吉凶星,「判断依据」列了大运、Narayana、D9、D10;两边对比题约一半句子没说是哪一边,适合 / 不适合两节没标边,西洋依据并进印度那一条,出现「(几种方法一致)」「逆行只列出、不作理由」「只作一种方法的指向」这类后台话,还有一句没标边的 2027 年印度盘时间句。 + - 根因:只靠写作规则约束结构(第一轮的做法),没有程序执行;写手没有拿到「并列」这件事本身,只有各元素的个数。 + - 修复(按结构和程序,不加更多文字规则;新模块 `frontend/src/lib/chat-western-answer.ts`): + - 范围由写手声明:`western_chart` 改为 "only" / "both"(第一轮的 true 仍等于 "only");由模型判断,不按字词匹配。工具结果多两项 `element_top` / `mode_top`(「火和土并列最多,各 3 颗」)。 + - "only":不取日历;程序删掉时间那一节和结论卡的时间 / 日子标签行,不补时间条;正文里含印度盘专有词(大运、Narayana、分盘、功能吉凶星、Yogakaraka、星宿、罗睺计都等)的段落送进原有那一次补写调用(改写或删掉),补写后仍含这些词的段落删掉(结论和各节受保护);「判断依据」只留西洋条,每条的行由程序照 western_natal 列出(「西洋盘:」开头,元素 / 星座类型 / 左右上下 / 星群 / 上升中天 / 行星 / 相位,重复的写「见上面」),印度编号和印度条删掉并记录;回执不带印度的方法行和「盘面数据」表。 + - "both":正文必须有「印度盘怎么看」「西洋盘怎么看」(可再有「两边一致和不同的地方」),缺了就在同一次补写调用里请它按句子重排正文,回复要通过标题、长度(0.7–1.4 倍)检查才用,不通过就保留原文;结论第一句要同时说到两边(不然交给补写调用);带印度编号又带「西洋盘:」的条先拆成两条,再展开编号;「判断依据」分「印度盘」「西洋盘」两组(页面多一行组名);任何补写都不能去掉原句里说的那一边;西洋那一节的句子不进正文的「讲构造」改写。 + - 并列:正文句子和「判断依据」的短标题把并列的最多元素 / 星座类型说成只有一个最多(「最突出的是火」「土其次」),就交给补写调用;改了还分高下的不用。 + - 后台话:「几种方法一致」「只列出、不作理由」「只作一种方法的指向」「只作有条件的时间段」「暂不作为两套确认」加进每一条回答都会过的后台用词清理(`chat-answer-checks.ts` `BACKSTAGE_PHRASES`)。卡片里的那句原文没改(改了卡片就不是逐字相同)。 + - 原值 / 新值 / 原因:`western_chart` boolean / true、"only"、"both" / 由写手声明范围、程序按范围执行;问答写法 9,850 字上限 / 10,620(实测 10,570)/ 第一轮加的西洋规则没有改这个上限,这一轮又加了两种写法;工具参数列表加 `western_chart`(`consultation-agentic-runtime.test.ts` 第一轮漏改)。 + - 验证:新增 `frontend/tests/western-chat-2342-round2.test.ts`(13 条,含经过真实回答流程的 "only" / "both" 两条,假模型)。非西洋题卡片:奥巴马事业题 `--dump-cards` 与基线 10074c2f3 逐字相同(237,555 字节)。tsc 通过;eslint 0 个错误;前端全量测试除 PostgreSQL / compose / rsync / 预发环境那 26 条外全部通过;Python 快检。真实调用(deepseek-flash,公开奥巴马资料,本地引擎,2 次,答案 `/workspace/eval-read-1116/western-chat-2342/r2-element/`、`r2-both/`): + - 元素题:写手带了 "only";结论「火和土两种元素并列最多,各三颗」;正文没有印度盘的内容,没有时间那一节,没有时间标签;「判断依据」9 条全是程序列的「西洋盘:」行;没有后台话,没有含糊话。 + - 两边题:写手带了 "both";正文按「印度盘怎么看」「西洋盘怎么看」「两边一致和不同的地方」写,每句按位置归边;「判断依据」分两组(印度 11 条、西洋 4 条);后台话已清掉。发现三处,已改并有测试,没有再调用真实模型:原有的「讲构造」改写把结论里的「印度盘里」「西洋盘里」改掉了,还在西洋那一节留下意思重复的句子;写手写在正文里的〔西洋盘:……〕注没有去掉。 +- 跟进:第一轮记下的「不适合你的」里出现年份运势句,原因仍未核实;两边题的时间句现在按位置归到印度盘那一节。第二轮修好的三处要等下一次真实调用确认。 diff --git a/frontend/src/app/api/consult/route.ts b/frontend/src/app/api/consult/route.ts index 30ee40b8c..5cbcda3da 100644 --- a/frontend/src/app/api/consult/route.ts +++ b/frontend/src/app/api/consult/route.ts @@ -1886,7 +1886,9 @@ export async function POST(request: Request) { stepBudget: consultationStepBudgetReceipt(state), workflow: state.workflowReceipt ?? workflowReceipt, techniqueTruth: state.techniqueTruth ?? "unknown", - ...(state.techniqueAuditTable?.length + // BUG-2342 round 2: a Western-only answer's evidence fold shows only Western rows, so the Indian method rows and the + // Indian 「盘面数据」 table are not on its receipt. + ...(state.techniqueAuditTable?.length && state.westernScope !== "only" ? { techniqueAuditTable: state.techniqueAuditTable } : {}), // The chat shows 「解读依据」 under a 简明解读 answer from the audit rows above. @@ -1894,7 +1896,7 @@ export async function POST(request: Request) { ...(answerMode === "professional" ? { functionalProfile: requestedFunctionalProfile ?? DEFAULT_FUNCTIONAL_PROFILE } : {}), // 产品 2026-11-16:页面按这份记录生成「盘面数据」表,模型不写表。取不到就不带。 ...(() => { - const chartData = consultChartDataFromCard(state.evidenceCard); + const chartData = state.westernScope === "only" ? null : consultChartDataFromCard(state.evidenceCard); return chartData ? { chartData } : {}; })(), // BUG-2281: lit chart areas and strip tones, derived from the answer's evidence keys (program, not model). diff --git a/frontend/src/app/globals.css b/frontend/src/app/globals.css index 5003bec9e..857fc5926 100644 --- a/frontend/src/app/globals.css +++ b/frontend/src/app/globals.css @@ -53,6 +53,10 @@ /* BUG-1981: the evidence-nature note under a judgment; a qualified one (one method, sensitive to the birth time …) in the action colour. */ .consult-judgment-basis-note { color: var(--color-ink-tertiary); font-size: var(--type-caption); } .consult-judgment-basis-note.is-conditional { color: var(--color-action); } +/* BUG-2342 round 2: the 印度盘 / 西洋盘 group label above each group of a both-sides answer's judgments. */ +.consult-judgment-basis-group { list-style: none; padding: var(--space-3) var(--space-1) var(--space-1); color: var(--color-ink-tertiary); font-size: var(--type-caption); } +.consult-judgment-basis-group:first-child { padding-top: 2px; } +.consult-judgment-basis-group + .consult-answer-basis-row { border-top: 0; } @media (hover: none) { .personal-report-fact-tables.consult-answer-basis summary:hover { background: transparent; } } /* 产品 2026-11-16:「盘面数据」折叠块,页面生成的三张表;表格不换行,窄屏横向滑动。 */ .consult-chart-data + .consult-answer-basis, .consult-judgment-basis + .consult-chart-data { margin-block-start: 0; } diff --git a/frontend/src/components/consult-judgment-basis.tsx b/frontend/src/components/consult-judgment-basis.tsx index f1d46854c..590981947 100644 --- a/frontend/src/components/consult-judgment-basis.tsx +++ b/frontend/src/components/consult-judgment-basis.tsx @@ -64,7 +64,11 @@ export function ConsultJudgmentBasis({ basis, children, methodRows, scopeLine }: {items ? ( ) : (
{children}
diff --git a/frontend/src/lib/chat-answer-checks.ts b/frontend/src/lib/chat-answer-checks.ts index e63134002..96b9675b2 100644 --- a/frontend/src/lib/chat-answer-checks.ts +++ b/frontend/src/lib/chat-answer-checks.ts @@ -584,9 +584,31 @@ export const BACKSTAGE_WORDS: ReadonlyArray = [ [/字段/gu, "项"], ]; +/** + * BUG-2342 round 2: notes about our method bookkeeping read aloud to the user (seen in the retest: 「(几种方法一致)」, + * 「逆行只列出、不作理由」, 「只作一种方法的指向」, 「暂不作为两套确认」). Every answer, every section; the sentence around them stays. + */ +export const BACKSTAGE_PHRASES: ReadonlyArray = [ + // A bracket that holds only these notes goes; inside a longer bracket only the phrase goes. + [/[((][ \t]*(?:几种|多种|几套|两套|两种)方法(?:都|全)?(?:一致|相互印证)[ \t]*[))]/gu, ""], + [/(?:几种|多种|几套|两套|两种)方法(?:都|全)?(?:一致|相互印证)[ \t]*[;;、,,]?[ \t]*/gu, ""], + [/[,,;;、]?[ \t]*(?:逆行)?只列出[、,,]?[ \t]*不作(?:为)?(?:判断)?理由/gu, ""], + [/[,,;;、]?[ \t]*只作(?:为)?一种方法的指向/gu, ""], + [/[,,;;、]?[ \t]*只作(?:为)?有条件的时间段/gu, ""], + [/[,,;;、]?[ \t]*(?:暂|暂时)?不(?:作为|足以拿来当|能当|算)(?:两套|双重|双轨)(?:的)?确认/gu, ""], +]; + export function fixBackstageWords(text: string): { output: string; fixed: string[] } { const fixed: string[] = []; let output = text; + for (const [pattern, to] of BACKSTAGE_PHRASES) { + output = output.replace(pattern, (hit) => { + fixed.push(`${hit.trim()}→(删去)`); + return to; + }); + } + // A bracket emptied by the phrases above, or left with a dangling separator. + output = output.replace(/[((][ \t]*[;;、,,]?[ \t]*[))]/gu, "").replace(/[;;、,,][ \t]*([))])/gu, "$1").replace(/([((])[ \t]*[;;、,,]/gu, "$1"); for (const [pattern, to] of BACKSTAGE_WORDS) { output = output.replace(pattern, (...args) => { const hit = args[0] as string; diff --git a/frontend/src/lib/chat-answer-repair.ts b/frontend/src/lib/chat-answer-repair.ts index b35088019..b8086c519 100644 --- a/frontend/src/lib/chat-answer-repair.ts +++ b/frontend/src/lib/chat-answer-repair.ts @@ -17,6 +17,7 @@ */ import { checkDayCalendar } from "./chat-day-calendar.ts"; import type { EvidenceCard } from "./consultation-evidence-card.ts"; +import type { WesternGuardFacts } from "./chat-western-facts.ts"; import { findAnswerFactMismatches } from "./consultation-answer-fact-guard.ts"; import { NEUTRAL_WORDING } from "./chat-answer-checks.ts"; import { isProtectedRemoval } from "./chat-answer-direct-reply.ts"; @@ -245,7 +246,7 @@ function newDetail(original: string, rewrite: string): boolean { return [...rewrite.matchAll(DETAIL_RE)].some((m) => !had.has(m[0].replace(/\s+/gu, ""))); } -export function applyAnswerRepair(answer: string, repair: AnswerRepair, flags: ReadonlyArray<{ id: number; sentence: string; kind?: string }>, card: EvidenceCard | null, incompleteLayers: ReadonlySet = new Set(), asked: ReadonlySet | null = null): { output: string; added: string[]; basis: string[]; fixed: number; deleted: number; rejected: string[] } { +export function applyAnswerRepair(answer: string, repair: AnswerRepair, flags: ReadonlyArray<{ id: number; sentence: string; kind?: string }>, card: EvidenceCard | null, incompleteLayers: ReadonlySet = new Set(), asked: ReadonlySet | null = null, western: WesternGuardFacts | null = null): { output: string; added: string[]; basis: string[]; fixed: number; deleted: number; rejected: string[] } { let output = answer; const added: string[] = []; const basis: string[] = []; @@ -256,7 +257,8 @@ export function applyAnswerRepair(answer: string, repair: AnswerRepair, flags: R if (!text || /\n|^#|\|/u.test(text)) return "structure"; if (STATUS_CODE.test(text)) return "status_code"; if (INCOMPLETE_WORDING.test(text) && !incompleteLayers.has(layer)) return "incomplete"; - if (card && findAnswerFactMismatches(text, card).length) return "fact"; + // BUG-2342 round 2: a Western position in a fix is a Western fact once the writer read the Western chart. + if (card && findAnswerFactMismatches(text, card, western).length) return "fact"; return null; }; // BUG-2235: an added layer text also passes the table checks (dates, durations, house lords), names a layer it was @@ -361,7 +363,13 @@ function headings(answer: string): string[] { /** BUG-2247 round 2: at most this many mechanism sentences go to the one repair call (the rest are only recorded). */ export const MECHANISM_FLAG_CAP = 16; -export function answerRepairPlan(text: string, card: EvidenceCard, options: Readonly<{ followUp?: boolean; userText?: string; extraFlags?: readonly TableFlag[] }> = {}): { missing: DeliveredLayer[]; flags: Array; optional: string[] } { +export function answerRepairPlan(text: string, card: EvidenceCard, options: Readonly<{ followUp?: boolean; userText?: string; extraFlags?: readonly TableFlag[]; westernOnly?: boolean; westernSection?: string }> = {}): { missing: DeliveredLayer[]; flags: Array; optional: string[] } { + // BUG-2342 round 2: a Western-only answer is not held to the Indian card (no left-out Indian layers, no Indian table + // checks); only its own flags (Indian paragraphs, broken ties) go to the call. + if (options.westernOnly) { + const extra = (options.extraFlags ?? []).filter((flag) => flag.sentence && text.includes(flag.sentence)); + return { missing: [], flags: extra.map((flag, index) => ({ id: index + 1, ...flag })), optional: [] }; + } // BUG-2247: 原值 missing = missingMustLayers(text, card)(首轮)、flags = tableFlags;新值:回答带证据编号时不补层(必看层的行由 // expandEvidenceKeys 从卡上原样列进「判断依据」),flags 另加时间线日期 / 压力段和没写编号的判断;原因:正文说人话,补写调用加的 // 段落会把术语写回正文,必看层改由程序列出。 @@ -371,7 +379,8 @@ export function answerRepairPlan(text: string, card: EvidenceCard, options: Read const plain = keyed // BUG-2281 review: strip segments whose title or sentence says the opposite of their program tone go first, so their // rewrite (which also says the pressure) wins over a pressure flag on the same lead. - ? [...checkStripTone(text, card), ...checkTimelineEntries(text, card), ...checkBodyDirection(text, card), ...addImpliedKeys(text, card).flags, ...checkBodyMechanism(text, options.userText ?? "").slice(0, MECHANISM_FLAG_CAP)] + // BUG-2342 round 2: sentences of a both-sides answer's Western section may name signs and aspects (skipped here). + ? [...checkStripTone(text, card), ...checkTimelineEntries(text, card), ...checkBodyDirection(text, card), ...addImpliedKeys(text, card).flags, ...checkBodyMechanism(text, options.userText ?? "").filter((flag) => !options.westernSection || !options.westernSection.includes(flag.sentence)).slice(0, MECHANISM_FLAG_CAP)] : []; // BUG-2285: the guarantee sentences Pass 4 softened and the front / behind-the-scenes sentences the clean-up kept go // to the same repair (extraFlags), each only while its sentence is still in the text. diff --git a/frontend/src/lib/chat-western-answer.ts b/frontend/src/lib/chat-western-answer.ts new file mode 100644 index 000000000..31d8152a3 --- /dev/null +++ b/frontend/src/lib/chat-western-answer.ts @@ -0,0 +1,493 @@ +/** + * BUG-2342 round 2: the shape of a chat answer about Western astrology, enforced by the program from the scope the writer + * declared on run-jyotish-consultation (`western_chart`: "only" | "both"; the writer's judgment, never a word match). + * + * The first round got the Western facts to the writer, but the retest answers were not clean: a Western-only answer + * carried an unlabelled Indian functional-benefic paragraph and dasha / Narayana / D9 / D10 rows in 「判断依据」, and broke + * a fire–earth tie by Sun dignity; a both-sides answer left half its sentences without a side and merged the Western basis + * into an Indian row. Prose rules alone did not converge (chat-voice-experiment-20261122), so: + * + * "only" no time section and no time label in the verdict (removed when written); 「判断依据」 holds only Western items, + * their rows printed by the program from western_natal with the 「西洋盘:」 prefix; Indian keys are dropped and + * logged; a body paragraph with Indian-only terms goes to the one repair call, and is dropped when it still + * has them. + * "both" the body sits under 「印度盘怎么看」 and 「西洋盘怎么看」 (optional 「两边一致和不同的地方」), so each sentence + * belongs to a side by position; missing headings go to the same one repair call (the body regrouped; kept + * as written when the reply fails a check); the verdict names both sides; 「判断依据」 has two groups. + * both a tied top element or modality is never stated as a single winner (flagged to the repair call). + * + * No model call here; every function returns the text it was given when it has nothing to do. + */ +import { splitJudgmentBasis } from "./consult-judgment-basis.ts"; +import { splitAfterSentencePunctuation } from "./sentence-split.ts"; +import { DAY_VERDICT_LABELS, FOLLOW_UP_HEADING, ASK_USER_HEADING, isTimelineHeading, TIME_WINDOW_LABELS, VERDICT_HEADING } from "./chat-answer-shape.ts"; +import { hasEvidenceTags, normalizeEvidenceTags, TAG_RE, tagKeys, withoutEvidenceTags } from "./chat-evidence-tags.ts"; +import type { WesternBasisFacts, WesternScope } from "./chat-western-facts.ts"; + +export const WESTERN_SIDE_HEADINGS = { indian: "印度盘怎么看", western: "西洋盘怎么看", compare: "两边一致和不同的地方" } as const; +export const BASIS_GROUP_LABELS = { indian: "印度盘", western: "西洋盘" } as const; +/** The 「判断依据」 group line (alone on its line): 「**印度盘**」「**西洋盘**」. */ +export const BASIS_GROUP_LINE = /^\*\*(印度盘|西洋盘)\*\*[ \t]*$/u; +const WESTERN_ITEM = /西洋盘/u; + +export type WesternFlag = { kind: "western_only_indian" | "western_tie" | "western_both_verdict"; sentence: string; card: string }; + +// ---- Indian-only terms --------------------------------------------------------------------------------------------- + +/** Words that exist only in the Indian reading (periods, varga charts, functional roles, lunar mansions, nodes as Rahu / Ketu). */ +export const INDIAN_ONLY_TERMS = new RegExp([ + "大运", "小运", "细运", "Vimshottari", "Narayana", "Dasha", "达沙", "Yogakaraka", "功能性?大?(?:吉星|凶星|中性)", + "星宿", "Nakshatra", "恒星黄道", "印度盘", "吠陀", "Sade\\s*Sati", "Ashtakavarga", "Shadbala", "Jaimini", "罗睺", "计都", + "分盘", "Chara", "Kantaka", "Argala", "Saham", "Mudda", "Tajika", "代表星", + "(? hit[0]))]; +} + +/** The answer's own lines outside 「判断依据」 (headings and blank lines left out), as written. */ +function bodyLines(text: string): string[] { + return splitJudgmentBasis(text).body.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); +} + +/** "only": each body line that uses Indian-only terms, for the one repair call (rewrite from the Western chart, or delete). */ +export function westernOnlyIndianFlags(text: string): WesternFlag[] { + return bodyLines(text).flatMap((line) => { + const terms = indianTermsIn(withoutEvidenceTags(line)); + if (!terms.length) return []; + const sentence = line.replace(/^(?:[-*+]|\d{1,2}[.、)])[ \t]+/u, ""); + return [{ + kind: "western_only_indian" as const, + sentence, + card: `这道题只问西洋盘,这一段讲的是印度盘(${terms.join("、")}):改写成只照西洋盘的一段,不提印度盘;西洋盘里没有对应的事就 text 写空字符串,删掉这一段`, + }]; + }); +} + +// ---- ties ---------------------------------------------------------------------------------------------------------- + +const SUPERLATIVE = "最(?:突出|多|强|重|明显|显眼|旺|大)"; +const AFTER_NAME = "(?:象|元素|星座)?"; +const esc = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); +/** 火 / 土 / 水 are also the first characters of 火星 / 土星 / 水星 / 水瓶. */ +const nameRe = (name: string) => `${esc(name)}(?![星瓶])`; + +/** Whether a sentence names one of the tied top values as the single winner (or another tied value as second). */ +export function breaksTie(sentence: string, top: readonly string[]): boolean { + if (top.length < 2) return false; + const plain = sentence.replace(/\*\*/gu, ""); + for (const name of top) { + const others = top.filter((other) => other !== name).map(nameRe).join("|"); + const joined = new RegExp(`(?:${others})${AFTER_NAME}[和与、跟及同]$`, "u"); + // 「最突出的是火」 not followed by 「和土」. + if (new RegExp(`${SUPERLATIVE}的?(?:是|就是|还是|要数|当属)${nameRe(name)}${AFTER_NAME}(?![和与、跟及同])`, "u").test(plain)) return true; + // 「火最突出」「火占上风」 not preceded by 「土和」. + for (const hit of plain.matchAll(new RegExp(`${nameRe(name)}${AFTER_NAME}(?:${SUPERLATIVE}|占上风|压过|排第一|居首|为主)`, "gu"))) { + if (!joined.test(plain.slice(0, hit.index))) return true; + } + // 「土紧跟在后面」「土其次」. + if (new RegExp(`${nameRe(name)}${AFTER_NAME}(?:紧跟在?后|其次|排第二|次之|稍弱|弱一点|略少)`, "u").test(plain)) return true; + } + return false; +} + +/** Body sentences that state a tied top element or modality as one winner, for the one repair call. */ +export function westernTieFlags(text: string, facts: WesternBasisFacts | null): WesternFlag[] { + if (!facts) return []; + const ties = [facts.elements, facts.modes].filter((row) => row.top.length >= 2 && row.topText); + if (!ties.length) return []; + const out: WesternFlag[] = []; + for (const line of bodyLines(text)) { + for (const sentence of splitAfterSentencePunctuation(line, "。!?").map((part) => part.trim()).filter(Boolean)) { + const tie = ties.find((row) => breaksTie(sentence, row.top)); + if (!tie || out.some((flag) => flag.sentence === sentence)) continue; + out.push({ + kind: "western_tie", + sentence: sentence.replace(/^(?:[-*+]|\d{1,2}[.、)])[ \t]+/u, ""), + card: `西洋盘上${tie.topText}:这几样一起说,不说哪一样最突出、哪一样其次,也不拿别的条件分出高下`, + }); + } + } + // The short judgments of 「判断依据」 restate the body's claims; a title that breaks the tie is reworded too (title only). + const basis = splitJudgmentBasis(text).basis ?? ""; + for (const hit of basis.matchAll(/^\s*[-*][ \t]+\*\*(.+?)\*\*/gmu)) { + const title = hit[1]!.replace(/[::]\s*$/u, ""); + const tie = ties.find((row) => breaksTie(title, row.top)); + if (!tie || out.some((flag) => flag.sentence === title) || text.indexOf(title) !== text.lastIndexOf(title)) continue; + out.push({ kind: "western_tie", sentence: title, card: `这是「判断依据」里一条的短标题,改写成 20 字以内的短标题:西洋盘上${tie.topText},几样一起说,不分高下` }); + } + return out; +} + +// ---- the both-sides structure -------------------------------------------------------------------------------------- + +function headingsOf(text: string): string[] { + return splitJudgmentBasis(text).body.split("\n").map((line) => /^##[ \t]+(.+?)[ \t]*$/u.exec(line)?.[1] ?? "").filter(Boolean); +} + +/** "both": the side headings the body does not have. */ +export function missingSideHeadings(text: string): string[] { + const have = new Set(headingsOf(text)); + return [WESTERN_SIDE_HEADINGS.indian, WESTERN_SIDE_HEADINGS.western].filter((heading) => !have.has(heading)); +} + +/** "both": the verdict's first sentence names the Indian and the Western side; otherwise it goes to the repair call. */ +export function westernBothVerdictFlags(text: string): WesternFlag[] { + const lines = text.split("\n"); + const at = lines.findIndex((line) => line.trim() === `## ${VERDICT_HEADING}`); + if (at < 0) return []; + const first = lines.slice(at + 1).find((line) => line.trim() && !line.trim().startsWith("#")); + if (!first || /^[-*+][ \t]/u.test(first.trim())) return []; + const sentence = splitAfterSentencePunctuation(first.trim(), "。!?")[0]!.trim(); + if (/印度/u.test(sentence) && /西洋/u.test(sentence)) return []; + return [{ kind: "western_both_verdict", sentence, card: "用户两边都问:结论这一句要把印度盘和西洋盘各自的看法都说到(写明「印度盘」「西洋盘」),一句写完" }]; +} + +/** The body the side regrouping replaces: from the first section after the verdict (and its time section) to 问你一句 / 接着问 / 判断依据. */ +function bodyRegion(text: string): { start: number; end: number; lines: string[] } | null { + const lines = text.split("\n"); + const heading = (line: string) => /^##[ \t]+(.+?)[ \t]*$/u.exec(line)?.[1] ?? null; + const verdict = lines.findIndex((line) => heading(line) === VERDICT_HEADING); + if (verdict < 0) return null; + let start = -1; + for (let index = verdict + 1; index < lines.length; index += 1) { + const name = heading(lines[index]!); + if (name === null) continue; + if (isTimelineHeading(name)) continue; + start = index; + break; + } + if (start < 0) return null; + let end = lines.length; + for (let index = start + 1; index < lines.length; index += 1) { + const name = heading(lines[index]!); + if (name === ASK_USER_HEADING || name === FOLLOW_UP_HEADING || name === "判断依据") { end = index; break; } + } + if ([ASK_USER_HEADING, FOLLOW_UP_HEADING, "判断依据"].includes(heading(lines[start]!) ?? "")) return null; + return { start, end, lines }; +} + +/** The extra instruction for the one repair call when a both-sides answer lacks its side headings. */ +export function sideStructurePrompt(text: string): string { + const region = bodyRegion(text); + if (!region) return ""; + return [ + "", + `这道题用户问的是印度盘和西洋盘两边。下面这段正文没有按两边分开写:把它按句子归到「## ${WESTERN_SIDE_HEADINGS.indian}」「## ${WESTERN_SIDE_HEADINGS.western}」两节(两边有一致和不同的地方时,再加最后一节「## ${WESTERN_SIDE_HEADINGS.compare}」)。`, + "句子照原文,只挪位置;一句没说是哪一边、又分不出来时,照它用到的盘归进那一节;讲时间的句子放进印度盘那一节。段末的〔〕编号照原样留着。不加新判断,不写别的标题。", + '在 JSON 里另加一个字段 "body":改好的这段正文(markdown,含上面这几个 ## 标题)。', + "", + "正文:", + region.lines.slice(region.start, region.end).join("\n").trim(), + ].join("\n"); +} + +export function parseSideBody(reply: string): string | null { + const start = reply.indexOf("{"); + const end = reply.lastIndexOf("}"); + if (start < 0 || end <= start) return null; + try { + const value = JSON.parse(reply.slice(start, end + 1)) as Record; + return typeof value.body === "string" && value.body.trim() ? value.body.trim() : null; + } catch { + return null; + } +} + +const chars = (text: string) => withoutEvidenceTags(text).replace(/\s|#|\*/gu, "").length; + +/** + * Splices the regrouped body in place of the old one when it has both side headings, no other kind of heading and about + * the same length (0.7 to 1.4 times); otherwise the answer stays as written (the reason is returned). + */ +export function applySideStructure(text: string, body: string | null): { output: string; applied: boolean; reason: string | null } { + if (!body) return { output: text, applied: false, reason: "no_body" }; + const region = bodyRegion(text); + if (!region) return { output: text, applied: false, reason: "no_region" }; + const names = body.split("\n").map((line) => /^##[ \t]+(.+?)[ \t]*$/u.exec(line)?.[1] ?? null).filter((name): name is string => name !== null); + const allowed = new Set(Object.values(WESTERN_SIDE_HEADINGS)); + if (!names.includes(WESTERN_SIDE_HEADINGS.indian) || !names.includes(WESTERN_SIDE_HEADINGS.western)) return { output: text, applied: false, reason: "headings" }; + if (names.some((name) => !allowed.has(name)) || /^#(?!#[ \t])/mu.test(body)) return { output: text, applied: false, reason: "other_heading" }; + const before = chars(region.lines.slice(region.start, region.end).join("\n")); + const ratio = before ? chars(body) / before : 0; + if (ratio < 0.7 || ratio > 1.4) return { output: text, applied: false, reason: `length:${ratio.toFixed(2)}` }; + const lines = [...region.lines]; + lines.splice(region.start, region.end - region.start, ...body.split("\n"), ""); + return { output: lines.join("\n").replace(/\n{3,}/gu, "\n\n"), applied: true, reason: null }; +} + +// ---- "only": no time parts ----------------------------------------------------------------------------------------- + +/** "only": the time section and the verdict's time / day label lines are removed (each recorded). */ +export function withoutTimeParts(text: string): { output: string; removed: string[] } { + const lines = text.split("\n"); + const removed: string[] = []; + const keep = lines.map(() => true); + const heading = (line: string) => /^##[ \t]+(.+?)[ \t]*$/u.exec(line)?.[1] ?? null; + const basisAt = lines.findIndex((line) => /^##\s*判断依据/u.test(line)); + const last = basisAt < 0 ? lines.length : basisAt; + let inVerdict = false; + for (let index = 0; index < last; index += 1) { + const name = heading(lines[index]!); + if (name !== null) { + inVerdict = name === VERDICT_HEADING; + if (name !== VERDICT_HEADING && isTimelineHeading(name)) { + removed.push(`section:${name}`); + let end = index + 1; + while (end < last && heading(lines[end]!) === null) end += 1; + for (let at = index; at < end; at += 1) keep[at] = false; + index = end - 1; + } + continue; + } + const label = inVerdict ? /^[-*+][ \t]+\*\*(.+?)\*\*/u.exec(lines[index]!.trim())?.[1] : undefined; + if (label && (TIME_WINDOW_LABELS.has(label) || (DAY_VERDICT_LABELS as readonly string[]).includes(label))) { + removed.push(`label:${label}`); + keep[index] = false; + } + } + if (!removed.length) return { output: text, removed }; + return { output: lines.filter((_, index) => keep[index]).join("\n").replace(/\n{3,}/gu, "\n\n"), removed }; +} + +// ---- 「判断依据」: the Western rows --------------------------------------------------------------------------------- + +const ELEMENT_WORDS = /元素|[火土风水]象|[火土风水][ \t]*\d{1,2}[ \t]*颗|[火土风水][和与、跟]?[火土风水](?![星瓶])/u; +const MODE_WORDS = /基本|固定|变动|开创/u; +const SIDE_WORDS = /半边|地平线|一边|东半|西半|上半|下半/u; +const STELLIUM_WORDS = /星群|聚在|挤在|三星|扎堆/u; +const PATTERN_WORDS = /大三角|T[ \t]*三角|大十字|大格局/u; +const ASPECT_WORDS = /相位|合相|对相|刑相|三分|六分|拱|冲|角|相刑|相合/u; +const MAX_PLANET_ROWS = 4; +const MAX_ASPECT_ROWS = 3; + +/** + * The Western rows for one 「判断依据」 item, from the facts its title and note name (planets named only inside a count's + * bracket do not count). A row already printed for an earlier item is referred to by that item's title. + */ +export function westernRowsFor(itemText: string, facts: WesternBasisFacts, printed: Map, title: string): string[] { + const text = itemText.replace(/\*\*/gu, ""); + const named = text.replace(/[((][^()()]*[))]/gu, ""); + const rows: Array<{ key: string; label: string; text: string }> = []; + if (ELEMENT_WORDS.test(text)) rows.push({ key: "elements", label: "元素", text: facts.elements.text }); + if (MODE_WORDS.test(text)) rows.push({ key: "modes", label: "星座类型", text: facts.modes.text }); + if (SIDE_WORDS.test(text)) rows.push({ key: "sides", label: "左右上下", text: facts.hemispheres }); + if (STELLIUM_WORDS.test(text) && facts.stelliums) rows.push({ key: "stelliums", label: "星群", text: facts.stelliums }); + if (PATTERN_WORDS.test(text)) rows.push({ key: "patterns", label: "大格局", text: facts.patterns }); + for (const angle of facts.angles) if (named.includes(angle.label)) rows.push({ key: `angle:${angle.label}`, label: angle.label, text: angle.text }); + const planets = facts.planets.filter((planet) => named.includes(planet.label)); + for (const planet of planets.slice(0, MAX_PLANET_ROWS)) rows.push({ key: `planet:${planet.label}`, label: `${planet.label}的位置`, text: planet.text }); + if (ASPECT_WORDS.test(named)) { + const names = new Set(planets.map((planet) => planet.label)); + for (const aspect of facts.aspects.filter((row) => names.has(row.left) && names.has(row.right)).slice(0, MAX_ASPECT_ROWS)) { + rows.push({ key: `aspect:${aspect.left}:${aspect.right}`, label: `${aspect.left}和${aspect.right}的相位`, text: aspect.text }); + } + } + return rows.map((row) => { + const where = printed.get(row.key); + if (where !== undefined) return where === title ? "" : `${row.label}见上面「${where}」`; + printed.set(row.key, title); + return row.text; + }).filter(Boolean); +} + +type BasisItem = { title: string; line: string }; + +/** The basis as items (an indented or bracket-only line joins the item above); loose lines are returned apart. */ +function basisItems(basis: string): { items: BasisItem[]; loose: string[] } { + const items: BasisItem[] = []; + const loose: string[] = []; + for (const line of basis.split("\n")) { + if (!line.trim() || BASIS_GROUP_LINE.test(line.trim())) continue; + const lead = /^\s*[-*][ \t]+\*\*(.+?)\*\*/u.exec(line); + if (lead) { items.push({ title: lead[1]!.replace(/[::]\s*$/u, "").trim(), line: line.trim() }); continue; } + if (items.length && (/^[ \t]+\S/u.test(line) || /^[ \t]*[((][^()()]+[))][ \t]*[。.]?[ \t]*$/u.test(line) || (hasEvidenceTags(line) && !withoutEvidenceTags(line).trim()))) { + items[items.length - 1]!.line += line.trim(); + continue; + } + loose.push(line.trim()); + } + return { items, loose }; +} + +const noteOf = (line: string) => line.replace(/^\s*[-*][ \t]+\*\*.+?\*\*[::]?[ \t]*/u, "").trim(); + +/** One Western item, its rows printed by the program; null when it names no Western fact and has no Western note. */ +function westernItem(item: BasisItem, facts: WesternBasisFacts | null, printed: Map): { line: string; matched: boolean } | null { + const note = withoutEvidenceTags(noteOf(item.line)); + const at = note.search(WESTERN_ITEM); + // Only the 「西洋盘」 part of a note speaks for the Western chart; an item with Indian terms and no such part is Indian. + const own = at < 0 ? note : note.slice(at).replace(/^西洋盘[::]?\s*/u, "").trim(); + if (at < 0 && indianTermsIn(`${item.title} ${note}`).length) return null; + const rows = facts ? westernRowsFor(`${item.title} ${own}`, facts, printed, item.title) : []; + if (rows.length) return { line: `- **${item.title}**:西洋盘:${rows.join(";")}。`, matched: true }; + if (at < 0) return null; + return own ? { line: `- **${item.title}**:西洋盘:${own}`, matched: false } : null; +} + +/** The facts row every Western group carries once: the element and modality counts (ties marked). */ +function countsItem(facts: WesternBasisFacts, printed: Map): string | null { + const rows = [ + ...(printed.has("elements") ? [] : [facts.elements.text]), + ...(printed.has("modes") ? [] : [facts.modes.text]), + ]; + return rows.length ? `- **西洋盘的元素和星座类型**:西洋盘:${rows.join(";")}。` : null; +} + +export type WesternBasisRecord = { droppedKeys: string[]; droppedItems: string[]; unmatched: string[]; western: number; indian: number }; + +/** + * "only": the body loses every evidence key (they point at the Indian card; logged), and 「判断依据」 keeps only Western + * items, each re-printed from western_natal; Indian items and loose lines are dropped and logged. + */ +export function westernOnlyBasis(text: string, facts: WesternBasisFacts | null): { output: string; record: WesternBasisRecord } { + const record: WesternBasisRecord = { droppedKeys: [], droppedItems: [], unmatched: [], western: 0, indian: 0 }; + const normalized = normalizeEvidenceTags(withoutWesternBodyNotes(text)); + for (const hit of normalized.matchAll(TAG_RE)) for (const key of tagKeys(hit[1]!)) if (!record.droppedKeys.includes(key)) record.droppedKeys.push(key); + const split = splitJudgmentBasis(normalized); + const body = withoutEvidenceTags(split.body).split("\n").map((line) => line.replace(/[ \t]+$/u, "")).join("\n").trim(); + if (split.basis === null && !facts) return { output: `${body}\n`, record }; + const printed = new Map(); + const lines: string[] = []; + const { items, loose } = basisItems(split.basis ?? ""); + record.droppedItems.push(...loose.map((line) => line.slice(0, 40))); + for (const item of items) { + const western = westernItem(item, facts, printed); + if (!western) { record.droppedItems.push(item.title.slice(0, 40)); continue; } + if (!western.matched) record.unmatched.push(item.title.slice(0, 40)); + lines.push(western.line); + } + const counts = facts ? countsItem(facts, printed) : null; + if (counts) lines.push(counts); + record.western = lines.length; + return { output: lines.length ? `${body}\n\n## 判断依据\n\n${lines.join("\n")}\n` : `${body}\n`, record }; +} + +/** + * "both", before the keys are expanded: an item that carries Indian keys and a 「西洋盘:」 part is split in two (the + * Indian part keeps the keys, the Western part becomes its own item), so the Western basis never borrows Indian rows. + */ +export function splitMixedWesternItems(text: string): { output: string; split: string[] } { + const parts = splitJudgmentBasis(normalizeEvidenceTags(text)); + if (parts.basis === null) return { output: text, split: [] }; + const split: string[] = []; + const { items, loose } = basisItems(parts.basis); + if (!items.some((item) => hasEvidenceTags(item.line) && WESTERN_ITEM.test(withoutEvidenceTags(noteOf(item.line))))) return { output: text, split }; + const out: string[] = []; + for (const item of items) { + const note = noteOf(item.line); + const at = note.search(WESTERN_ITEM); + if (!hasEvidenceTags(item.line) || at < 0) { out.push(item.line); continue; } + const tags = [...note.matchAll(TAG_RE)].map((hit) => hit[0].trim()).join(""); + const indian = withoutEvidenceTags(note.slice(0, at)).replace(/[\s—–\-,,;;::]+$/u, "").trim(); + const western = withoutEvidenceTags(note.slice(at)).trim(); + out.push(`- **${item.title}**:${indian ? (/[))]$/u.test(indian) ? indian : indian.replace(/[。.]?$/u, "。")) : ""}${tags}`); + out.push(`- **${item.title}**:${western}`); + split.push(item.title.slice(0, 40)); + } + return { output: `${parts.body}\n\n## 判断依据\n\n${[...out, ...loose].join("\n")}\n`, split }; +} + +/** "both", after the keys are expanded: 「判断依据」 in two groups, 印度盘 then 西洋盘 (Western rows printed by the program). */ +export function groupedBothBasis(text: string, facts: WesternBasisFacts | null): { output: string; record: WesternBasisRecord } { + const record: WesternBasisRecord = { droppedKeys: [], droppedItems: [], unmatched: [], western: 0, indian: 0 }; + const cleaned = withoutWesternBodyNotes(text); + const split = splitJudgmentBasis(cleaned); + if (split.basis === null) return { output: cleaned, record }; + const { items, loose } = basisItems(split.basis); + const printed = new Map(); + const indian: string[] = []; + const western: string[] = []; + for (const item of items) { + if (!WESTERN_ITEM.test(noteOf(item.line))) { indian.push(item.line); continue; } + const built = westernItem(item, facts, printed); + if (!built) { indian.push(item.line); continue; } + if (!built.matched) record.unmatched.push(item.title.slice(0, 40)); + western.push(built.line); + } + const counts = facts ? countsItem(facts, printed) : null; + if (counts) western.push(counts); + record.western = western.length; + record.indian = indian.length; + if (!western.length) return { output: cleaned, record }; + const groups = [ + ...(indian.length ? [`**${BASIS_GROUP_LABELS.indian}**`, ...indian] : []), + `**${BASIS_GROUP_LABELS.western}**`, ...western, + ...loose, + ]; + return { output: `${split.body}\n\n## 判断依据\n\n${groups.join("\n")}\n`, record }; +} + +/** The writer's own 〔西洋盘:……〕 notes in the body (not evidence keys, so the key expansion leaves them): removed. */ +export function withoutWesternBodyNotes(text: string): string { + const split = splitJudgmentBasis(text); + const body = split.body.replace(/[ \t]*〔[^〔〕\n]*西洋盘[^〔〕\n]*〕/gu, ""); + if (body === split.body) return text; + return split.basis === null ? body : `${body}\n\n## 判断依据\n\n${split.basis}\n`; +} + +/** + * "both": the sentences under 「西洋盘怎么看」. The Western reading may name signs, elements and aspects in the body (the + * user asked for them), so the plain-body mechanism rewrite skips them (in the retest it duplicated those sentences). + */ +export function westernSectionText(text: string): string { + const lines = splitJudgmentBasis(text).body.split("\n"); + const at = lines.findIndex((line) => line.trim() === `## ${WESTERN_SIDE_HEADINGS.western}`); + if (at < 0) return ""; + let end = at + 1; + while (end < lines.length && !/^##[ \t]/u.test(lines[end]!)) end += 1; + return lines.slice(at + 1, end).join("\n"); +} + +// ---- the repair call's flags and its filter ------------------------------------------------------------------------ + +/** The flags this answer's scope sends to the one repair call. */ +export function westernAnswerFlags(text: string, scope: WesternScope | null | undefined, facts: WesternBasisFacts | null | undefined): WesternFlag[] { + if (!scope) return []; + return [ + ...(scope === "only" ? westernOnlyIndianFlags(text) : westernBothVerdictFlags(text)), + ...westernTieFlags(text, facts ?? null), + ]; +} + +/** A Western fix that still fails its own check is not used (the flagged text stays, or is dropped below for "only"). */ +export function withoutFailingWesternFixes }>( + repair: T, + flags: ReadonlyArray<{ id: number; kind?: string; sentence?: string }>, + facts: WesternBasisFacts | null | undefined, +): { repair: T; rejected: string[] } { + const rejected: string[] = []; + const ties = facts ? [facts.elements.top, facts.modes.top].filter((top) => top.length >= 2) : []; + const fixes = repair.fixes.filter((fix) => { + const flag = flags.find((item) => item.id === fix.id); + const kind = flag?.kind; + // Any rewrite (a plain-body one too) keeps the side its sentence names: in the retest a mechanism rewrite took + // 「印度盘里」「西洋盘里」 out of the verdict. + const sides = ["印度", "西洋"].filter((side) => flag?.sentence?.includes(side)); + if (fix.text && sides.some((side) => !fix.text.includes(side))) { rejected.push(`fix#${fix.id}:side`); return false; } + if (!fix.text || !kind?.startsWith("western_")) return true; + if (indianTermsIn(fix.text).length && kind === "western_only_indian") { rejected.push(`fix#${fix.id}:indian`); return false; } + if (ties.some((top) => breaksTie(fix.text, top))) { rejected.push(`fix#${fix.id}:tie`); return false; } + if (kind === "western_both_verdict" && !(/印度/u.test(fix.text) && /西洋/u.test(fix.text))) { rejected.push(`fix#${fix.id}:sides`); return false; } + return true; + }); + return { repair: { ...repair, fixes }, rejected }; +} + +/** "only", after the repair: body lines that still use Indian-only terms are dropped (unless `isProtected` says no). */ +export function withoutIndianLines(text: string, isProtected: (text: string, start: number, end: number) => boolean): { output: string; dropped: string[] } { + const split = splitJudgmentBasis(text); + const dropped: string[] = []; + let body = split.body; + for (const flag of westernOnlyIndianFlags(text)) { + const at = body.indexOf(flag.sentence); + if (at < 0 || isProtected(body, at, at + flag.sentence.length)) continue; + body = `${body.slice(0, at)}${body.slice(at + flag.sentence.length)}`; + dropped.push(flag.sentence.slice(0, 40)); + } + if (!dropped.length) return { output: text, dropped }; + body = body.split("\n").filter((line) => !/^[ \t]*(?:[-*+]|\d{1,2}[.、)])?[ \t]*$/u.test(line) || !line.trim()).join("\n").replace(/\n{3,}/gu, "\n\n").trim(); + return { output: split.basis === null ? `${body}\n` : `${body}\n\n## 判断依据\n\n${split.basis}\n`, dropped }; +} diff --git a/frontend/src/lib/chat-western-facts.ts b/frontend/src/lib/chat-western-facts.ts index 298cf50fe..8260c54b4 100644 --- a/frontend/src/lib/chat-western-facts.ts +++ b/frontend/src/lib/chat-western-facts.ts @@ -74,23 +74,107 @@ export function westernGuardFacts(raw: unknown): WesternGuardFacts | null { return { ascendant: view.houses.find((house) => house.house === 1)?.signLabel ?? null, signs, houses }; } -/** The compact Western facts for the tool result, or null when the engine payload is not a full chart. */ -export function westernNatalToolFacts(raw: unknown): Json | null { - const view = westernView(raw); - if (!view) return null; +/** + * BUG-2342 round 2: what the writer declared about the question (the `western_chart` argument, the writer's own judgment, + * never a word match): "only" — a Western-only answer; "both" — the Indian and the Western reading side by side. The + * first round's boolean true stays valid and means "only". + */ +export type WesternScope = "only" | "both"; + +export function westernScope(value: unknown): WesternScope | null { + if (value === true || value === "only") return "only"; + if (value === "both") return "both"; + return null; +} + +/** 「火、土」 → 「火和土」, three or more 「火、土和风」. */ +function joinNames(names: readonly string[]): string { + return names.length <= 1 ? names.join("") : `${names.slice(0, -1).join("、")}和${names[names.length - 1]}`; +} + +/** + * BUG-2342 round 2: the top of a count with ties marked — 「火和土并列最多,各 3 颗」 or 「固定最多,5 颗」. The writer gets this + * sentence, so a tie is never broken by another factor (the retest said 「最突出的是火」 at fire 3, earth 3). + */ +export function westernTopCount(rows: readonly { label: string; count: number }[]): { text: string; top: string[] } | null { + const max = Math.max(0, ...rows.map((row) => row.count)); + if (max <= 0) return null; + const top = rows.filter((row) => row.count === max).map((row) => row.label); + return { text: top.length > 1 ? `${joinNames(top)}并列最多,各 ${max} 颗` : `${top[0]}最多,${max} 颗`, top }; +} + +type View = NonNullable>; + +/** Each planet's row: 「太阳 狮子 12°32′ 第 6 宫 入庙」 for the tool, 「太阳在狮子 12°32′,第 6 宫,入庙」 for 「判断依据」. */ +function planetRows(view: View): Array<{ label: string; text: string; plain: string }> { const dignity = new Map((view.classical?.dignities ?? []).map((row) => [row.id, row.words])); const counted = new Set(countedPlanets(view.planets).map((planet) => planet.id)); - const planets = view.planets.map((planet) => { + return view.planets.map((planet) => { const words = dignity.get(planet.id) ?? []; - return [ - planet.label, - westernPositionText(planet), + const rest = [ planet.house !== null ? `第 ${planet.house} 宫` : null, planet.retrograde && counted.has(planet.id) ? "逆行" : null, words.length ? words.join("、") : null, counted.has(planet.id) ? null : "点,不计数", - ].filter(Boolean).join(" "); + ].filter((part): part is string => Boolean(part)); + return { + label: planet.label, + text: [planet.label, westernPositionText(planet), ...rest].join(" "), + plain: [`${planet.label}在${westernPositionText(planet)}`, ...rest].join(","), + }; }); +} + +const countText = (rows: readonly { label: string; count: number; members?: string[] }[]) => + rows.map((row) => `${row.label} ${row.count} 颗${row.members?.length ? `(${row.members.join("、")})` : ""}`).join("、"); + +/** + * BUG-2342 round 2: the Western rows the program prints in 「判断依据」 (plain words; each row starts nothing — the item + * carries the 「西洋盘:」 prefix). Each item gets the rows of the facts it names; the writer's own note is not printed, so + * the counts in the box are the chart's. + */ +export type WesternBasisFacts = Readonly<{ + /** The count row, the tied (or single) top and its sentence (「火和土并列最多,各 3 颗」). */ + elements: Readonly<{ text: string; top: readonly string[]; topText: string | null }>; + modes: Readonly<{ text: string; top: readonly string[]; topText: string | null }>; + hemispheres: string; + stelliums: string | null; + patterns: string; + angles: ReadonlyArray>; + planets: ReadonlyArray>; + aspects: ReadonlyArray>; +}>; + +export function westernBasisFacts(raw: unknown): WesternBasisFacts | null { + const view = westernView(raw); + if (!view) return null; + const elementTop = westernTopCount(view.elements); + const modeTop = westernTopCount(view.modes); + const sides = westernHemispheres(view.planets); + const stelliums = westernStelliums(view.planets); + const patterns = westernPatterns(view); + const ascendant = view.houses.find((house) => house.house === 1); + return { + elements: { text: `元素:${countText(view.elements)}${elementTop ? `;${elementTop.text}` : ""}`, top: elementTop?.top ?? [], topText: elementTop?.text ?? null }, + modes: { text: `星座类型:${countText(view.modes)}${modeTop ? `;${modeTop.text}` : ""}`, top: modeTop?.top ?? [], topText: modeTop?.text ?? null }, + hemispheres: `盘面左半边 ${sides.left.length} 颗、右半边 ${sides.right.length} 颗,地平线以上 ${sides.above.length} 颗、以下 ${sides.below.length} 颗`, + stelliums: stelliums.length ? `星群:${stelliums.map((item) => `${item.signLabel}有${item.members.join("、")}`).join(";")}` : null, + patterns: patterns.length ? `大格局:${patterns.map((item) => `${item.name}(${item.members.join("、")})`).join(";")}` : "没有大三角、T 三角、大十字", + angles: [ + ...(ascendant ? [{ label: "上升", text: `上升 ${westernPositionText(ascendant)}` }] : []), + ...(view.mc ? [{ label: "中天", text: `中天 ${westernPositionText(view.mc)}` }] : []), + ], + planets: planetRows(view).map((row) => ({ label: row.label, text: row.plain })), + aspects: [...view.aspects].sort((left, right) => left.orb - right.orb) + .map((aspect) => ({ left: aspect.left, right: aspect.right, text: `${aspect.left}${aspect.aspectLabel}${aspect.right},差 ${aspect.orb.toFixed(1)}°` })), + }; +} + +/** The compact Western facts for the tool result, or null when the engine payload is not a full chart. */ +export function westernNatalToolFacts(raw: unknown): Json | null { + const view = westernView(raw); + if (!view) return null; + const planets = planetRows(view).map((row) => row.text); const countRow = (rows: readonly { label: string; count: number; members?: string[] }[]) => Object.fromEntries(rows.map((row) => [row.label, `${row.count}${row.members?.length ? `(${row.members.join("、")})` : ""}`])); const sides = westernHemispheres(view.planets); @@ -112,7 +196,10 @@ export function westernNatalToolFacts(raw: unknown): Json | null { }, planets, elements: countRow(view.elements), + // BUG-2342 round 2: the top with ties marked (「火和土并列最多,各 3 颗」); a tie is said as a tie. + element_top: westernTopCount(view.elements)?.text ?? null, modes: countRow(view.modes), + mode_top: westernTopCount(view.modes)?.text ?? null, hemispheres: { 左半边: sides.left.length, 右半边: sides.right.length, @@ -135,10 +222,10 @@ export function westernNatalToolFacts(raw: unknown): Json | null { export async function fetchWesternNatalFacts( chart: unknown, fetchImpl: typeof fetch = fetch, -): Promise<{ facts: Json | null; guard: WesternGuardFacts | null; reason?: string; elapsedMs: number }> { +): Promise<{ facts: Json | null; guard: WesternGuardFacts | null; basis: WesternBasisFacts | null; reason?: string; elapsedMs: number }> { const started = Date.now(); const body = westernNatalRequestBody(chart); - if (!body) return { facts: null, guard: null, reason: "birth_fields_missing", elapsedMs: 0 }; + if (!body) return { facts: null, guard: null, basis: null, reason: "birth_fields_missing", elapsedMs: 0 }; const apiBase = process.env.JYOTISH_API_BASE?.trim() || "http://127.0.0.1:5200"; try { const response = await fetchImpl(`${apiBase}/api/western`, { @@ -147,11 +234,17 @@ export async function fetchWesternNatalFacts( body: JSON.stringify(body), signal: AbortSignal.timeout(15_000), }); - if (!response.ok) return { facts: null, guard: null, reason: `http_${response.status}`, elapsedMs: Date.now() - started }; + if (!response.ok) return { facts: null, guard: null, basis: null, reason: `http_${response.status}`, elapsedMs: Date.now() - started }; const raw = await response.json().catch(() => null); const facts = westernNatalToolFacts(raw); - return { facts, guard: facts ? westernGuardFacts(raw) : null, ...(facts ? {} : { reason: "payload_incomplete" }), elapsedMs: Date.now() - started }; + return { + facts, + guard: facts ? westernGuardFacts(raw) : null, + basis: facts ? westernBasisFacts(raw) : null, + ...(facts ? {} : { reason: "payload_incomplete" }), + elapsedMs: Date.now() - started, + }; } catch (error) { - return { facts: null, guard: null, reason: error instanceof Error ? error.name : "fetch_failed", elapsedMs: Date.now() - started }; + return { facts: null, guard: null, basis: null, reason: error instanceof Error ? error.name : "fetch_failed", elapsedMs: Date.now() - started }; } } diff --git a/frontend/src/lib/consult-judgment-basis.ts b/frontend/src/lib/consult-judgment-basis.ts index 980ffb656..5b977fe85 100644 --- a/frontend/src/lib/consult-judgment-basis.ts +++ b/frontend/src/lib/consult-judgment-basis.ts @@ -113,8 +113,13 @@ export type JudgmentBasisItem = Readonly<{ grade: JudgmentBasisGrade | null; /** The item's closing note in brackets (BUG-1981); for an older answer, its grade word. */ note: string | null; + /** BUG-2342 round 2: the group line above the item in a both-sides answer (「印度盘」「西洋盘」); absent otherwise. */ + group?: string; }>; +/** BUG-2342 round 2: a group line of 「判断依据」 (alone on its line), 「**印度盘**」「**西洋盘**」. */ +const GROUP_LINE_RE = /^\*\*(印度盘|西洋盘)\*\*[ \t]*$/; + const ITEM_START_RE = /^[-*][ \t]+/; const ITEM_LEAD_RE = /^\*\*(.+?)\*\*[ \t]*[::]?[ \t]*/; // 「(明显,B)」「(只是可能,C)」「(有条件)」 at the end of an item. The letter is @@ -155,9 +160,13 @@ function basisSentences(text: string): string[] { */ export function parseJudgmentBasisItems(basis: string): JudgmentBasisItem[] | null { const raw: string[] = []; + const groups: Array = []; + let group: string | undefined; for (const line of basis.split(/\r?\n/)) { if (!line.trim()) continue; - if (ITEM_START_RE.test(line)) raw.push(line.replace(ITEM_START_RE, "")); + const groupLine = GROUP_LINE_RE.exec(line.trim()); + if (groupLine) { group = groupLine[1]; continue; } + if (ITEM_START_RE.test(line)) { raw.push(line.replace(ITEM_START_RE, "")); groups.push(group); } else if (raw.length && /^[ \t]+\S/.test(line)) raw[raw.length - 1] += line.trim(); // BUG-2241: a line that is only the item's evidence note (「(只有一种方法支持)」) belongs to the item above. else if (raw.length && BRACKET_ONLY_RE.test(line)) raw[raw.length - 1] += line.trim(); @@ -165,7 +174,7 @@ export function parseJudgmentBasisItems(basis: string): JudgmentBasisItem[] | nu } if (!raw.length) return null; const items: JudgmentBasisItem[] = []; - for (const entry of raw) { + for (const [index, entry] of raw.entries()) { const lead = ITEM_LEAD_RE.exec(entry); if (!lead) return null; let rest = entry.slice(lead[0].length); @@ -187,7 +196,7 @@ export function parseJudgmentBasisItems(basis: string): JudgmentBasisItem[] | nu text, book: text.includes("《") || text.startsWith(CLASSICAL_GIST_LEAD), })); - items.push({ title: basisTitleWithoutNoise(lead[1].replace(/[::]\s*$/, "").trim()), facts, grade, note }); + items.push({ title: basisTitleWithoutNoise(lead[1].replace(/[::]\s*$/, "").trim()), facts, grade, note, ...(groups[index] ? { group: groups[index] } : {}) }); } return items; } diff --git a/frontend/src/lib/stream-agent-response.ts b/frontend/src/lib/stream-agent-response.ts index 740940024..1c24168f3 100644 --- a/frontend/src/lib/stream-agent-response.ts +++ b/frontend/src/lib/stream-agent-response.ts @@ -35,6 +35,10 @@ import { addImpliedKeys, bodyMechanismSentences, bodyTerms, checkBodyDirection, import { chineseNamesAndTerms, cleanChatAnswer } from "./chat-answer-checks.ts"; import { isProtectedRemoval, keepDirectReply } from "./chat-answer-direct-reply.ts"; import { answerRepairPlan, answerRepairPrompt, applyAnswerRepair, parseAnswerRepair, withoutFailingFixes } from "./chat-answer-repair.ts"; +import { + applySideStructure, groupedBothBasis, missingSideHeadings, parseSideBody, sideStructurePrompt, splitMixedWesternItems, westernAnswerFlags, + westernOnlyBasis, westernSectionText, withoutFailingWesternFixes, withoutIndianLines, withoutTimeParts, +} from "./chat-western-answer.ts"; import { classifyPass4, softenGuarantee, @@ -1250,6 +1254,8 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { // BUG-2229: then the one repair call for left-out layers and flagged dates / durations / house lords. It runs here, // before completeBasis, so the post-step order the product tests pin is unchanged. await repairLeftOutLayers(controller); + // BUG-2342 round 2: a Western-only answer loses its time parts and any Indian paragraph the repair left. + shapeWesternOnly(controller); // BUG-2308: then the required strip (a missing section is added by one targeted call) and the 「最好的时候」 value, while // the evidence keys are still in the text (the strip's tones are read from them). await addRequiredTimeline(controller); @@ -1270,7 +1276,8 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { let timelineSectionAdded: string | null = null; async function addRequiredTimeline(controller: ReadableStreamDefaultController | undefined) { const card = options.state.evidenceCard ?? null; - if (!card) return; + // BUG-2342 round 2: a Western-only answer has no strip, required or added. + if (!card || options.state.westernScope === "only") return; try { const record: Record = {}; const shape = serverAnswerShape(fullOutput); @@ -1323,6 +1330,25 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { } } + /** + * BUG-2342 round 2 ("only"): the time section and the verdict's time label come out, and body lines that still use + * Indian-only terms after the repair call are dropped (the verdict and sections are protected). No model call. + */ + function shapeWesternOnly(controller: ReadableStreamDefaultController | undefined) { + if (options.state.westernScope !== "only") return; + try { + const time = withoutTimeParts(fullOutput); + const indian = withoutIndianLines(time.output, isProtectedRemoval); + options.state.answerChecks = { ...options.state.answerChecks, western: { ...options.state.answerChecks?.western, scope: "only", timeRemoved: time.removed, indianDropped: indian.dropped } }; + if (indian.output === fullOutput) return; + appendConsultationRuntimeStep(options.state, { kind: "validation", name: "answer-western-only", status: "completed", failureCode: `time:${time.removed.length};indian:${indian.dropped.length}` }); + fullOutput = indian.output; + send(controller, { type: "answer.delta", text: fullOutput, replace: true }); + } catch { + // Keep the answer as written. + } + } + async function guardInternalWordsOnce(controller: ReadableStreamDefaultController | undefined) { try { // 原值:scanInternalWords 带宫位选项(简明解读为真,BUG-2149 把正文写宫位的行 @@ -1377,7 +1403,14 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { */ function completeBasis(controller: ReadableStreamDefaultController | undefined) { try { - completeBasisOnce(controller); + // BUG-2342 round 2: a Western-only answer's 「判断依据」 is the Western rows only (no Indian keys, rows or must-see + // items); a both-sides answer's Western part is split off its Indian item first and grouped after. + if (options.state.westernScope === "only") westernOnlyEvidence(controller); + else { + if (options.state.westernScope === "both") splitWesternItems(controller); + completeBasisOnce(controller); + if (options.state.westernScope === "both") groupWesternEvidence(controller); + } } finally { cleanAnswerText(controller); attachDayCalendarShape(); @@ -1448,26 +1481,45 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { * (flagged, never substituted in place). A fix that fails the same checks again is not used; the clean-up runs on the * result. Any error keeps the answer as written. */ + /** BUG-2342 round 2: the regrouped body of a both-sides answer; keepWrittenReply's baseline takes it too. */ + let westernSideBody: string | null = null; async function repairLeftOutLayers(controller: ReadableStreamDefaultController | undefined) { const card = options.state.evidenceCard ?? null; if (!card || !options.repairLeftOutLayers) return; try { const pre = cleanChatAnswer(fullOutput, card, { userText: options.userText }); + // BUG-2342 round 2: the Western scope's flags (Indian paragraphs in a Western-only answer, a broken tie, a verdict + // that names one side) and the both-sides headings go to this same call. + const scope = options.state.westernScope ?? null; + const westernFlags = westernAnswerFlags(pre.output, scope, options.state.westernBasis); + const sides = scope === "both" ? missingSideHeadings(pre.output) : []; const plan = answerRepairPlan(pre.output, card, { followUp: options.followUpTurn === true, userText: options.userText, + westernOnly: scope === "only", + ...(scope === "both" ? { westernSection: westernSectionText(pre.output) } : {}), extraFlags: [ ...(options.state.guaranteeSoftened ?? []).map((item) => ({ kind: "guarantee", sentence: item.softened, card: GUARANTEE_REPAIR_NOTE })), ...pre.record.stageRepair.map((sentence) => ({ kind: "stage_claim", sentence, card: STAGE_REPAIR_NOTE })), + ...westernFlags, ], }); options.state.answerChecks = { ...options.state.answerChecks, flags: plan.flags.length, asked: plan.missing.map((layer) => layer.id), optionalNotMentioned: plan.optional }; - if (!plan.missing.length && !plan.flags.length) return; + if (scope) options.state.answerChecks = { ...options.state.answerChecks, western: { scope, flags: westernFlags.map((flag) => `${flag.kind}:${flag.sentence.slice(0, 40)}`), missingHeadings: sides } }; + const structure = sides.length ? sideStructurePrompt(pre.output) : ""; + if (!plan.missing.length && !plan.flags.length && !structure) return; send(controller, { type: "activity", phase: "answer-composition", label: "正在补上漏写的盘面依据" }); - const reply = await options.repairLeftOutLayers(answerRepairPrompt(pre.output, plan.missing, plan.flags)); - const filtered = withoutFailingFixes(parseAnswerRepair(reply.text), card); - const applied = applyAnswerRepair(pre.output, filtered.repair, plan.flags, card, new Set(), new Set(plan.missing.map((layer) => layer.id))); - const cleaned = cleanChatAnswer(applied.output, card, { userText: options.userText }); + const reply = await options.repairLeftOutLayers(`${answerRepairPrompt(pre.output, plan.missing, plan.flags)}${structure}`); + const filteredCard = withoutFailingFixes(parseAnswerRepair(reply.text), card); + const filteredWestern = scope ? withoutFailingWesternFixes(filteredCard.repair, plan.flags, options.state.westernBasis) : { repair: filteredCard.repair, rejected: [] }; + const filtered = { repair: filteredWestern.repair, rejected: [...filteredCard.rejected, ...filteredWestern.rejected] }; + const applied = applyAnswerRepair(pre.output, filtered.repair, plan.flags, card, new Set(), new Set(plan.missing.map((layer) => layer.id)), options.state.westernGuard ?? null); + // BUG-2342 round 2: the regrouped body of a both-sides answer, used only when it passes its checks. + const sideBody = structure ? parseSideBody(reply.text) : null; + const regrouped = structure ? applySideStructure(applied.output, sideBody) : null; + if (regrouped?.applied) westernSideBody = sideBody; + if (regrouped) options.state.answerChecks = { ...options.state.answerChecks, western: { ...options.state.answerChecks?.western, sidesRegrouped: regrouped.applied, ...(regrouped.reason ? { sidesRejected: regrouped.reason } : {}) } }; + const cleaned = cleanChatAnswer(regrouped?.output ?? applied.output, card, { userText: options.userText }); options.state.answerChecks = { ...options.state.answerChecks, repair: { added: applied.added.length, basis: applied.basis.length, fixed: applied.fixed, deleted: applied.deleted, rejected: filtered.rejected.length + applied.rejected.length }, @@ -1487,6 +1539,44 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { } } + function westernOnlyEvidence(controller: ReadableStreamDefaultController | undefined) { + try { + const result = westernOnlyBasis(fullOutput, options.state.westernBasis ?? null); + options.state.answerChecks = { ...options.state.answerChecks, western: { ...options.state.answerChecks?.western, basis: result.record } }; + appendConsultationRuntimeStep(options.state, { kind: "validation", name: "answer-western-basis", status: "completed", failureCode: `western:${result.record.western};keysDropped:${result.record.droppedKeys.length};itemsDropped:${result.record.droppedItems.length}` }); + if (result.output === fullOutput) return; + fullOutput = result.output; + send(controller, { type: "answer.delta", text: fullOutput, replace: true }); + } catch { + // Keep the answer as written. + } + } + + function splitWesternItems(controller: ReadableStreamDefaultController | undefined) { + try { + const result = splitMixedWesternItems(fullOutput); + if (!result.split.length) return; + options.state.answerChecks = { ...options.state.answerChecks, western: { ...options.state.answerChecks?.western, splitItems: result.split } }; + fullOutput = result.output; + send(controller, { type: "answer.delta", text: fullOutput, replace: true }); + } catch { + // Keep the answer as written. + } + } + + function groupWesternEvidence(controller: ReadableStreamDefaultController | undefined) { + try { + const result = groupedBothBasis(fullOutput, options.state.westernBasis ?? null); + options.state.answerChecks = { ...options.state.answerChecks, western: { ...options.state.answerChecks?.western, basis: result.record } }; + if (result.output === fullOutput) return; + appendConsultationRuntimeStep(options.state, { kind: "validation", name: "answer-western-basis", status: "completed", failureCode: `western:${result.record.western};indian:${result.record.indian}` }); + fullOutput = result.output; + send(controller, { type: "answer.delta", text: fullOutput, replace: true }); + } catch { + // Keep the answer as written. + } + } + function completeBasisOnce(controller: ReadableStreamDefaultController | undefined) { const card = options.state.evidenceCard; if (!card) return; @@ -1581,7 +1671,12 @@ export function streamAgentResponse(options: StreamAgentResponseOptions) { ...list("metaDropped").map((sentence) => `meta:${sentence.slice(0, 40)}`), ...(options.state.answerChecks?.repair?.deleted ? [`repair:${options.state.answerChecks.repair.deleted}`] : []), ].slice(0, 40); - const result = keepDirectReply(timelineSectionAdded ? withTimelineSection(written, timelineSectionAdded) : written, fullOutput); + let baseline = timelineSectionAdded ? withTimelineSection(written, timelineSectionAdded) : written; + // BUG-2342 round 2: what the Western shape took out on purpose (a Western-only answer's time parts and Indian lines, + // a both-sides answer's old sections) is not put back. + if (options.state.westernScope === "only") baseline = withoutIndianLines(withoutTimeParts(baseline).output, () => false).output; + if (westernSideBody) baseline = applySideStructure(baseline, westernSideBody).output; + const result = keepDirectReply(baseline, fullOutput); options.state.answerChecks = { ...options.state.answerChecks, directReply: { restored: result.restored, deletions } }; if (!result.restored.length || result.output === fullOutput) return; appendConsultationRuntimeStep(options.state, { diff --git a/frontend/src/mastra/consultation-tools.ts b/frontend/src/mastra/consultation-tools.ts index 94e1c4e07..07f86bfaa 100644 --- a/frontend/src/mastra/consultation-tools.ts +++ b/frontend/src/mastra/consultation-tools.ts @@ -1,4 +1,4 @@ -import { fetchWesternNatalFacts, type WesternGuardFacts } from "../lib/chat-western-facts.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"; import { isKpDomain } from "../lib/chat-kp-timing.ts"; @@ -390,7 +390,9 @@ const consultationToolInputSchema = z.object({ }).strict().optional(), // BUG-2342: the question asks for Western astrology (the writer's own judgment, never a word match); the result then // carries western_natal, the Western chart facts (the same as the western:natal lookup). Absent: nothing changes. - western_chart: z.boolean().optional(), + // Round 2: the writer also declares the scope — "only" (Western only) or "both" (Indian and Western side by side); + // true is the first round's value and means "only". + western_chart: z.union([z.boolean(), z.enum(["only", "both"])]).optional(), }).strict(); const MAX_RECORDED_STEPS = 32; @@ -481,6 +483,10 @@ export type ConsultationRuntimeState = { evidenceCard?: EvidenceCard; /** BUG-2342: the Western chart the writer read this turn (western:natal); the fact guard accepts its positions. */ westernGuard?: WesternGuardFacts; + /** BUG-2342 round 2: the scope the writer declared with western_chart; the answer's shape is enforced from it. */ + westernScope?: WesternScope; + /** BUG-2342 round 2: the Western rows the program prints in 「判断依据」 (and the tie check reads). */ + westernBasis?: WesternBasisFacts; /** Characters of the card's model-visible JSON (claim cards + card meta). */ evidenceCardChars?: number; /** Characters of the whole tool result the model saw. */ @@ -496,7 +502,7 @@ export type ConsultationRuntimeState = { /** BUG-2229: what the deterministic clean-up and the layer repair did to this answer (records only). */ /** BUG-2281: lit chart areas and one-year strip tones, derived from the answer's evidence keys; goes on the receipt. */ answerShape?: AnswerShapeData; - answerChecks?: { steps?: unknown; flags?: number; asked?: string[]; optionalNotMentioned?: string[]; repair?: Record; plainBody?: Record; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record; dayCalendar?: { mentioned: number; conflicts: string[] } }; + answerChecks?: { steps?: unknown; flags?: number; asked?: string[]; optionalNotMentioned?: string[]; repair?: Record; plainBody?: Record; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record; dayCalendar?: { mentioned: number; conflicts: string[] }; western?: Record }; }; export function createConsultationRuntimeState(options: { plannedSteps?: number; reservedValidationSteps?: number } = {}): ConsultationRuntimeState { @@ -1647,13 +1653,14 @@ export function createConsultationTools(ctx: ConsultationAgentContext) { const westernNatalLookup = (cache: EvidenceLookupCache) => { westernFacts ??= fetchWesternNatalFacts(cache.executions[0]?.context.chart, ctx.westernFetch).then((result) => { if (result.guard) ctx.state.westernGuard = result.guard; + if (result.basis) ctx.state.westernBasis = result.basis; return result.facts; }); return westernFacts.then((facts) => facts ?? undefined); }; 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: true: 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.`, + 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.`, 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. @@ -1670,7 +1677,10 @@ export function createConsultationTools(ctx: ConsultationAgentContext) { } const { domains } = executableDomainPlan(requestedDomains); // BUG-2336: the day calendar for the writer's own day range (checked and cut to 45 days; null when unreadable). - const dayRange = clampDayRange(input.day_range, (ctx.requestTime ?? new Date()).toISOString().slice(0, 10)); + // BUG-2342 round 2: a Western-only answer has no time parts, so it never gets a day calendar. + const scope = westernScope(input.western_chart); + if (scope) ctx.state.westernScope = scope; + const dayRange = scope === "only" ? null : clampDayRange(input.day_range, (ctx.requestTime ?? new Date()).toISOString().slice(0, 10)); const dayCalendar: { pending: ReturnType | null } = { pending: null }; // BUG-1973: a repeated call used to return the whole result again, so a // 10–17 万-character card entered the context twice (an annual answer went @@ -1895,7 +1905,7 @@ export function createConsultationTools(ctx: ConsultationAgentContext) { : undefined, }); // BUG-2342: a Western question gets the Western chart here, next to (not inside) the card; the card is unchanged. - if (input.western_chart === true) { + if (scope) { const western = await westernNatalLookup({ executions }); modelView.western_natal = western ?? readEvidenceLookupSection({ executions }, "western:natal") ?? null; appendConsultationRuntimeStep(ctx.state, { kind: "tool", name: "western-natal", status: western ? "completed" : "failed", ...(western ? {} : { failureCode: "western_chart_unavailable" }) }); diff --git a/frontend/src/mastra/product-voice.ts b/frontend/src/mastra/product-voice.ts index 19478cdd6..391f4dd03 100644 --- a/frontend/src/mastra/product-voice.ts +++ b/frontend/src/mastra/product-voice.ts @@ -341,7 +341,9 @@ ${bodyHeadingLines()} - 正文写到时间条以外的日期时写到年月。「出生时间差几分钟会移动几天」这句不写:页面在时间条下面统一显示一次。 - 日期写多细按出生时间来源定(用户轮里出生时间那一句):医院记录、证件、家里记得准的时间,或在生时纠正里定过的,日期照卡上算出来的写,问到哪天就写到哪天;大概的时间,运期交接写到月或旬。行星换座、接触这些行运日期和按天的 day_calendar 不受出生分钟影响,任何来源都写到天。 - 问的是具体哪几天(这周、这几天、某一天、某个月里哪几天、接下来几周哪天)时,调用 run-jyotish-consultation 带上 day_range(这几天的起止,一周从周一到周日),照卡上的 day_calendar 在对话里直接答,不叫用户去星历页看;只有「几点几分」办事的择时对话里不做。结论只写一句,直接答哪天最好、哪天避开,例如「这周最好的是周四 26 日,要避开的是下周一 30 日。」(日子照表),前面不先说能不能答、打算怎么答;结论下面不写标签行(页面的日历每格都有吉平凶);不写时间那一节;正文每块照写,点到的日子都要说那天做什么、为什么(用表里那一行的话,换成你自己的句子),句末写它的〔C 编号〕;吉、平、凶照表,不自己改,表外的日子不说好坏。 -- 用户要的是西洋占星(西洋、西方占星、太阳星座,或说明按西洋看的元素、相位、格局)时,调用 run-jyotish-consultation 时带上 western_chart: true(漏带了就用 read-consultation-evidence 取 section=western:natal),西洋的判断只照结果里的 western_natal 写:元素、星座类型、左右上下、相位、格局、庙旺照那里的计数和行,不自己重数;卡上是印度盘,上升、星座、宫位都和西洋盘不同,不拿来当西洋判断的依据。用户两边都问时,两边分开写,每句说清是西洋盘还是印度盘。正文可以照用户的问法用元素、星座、相位这些词。西洋的判断在「判断依据」里单独成条,不写〔编号〕,说明以「西洋盘:」开头,写用到的西洋盘事实(例如「西洋盘:火、土元素各 3 颗,固定星座 5 颗」),这几条可以写星座和个数。只问西洋盘的题不写时间那一节。 +- 用户要的是西洋占星(西洋、西方占星、太阳星座,或说明按西洋看的元素、相位、格局)时,调用 run-jyotish-consultation 时带上 western_chart:只问西洋盘写 "only",印度盘和西洋盘两边都问写 "both"(漏带了就用 read-consultation-evidence 取 section=western:natal)。西洋的判断只照结果里的 western_natal 写:元素、星座类型、左右上下、相位、格局、庙旺照那里的计数和行,不自己重数;最多的元素或星座类型并列时(element_top、mode_top 写着并列),几样一起说,不说哪一样最突出、哪一样其次。卡上是印度盘,上升、星座、宫位都和西洋盘不同,不拿来当西洋判断的依据。正文可以照用户的问法用元素、星座、相位这些词。西洋的判断在「判断依据」里单独成条,写成「- **判断短句**:西洋盘:用到的西洋盘事实。」,不写〔编号〕,程序照 western_natal 列出这几样事实。 + - "only":全文只讲西洋盘,不写印度盘的东西(大运、小运、Narayana、分盘、功能吉凶星、Yogakaraka、星宿都不写),「判断依据」只写西洋盘的条;不写时间那一节;性格这类题结论卡用性格那组标签。 + - "both":结论第一句把两边的看法都说到;结论后面的正文只用这几节,替代平常那五块:「## 印度盘怎么看」「## 西洋盘怎么看」,两边有一致和不同的地方时再加「## 两边一致和不同的地方」。长处短处、适合不适合、要留意的写进它属于的那一节,每节里的句子就是那一边的看法;讲时间的句子只写在印度盘那一节。「判断依据」里印度盘的条照平常写〔编号〕,西洋盘的条照上面的写法,一条只写一边。 - 问换工作、要不要做某件事、今年明年怎样这类按月按年的题(不是按天的题)时,结论第一句后面、同一段里接一句「现在走的是某某大运里的某某小运,到某年某月」,大运、小运照卡上当前那两层写,主星写中文;这是正文里唯一可以写大运、小运名字的一句,只写一次。 - 建议要具体:每段时间写做什么、不做什么。不给医疗、法律、投资指令:不推荐具体投资品,不开药,不列化验单;健康只写作息、减负、什么情况该去看医生。 - 用户说过的事实照用。要问用户的只写在「## ${ASK_USER_HEADING}」那一节,别处(正文末尾、「接着问」、「判断依据」前后)不问用户问题;不请用户回想过去的事来帮着推将来。 diff --git a/frontend/tests/chat-voice-2229.test.ts b/frontend/tests/chat-voice-2229.test.ts index e68d0d3cc..31277d329 100644 --- a/frontend/tests/chat-voice-2229.test.ts +++ b/frontend/tests/chat-voice-2229.test.ts @@ -68,7 +68,8 @@ test("BUG-2229: the plain chat voice is the sectioned voice; the old plain voice // 原值:9_000;新值:9_200(实测 9,093);原因:BUG-2320 时间那一节紧跟结论写、那一句和该做别做的字数、有机会的小标题不用紧 / 守住 / // 收着、转折点那一句的写法,正文不再重复时间条的起止(指「时间轴里某一段」)。 // 原值 9,200 / 新值 9,850 / 原因: BUG-2335 / 2336 加按出生时间来源定日期精度、按天的问题照 day_calendar 答、按月按年的题说一次现在的大运小运(实测 9,817)。 - assert.ok([...voice].length <= 9_850, String([...voice].length)); + // 原值 9,850 / 新值 10,620 / 原因: BUG-2342 西洋题带 western_chart(第一轮);第二轮分 "only" / "both" 两种写法、并列的计数照并列说(实测 10,570)。 + assert.ok([...voice].length <= 10_620, 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); }); diff --git a/frontend/tests/consult-chart-data-20261116.test.tsx b/frontend/tests/consult-chart-data-20261116.test.tsx index 166dc1343..095134289 100644 --- a/frontend/tests/consult-chart-data-20261116.test.tsx +++ b/frontend/tests/consult-chart-data-20261116.test.tsx @@ -82,7 +82,8 @@ test("the receipt carries the record and older receipts without it still parse", assert.equal(shape.chartData.safeParse(undefined).success, true); assert.equal(shape.chartData.safeParse({ natal: [{ body: "Sun", sign: "Leo", extra: 1 }], periods: [], transits: [] }).success, false); const route = readFileSync(new URL("../src/app/api/consult/route.ts", import.meta.url), "utf8"); - assert.match(route, /const chartData = consultChartDataFromCard\(state\.evidenceCard\);\n\s+return chartData \? \{ chartData \} : \{\};/); + // 原值:const chartData = consultChartDataFromCard(state.evidenceCard);新值:西洋专问(westernScope "only")不带印度盘的表;原因:BUG-2342 第二轮。 + assert.match(route, /const chartData = state\.westernScope === "only" \? null : consultChartDataFromCard\(state\.evidenceCard\);\n\s+return chartData \? \{ chartData \} : \{\};/); }); test("the fold renders three tables in Chinese, one line per row, and only under a settled answer", () => { diff --git a/frontend/tests/consultation-agentic-runtime.test.ts b/frontend/tests/consultation-agentic-runtime.test.ts index 90add470a..9647e2a1f 100644 --- a/frontend/tests/consultation-agentic-runtime.test.ts +++ b/frontend/tests/consultation-agentic-runtime.test.ts @@ -179,7 +179,8 @@ test("BUG-2287: the model must name the domains; one calculation per request", a // A single-value theme is deliberately absent: two mutually exclusive ways to // name a domain cost the model a step per call to discover the rule. // 原值 ["question", "domains"];新值加可选的 day_range;原因:BUG-2336,按天的问题由写手在工具调用里给出日子范围(不按用户原话匹配)。 - assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains", "day_range"]); + // 原值 ["question", "domains", "day_range"];新值加可选的 western_chart;原因:BUG-2342,西洋题由写手在工具调用里声明范围("only" / "both")。 + assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains", "day_range", "western_chart"]); const execute = tool.execute!; const context = { observe: { span: async (_n: string, fn: () => Promise) => fn(), log() {} } } as never; const schema = tool.inputSchema as unknown as { safeParse: (value: unknown) => { success: boolean } }; diff --git a/frontend/tests/western-chat-2342-round2.test.ts b/frontend/tests/western-chat-2342-round2.test.ts new file mode 100644 index 000000000..6e4737d2b --- /dev/null +++ b/frontend/tests/western-chat-2342-round2.test.ts @@ -0,0 +1,378 @@ +// BUG-2342 round 2: Western answers clean by structure, not by more prose rules. The writer declares the scope +// (western_chart "only" | "both"); the program then removes the time parts of a Western-only answer, prints only Western +// rows in its 「判断依据」, sends Indian paragraphs and broken ties to the one repair call, enforces the two side headings +// of a both-sides answer and groups its evidence; backstage notes leave every answer. +// Retest answers behind each case: /workspace/eval-read-1116/western-chat-2342/retest-element.md, retest-both.md. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { Agent } from "@mastra/core/agent"; + +import { cleanChatAnswer, fixBackstageWords } from "../src/lib/chat-answer-checks.ts"; +import { answerRepairPlan } from "../src/lib/chat-answer-repair.ts"; +import { + applySideStructure, + breaksTie, + groupedBothBasis, + missingSideHeadings, + parseSideBody, + sideStructurePrompt, + splitMixedWesternItems, + westernAnswerFlags, + westernOnlyBasis, + westernOnlyIndianFlags, + westernSectionText, + withoutWesternBodyNotes, + westernTieFlags, + withoutFailingWesternFixes, + withoutIndianLines, + withoutTimeParts, +} from "../src/lib/chat-western-answer.ts"; +import { westernBasisFacts, westernNatalToolFacts, westernScope, westernTopCount } from "../src/lib/chat-western-facts.ts"; +import { isProtectedRemoval } from "../src/lib/chat-answer-direct-reply.ts"; +import { parseJudgmentBasisItems, splitJudgmentBasis } from "../src/lib/consult-judgment-basis.ts"; +import { createNdjsonParser } from "../src/lib/consultation-agent-events.ts"; +import { streamAgentResponse } from "../src/lib/stream-agent-response.ts"; +import { chatConversationVoice } from "../src/mastra/product-voice.ts"; +import { + consultationStepBudgetReceipt, + createConsultationRuntimeState, + createConsultationTools, + publicConsultationRuntimeSteps, +} from "../src/mastra/consultation-tools.ts"; +import { publicServerChart } from "./consult-natal-agent-test-support.ts"; + +type Json = Record; +const obama = JSON.parse(readFileSync(new URL("./fixtures/western-obama-2340.json", import.meta.url), "utf8")) as Json; +const golden = JSON.parse(readFileSync(new URL("./fixtures/consult-evidence-card-golden.json", import.meta.url), "utf8")) as { + charts: Array<{ id: string; workflow: Json }>; +}; +const jobs = golden.charts.find((chart) => chart.id === "steve_jobs")!.workflow; +const facts = westernBasisFacts(obama)!; + +// The element question's retest answer, cut to the parts each check reads (anonymous wording kept from the retest). +const ONLY_ANSWER = [ + "## 结论", + "你的性格里最突出的是火,土紧跟在后面,和火一样多。〔Su〕", + "- **长处**:敢定方向,扛得住长期", + "- **短处**:太要面子,改主意慢", + "- **最好的时候**:2027 年 3 月到 8 月", + "", + "## 接下来一年", + "- **起步**(现在到 2027 年 2 月):适合定方向。该做:定一件事。别做:别铺开。〔W1〕", + "", + "## 你的长处和短处", + "**固定星座最多,你认定的事不太爱改。** 答应下来的事会做到底。", + "", + "按这个上升算,土星管第 1、2 宫,是功能吉星,金星还是 Yogakaraka。〔FB Sa〕", + "", + "**你想得比说得多。** 月亮在双子,和冥王之间是一个紧张的角。", + "", + "## 接着问", + "- 我适合自己做事还是跟人合伙?", + "", + "## 判断依据", + "- **最突出的是火,土并列**:西洋盘:火 3 颗(太阳、水星、天王),土 3 颗。", + "- **认定了不爱改**:西洋盘:固定星座 5 颗最多。", + "- **想得多**:西洋盘:月亮在双子,与冥王成刑相。", + "- 现在走土星大运(2011-06-24 至 2030-06-24),土星是功能吉星。〔V1 V2〕", + "- **相关分盘**:D9(看婚姻):第 1 宫狮子;D10(看事业):第 1 宫金牛。〔D9 D10〕", + "", +].join("\n"); + +const BOTH_ANSWER = [ + "## 结论", + "两边看到的是同一个底子:你是自己拿主意、慢慢把事做出来的人。", + "- **长处**:耐力长", + "- **短处**:话少", + "- **适合**:长期做一件事", + "", + "## 你的长处和短处", + "**两边都说你耐得住。** 你凡事愿意自己动手。〔H1 Sa〕", + "", + "**你心里要强。** 你希望别人看见你手上的活。", + "", + "## 接着问", + "- 我该怎么让别人看见我做的事?", + "", + "## 判断依据", + "- **你耐得住**:命主入庙、逆行,逆行只列出、不作理由。(几种方法一致)〔H1 Sa〕", + "- **里面的你要强**:命主与自我代表星各撑一半。 — 西洋盘:太阳在狮子、入庙;火与土元素各 3 颗。〔H7 Su〕", + "", +].join("\n"); + +test("the writer's scope: \"only\" / \"both\", and the first round's true still means only", () => { + assert.equal(westernScope(true), "only"); + assert.equal(westernScope("only"), "only"); + assert.equal(westernScope("both"), "both"); + assert.equal(westernScope(false), null); + assert.equal(westernScope(undefined), null); + assert.equal(westernScope("yes"), null); +}); + +test("ties: the writer gets the top count with ties marked; the basis facts carry the same sentence", () => { + assert.deepEqual(westernTopCount([{ label: "火", count: 3 }, { label: "土", count: 3 }, { label: "风", count: 2 }]), { text: "火和土并列最多,各 3 颗", top: ["火", "土"] }); + assert.deepEqual(westernTopCount([{ label: "基本", count: 2 }, { label: "固定", count: 5 }]), { text: "固定最多,5 颗", top: ["固定"] }); + assert.equal(westernTopCount([{ label: "火", count: 3 }, { label: "土", count: 3 }, { label: "风", count: 3 }])!.text, "火、土和风并列最多,各 3 颗"); + const tool = westernNatalToolFacts(obama)!; + assert.equal(tool.element_top, "火和土并列最多,各 3 颗"); + assert.equal(tool.mode_top, "固定最多,5 颗"); + // Pinned with round 1: the tool facts stay under 2,000 characters. + assert.ok(JSON.stringify(tool).length <= 2_000, `western tool facts ${JSON.stringify(tool).length} chars`); + assert.equal(facts.elements.topText, "火和土并列最多,各 3 颗"); + assert.deepEqual(facts.elements.top, ["火", "土"]); +}); + +test("ties: a tied top stated as one winner is flagged (body and basis title); a tie said as a tie is not", () => { + const top = ["火", "土"]; + for (const sentence of ["你的性格里最突出的是火,土紧跟在后面。", "火最突出。", "火象占上风。", "最多的是土元素。", "土其次。"]) { + assert.equal(breaksTie(sentence, top), true, sentence); + } + for (const sentence of ["火和土并列最多,各 3 颗。", "最突出的是火和土。", "火和土最突出。", "火星最突出。", "水星最多。", "土星在摩羯入庙。"]) { + assert.equal(breaksTie(sentence, top), false, sentence); + } + const flags = westernTieFlags(ONLY_ANSWER, facts); + assert.deepEqual(flags.map((flag) => flag.sentence), ["你的性格里最突出的是火,土紧跟在后面,和火一样多。", "最突出的是火,土并列"]); + assert.ok(flags.every((flag) => flag.kind === "western_tie" && flag.card.includes("火和土并列最多,各 3 颗"))); + // Fixed modality is a single top: 「固定星座最多」 is right and not flagged. + assert.ok(!flags.some((flag) => flag.sentence.includes("固定"))); + // A fix that still breaks the tie is not used. + const filtered = withoutFailingWesternFixes({ fixes: [{ id: 1, text: "火最突出,土其次。" }, { id: 2, text: "火和土并列最多。" }] }, [{ id: 1, kind: "western_tie" }, { id: 2, kind: "western_tie" }], facts); + assert.deepEqual(filtered.repair.fixes.map((fix) => fix.id), [2]); + assert.deepEqual(filtered.rejected, ["fix#1:tie"]); +}); + +test("only: Indian-only paragraphs are flagged for the repair call, and dropped when the repair leaves them", () => { + const flags = westernOnlyIndianFlags(ONLY_ANSWER); + assert.equal(flags.length, 1); + assert.match(flags[0]!.sentence, /^按这个上升算/u); + assert.match(flags[0]!.card, /功能吉星、Yogakaraka/u); + assert.deepEqual(westernAnswerFlags(ONLY_ANSWER, "only", facts).map((flag) => flag.kind), ["western_only_indian", "western_tie", "western_tie"]); + // A rewrite that keeps the Indian terms is not used. + const filtered = withoutFailingWesternFixes({ fixes: [{ id: 1, text: "土星是功能吉星。" }] }, [{ id: 1, kind: "western_only_indian" }], facts); + assert.deepEqual(filtered.rejected, ["fix#1:indian"]); + const dropped = withoutIndianLines(ONLY_ANSWER, isProtectedRemoval); + assert.equal(dropped.dropped.length, 1); + assert.doesNotMatch(splitJudgmentBasis(dropped.output).body, /功能吉星|Yogakaraka/u); + assert.match(dropped.output, /你想得比说得多/u); + // The repair plan of a Western-only answer is its own flags only (no Indian layers, no Indian table checks). + const plan = answerRepairPlan(ONLY_ANSWER, {} as never, { westernOnly: true, extraFlags: flags }); + assert.deepEqual(plan.missing, []); + assert.deepEqual(plan.flags.map((flag) => flag.kind), ["western_only_indian"]); +}); + +test("only: no time section and no time label in the verdict", () => { + const result = withoutTimeParts(ONLY_ANSWER); + assert.deepEqual(result.removed, ["label:最好的时候", "section:接下来一年"]); + assert.doesNotMatch(result.output, /接下来一年|最好的时候|起步/u); + assert.match(result.output, /- \*\*长处\*\*:敢定方向/u); + assert.match(result.output, /## 你的长处和短处/u); + assert.deepEqual(withoutTimeParts(result.output).removed, []); +}); + +test("only: 「判断依据」 is Western rows printed from western_natal; Indian keys and items are dropped and logged", () => { + const { output, record } = westernOnlyBasis(ONLY_ANSWER, facts); + const split = splitJudgmentBasis(output); + assert.doesNotMatch(output, /〔/u, "every key tag is gone"); + assert.deepEqual(record.droppedKeys.sort(), ["D10", "D9", "FB", "Sa", "Su", "V1", "V2", "W1"].sort()); + assert.equal(record.droppedItems.length, 2); + const items = parseJudgmentBasisItems(split.basis!)!; + assert.ok(items.every((item) => item.facts[0]!.text.startsWith("西洋盘:")), JSON.stringify(items)); + assert.doesNotMatch(split.basis!, /大运|D9|D10|功能吉星|Narayana/u); + // The rows are the chart's, not the writer's (「土 3 颗」 without members became the full count row with the tie). + assert.match(split.basis!, /- \*\*最突出的是火,土并列\*\*:西洋盘:元素:火 3 颗(太阳、水星、天王)、土 3 颗(火星、土星、冥王)、风 2 颗(月亮、木星)、水 2 颗(金星、海王);火和土并列最多,各 3 颗/u); + assert.match(split.basis!, /- \*\*认定了不爱改\*\*:西洋盘:星座类型:基本 2 颗(金星、土星)、固定 5 颗(太阳、水星、木星、天王、海王)、变动 3 颗(月亮、火星、冥王);固定最多,5 颗。/u); + assert.match(split.basis!, /- \*\*想得多\*\*:西洋盘:月亮在双子 3°21′,第 4 宫;冥王在处女 6°58′,第 7 宫;月亮刑相冥王,差 3\.6°。/u); + assert.equal(items.length, 3); +}); + +test("both: the side headings, the regrouped body from the one repair call, and the verdict naming both sides", () => { + assert.deepEqual(missingSideHeadings(BOTH_ANSWER), ["印度盘怎么看", "西洋盘怎么看"]); + const prompt = sideStructurePrompt(BOTH_ANSWER); + assert.match(prompt, /「## 印度盘怎么看」「## 西洋盘怎么看」/u); + assert.match(prompt, /两边都说你耐得住/u); + assert.doesNotMatch(prompt, /判断依据|接着问/u); + const body = "## 印度盘怎么看\n\n**印度盘上你耐得住。** 你凡事愿意自己动手。〔H1 Sa〕\n\n## 西洋盘怎么看\n\n**西洋盘上你心里要强。** 你希望别人看见你手上的活。"; + const reply = JSON.stringify({ layers: [], fixes: [], body }); + assert.equal(parseSideBody(reply), body); + const applied = applySideStructure(BOTH_ANSWER, parseSideBody(reply)); + assert.equal(applied.applied, true); + assert.deepEqual(missingSideHeadings(applied.output), []); + assert.match(applied.output, /## 结论\n两边看到的是同一个底子/u); + assert.match(applied.output, /## 接着问\n- 我该怎么让别人看见我做的事?/u); + assert.doesNotMatch(applied.output, /## 你的长处和短处/u); + // Missing a side, another heading, or a much shorter body: the answer stays as written. + assert.equal(applySideStructure(BOTH_ANSWER, body.replace("## 西洋盘怎么看", "")).reason, "headings"); + assert.equal(applySideStructure(BOTH_ANSWER, `${body}\n\n## 判断依据\n- x`).reason, "other_heading"); + assert.match(String(applySideStructure(BOTH_ANSWER, "## 印度盘怎么看\n短。\n## 西洋盘怎么看\n短。").reason), /^length/u); + assert.equal(applySideStructure(BOTH_ANSWER, null).applied, false); + // The verdict sentence names one side only → flagged; a fix naming both is used. + const verdict = westernAnswerFlags(BOTH_ANSWER, "both", facts).filter((flag) => flag.kind === "western_both_verdict"); + assert.equal(verdict.length, 1); + assert.equal(verdict[0]!.sentence, "两边看到的是同一个底子:你是自己拿主意、慢慢把事做出来的人。"); + const filtered = withoutFailingWesternFixes({ fixes: [{ id: 1, text: "你很稳。" }, { id: 2, text: "印度盘看你沉稳,西洋盘看你要强。" }] }, [{ id: 1, kind: "western_both_verdict" }, { id: 2, kind: "western_both_verdict" }], facts); + assert.deepEqual(filtered.repair.fixes.map((fix) => fix.id), [2]); +}); + +test("both: a mixed item is split before the keys expand, and 「判断依据」 shows 印度盘 then 西洋盘", () => { + const split = splitMixedWesternItems(BOTH_ANSWER); + assert.deepEqual(split.split, ["里面的你要强"]); + const basis = splitJudgmentBasis(split.output).basis!; + assert.match(basis, /- \*\*里面的你要强\*\*:命主与自我代表星各撑一半。〔H7 Su〕\n- \*\*里面的你要强\*\*:西洋盘:太阳在狮子、入庙;火与土元素各 3 颗。/u); + const grouped = groupedBothBasis(split.output, facts); + assert.equal(grouped.record.western, 2); + assert.equal(grouped.record.indian, 2); + const items = parseJudgmentBasisItems(splitJudgmentBasis(grouped.output).basis!)!; + assert.deepEqual(items.map((item) => item.group), ["印度盘", "印度盘", "西洋盘", "西洋盘"]); + assert.equal(items[2]!.facts[0]!.text.startsWith("西洋盘:元素:火 3 颗"), true); + assert.equal(items[3]!.title, "西洋盘的元素和星座类型"); + // An answer without Western items is left alone. + const indianOnly = BOTH_ANSWER.replace(/\n- \*\*里面的你要强.*\n/u, "\n"); + assert.equal(groupedBothBasis(indianOnly, null).output, indianOnly); + // Older answers (no group lines) parse exactly as before. + assert.equal(parseJudgmentBasisItems("- **a**:b。")![0]!.group, undefined); +}); + +test("backstage notes leave every answer (any scope, any section)", () => { + const text = "- **你耐得住**:命主入庙、逆行,逆行只列出、不作理由。(几种方法一致)\n- **时间线各段**:Narayana 从哪年起算还有分歧,只作有条件的时间段,暂不作为两套确认。白羊 2021 至 2028(Narayana 从哪年起算还有分歧,只作一种方法的指向)。\n- **x**:y。(几种方法一致;出生时间稍有出入就会变)"; + const fixed = fixBackstageWords(text).output; + assert.equal(fixed, "- **你耐得住**:命主入庙、逆行。\n- **时间线各段**:Narayana 从哪年起算还有分歧。白羊 2021 至 2028(Narayana 从哪年起算还有分歧)。\n- **x**:y。(出生时间稍有出入就会变)"); + const cleaned = cleanChatAnswer(`## 结论\n你很稳。\n\n## 判断依据\n${text}\n`, null).output; + assert.doesNotMatch(cleaned, /几种方法一致|只列出、不作理由|只作一种方法的指向|只作有条件的时间段|两套确认/u); +}); + +test("the tool takes the scope; \"only\" gets no day calendar; the writing rule says the two shapes", async () => { + const fake = (async () => new Response(JSON.stringify(obama), { status: 200 })) as unknown as typeof fetch; + const writer = { writer: { custom: async () => {} } } as never; + for (const [value, scope] of [["only", "only"], ["both", "both"], [true, "only"]] as const) { + const state = createConsultationRuntimeState(); + const tools = createConsultationTools({ + userId: "u", sessionId: "s", requestId: `scope-${String(value)}`, consultationMode: "verified_chart", + serverChart: publicServerChart as never, state, runWorkflow: async () => structuredClone(jobs) as never, westernFetch: fake, + requestTime: new Date("2026-09-27T04:00:00.000Z"), + }); + const result = await tools["run-jyotish-consultation"].execute!({ question: "q", domains: ["parents"], western_chart: value, ...(scope === "only" ? { day_range: { start: "2026-09-28", end: "2026-10-04" } } : {}) } as never, writer) as Json; + assert.equal(state.westernScope, scope); + assert.deepEqual(result.western_natal, westernNatalToolFacts(obama)); + assert.deepEqual(state.westernBasis, facts); + if (scope === "only") assert.ok(!state.steps.some((step) => step.name === "day-calendar"), "no day calendar for a Western-only answer"); + } + const calc = String(createConsultationTools({ userId: "u", sessionId: "s", requestId: "d", consultationMode: "verified_chart", serverChart: publicServerChart as never, state: createConsultationRuntimeState() })["run-jyotish-consultation"].description); + assert.match(calc, /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/u); + assert.match(chatConversationVoice, /只问西洋盘写 "only",印度盘和西洋盘两边都问写 "both"/u); + assert.match(chatConversationVoice, /"only":全文只讲西洋盘.*不写时间那一节/u); + assert.match(chatConversationVoice, /"both":结论第一句把两边的看法都说到;结论后面的正文只用这几节.*「## 印度盘怎么看」「## 西洋盘怎么看」/u); + assert.match(chatConversationVoice, /并列时(element_top、mode_top 写着并列),几样一起说/u); +}); + +// ---- through the real answer stream ------------------------------------------------------------------------------ + +function fakeModel(parts: readonly string[]) { + return { + specificationVersion: "v2", provider: "fake", modelId: "fake-writer", supportedUrls: {}, + async doGenerate() { throw new Error("not used"); }, + async doStream() { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue({ type: "stream-start", warnings: [] }); + controller.enqueue({ type: "text-start", id: "1" }); + for (const part of parts) controller.enqueue({ type: "text-delta", id: "1", delta: part }); + controller.enqueue({ type: "text-end", id: "1" }); + controller.enqueue({ type: "finish", finishReason: "stop", usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 } }); + controller.close(); + }, + }); + return { stream }; + }, + }; +} +let seq = 0; +async function realStream(text: string) { + seq += 1; + const agent = new Agent({ id: `w-${seq}`, name: `w-${seq}`, model: fakeModel(text.match(/[\s\S]{1,12}/gu) ?? []) as never, instructions: "fictional writer" } as never); + const result = await agent.stream([{ role: "user", content: "fictional question" }] as never, { maxSteps: 1, toolChoice: "none" } as never); + return result.fullStream as ReadableStream; +} + +async function runAnswer(answer: string, scope: "only" | "both", repairReply: (prompt: string) => string) { + const state = createConsultationRuntimeState(); + const tools = createConsultationTools({ + userId: "u", sessionId: "s", requestId: "stream", consultationMode: "verified_chart", serverChart: publicServerChart as never, state, + runWorkflow: async () => structuredClone(jobs) as never, westernFetch: (async () => new Response(JSON.stringify(obama), { status: 200 })) as unknown as typeof fetch, + requestTime: new Date("2026-09-27T04:00:00.000Z"), + }); + await tools["run-jyotish-consultation"].execute!({ question: "q", domains: ["parents"], western_chart: scope } as never, { writer: { custom: async () => {} } } as never); + state.jyotishSkillBound = true; + let completed = ""; + const prompts: string[] = []; + const response = streamAgentResponse({ + runId: "run", requestId: "req", state, stream: () => realStream(answer), requireTool: true, stepScopedAnswer: true, toolStatus: () => "ready", + receipt: () => ({ runId: "run", runtime: "mastra-agentic", skill: { name: "jyotish-vedic-astrology", loaded: true, referenceReads: 0, methodologySections: 0 }, steps: publicConsultationRuntimeSteps(state), stepBudget: consultationStepBudgetReceipt(state), workflow: state.workflowReceipt!, techniqueTruth: "unknown" }) as never, + continueAfterLength: async () => { throw new Error("not expected"); }, + repairLeftOutLayers: async (prompt: string) => { prompts.push(prompt); return { text: repairReply(prompt), usage: {}, attempts: 1, truncated: false }; }, + onComplete: (output: string) => { completed = output; }, + } as never); + const parser = createNdjsonParser(() => {}); + parser.finish(await response.text()); + return { state, completed, prompts }; +} + +test("stream, only: Indian paragraph out, tie reworded, no time parts, Western-only 「判断依据」", async () => { + const { completed, prompts, state } = await runAnswer(ONLY_ANSWER, "only", (prompt) => { + const id = (pattern: RegExp) => Number(new RegExp(`#(\\d+) 原句:${pattern.source}`, "u").exec(prompt)?.[1]); + return JSON.stringify({ layers: [], fixes: [ + { id: id(/你的性格里最突出的是火/u), text: "你的性格里火和土一样突出,各 3 颗,两样一起用。" }, + { id: id(/最突出的是火,土并列/u), text: "火和土并列最多" }, + { id: id(/按这个上升算/u), text: "" }, + ] }); + }); + assert.equal(prompts.length, 1, "one repair call"); + assert.doesNotMatch(prompts[0]!, /漏掉的层(id|名称|放进的小节|数据):\n- /u, "no Indian layer is asked for"); + assert.match(completed, /^## 结论\n你的性格里火和土一样突出,各 3 颗,两样一起用。/u); + assert.doesNotMatch(completed, /接下来一年|最好的时候|功能吉星|Yogakaraka|大运|D9|D10|〔/u); + const basis = splitJudgmentBasis(completed).basis!; + assert.match(basis, /^- \*\*火和土并列最多\*\*:西洋盘:元素:/mu); + assert.ok(parseJudgmentBasisItems(basis)!.every((item) => item.facts[0]!.text.startsWith("西洋盘:"))); + assert.equal(state.answerShape, undefined, "no Indian chart areas on the receipt"); +}); + +test("stream, both: missing side headings regrouped by the one repair call; evidence in two groups", async () => { + const body = "## 印度盘怎么看\n\n**印度盘上你耐得住。** 你凡事愿意自己动手。〔H1 Sa〕\n\n## 西洋盘怎么看\n\n**西洋盘上你心里要强。** 你希望别人看见你手上的活。"; + const { completed, prompts } = await runAnswer(BOTH_ANSWER, "both", (prompt) => { + const verdict = Number(/#(\d+) 原句:两边看到的是同一个底子/u.exec(prompt)?.[1]); + return JSON.stringify({ layers: [], fixes: [{ id: verdict, text: "印度盘看你沉稳、慢慢做成事,西洋盘看你要强、想被看见。" }], body }); + }); + assert.equal(prompts.length, 1); + assert.match(prompts[0]!, /"body"/u); + assert.match(completed, /^## 结论\n印度盘看你沉稳、慢慢做成事,西洋盘看你要强、想被看见。/u); + assert.match(completed, /## 印度盘怎么看\n\n\*\*印度盘上你耐得住。\*\*/u); + assert.match(completed, /## 西洋盘怎么看\n\n\*\*西洋盘上你心里要强。\*\*/u); + const items = parseJudgmentBasisItems(splitJudgmentBasis(completed).basis!)!; + const groups = items.map((item) => item.group); + assert.equal(groups[0], "印度盘"); + assert.equal(groups.at(-1), "西洋盘"); + assert.deepEqual([...new Set(groups)], ["印度盘", "西洋盘"], "two groups, Indian first"); + assert.ok(items.filter((item) => item.group === "西洋盘").every((item) => item.facts[0]!.text.startsWith("西洋盘:"))); + assert.doesNotMatch(completed, /几种方法一致|只列出、不作理由/u); +}); + +// Found in the round-2 real both-sides answer (r2-both): the plain-body mechanism rewrite took 「印度盘里」「西洋盘里」 out of +// the verdict and duplicated Western sentences; the writer's 〔西洋盘:……〕 notes stayed in the body. +test("both, from the real run: rewrites keep the side they name, the Western section skips the mechanism rewrite, body notes go", () => { + const verdict = "两边说的是同一个你:印度盘里你更收着,西洋盘里你更爱说话。"; + const filtered = withoutFailingWesternFixes( + { fixes: [{ id: 1, text: "你稳、能扛事;你收着,可心里更爱说话。" }, { id: 2, text: "印度盘看你收着,西洋盘看你爱说话。" }] }, + [{ id: 1, kind: "mechanism", sentence: verdict }, { id: 2, kind: "mechanism", sentence: verdict }], + facts, + ); + assert.deepEqual(filtered.repair.fixes.map((fix) => fix.id), [2]); + assert.deepEqual(filtered.rejected, ["fix#1:side"]); + const text = "## 结论\n印度盘看你稳,西洋盘看你爱说。\n\n## 印度盘怎么看\n**你稳。** 你慢热。〔H1〕\n\n## 西洋盘怎么看\n**你话多。** 上升在水瓶,月亮在双子落第 4 宫。〔西洋盘:上升水瓶;月亮双子第 4 宫〕\n\n## 判断依据\n- **你话多**:西洋盘:上升水瓶。\n"; + const section = westernSectionText(text); + assert.match(section, /上升在水瓶/u); + assert.doesNotMatch(section, /慢热/u); + const cleaned = withoutWesternBodyNotes(text); + assert.doesNotMatch(splitJudgmentBasis(cleaned).body, /〔西洋盘/u); + assert.match(cleaned, /〔H1〕/u, "evidence keys stay for the expansion"); + assert.match(groupedBothBasis(text, facts).output, /落第 4 宫。\n/u); +}); diff --git a/frontend/tests/western-chat-2342.test.ts b/frontend/tests/western-chat-2342.test.ts index c7d9de543..e0208550f 100644 --- a/frontend/tests/western-chat-2342.test.ts +++ b/frontend/tests/western-chat-2342.test.ts @@ -148,11 +148,13 @@ test("the lookup tool and the writing rule send Western questions to western:nat const description = String(tools[CONSULTATION_EVIDENCE_LOOKUP_TOOL_ID].description); assert.match(description, /Western-astrology question's calculation was run without western_chart, call it with western:natal/u); const calc = String(tools["run-jyotish-consultation"].description); - assert.match(calc, /Western astrology .*send western_chart: true: the result then carries western_natal/u); + // 原值:western_chart: true;「两边分开写,每句说清是西洋盘还是印度盘」;「说明以「西洋盘:」开头」。新值:western_chart "only" / "both" + // (true 仍等于 only),两边都问时正文分「印度盘怎么看」「西洋盘怎么看」两节;西洋条写成「西洋盘:……」由程序列行。原因:BUG-2342 第二轮。 + assert.match(calc, /Western astrology .*send western_chart: "only" .* or "both" .*: the result then carries western_natal/u); assert.match(calc, /never the basis of a Western claim\. Do not send western_chart for a question that does not ask about Western astrology/u); - assert.match(chatConversationVoice, /用户要的是西洋占星.*western_chart: true.*section=western:natal.*western_natal.*不拿来当西洋判断的依据/u); - assert.match(chatConversationVoice, /两边分开写,每句说清是西洋盘还是印度盘/u); - assert.match(chatConversationVoice, /说明以「西洋盘:」开头/u); + assert.match(chatConversationVoice, /用户要的是西洋占星.*western_chart.*section=western:natal.*western_natal.*不拿来当西洋判断的依据/u); + assert.match(chatConversationVoice, /「## 印度盘怎么看」「## 西洋盘怎么看」/u); + assert.match(chatConversationVoice, /写成「- \*\*判断短句\*\*:西洋盘:用到的西洋盘事实。」/u); }); // Steve Jobs (public AA): Indian D1 Leo lagna, Sun in Aquarius; Western tropical ascendant Virgo, Sun in Pisces.