From 041069ebaa892e72a543330591dd6230df33e9d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 19:05:52 +0800 Subject: [PATCH] =?UTF-8?q?feat(chat):=20KP=20dates=20inside=20the=20strip?= =?UTF-8?q?'s=20stretches=20for=20career,=20money=20and=20relationship=20q?= =?UTF-8?q?uestions=20=E2=80=94=20cusp=20sub=20lord=20promise,=20running?= =?UTF-8?q?=20lords=20as=20significators,=20Sun=20/=20Moon=20in=20their=20?= =?UTF-8?q?stars=20from=20a=20bounded,=20cached=20engine=20tool=20(BUG-232?= =?UTF-8?q?5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq --- docs/BUG_HISTORY.md | 20 ++ frontend/src/lib/chat-answer-timeline.ts | 14 +- frontend/src/lib/chat-evidence-keys.ts | 4 +- frontend/src/lib/chat-kp-timing.ts | 333 ++++++++++++++++++ frontend/src/lib/chat-transit-window.ts | 33 ++ .../src/lib/consultation-evidence-card.ts | 4 + frontend/src/mastra/consultation-tools.ts | 5 +- frontend/tests/chat-kp-timing-2325.test.ts | 186 ++++++++++ scripts/ondemand_calc/kp_transit_lords.py | 146 ++++++++ scripts/ondemand_calc/registry.py | 4 +- tests/test_ondemand_kp_transit_lords_2325.py | 93 +++++ 11 files changed, 837 insertions(+), 5 deletions(-) create mode 100644 frontend/src/lib/chat-kp-timing.ts create mode 100644 frontend/tests/chat-kp-timing-2325.test.ts create mode 100644 scripts/ondemand_calc/kp_transit_lords.py create mode 100644 tests/test_ondemand_kp_transit_lords_2325.py diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index dddc126b5..d57fc5ade 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -31458,3 +31458,23 @@ - 影响范围:生产 1.0(d6f41c9e9)没有 BUG-2294,不受影响;1.1(e29b7e3a7)包含 BUG-2294,**上线后生成的个人报告都会没有英文版**,直到本修复发到生产。 - 关联记录:BUG-2294、BUG-2185、BUG-2204、BUG-2109。 - 修复版本:`claude/report-english-2324`。 + +## BUG-2325 | 问答推运没用上 KP:卡上只有本命一半(宫头承诺、现在的运期主星),没有太阳、月亮走到谁的星宿,KP 说不出月份和日子 + +- 状态:fixed-pending-verify(程序和写法已改,本地提交未推送;KP 推运的宫位表和写法等占星师复核)。 +- 首次发现 / 最近更新:2026-11-24(占星师经负责人:「推运的时候最好可以把仓内的 KP 体系使用上……KP 体系结合星历(月、日)会精确这个应期」;负责人截图里用户要自己说「用 kp 体系来推运」)/ 2026-11-24。 +- 现象:事业、钱、感情问时间时,回答只按大运和行运说哪几个月,看不出用了 KP;用户点名要 KP 推运也一样。 +- 触发条件:本命问答的事业、钱、感情题,首轮和追问。 +- 根因:KP 一直在卡上,也不用用户点名(`consultation-evidence-card.ts` `domainKp`,BUG-1701 起每张卡都有),但只有本命那一半:宫头的 Sub Lord、四级 significator、现在这一刻的大运小运细运主星指哪几宫。往后十二个月里太阳、月亮、木星走到谁的星宿,卡上没有。星历页的日历故意没接 KP(`scripts/personal_calendar.py` 文件头),报告的 KP 流月只在报告里、每月一个点。所以模型拿 KP 只能说有没有承诺,排不出月和日。写法只让它「和整宫不一致时两面都写」,正文还禁用 KP 这个词(`chat-evidence-keys.ts` `BODY_TERMS`)。 +- 修复(冻结文件未改): + - 引擎新增按需工具 `kp_transit_lords`(`scripts/ondemand_calc/kp_transit_lords.py`,注册在 `ondemand_calc/registry.py`):太阳、月亮、木星每天当地 12:00 的 KP 星宿主和 Sub(月亮只取星宿主),连续相同的日子合成一段。上限 400 天,KP 岁差在 `temporary_ayanamsa` 里算完即恢复;结果与本命盘无关,进程内 LRU(64 条),键为(起始日、天数、时区、交点口径、kp、规则版本)。 + - 问答(`chat-transit-window.ts` `attachKpTransitLords`,`consultation-tools.ts` 在快星行运之后调用):只有事业、钱、感情领域才调,起点和慢星行运同一天,372 天;失败记 blocked(和快星行运一样留在那一层),不挡回答,也不出 KP 日子。 + - 程序判断(新文件 `frontend/src/lib/chat-kp-timing.ts`,卡建好后由 `buildEvidenceCard` 调 `attachKpTiming`):(1)承诺:事业 10 宫头、钱 2 和 11 宫头、感情 7 宫头的 Sub Lord 指到这件事的宫(事业 2、6、10、11;钱 2、6、11;感情 2、7、11),否定宫事业 5、8、12,钱 8、12,感情 1、6、10。(2)一颗星指哪几宫:宫头一侧和行星一侧的 A–D 合起来;罗睺、计都再带上星座主和星宿主指的宫。(3)窗口:卡上的小运或细运主星指到这件事的宫、太阳走在它的星宿的那些天;其中月亮也走在它星宿的日子(最多 3 天);木星走在指到这件事的运期主星星宿时记一笔;主星也指到否定宫时记「要先过一道关」。没有承诺就不出窗口。每个领域最多 10 个窗口。卡上写成 `domain_sections.<领域>.kp.timing`(承诺、主星、窗口三张小表)。 + - 给写的人:`timing` 卡的预算表加 `kp_windows`(每行「〔KP1 W3〕2027 年 2 月 19 日到 3 月 4 日|工作上的事会有回音,但要先过一道关|其中 2 月 25 日最明显」,按所在时间条段落标 W 编号;时间条之外的窗口不给)和读法 `kp_windows_reading`:在那一段的那句话里用平常话带上日子,句末加 KP 编号,正文不写 KP 名词,不改那一段的说法。判断依据加 KP 行(`timing.kp_windows`),KP 名词只在这里。 +- 实测:开发机冷算一年 0.41 秒 CPU,命中缓存约 0.1 毫秒;公开盘事业卡多 890 字符(原 145,395)。 +- 验证:新增 `frontend/tests/chat-kp-timing-2325.test.ts`(9 条:significator 合并和罗睺代理、窗口和月亮日子、没承诺不出窗口、不相关的星宿不出窗口、只在三个领域上卡、引擎失败或没请求时不出日子也不记缺口、写给写的人的行和判断依据行同一编号且正文行没有 KP 名词和工程用词、时间条之外的窗口丢掉、日期写法、卡上 KP 段和行的大小上限)和 `tests/test_ondemand_kp_transit_lords_2325.py`(6 条:注册和整段覆盖、月亮约一天一换、缓存键与本命无关、上限和岁差检查、进程岁差恢复、一年 CPU 上限)。读改动文件的前端测试和三个守护测试逐个跑;tsc、ESLint 0 错误;快检。钉住的卡片大小测试(`consult-dasha-horizon-20261105`)用的样例盘没有 KP 层,数字不变,所以没改;KP 的增量由新测试单独钉住。真实路由(同 BUG-2281 的桩,默认模型,公开盘,每题一次,用户没提 KP):事业时间条最后一段写「10 月 12 日到 23 日更容易谈下来」;钱有三段带日子(「其中 2 月下旬到 3 月初钱上的事更容易谈成」等);感情四段带日子(「其中 12 月 29 日到 1 月 10 日更容易进一步」等)。三条回答的正文和时间条都没有 KP 名词,判断依据里有 KP 行。 +- 已知不足:只问「推运」、没落到事业、钱、感情的追问(路由为「时运」)不带 KP 日子;运期用产品的 Raman Vimshottari,没有另算 KP 大运;罗睺、计都的代理没算合相和相位;月亮按天取样;Ruling Planets 没用(问答没有提问时刻)。方案和待占星师复核的问题:`/workspace/eval-read-1116/kp-timing-proposal-20261124.md`。 +- 防复发:KP 的日子只由 `chat-kp-timing.ts` 算,写的人只照 `kp_windows` 写;正文禁用 KP 名词的检查(`BODY_TERMS`)不变。 +- 关联记录:BUG-1701(KP 上卡)、BUG-1884(年度 KP 宫头精度分支)、BUG-2229(快星行运的同类引擎调用)、BUG-2310(时间条按领域分段)、BUG-2326(同一截图里的两处旁证)。 +- 修复版本:分支 `claude/kp-timing`(本地提交,未推送)。 + diff --git a/frontend/src/lib/chat-answer-timeline.ts b/frontend/src/lib/chat-answer-timeline.ts index 25f6f0d51..ca010f2ab 100644 --- a/frontend/src/lib/chat-answer-timeline.ts +++ b/frontend/src/lib/chat-answer-timeline.ts @@ -13,7 +13,8 @@ * two; else 「最省力的时候」; else none); a value that pairs it with a resistance word takes the program's value. */ import type { EvidenceCard } from "./consultation-evidence-card.ts"; -import { basisLine, plainReasonLine, saturnBackground, statusAnalysis, statusStretches, STRIP_LABEL_TEXT, yearBasis, yearLine, type StripLabel } from "./chat-strip-status.ts"; +import { basisLine, plainReasonLine, saturnBackground, statusAnalysis, statusStretches, STRIP_LABEL_TEXT, stripDomain, yearBasis, yearLine, type StripLabel } from "./chat-strip-status.ts"; +import { KP_WINDOWS_READING, kpLines } from "./chat-kp-timing.ts"; import { normalizeEvidenceTags } from "./chat-evidence-tags.ts"; import { splitJudgmentBasis } from "./consult-judgment-basis.ts"; import { @@ -208,6 +209,12 @@ export function bestTimeValue(stretches: readonly ProgramStretch[]): string | nu return bestTime(stretches)?.value ?? null; } +/** BUG-2325: the KP lines of the question's domain, placed in the program's stretches (KP keys; none for other domains). */ +export function programKpLines(card: EvidenceCard | null, stretches: readonly ProgramStretch[] = programStretches(card)) { + if (!card || !stretches.length) return []; + return kpLines(card, stripDomain(card), stretches); +} + /** The writer's table lines (timing.strip_stretches): 「〔W2 T3 T4〕现在到 2026 年 12 月|有机会,但费力|有利:……|费力:……」. */ export function stripStretchLines(stretches: readonly ProgramStretch[]): string[] { return stretches.map((item) => [`〔${item.keys.join(" ")}〕${item.range}`, STRIP_LABEL_TEXT[item.label] || "不标", item.reasons].filter(Boolean).join("|")); @@ -475,10 +482,13 @@ export function claimCardsWithStripStretches item.line); } catch { kp = []; } return claimCards.map((claim) => { if (claim.category !== "timing") return claim; const evidence = (claim.evidence && typeof claim.evidence === "object" ? claim.evidence : {}) as Record; const tables = (evidence.precomputed_tables && typeof evidence.precomputed_tables === "object" ? evidence.precomputed_tables : {}) as Record; - return { ...claim, evidence: { ...evidence, precomputed_tables: { ...tables, strip_stretches_reading: STRIP_STRETCHES_READING, strip_stretches: stripStretchLines(stretches), ...(best ? { best_time: best } : {}), ...(background.length ? { saturn_background: background } : {}), ...(year.line ? { year_background: `〔YR〕${year.line}` } : {}) } } }; + return { ...claim, evidence: { ...evidence, precomputed_tables: { ...tables, strip_stretches_reading: STRIP_STRETCHES_READING, strip_stretches: stripStretchLines(stretches), ...(best ? { best_time: best } : {}), ...(background.length ? { saturn_background: background } : {}), ...(year.line ? { year_background: `〔YR〕${year.line}` } : {}), ...(kp.length ? { kp_windows_reading: KP_WINDOWS_READING, kp_windows: kp } : {}) } } }; }); } diff --git a/frontend/src/lib/chat-evidence-keys.ts b/frontend/src/lib/chat-evidence-keys.ts index 3988a3d47..29efce432 100644 --- a/frontend/src/lib/chat-evidence-keys.ts +++ b/frontend/src/lib/chat-evidence-keys.ts @@ -23,7 +23,7 @@ import { } from "./chat-answer-tables.ts"; import { argalaTable, sahamTable, savOrder } from "./chat-point-checks.ts"; import { periodCoverageRows, pressureRangeTable, transitWindow } from "./chat-period-coverage.ts"; -import { programStretches, programYear, segmentLabel } from "./chat-answer-timeline.ts"; +import { programKpLines, programStretches, programYear, segmentLabel } from "./chat-answer-timeline.ts"; import { splitJudgmentBasis } from "./consult-judgment-basis.ts"; import { ANSWER_TONE_LABELS, FOLLOW_UP_HEADING, isTimelineHeading, STRIP_ENGINEERING_WORDS, STRIP_HEDGE_WORDS, stripLabelMismatch, stripTitleMismatch, VERDICT_HEADING, type AnswerTone } from "./chat-answer-shape.ts"; @@ -186,6 +186,8 @@ export function evidenceKeyRows(card: EvidenceCard): KeyRow[] { const name = ANSWER_TONE_LABELS[stretch.label]; add({ key, label: `时间条里「${stretch.range}」这一段`, text: `${stretch.range}(${stretch.fromDay} 起)${name ? `,${name}` : ""}:${stretch.basis}`, polarity: 0, table: "timing.strip_stretches" }); }); + // BUG-2325: KP's narrower days inside a stretch; the KP names stay in this row (「判断依据」), never in the body. + safe(() => programKpLines(card), []).forEach((item) => add({ key: item.key, label: `KP 推运 ${item.window.from} 起`, text: item.basis, polarity: 0, table: "timing.kp_windows" })); safe(() => pressureRangeTable(card), [] as string[]).forEach((text, index) => add({ key: `Z${index + 1}`, label: text.split(":")[0]!, text, polarity: 0, table: "timing.pressure_ranges" })); safe(() => doubleTransitTable(view, domain), [] as string[]).forEach((text, index) => add({ key: `X${index + 1}`, label: "双重行运", text, polarity: 0, table: "timing.double_transit" })); safe(() => transitTable(view), [] as string[]).forEach((text, index) => add({ key: `R${index + 1}`, label: text.split(":")[0]!, text, polarity: 0, table: "timing.transits" })); diff --git a/frontend/src/lib/chat-kp-timing.ts b/frontend/src/lib/chat-kp-timing.ts new file mode 100644 index 000000000..0da47cd16 --- /dev/null +++ b/frontend/src/lib/chat-kp-timing.ts @@ -0,0 +1,333 @@ +/** + * BUG-2325 (astrologer via the owner, 2026-11-24: 「推运的时候最好可以把仓内的 KP 体系使用上……KP 体系结合星历(月、日)会精确 + * 这个应期」): KP timing inside the strip's stretches for career, money and relationship questions, decided by the program + * from data already computed — never by the model and never by the user naming KP. + * + * The standard KP method, as a practitioner states it: + * 1. Promise: the cusp sub lord of the matter's cusp (career 10, money 2 and 11, relationship 7) signifies the matter's + * houses (career 2, 6, 10, 11; money 2, 6, 11; relationship 2, 7, 11), not mainly the negating ones (career 5, 8, 12 — + * 12th from the 6th, losses, breaks; money 8, 12; relationship 1, 6, 10; coordinator 2026-11-24 from the astrologer's + * brief: support and resistance per life change). + * 2. Period: the event comes in the joint period of dasha lords that are significators of those houses. + * 3. Transit: inside that period the Sun passing the star of a running lord gives the weeks (the month), the Moon passing + * the same star gives the days; Jupiter in the star of a running lord is the longer support. + * A planet signifies a house when it is one of the house's four significator levels (A: in the star of an occupant, + * B: occupant, C: in the star of the lord, D: the lord), the same reading the card's running_lords row already uses. + * + * Bounds (coordinator 2026-11-24, production 2 vCPU): one fixed window (the strip's twelve months), the engine's + * day-sampled star / sub lords of the Sun, Moon and Jupiter (scripts/ondemand_calc/kp_transit_lords.py, cached by start + * date + tz, not per chart), and here only a pass over at most 400 days. The sub-period lords that drive the windows are + * the card's own Vimshottari (the strip's periods), not a separate KP-ayanamsa dasha. + * + * Self-contained on purpose (type-only imports): consultation-evidence-card.ts calls it while it builds the card. + */ +import type { EvidenceCard } from "./consultation-evidence-card.ts"; + +type Rec = Record; +const rec = (value: unknown): Rec => (value && typeof value === "object" && !Array.isArray(value) ? value as Rec : {}); +const arr = (value: unknown): unknown[] => (Array.isArray(value) ? value : []); +const day = (value: unknown) => (typeof value === "string" && /^\d{4}-\d{2}-\d{2}/u.test(value) ? value.slice(0, 10) : ""); + +export type KpDomain = "career" | "wealth" | "marriage"; +export const KP_DOMAIN_RULES: Readonly>> = { + career: { promise: [10], good: [2, 6, 10, 11], bad: [5, 8, 12] }, + wealth: { promise: [2, 11], good: [2, 6, 11], bad: [8, 12] }, + marriage: { promise: [7], good: [2, 7, 11], bad: [1, 6, 10] }, +}; +export const isKpDomain = (domain: string): domain is KpDomain => domain in KP_DOMAIN_RULES; + +/** Windows the card keeps for one domain (the strip has at most eight stretches; more would be noise). */ +export const KP_WINDOWS_MAX = 10; +/** Moon days named inside one window. */ +export const KP_MOON_DAYS_MAX = 3; +/** The strip's twelve months, plus a week for a window that opens just before the end. */ +export const KP_WINDOW_DAYS = 372; + +/** Houses each planet signifies, from every cusp's four significator levels (A–D) and the planet's own A–D. */ +export function kpSignifiedHouses(kpLayer: unknown): Record { + const out: Record = {}; + for (const [number, raw] of Object.entries(rec(rec(kpLayer).houses))) { + const house = Number(number); + if (!Number.isInteger(house)) continue; + for (const value of Object.values(rec(rec(raw).significators))) { + for (const planet of (Array.isArray(value) ? value : [value])) { + if (typeof planet !== "string" || !planet) continue; + const list = (out[planet] ??= []); + if (!list.includes(house)) list.push(house); + } + } + } + // The planet-side table (A: house of its star lord, B: its own house, C: houses its star lord owns, D: houses it owns) + // is the same relation read from the planet; both are merged so a planet's full signification is used. + for (const [planet, raw] of Object.entries(rec(rec(kpLayer).planets))) { + for (const value of Object.values(rec(rec(raw).significators))) { + for (const house of (Array.isArray(value) ? value : [value])) { + if (typeof house !== "number" || !Number.isInteger(house) || house < 1 || house > 12) continue; + const list = (out[planet] ??= []); + if (!list.includes(house)) list.push(house); + } + } + } + // KP node rule: Rahu and Ketu are agents — they also give what their sign lord and star lord signify (one step, from + // the planets' own significations above). Conjunctions and aspects to the nodes are not in the layer and are not added. + const own = Object.fromEntries(Object.entries(out).map(([planet, houses]) => [planet, [...houses]])); + for (const node of ["Rahu", "Ketu"]) { + const row = rec(rec(rec(kpLayer).planets)[node]); + for (const agent of [row.rasi_lord, row.nakshatra_lord]) { + if (typeof agent !== "string" || agent === node) continue; + const list = (out[node] ??= []); + for (const house of own[agent] ?? []) if (!list.includes(house)) list.push(house); + } + } + for (const list of Object.values(out)) list.sort((a, b) => a - b); + return out; +} + +type Segment = readonly [string, string, string, string]; +const segments = (layer: Rec, body: string): Segment[] => arr(rec(layer.bodies)[body]) + .map((row) => arr(row).map(String)) + .filter((row) => day(row[0]) && day(row[1])) + .map((row) => [row[0]!, row[1]!, row[2] ?? "", row[3] ?? ""] as const); + +type RunningPeriod = { level: "小运" | "细运"; lord: string; start: string; end: string }; + +/** The card's sub-periods and sub-sub-periods (the same rows the strip reads). */ +function runningPeriods(base: EvidenceCard["base"]): { md: Array<{ lord: string; start: string; end: string }>; periods: RunningPeriod[] } { + const vim = rec(rec(base.timing).vimshottari); + const periods: RunningPeriod[] = []; + const md: Array<{ lord: string; start: string; end: string }> = []; + const mdRow = rec(vim.mahadasha); + if (typeof mdRow.lord === "string") md.push({ lord: mdRow.lord, start: day(mdRow.start), end: day(mdRow.end) || "9999-12-31" }); + const next = rec(vim.next_mahadasha); + if (typeof next.lord === "string") md.push({ lord: next.lord, start: day(next.start) || day(mdRow.end), end: day(next.end) || "9999-12-31" }); + for (const row of [...arr(vim.antardashas_in_mahadasha), ...arr(next.antardashas)]) { + const [lord, start, end] = arr(row).map(String); + if (lord && day(start) && day(end)) periods.push({ level: "小运", lord, start: day(start), end: day(end) }); + } + for (const row of arr(rec(rec(base.timing).sub_periods).rows)) { + const [, , pd, start, end] = arr(row).map(String); + if (pd && day(start) && day(end)) periods.push({ level: "细运", lord: pd, start: day(start), end: day(end) }); + } + return { md, periods }; +} + +const DAY = 86_400_000; +const addDays = (iso: string, n: number) => new Date(Date.parse(`${iso}T00:00:00Z`) + n * DAY).toISOString().slice(0, 10); +const at = (rows: readonly T[], iso: string) => rows.find((row) => row.start <= iso && row.end > iso); +const atSeg = (rows: readonly Segment[], iso: string) => rows.find((row) => row[0] <= iso && row[1] > iso); + +export type KpWindow = Readonly<{ + from: string; + /** Exclusive. */ + to: string; + lord: string; + level: "小运" | "细运"; + /** On some days the Sun is in that lord's star and its sub too (the tightest part of the weeks). */ + sunSub: boolean; + moonDays: readonly string[]; + /** Jupiter is in the star of one of the running lords that signify the matter. */ + jupiter: boolean; + /** The lord also signifies a negating house: it comes, with a hurdle. */ + mixed: boolean; +}>; + +export type KpTiming = Readonly<{ + promise: ReadonlyArray>; + /** The cusp sub lords signify at least one of the matter's houses. */ + promised: boolean; + lords: Readonly>>; + windows: readonly KpWindow[]; + from: string; + to: string; +}>; + +/** + * KP windows for one domain from the KP layer (cusps, significators), the transit star / sub lords and the card's periods. + * null when an input is missing. No windows when the cusp sub lords promise nothing (KP: no promise, no event). + */ +export function kpTiming(domain: KpDomain, kpLayer: unknown, transitLayer: unknown, base: EvidenceCard["base"]): KpTiming | null { + const rule = KP_DOMAIN_RULES[domain]; + const houses = rec(rec(kpLayer).houses); + const transits = rec(transitLayer); + const window = rec(transits.window); + const from = day(window.start); + const to = day(window.end); + if (!Object.keys(houses).length || !from || !to) return null; + const signified = kpSignifiedHouses(kpLayer); + const split = (planet: string) => { + const list = signified[planet] ?? []; + return { good: rule.good.filter((h) => list.includes(h)), bad: rule.bad.filter((h) => list.includes(h)) }; + }; + const promise = rule.promise.map((cusp) => { + const subLord = String(rec(houses[String(cusp)]).sub_lord ?? ""); + return { cusp, subLord, ...split(subLord) }; + }).filter((row) => row.subLord); + const promised = promise.some((row) => row.good.length > 0); + const { md, periods } = runningPeriods(base); + const sun = segments(transits, "Sun"); + const moon = segments(transits, "Moon"); + const jupiter = segments(transits, "Jupiter"); + const lords: Record = {}; + const windows: KpWindow[] = []; + // Every running lord inside the window, promised or not (the strip reads their support and resistance). + for (const row of [...periods, ...md]) if (row.start < to && row.end > from) lords[row.lord] ??= split(row.lord); + if (promised && sun.length && periods.length) { + type Open = { from: string; lord: string; level: "小运" | "细运"; sunSub: boolean; moonDays: string[]; jupiter: boolean; mixed: boolean }; + let open: Open | null = null; + const subs = periods.filter((row) => row.level === "细运"); + const ads = periods.filter((row) => row.level === "小运"); + for (let iso = from; iso < to; iso = addDays(iso, 1)) { + const running = [at(subs, iso), at(ads, iso)].filter((row): row is RunningPeriod => !!row); + const main = at(md, iso); + // The sub-sub-period lord first (the narrower period), then the sub-period lord. + const fruitful = running.filter((row) => split(row.lord).good.length > 0); + const sunNow = atSeg(sun, iso); + const hit = sunNow ? fruitful.find((row) => row.lord === sunNow[2]) : undefined; + if (open && (!hit || open.lord !== hit.lord || open.level !== hit.level)) { + windows.push({ ...open, to: iso }); + open = null; + } + if (!hit) continue; + const fruitfulLords = new Set([...fruitful.map((row) => row.lord), ...(main && split(main.lord).good.length ? [main.lord] : [])]); + open ??= { from: iso, lord: hit.lord, level: hit.level, sunSub: false, moonDays: [], jupiter: false, mixed: split(hit.lord).bad.length > 0 }; + if (sunNow && sunNow[3] === hit.lord) open.sunSub = true; + const moonNow = atSeg(moon, iso); + if (moonNow && moonNow[2] === hit.lord && open.moonDays.length < KP_MOON_DAYS_MAX) open.moonDays.push(iso); + const jupiterNow = atSeg(jupiter, iso); + if (jupiterNow && fruitfulLords.has(jupiterNow[2])) open.jupiter = true; + } + if (open) windows.push({ ...open, to }); + } + return { promise, promised, lords, windows: windows.slice(0, KP_WINDOWS_MAX), from, to }; +} + +/** The card's compact view (domain_sections..kp.timing): what the program found, in the card's column style. */ +export function kpTimingCardView(timing: KpTiming): Rec { + return { + method: "KP 推运:宫头 Sub Lord 定这件事有没有承诺;运期主星是这件事的 significator 时,太阳走进它的星宿那十几天给出月份,其中月亮也走进它的星宿那一两天给出日子;木星走在运期主星的星宿是更长的支持", + promise: timing.promise.map((row) => [row.cusp, row.subLord, row.good, row.bad]), + promise_columns: "[宫头, Sub Lord, 它指到的这件事的宫, 它指到的否定宫]", + promised: timing.promised, + lords: Object.fromEntries(Object.entries(timing.lords).map(([planet, row]) => [planet, [row.good, row.bad]])), + lords_columns: "{运期主星: [指到的这件事的宫, 指到的否定宫]}", + windows: timing.windows.map((row) => [row.from, addDays(row.to, -1), row.lord, row.level, row.moonDays.join("、"), row.sunSub ? "star+sub" : "", row.jupiter ? "jupiter" : "", row.mixed ? "mixed" : ""]), + windows_columns: "[起, 止(含), 运期主星, 小运或细运, 月亮也在它星宿的日子, star+sub = 有几天太阳也走在这颗主星的 sub, jupiter = 木星同时走在运期主星的星宿, mixed = 这颗主星也指到否定宫]", + window: [timing.from, timing.to], + }; +} + +/** Reads the card view back (the chat layer only has the card). */ +export function kpTimingFromCard(card: EvidenceCard | null, domain: string): KpTiming | null { + if (!card || !isKpDomain(domain)) return null; + const view = rec(rec(rec(card.domain_sections)[domain]).kp).timing; + const timing = rec(view); + if (!Object.keys(timing).length) return null; + const nums = (value: unknown) => arr(value).filter((item): item is number => typeof item === "number"); + const windowSpan = arr(timing.window).map(String); + return { + promise: arr(timing.promise).map((row) => { const [cusp, subLord, good, bad] = arr(row); return { cusp: Number(cusp), subLord: String(subLord ?? ""), good: nums(good), bad: nums(bad) }; }), + promised: timing.promised === true, + lords: Object.fromEntries(Object.entries(rec(timing.lords)).map(([planet, row]) => [planet, { good: nums(arr(row)[0]), bad: nums(arr(row)[1]) }])), + windows: arr(timing.windows).map((row) => { + const [from, last, lord, level, moonDays, sub, jupiter, mixed] = arr(row).map((item) => String(item ?? "")); + return { from: from!, to: addDays(last!, 1), lord: lord!, level: level === "细运" ? "细运" as const : "小运" as const, sunSub: sub === "star+sub", moonDays: moonDays ? moonDays.split("、") : [], jupiter: jupiter === "jupiter", mixed: mixed === "mixed" }; + }).filter((row) => day(row.from) && day(row.to)), + from: day(windowSpan[0]), + to: day(windowSpan[1]), + }; +} + +/** Attaches the KP timing to each career / money / relationship section whose source carries both engine layers; a gap only when the computation itself fails. */ +export function attachKpTiming(card: EvidenceCard, layersOf: (domain: string) => Rec): void { + for (const domain of card.domains) { + if (!isKpDomain(domain)) continue; + const section = card.domain_sections[domain] as unknown as Rec | undefined; + const kp = rec(section?.kp); + if (!section || !Object.keys(kp).length) continue; + const layers = layersOf(domain); + const transit = rec(layers.kp_transit_lords); + const raw = rec(transit.raw); + // Not asked for (another caller of the card) or failed (the layer keeps its blocked reason, like fast_transits): no + // timing rows; the strip keeps its own stretches. + if (transit.calculation_status !== "executed" || !Object.keys(raw).length) continue; + try { + const own = rec(section.base).timing ? section.base as EvidenceCard["base"] : card.base; + const timing = kpTiming(domain, layers.kp_placidus, raw, own); + if (timing) kp.timing = kpTimingCardView(timing); + else card.meta.gaps.push(`${domain}.kp.timing`); + } catch { + card.meta.gaps.push(`${domain}.kp.timing`); + } + } +} + +// ---- the writer's lines and the 判断依据 rows --------------------------------------------------------------------------- + +const PLANET_ZH: Readonly> = { Sun: "太阳", Moon: "月亮", Mars: "火星", Mercury: "水星", Jupiter: "木星", Venus: "金星", Saturn: "土星", Rahu: "罗睺", Ketu: "计都" }; +const zh = (planet: string) => PLANET_ZH[planet] ?? planet; +const list = (items: readonly (string | number)[]) => items.join("、"); + +/** What becomes easier in that window, in plain life words (no chart words). */ +export const KP_PLAIN: Readonly> = { + career: "工作上的事更容易有回音、谈得下来", + wealth: "钱上的事更容易谈成、到账", + marriage: "感情上的事更容易往前走一步", +}; +const KP_PLAIN_MIXED: Readonly> = { + career: "工作上的事会有回音,但要先过一道关", + wealth: "钱上的事谈得成,但会多一道手续或开销", + marriage: "感情上会往前走一步,但要先磨合一下", +}; + +const md = (iso: string) => `${Number(iso.slice(5, 7))} 月 ${Number(iso.slice(8, 10))} 日`; +/** 「2027 年 3 月 5 日到 18 日」 / 「2027 年 3 月 28 日到 4 月 9 日」 / 「2027 年 12 月 30 日到 2028 年 1 月 8 日」. */ +export function kpRangeWords(from: string, toExclusive: string): string { + const last = addDays(toExclusive, -1); + const head = `${from.slice(0, 4)} 年 ${md(from)}`; + if (last === from) return head; + if (last.slice(0, 4) !== from.slice(0, 4)) return `${head}到 ${last.slice(0, 4)} 年 ${md(last)}`; + if (last.slice(5, 7) === from.slice(5, 7)) return `${head}到 ${Number(last.slice(8, 10))} 日`; + return `${head}到 ${md(last)}`; +} +const dayWords = (days: readonly string[]) => { + if (!days.length) return ""; + const month = days[0]!.slice(5, 7); + return days.every((iso) => iso.slice(5, 7) === month) + ? `${Number(month)} 月 ${days.map((iso) => Number(iso.slice(8, 10))).join("、")} 日` + : days.map(md).join("、"); +}; + +export type KpLine = Readonly<{ key: string; window: KpWindow; stretchKey: string | null; line: string; basis: string }>; + +/** + * The writer's lines (timing.kp_windows) and the 判断依据 rows (KP keys): one per window, tied to the strip stretch it sits + * in (its W key). `stretches` are the strip's stretches with their W keys and [fromDay, toDay). + */ +export function kpLines(card: EvidenceCard | null, domain: string, stretches: ReadonlyArray>): KpLine[] { + if (!isKpDomain(domain)) return []; + const timing = kpTimingFromCard(card, domain); + if (!timing || !timing.promised) return []; + const promise = timing.promise.map((row) => `${row.cusp} 宫头 Sub Lord ${zh(row.subLord)}指到第 ${list(row.good.length ? row.good : ["—"])} 宫${row.bad.length ? `,也指到否定宫第 ${list(row.bad)} 宫` : ""}`).join(";"); + const placed = timing.windows + .map((window) => ({ window, stretch: stretches.find((item) => item.fromDay <= window.from && item.toDay > window.from) ?? null })) + // A window after the strip's last stretch (the engine's window runs a week longer) has nowhere to go. + .filter((item) => !stretches.length || item.stretch); + return placed.map(({ window, stretch }, index) => { + const key = `KP${index + 1}`; + const stretchKey = stretch?.keys.find((item) => /^W\d/u.test(item)) ?? null; + const signs = timing.lords[window.lord] ?? { good: [], bad: [] }; + const plain = (window.mixed ? KP_PLAIN_MIXED : KP_PLAIN)[domain]; + const line = [`〔${[key, stretchKey].filter(Boolean).join(" ")}〕${kpRangeWords(window.from, window.to)}`, plain, window.moonDays.length ? `其中 ${dayWords(window.moonDays)}最明显` : ""].filter(Boolean).join("|"); + const basis = [ + `KP:${promise}`, + `${zh(window.lord)}${window.level}是第 ${list(signs.good)} 宫的 significator${signs.bad.length ? `(也指到第 ${list(signs.bad)} 宫)` : ""}`, + `太阳 ${kpRangeWords(window.from, window.to)}走在${zh(window.lord)}的星宿${window.sunSub ? ",其中几天也走在它的 sub" : ""}`, + window.moonDays.length ? `月亮 ${dayWords(window.moonDays)}走在${zh(window.lord)}的星宿` : "", + window.jupiter ? "木星这时走在运期主星的星宿" : "", + ].filter(Boolean).join(";"); + return { key, window, stretchKey, line, basis }; + }); +} + +export const KP_WINDOWS_READING = + "kp_windows 是程序按 KP 推运算出的、时间条某一段里更具体的日子(运期主星管这件事时,太阳和月亮走到它的星宿那几天)。照这样用:写「## 接下来一年」时,〔〕里的 W 编号是哪一段,就在那一段的那句话里用平常话带上这个日子(「其中 3 月 5 日到 18 日,工作上的事更容易有回音」),句末〔〕里加上它的 KP 编号;一段最多带一个,挑和这一段说法最贴的那个;结论卡「最好的时候」那一行可以写成这里的日子。正文和时间条里只写日子和会发生什么,不写 KP、星宿、Sub Lord、significator 这些词,也不说「按另一种方法」;这些写进「判断依据」那一条(编号会自动带出数据)。kp_windows 说的只是这件事更容易落地的日子,不改变那一段的说法(有机会、较费力)。用户问到具体哪个月、哪几天时,先用这里的日子回答。"; diff --git a/frontend/src/lib/chat-transit-window.ts b/frontend/src/lib/chat-transit-window.ts index 2136443cf..9f83248bc 100644 --- a/frontend/src/lib/chat-transit-window.ts +++ b/frontend/src/lib/chat-transit-window.ts @@ -5,6 +5,7 @@ * recorded as blocked and never stops the answer. */ import { evidenceCardTimingHorizonYears } from "./consultation-evidence-card.ts"; +import { KP_WINDOW_DAYS } from "./chat-kp-timing.ts"; type Json = Record; const rec = (value: unknown): Json => (value && typeof value === "object" && !Array.isArray(value) ? value as Json : {}); @@ -87,3 +88,35 @@ export async function attachFastTransits(workflow: unknown, question: string, fe } } + +/** + * BUG-2325: the Sun, Moon and Jupiter KP star / sub lords for the strip's twelve months, from the engine's on-demand tool + * `kp_transit_lords` (day sampling, cached by start date + tz in the engine, not per chart). Only for career, money and + * relationship questions (the KP timing rows read it). A failure is recorded as blocked and never stops the answer. + */ +export async function attachKpTransitLords(workflow: unknown, fetchImpl: typeof fetch = fetch): Promise { + const chart = rec(rec(workflow).chart); + const layers = rec(chart.consultation_native_layers); + if (!Object.keys(layers).length || !Object.keys(rec(layers.kp_placidus)).length) return; + const birth = birthFromChart(chart); + const start = rec(rec(layers.slow_transits).window).start; + const from = typeof start === "string" && /^\d{4}-\d{2}-\d{2}/u.test(start) ? start.slice(0, 10) : new Date().toISOString().slice(0, 10); + if (!birth) { + layers.kp_transit_lords = { calculation_status: "blocked", reason: "birth_fields_missing" }; + return; + } + const apiBase = process.env.JYOTISH_API_BASE?.trim() || "http://127.0.0.1:5200"; + const started = Date.now(); + try { + const response = await fetchImpl(`${apiBase}/api/ondemand_calc`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ tool: "kp_transit_lords", start_date: from, days: KP_WINDOW_DAYS, lat: birth.lat, lon: birth.lon, tz: birth.tz, ayanamsa: "kp", node_mode: birth.node_mode }), + signal: AbortSignal.timeout(15_000), + }); + const data = rec(await response.json().catch(() => null)); + layers.kp_transit_lords = response.ok ? { ...data, elapsed_ms: Date.now() - started } : { calculation_status: "blocked", reason: `http_${response.status}` }; + } catch (error) { + layers.kp_transit_lords = { calculation_status: "blocked", reason: error instanceof Error ? error.name : "fetch_failed" }; + } +} diff --git a/frontend/src/lib/consultation-evidence-card.ts b/frontend/src/lib/consultation-evidence-card.ts index 2d8a8d7d7..6f3bcdb67 100644 --- a/frontend/src/lib/consultation-evidence-card.ts +++ b/frontend/src/lib/consultation-evidence-card.ts @@ -1,4 +1,5 @@ import { transitNatalSignFacts, type TransitNatalSignFact } from "./consultation-transit-natal-sign.ts"; +import { attachKpTiming } from "./chat-kp-timing.ts"; import type { ConsultationDomain } from "./consultation-domain-registry.ts"; import { shadbalaMinimumRatio, shadbalaWithoutBand } from "./shadbala-minimum.ts"; import { dashaEvidenceId, shadbalaEvidenceId, yogaEvidenceId } from "./evidence-ids.ts"; @@ -3743,6 +3744,9 @@ export function buildEvidenceCard( attachEngineAdditionLayers(card, first.context, domains); attachNatalHouseViews(card, first.context); attachTimelineViews(card); + // BUG-2325: KP timing (cusp sub lord promise, running lords as significators, Sun / Moon / Jupiter in their stars) for + // career, money and relationship sections, from each domain's own engine layers. + attachKpTiming(card, (domain) => nativeLayers((sources.find((item) => item.domain === domain) ?? first).context)); return card; } diff --git a/frontend/src/mastra/consultation-tools.ts b/frontend/src/mastra/consultation-tools.ts index fa50da8dd..edd19a6b6 100644 --- a/frontend/src/mastra/consultation-tools.ts +++ b/frontend/src/mastra/consultation-tools.ts @@ -1,4 +1,5 @@ -import { attachFastTransits } from "../lib/chat-transit-window.ts"; +import { attachFastTransits, attachKpTransitLords } from "../lib/chat-transit-window.ts"; +import { isKpDomain } from "../lib/chat-kp-timing.ts"; import { claimCardsWithTables } from "../lib/chat-answer-tables.ts"; import { claimCardsWithKeyedTables } from "../lib/chat-evidence-keys.ts"; import { claimCardsWithStripStretches } from "../lib/chat-answer-timeline.ts"; @@ -1687,6 +1688,8 @@ export function createConsultationTools(ctx: ConsultationAgentContext) { // BUG-2229: the fast-planet transits (Sun, Mercury, Venus, Mars) of the question's range, from the engine's // /api/fast_transits; a failure is recorded as blocked and never stops the answer. await attachFastTransits(workflow, userIntent); + // BUG-2325: the KP transit star / sub lords for career, money and relationship questions (bounded, cached). + if (domainPlan.requestedDomains.some((domain) => isKpDomain(domain))) await attachKpTransitLords(workflow); return workflow; }; if (consultDomainConcurrency() === 1) { diff --git a/frontend/tests/chat-kp-timing-2325.test.ts b/frontend/tests/chat-kp-timing-2325.test.ts new file mode 100644 index 000000000..a08a32e4f --- /dev/null +++ b/frontend/tests/chat-kp-timing-2325.test.ts @@ -0,0 +1,186 @@ +/** + * BUG-2325: KP timing inside the strip's stretches for career, money and relationship questions — the cusp sub lord's + * promise, the running sub-period lords as significators, the Sun / Moon / Jupiter in their stars (chat-kp-timing.ts). + * Synthetic charts only (Aries lagna, so house N is sign N). + */ +import assert from "node:assert/strict"; +import test from "node:test"; + +import type { EvidenceCard } from "../src/lib/consultation-evidence-card.ts"; +import { + attachKpTiming, KP_WINDOWS_READING, kpLines, kpRangeWords, kpSignifiedHouses, kpTiming, kpTimingCardView, kpTimingFromCard, +} from "../src/lib/chat-kp-timing.ts"; +import { claimCardsWithStripStretches, programKpLines, programStretches } from "../src/lib/chat-answer-timeline.ts"; +import { evidenceKeyRows } from "../src/lib/chat-evidence-keys.ts"; +import { STRIP_ENGINEERING_WORDS } from "../src/lib/chat-answer-shape.ts"; + +const SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]; +const FROM = "2026-12-01"; +const TO = "2027-12-01"; +const NOW = 2026 * 12 + 11; + +/** A KP layer: 10th cusp sub lord Mercury; Mercury and Venus signify career houses; Rahu signifies nothing on its own. */ +function kpLayer(options: { cuspSub?: string } = {}) { + const houses: Record = {}; + for (let h = 1; h <= 12; h += 1) houses[String(h)] = { sub_lord: h === 10 ? (options.cuspSub ?? "Mercury") : "Moon", significators: { A: [], B: [], C: [], D: "Mars" } }; + houses["10"] = { ...(houses["10"] as object), significators: { A: ["Venus"], B: ["Mercury"], C: [], D: "Saturn" } }; + houses["11"] = { ...(houses["11"] as object), significators: { A: [], B: [], C: [], D: "Saturn" } }; + houses["5"] = { ...(houses["5"] as object), significators: { A: [], B: ["Venus"], C: [], D: "Sun" } }; + return { + houses, + planets: { + Mercury: { significators: { A: 2, B: 10, C: [], D: [3, 6] } }, + Venus: { significators: { A: 5, B: 5, C: [], D: [2, 7] } }, + Rahu: { rasi_lord: "Saturn", nakshatra_lord: "Moon", significators: { A: 4, B: 4, C: [], D: [] } }, + Saturn: { significators: { A: 10, B: 1, C: [], D: [10, 11] } }, + }, + }; +} + +/** Transit star / sub lords: the Sun in Venus's star 2027-03-10..2027-03-23, the Moon in Venus's star on 03-14 and 03-15. */ +function transits() { + return { + window: { start: FROM, end: "2027-12-08", days: 372 }, + bodies: { + Sun: [[FROM, "2027-03-10", "Ketu", "Ketu"], ["2027-03-10", "2027-03-14", "Venus", "Venus"], ["2027-03-14", "2027-03-23", "Venus", "Sun"], ["2027-03-23", "2027-12-08", "Sun", "Sun"]], + Moon: [[FROM, "2027-03-14", "Ketu", ""], ["2027-03-14", "2027-03-16", "Venus", ""], ["2027-03-16", "2027-12-08", "Sun", ""]], + Jupiter: [[FROM, "2027-12-08", "Saturn", "Venus"]], + }, + }; +} + +/** A card base: MD Ketu, AD Ketu over the year, PD Venus 2027-03-01..2027-06-01. */ +function base(pds: Array<[string, string, string, string, string]> = [["Ketu", "Ketu", "Ketu", "2026-01-01", "2027-03-01"], ["Ketu", "Ketu", "Venus", "2027-03-01", "2027-06-01"], ["Ketu", "Ketu", "Ketu", "2027-06-01", "2028-06-01"]]) { + return { + natal: { + ascendant: { sign: "Aries" }, + houses: Object.fromEntries(SIGNS.map((name, index) => [String(index + 1), name])), + functional_benefic_malefic: { functional_benefics: [], functional_malefics: [], functional_neutrals: [], yogakarakas: [] }, + planets: Object.fromEntries(["Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn", "Rahu", "Ketu"].map((name) => [name, { sign: "Sagittarius", house: 9, status: "中性", combust: false }])), + more: { sav_all_houses: { rows: Object.fromEntries(SIGNS.map((name, index) => [String(index + 1), [name, 27, "中等"]])) } }, + }, + timing: { + vimshottari: { mahadasha: { lord: "Ketu", start: "2020-01-01", end: "2030-01-01" }, antardashas_in_mahadasha: [["Ketu", "2026-01-01", "2028-06-01"]] }, + sub_periods: { rows: pds }, + transits_detail: { reference_date: FROM, bodies: { Jupiter: { sign: "Sagittarius" }, Saturn: { sign: "Sagittarius" } }, key_dates_window: { start: FROM, end: "2029-12-01" }, key_dates: [] }, + }, + } as unknown as EvidenceCard["base"]; +} + +function card(domain = "career", options: { cuspSub?: string; transit?: unknown } = {}): EvidenceCard { + const result = { domains: [domain], base: base(), domain_sections: { [domain]: { kp: { status: "parameter_sensitive" } } }, meta: { gaps: [] } } as unknown as EvidenceCard; + const layers = { kp_placidus: kpLayer(options), kp_transit_lords: options.transit ?? { calculation_status: "executed", raw: transits() } }; + attachKpTiming(result, () => layers); + return result; +} + +test("BUG-2325 significators: house-side and planet-side A–D merged; Rahu and Ketu also give their sign and star lords' houses", () => { + const houses = kpSignifiedHouses(kpLayer()); + assert.deepEqual(houses.Mercury, [2, 3, 6, 10]); + assert.deepEqual(houses.Venus, [2, 5, 7, 10]); + // Rahu: its own 4, plus Saturn's (sign lord: 1, 10, 11) and the Moon's (star lord: none here). + assert.deepEqual(houses.Rahu, [1, 4, 10, 11]); +}); + +test("BUG-2325 window: a running lord that signifies career, the Sun in its star (weeks), the Moon in its star (days)", () => { + const timing = kpTiming("career", kpLayer(), transits(), base())!; + assert.equal(timing.promised, true); + assert.deepEqual(timing.promise, [{ cusp: 10, subLord: "Mercury", good: [2, 6, 10], bad: [] }]); + assert.equal(timing.windows.length, 1); + const [window] = timing.windows; + assert.deepEqual({ ...window, moonDays: [...window!.moonDays] }, { + from: "2027-03-10", to: "2027-03-23", lord: "Venus", level: "细运", sunSub: true, moonDays: ["2027-03-14", "2027-03-15"], jupiter: false, mixed: true, + }); + // Venus also signifies the 5th (negating for career): the window comes with a hurdle. + assert.deepEqual(timing.lords.Venus, { good: [2, 10], bad: [5] }); +}); + +test("BUG-2325 no promise, no window: the 10th cusp sub lord signifies none of 2, 6, 10, 11", () => { + const timing = kpTiming("career", kpLayer({ cuspSub: "Moon" }), transits(), base())!; + assert.equal(timing.promised, false); + assert.deepEqual(timing.windows, []); + assert.deepEqual(kpLines(card("career", { cuspSub: "Moon" }), "career", []), []); +}); + +test("BUG-2325 the Sun in the star of a lord that does not signify the matter gives nothing; no running period, nothing", () => { + // Ketu (MD / AD / other PDs) signifies no career house in this layer, so its stars open no window. + const ketuOnly = base([["Ketu", "Ketu", "Ketu", "2026-01-01", "2028-06-01"]]); + assert.deepEqual(kpTiming("career", kpLayer(), transits(), ketuOnly)!.windows, []); + const empty = { ...base(), timing: { vimshottari: {} } } as unknown as EvidenceCard["base"]; + assert.deepEqual(kpTiming("career", kpLayer(), transits(), empty)!.windows, []); +}); + +test("BUG-2325 card: only career / money / relationship sections get kp.timing; without the engine layer nothing is guessed", () => { + const career = card("career"); + const view = (career.domain_sections.career as unknown as { kp: { timing: Record } }).kp.timing; + assert.deepEqual(view.windows, [["2027-03-10", "2027-03-22", "Venus", "细运", "2027-03-14、2027-03-15", "star+sub", "", "mixed"]]); + assert.deepEqual(kpTimingFromCard(career, "career")!.windows[0]!.to, "2027-03-23"); + const general = card("general"); + assert.equal((general.domain_sections.general as unknown as { kp: Record }).kp.timing, undefined); + // The engine call failed: no timing rows (the layer keeps its blocked reason, as fast_transits does), and no gap. + const blocked = card("career", { transit: { calculation_status: "blocked", reason: "http_500" } }); + assert.equal((blocked.domain_sections.career as unknown as { kp: Record }).kp.timing, undefined); + assert.deepEqual(blocked.meta.gaps, []); + // Another caller that never asked for the transit lords (reports, fixtures): no timing and no gap. + const quiet = { domains: ["career"], base: base(), domain_sections: { career: { kp: { status: "parameter_sensitive" } } }, meta: { gaps: [] } } as unknown as EvidenceCard; + attachKpTiming(quiet, () => ({ kp_placidus: kpLayer() })); + assert.deepEqual(quiet.meta.gaps, []); +}); + +test("BUG-2325 writer lines: dated plain words tied to the stretch's W key; KP words only in the 判断依据 row", () => { + const career = card("career"); + const stretches = programStretches(career, { now: NOW }); + const lines = programKpLines(career, stretches); + assert.equal(lines.length, 1); + const [line] = lines; + const stretch = stretches.find((item) => item.fromDay <= "2027-03-10" && item.toDay > "2027-03-10")!; + assert.equal(line!.stretchKey, stretch.keys.find((key) => /^W\d/u.test(key))); + assert.equal(line!.line, `〔KP1 ${line!.stretchKey}〕2027 年 3 月 10 日到 22 日|工作上的事会有回音,但要先过一道关|其中 3 月 14、15 日最明显`); + const body = line!.line.replace(/〔[^〕]*〕/gu, ""); + assert.doesNotMatch(body, /KP|星宿|Sub|significator|指示星|子主星/u); + assert.doesNotMatch(body, STRIP_ENGINEERING_WORDS); + assert.match(line!.basis, /^KP:10 宫头 Sub Lord 水星指到第 2、6、10 宫;金星细运是第 2、10 宫的 significator(也指到第 5 宫);太阳 2027 年 3 月 10 日到 22 日走在金星的星宿,其中几天也走在它的 sub;月亮 3 月 14、15 日走在金星的星宿$/u); + // The writer's table and the 判断依据 rows carry the same key. + const [timing] = claimCardsWithStripStretches([{ category: "timing", evidence: { precomputed_tables: {} } }], career, NOW); + const tables = (timing!.evidence as { precomputed_tables: Record }).precomputed_tables; + assert.deepEqual(tables.kp_windows, [line!.line]); + assert.equal(tables.kp_windows_reading, KP_WINDOWS_READING); + const row = evidenceKeyRows(career).find((item) => item.key === "KP1"); + assert.equal(row?.text, line!.basis); + assert.equal(row?.table, "timing.kp_windows"); + // A question outside career / money / relationship gets none. + const [plain] = claimCardsWithStripStretches([{ category: "timing", evidence: { precomputed_tables: {} } }], card("general"), NOW); + assert.equal((plain!.evidence as { precomputed_tables: Record }).precomputed_tables.kp_windows, undefined); +}); + +test("BUG-2325 a window after the strip's last stretch is dropped; keys stay consecutive", () => { + const late = transits(); + late.bodies.Sun = [[FROM, "2027-03-10", "Ketu", "Ketu"], ["2027-03-10", "2027-03-23", "Venus", "Venus"], ["2027-03-23", "2027-12-02", "Sun", "Sun"], ["2027-12-02", "2027-12-08", "Venus", "Venus"]]; + const pds: Array<[string, string, string, string, string]> = [["Ketu", "Ketu", "Ketu", "2026-01-01", "2027-03-01"], ["Ketu", "Ketu", "Venus", "2027-03-01", "2027-06-01"], ["Ketu", "Ketu", "Ketu", "2027-06-01", "2027-11-30"], ["Ketu", "Ketu", "Venus", "2027-11-30", "2028-06-01"]]; + const timing = kpTiming("career", kpLayer(), late, base(pds))!; + assert.equal(timing.windows.length, 2); + const stretches = [{ keys: ["W1"], fromDay: FROM, toDay: TO }]; + const view = { domains: ["career"], domain_sections: { career: { kp: { timing: kpTimingCardView(timing) } } } } as unknown as EvidenceCard; + assert.deepEqual(kpLines(view, "career", stretches).map((item) => item.key), ["KP1"]); +}); + +test("BUG-2325 dates in words", () => { + assert.equal(kpRangeWords("2027-03-05", "2027-03-19"), "2027 年 3 月 5 日到 18 日"); + assert.equal(kpRangeWords("2027-03-28", "2027-04-10"), "2027 年 3 月 28 日到 4 月 9 日"); + assert.equal(kpRangeWords("2027-12-30", "2028-01-09"), "2027 年 12 月 30 日到 2028 年 1 月 8 日"); + assert.equal(kpRangeWords("2027-03-05", "2027-03-06"), "2027 年 3 月 5 日"); +}); + +test("BUG-2325 size: the card view and the writer's lines stay small at the window cap", () => { + // Ten windows (KP_WINDOWS_MAX), each with three Moon days. + const windows = Array.from({ length: 10 }, (_, index) => ({ from: `2027-${String(index + 1).padStart(2, "0")}-01`, to: `2027-${String(index + 1).padStart(2, "0")}-14`, lord: "Venus", level: "细运" as const, sunSub: true, moonDays: ["2027-01-02", "2027-01-03", "2027-01-04"], jupiter: true, mixed: true })); + const timing = { promise: [{ cusp: 2, subLord: "Mercury", good: [2, 6, 11], bad: [5, 8, 12] }, { cusp: 11, subLord: "Venus", good: [2, 6, 11], bad: [5] }], promised: true, lords: { Ketu: { good: [2, 6, 11], bad: [5, 8, 12] }, Venus: { good: [2], bad: [] }, Saturn: { good: [6], bad: [12] }, Moon: { good: [11], bad: [] } }, windows, from: FROM, to: TO }; + const view = kpTimingCardView(timing); + // Measured 1,626 characters at the cap (the real public chart: 890 for career). + assert.ok(JSON.stringify(view).length <= 1_800, `card view ${JSON.stringify(view).length}`); + const cardWith = { domains: ["wealth"], domain_sections: { wealth: { kp: { timing: view } } } } as unknown as EvidenceCard; + const lines = kpLines(cardWith, "wealth", [{ keys: ["W1"], fromDay: FROM, toDay: TO }]).map((item) => item.line); + // Measured 683 characters for the ten lines (the reading line is 371 more, once). + assert.ok(JSON.stringify(lines).length <= 800, `lines ${JSON.stringify(lines).length}`); + assert.ok(KP_WINDOWS_READING.length <= 400, `reading ${KP_WINDOWS_READING.length}`); +}); diff --git a/scripts/ondemand_calc/kp_transit_lords.py b/scripts/ondemand_calc/kp_transit_lords.py new file mode 100644 index 000000000..042bc6e58 --- /dev/null +++ b/scripts/ondemand_calc/kp_transit_lords.py @@ -0,0 +1,146 @@ +"""按需计算:KP 推运用的行运星宿主 / 子主时间表(BUG-2325)。 + +KP 推运的常规做法:运期主星(大运、小运、细运主星)是这件事的 significator 时,太阳走进它们的星宿(或子) +给出月份,月亮走进它们的星宿给出日子,木星走进它们的星宿是更长的背景。本工具只算行运的那一半: +一段日期里太阳、月亮、木星每天当地 12:00 的 KP 星宿主(star lord)和子主(sub lord),相同的连续日子合成一段。 +运期主星和 significator 的比对在问答证据卡里做(frontend/src/lib/chat-kp-timing.ts),这里不读本命盘。 + +边界(与协调窗口 2026-11-24 约定,生产机 2 vCPU): +- 窗口固定、有上限:最多 MAX_DAYS 天,按天取样(每天一次),不做二分。 +- 只算三颗星:太阳(星宿主 + 子主)、月亮(只到星宿主,一天之内月亮的子主会换好几次,按天取样没有意义)、 + 木星(星宿主 + 子主)。 +- KP 岁差(Krishnamurti),在 `temporary_ayanamsa` 里算完即恢复进程原来的岁差。 +- 结果和本命盘无关,只取决于起始日期、天数、时区和口径,按这几项缓存在进程内(LRU)。 +""" + +from __future__ import annotations + +import sys +from collections import OrderedDict +from datetime import timedelta +from pathlib import Path +from threading import Lock +from typing import Any, Dict, List, Tuple + +from . import contract +from .contract import OnDemandInputError + +_SCRIPTS_DIR = Path(__file__).resolve().parents[1] +if str(_SCRIPTS_DIR) not in sys.path: + sys.path.insert(0, str(_SCRIPTS_DIR)) + +TOOL = 'kp_transit_lords' +MAX_DAYS = 400 +SAMPLE_LOCAL_HOUR = 12.0 +BODIES: Tuple[Tuple[str, bool], ...] = (('Sun', True), ('Moon', False), ('Jupiter', True)) +CACHE_MAX_ENTRIES = 64 +RULES_VERSION = 'kp_transit_lords_v1' + +_CACHE: 'OrderedDict[Tuple[Any, ...], Dict[str, Any]]' = OrderedDict() +_CACHE_LOCK = Lock() + + +def _engine(): + try: + from scripts import jyotish_engine as engine + except ModuleNotFoundError: # pragma: no cover - 直接跑 scripts/ + import jyotish_engine as engine # type: ignore[no-redef] + return engine + + +def _kp_helpers(): + try: + from scripts.kp_system import get_kp_lords + from scripts.ayanamsa_utils import temporary_ayanamsa + except ModuleNotFoundError: # pragma: no cover + from kp_system import get_kp_lords # type: ignore[no-redef] + from ayanamsa_utils import temporary_ayanamsa # type: ignore[no-redef] + return get_kp_lords, temporary_ayanamsa + + +def cache_key(start: str, days: int, tz: float, node_mode: str) -> Tuple[Any, ...]: + """缓存键:起始日、天数、时区(到 0.01 小时)、交点口径、岁差(固定 KP)、规则版本。与本命盘无关。""" + return (start, int(days), round(float(tz), 2), node_mode, 'kp', RULES_VERSION) + + +def _segments(rows: List[Tuple[str, str, str]], with_sub: bool) -> List[List[str]]: + """按天的 (日期, 星宿主, 子主) 合成 [起, 止(不含), 星宿主, 子主] 段。""" + out: List[List[str]] = [] + for day, star, sub in rows: + key = (star, sub if with_sub else '') + if out and (out[-1][2], out[-1][3]) == key: + continue + if out: + out[-1][1] = day + out.append([day, '', key[0], key[1]]) + return out + + +def compute(start: str, days: int, tz: float, node_mode: str = 'mean') -> Dict[str, Any]: + """太阳、月亮、木星每天当地 12:00 的 KP 星宿主 / 子主,合成段。命中缓存时直接返回同一份结果。""" + key = cache_key(start, days, tz, node_mode) + with _CACHE_LOCK: + hit = _CACHE.get(key) + if hit is not None: + _CACHE.move_to_end(key) + return {**hit, 'cache': 'hit'} + engine = _engine() + get_kp_lords, temporary_ayanamsa = _kp_helpers() + if hasattr(engine, '_configure_ephemeris_path'): + engine._configure_ephemeris_path() # noqa: SLF001 + first = contract.parse_date(start, 'start_date') + daily: Dict[str, List[Tuple[str, str, str]]] = {name: [] for name, _ in BODIES} + with temporary_ayanamsa('kp'): + for offset in range(days + 1): + day = first + timedelta(days=offset) + jd = contract.jd_for_local(day, SAMPLE_LOCAL_HOUR, tz) + data, _ayanamsa = engine._calc_sidereal_planets_for_jd( # noqa: SLF001 + jd, node_mode=node_mode, include_ketu=False, ayanamsa_name='kp', + ) + for name, _with_sub in BODIES: + row = data.get(name) or {} + lon = row.get('degree_raw', row.get('degree')) + if lon is None: + continue + lords = get_kp_lords(float(lon)) + daily[name].append((day.strftime('%Y-%m-%d'), str(lords['nakshatra_lord']), str(lords['sub_lord']))) + bodies: Dict[str, List[List[str]]] = {} + for name, with_sub in BODIES: + rows = daily[name] + if not rows: + continue + # The last sampled day only closes the previous segment (the window is [start, start + days)). + segments = _segments(rows[:-1], with_sub) + if segments: + segments[-1][1] = rows[-1][0] + bodies[name] = segments + result = { + 'window': {'start': start, 'end': (first + timedelta(days=days)).strftime('%Y-%m-%d'), 'days': days}, + 'sample': f'local {int(SAMPLE_LOCAL_HOUR):02d}:00 daily (tz {tz:+.2f})', + 'columns': '[from, to (exclusive), star_lord, sub_lord]; Moon sub_lord is empty (day sampling)', + 'bodies': bodies, + 'rules_version': RULES_VERSION, + } + with _CACHE_LOCK: + _CACHE[key] = result + _CACHE.move_to_end(key) + while len(_CACHE) > CACHE_MAX_ENTRIES: + _CACHE.popitem(last=False) + return {**result, 'cache': 'miss'} + + +def run(body: Dict[str, Any]) -> Dict[str, Any]: + """body:start_date、days(1–400)、lat、lon、tz 或 timezone_id;ayanamsa 必须是 kp。""" + try: + if not isinstance(body, dict): + raise OnDemandInputError('body must be an object') + start = contract.parse_date(body.get('start_date'), 'start_date').strftime('%Y-%m-%d') + days = int(contract._number(body.get('days'), 'days', 1, MAX_DAYS)) # noqa: SLF001 + common = contract.validate_common({**body, 'date': start}) + profile = contract.resolve_profile(body, common) + if profile['ayanamsa'] != 'kp': + raise OnDemandInputError('ayanamsa must be kp for KP transit lords', 'ayanamsa') + except OnDemandInputError as error: + return contract.blocked_envelope(tool=TOOL, body=body if isinstance(body, dict) else {}, error=error) + raw = compute(start, days, profile['tz'], profile['node_mode']) + return contract.build_envelope(tool=TOOL, requested=body, profile=profile, status='executed', raw=raw) diff --git a/scripts/ondemand_calc/registry.py b/scripts/ondemand_calc/registry.py index 30a81c5a6..8b5ce638c 100644 --- a/scripts/ondemand_calc/registry.py +++ b/scripts/ondemand_calc/registry.py @@ -7,7 +7,7 @@ from __future__ import annotations from typing import Any, Callable, Dict -from . import dasha_date, prashna, solar_return, transit_date, transit_window, varga +from . import dasha_date, kp_transit_lords, prashna, solar_return, transit_date, transit_window, varga from .contract import OnDemandInputError, blocked_envelope # 工具名 → run(body) -> envelope @@ -26,6 +26,8 @@ TOOLS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = { 'varga': varga.run, 'dasha_date': dasha_date.run, 'prashna': prashna.run, # question_text, question_time, location, ayanamsa + # BUG-2325:KP 推运用的太阳、月亮、木星每天的星宿主 / 子主(start_date、days ≤ 400、地点、时区、ayanamsa=kp)。 + 'kp_transit_lords': kp_transit_lords.run, } __all__ = ['TOOLS', 'OnDemandInputError', 'ondemand_calc_api'] diff --git a/tests/test_ondemand_kp_transit_lords_2325.py b/tests/test_ondemand_kp_transit_lords_2325.py new file mode 100644 index 000000000..978a2f680 --- /dev/null +++ b/tests/test_ondemand_kp_transit_lords_2325.py @@ -0,0 +1,93 @@ +"""BUG-2325:KP 推运用的太阳、月亮、木星每天的星宿主 / 子主(按需计算 kp_transit_lords)。 + +窗口固定有上限、按天取样、只算三颗星、KP 岁差算完即恢复、按起始日 + 天数 + 时区缓存(与本命盘无关)。 +只用合成坐标,不含任何个人资料。 +""" + +from __future__ import annotations + +import sys +from datetime import datetime, timedelta +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +for path in (str(ROOT), str(ROOT / 'scripts')): + if path not in sys.path: + sys.path.insert(0, path) + +from scripts.ondemand_calc import TOOLS, ondemand_calc_api # noqa: E402 +from scripts.ondemand_calc import kp_transit_lords # noqa: E402 + +LORDS = {'Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu', 'Ketu'} +BASE = {'tool': 'kp_transit_lords', 'start_date': '2026-01-01', 'days': 60, 'lat': 0.0, 'lon': 0.0, 'tz': 0.0, 'ayanamsa': 'kp'} + + +def _body(**overrides): + return {**BASE, **overrides} + + +def test_registered_and_executed_segments_cover_the_window(): + assert TOOLS['kp_transit_lords'] is kp_transit_lords.run + result = ondemand_calc_api(_body()) + assert result['calculation_status'] == 'executed' + raw = result['raw'] + assert raw['window'] == {'start': '2026-01-01', 'end': '2026-03-02', 'days': 60} + for body in ('Sun', 'Moon', 'Jupiter'): + rows = raw['bodies'][body] + assert rows[0][0] == '2026-01-01' and rows[-1][1] == '2026-03-02' + for left, right in zip(rows, rows[1:]): + assert left[1] == right[0] and left[0] < left[1] + assert {row[2] for row in rows} <= LORDS + # The Moon is sampled once a day: star lord only. + assert all(row[3] == '' for row in raw['bodies']['Moon']) + assert all(row[3] in LORDS for row in raw['bodies']['Sun']) + # The Sun stays about 13 days in one star: 60 days cross four to six stars. + assert 4 <= len({(row[2]) for row in raw['bodies']['Sun']}) <= 6 + + +def test_the_moon_changes_star_about_daily_and_jupiter_slowly(): + raw = ondemand_calc_api(_body(days=30))['raw'] + moon_stars = [row[2] for row in raw['bodies']['Moon']] + assert 25 <= len(moon_stars) <= 31 + assert len(raw['bodies']['Jupiter']) <= 6 + + +def test_cache_key_is_start_days_tz_not_the_chart(): + first = kp_transit_lords.compute('2026-05-01', 20, 8.0) + second = kp_transit_lords.compute('2026-05-01', 20, 8.0) + assert second['cache'] == 'hit' + assert {k: v for k, v in first.items() if k != 'cache'} == {k: v for k, v in second.items() if k != 'cache'} + assert kp_transit_lords.cache_key('2026-05-01', 20, 8.0, 'mean') == ('2026-05-01', 20, 8.0, 'mean', 'kp', 'kp_transit_lords_v1') + # Another place in the same time zone shares the entry (positions at local noon do not depend on the chart). + third = ondemand_calc_api(_body(start_date='2026-05-01', days=20, tz=8.0, lat=31.2, lon=121.5)) + assert third['raw']['cache'] == 'hit' + + +def test_bounds_and_ayanamsa_are_enforced(): + assert ondemand_calc_api(_body(days=401))['calculation_status'] == 'blocked' + assert ondemand_calc_api(_body(days=0))['calculation_status'] == 'blocked' + assert ondemand_calc_api(_body(ayanamsa='lahiri'))['calculation_status'] == 'blocked' + missing = _body() + del missing['start_date'] + assert ondemand_calc_api(missing)['calculation_status'] == 'blocked' + + +def test_the_process_ayanamsa_is_restored(): + from scripts import ayanamsa_utils + from scripts import jyotish_engine as engine + + engine._apply_ayanamsa('raman') # noqa: SLF001 + before = ayanamsa_utils.ACTIVE_AYANAMSA_NAME + kp_transit_lords.compute((datetime(2026, 7, 1) + timedelta(days=3)).strftime('%Y-%m-%d'), 5, 0.0) + assert ayanamsa_utils.ACTIVE_AYANAMSA_NAME == before + + +def test_a_year_is_bounded_in_cpu(): + import time + + started = time.process_time() + result = kp_transit_lords.compute('2027-01-01', kp_transit_lords.MAX_DAYS, -5.0) + spent = time.process_time() - started + assert result['window']['days'] == kp_transit_lords.MAX_DAYS + # Measured about 0.4 s on the development machine for 372 days; a cold year must stay well under two seconds. + assert spent < 2.0, spent