feat(chat): personal day calendar on the card for the writer's day range, checked against the answer (BUG-2336)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
This commit is contained in:
@@ -31780,3 +31780,19 @@
|
||||
- 已知不足:`timing_layer_gaps` 只在服务端回执,没给写手;个人报告读同一个 `answer_policy`,出生时间敏感的盘在报告里也会放开精确应期。
|
||||
- 关联记录:BUG-279(子运门),BUG-2281、BUG-2320(问答写法与结论卡),BUG-1920(不推责)。
|
||||
- 修复版本:分支 `claude/day-calendar`(本地提交,未推送)。
|
||||
|
||||
## BUG-2336 | 问答问具体哪几天时没有个人日历数据可用
|
||||
|
||||
- 状态:fixed-pending-verify(本地提交,未推送)。
|
||||
- 首次发现 / 最近更新:2026-11-24 / 2026-11-24。
|
||||
- 现象:问「这周哪天」「12 月哪几天」时证据卡上没有按天的数据,只能按运期说阶段。
|
||||
- 根因:星历页的个人日历(`scripts/personal_calendar.py`,`/api/personal_calendar`)从未接进问答。
|
||||
- 修复:
|
||||
- `run-jyotish-consultation` 工具新增可选 `day_range {start, end}`,由写手按问题的时间尺度自己给(工具说明和写法规则里写明;不对用户原话做正则匹配);服务端检查并截到 45 天(`clampDayRange`),调同一个 `/api/personal_calendar`(出生地作所在地,和星历页一样),结果放在卡上 `day_calendar`,每天一行 〔C 编号〕,文字复用 `ephemeris-month-copy.ts` 的 THEME_NAME / THEME_LINE / levelLine(`chat-day-calendar.ts`)。失败记一步 `day-calendar` failed,不挡回答。
|
||||
- 一致性检查(`checkDayCalendar`):结论卡「最好的日子」和正文推荐的日子不能是凶(结论卡里有吉日时也不能是平),「避开」和正文说别排的日子不能是吉;不一致的句子进现有的补写调用,补写后仍不一致的不用(`withoutFailingFixes`);最后的结果记在 `answerChecks.dayCalendar`。
|
||||
- 有 day_calendar 时不要求时间条(`timelineRequirement`);写法要结论卡写「最好的日子」「避开」两行、不写时间那一节、点到的日子写〔C 编号〕。
|
||||
- 引擎:`personal_calendar.py` 按出生资料 + 区间 + 地点 + 口径缓存(LRU 64),`ephemeris-month.ts` 导出逐日解析(月历合同要 28 天以上,一周不过)。
|
||||
- 实测:45 天冷算 0.10 秒 CPU(新进程),命中缓存只剩一次深拷贝;真实路由里日历调用 4.9 秒墙钟(与排盘并行)。
|
||||
- 验证:`frontend/tests/chat-day-calendar-2336.test.ts`(8 条);`consultation-agentic-runtime` 工具入参钉住断言按原值 / 新值 / 原因改。真实路由:Obama「这周」11-24→29、「12 月」12-01→31,Jobs「这周」11-24→30、「12 月」12-01→31,四次的日历与直接调 `/api/personal_calendar` 同一区间逐日相同;点到的日子:Obama 本周 25 日吉(最好)、26 日凶(避开)、29 日平(避开,毗湿提);Obama 12 月 4、18 日吉,5、9–11、27 日凶;Jobs 本周 24 日吉、30 日凶;Jobs 12 月 24、3 日吉,4–6 日凶。Obama 本周那一次跑在放宽规则前,「避开」里的平日被记成冲突并送了补写(补写没改),之后改为避开平日不算冲突。
|
||||
- 关联记录:BUG-1947(日历 Kantaka),BUG-2229(问答的引擎补调),BUG-2333。
|
||||
- 修复版本:分支 `claude/day-calendar`(本地提交,未推送)。
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
* the main answer), the two end-to-end runs ≈7 errors in ≈2,300 added characters, not one call added a must-mention
|
||||
* layer, and the follow-up calls appended 13–19 「中性」 lines.
|
||||
*/
|
||||
import { checkDayCalendar } from "./chat-day-calendar.ts";
|
||||
import type { EvidenceCard } from "./consultation-evidence-card.ts";
|
||||
import { findAnswerFactMismatches } from "./consultation-answer-fact-guard.ts";
|
||||
import { NEUTRAL_WORDING } from "./chat-answer-checks.ts";
|
||||
@@ -370,7 +371,9 @@ export function answerRepairPlan(text: string, card: EvidenceCard, options: Read
|
||||
// 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.
|
||||
const extra = (options.extraFlags ?? []).filter((flag) => flag.sentence && text.includes(flag.sentence));
|
||||
const flags = [...tableFlags(text, card), ...plain.map((flag) => ({ kind: flag.kind, sentence: flag.sentence, card: flag.card })), ...extra];
|
||||
// BUG-2336: a day named as good or to avoid against the card's day calendar (any answer, keyed or not).
|
||||
const days = checkDayCalendar(text, card.day_calendar);
|
||||
const flags = [...tableFlags(text, card), ...days, ...plain.map((flag) => ({ kind: flag.kind, sentence: flag.sentence, card: flag.card })), ...extra];
|
||||
return {
|
||||
missing: options.followUp || keyed ? [] : missingMustLayers(text, card),
|
||||
// One flag per stretch of text: a sentence inside (or around) an earlier flagged one is left to that one's rewrite.
|
||||
@@ -385,6 +388,8 @@ export function withoutFailingFixes(repair: AnswerRepair, card: EvidenceCard): {
|
||||
const fixes = repair.fixes.filter((fix) => {
|
||||
if (!fix.text) return true;
|
||||
if (tableFlags(fix.text, card).length) { rejected.push(`fix#${fix.id}:recheck`); return false; }
|
||||
// BUG-2336: a rewrite that still puts a day on the wrong side of the calendar is not used.
|
||||
if (checkDayCalendar(fix.text, card.day_calendar).length) { rejected.push(`fix#${fix.id}:day_level`); return false; }
|
||||
return true;
|
||||
});
|
||||
return { repair: { ...repair, fixes }, rejected };
|
||||
|
||||
@@ -51,8 +51,10 @@ export function bodyDatedStretches(shapeBody: string): Array<{ text: string; mon
|
||||
export type TimelineRequirement = Readonly<{ required: boolean; reason: "first_turn" | "time_label" | "dated_body" | null; domain: AnswerShapeDomain | null }>;
|
||||
|
||||
/** Whether this answer must carry the strip, from its structure (turn, label trio, dated stretches), never the user's words. */
|
||||
export function timelineRequirement(shape: AnswerShape | null, options: { followUp: boolean }): TimelineRequirement {
|
||||
export function timelineRequirement(shape: AnswerShape | null, options: { followUp: boolean; dayCalendar?: boolean }): TimelineRequirement {
|
||||
if (!shape) return { required: false, reason: null, domain: null };
|
||||
// BUG-2337: an answer about specific days shows the day calendar in the strip's place; the two never show together.
|
||||
if (options.dayCalendar) return { required: false, reason: null, domain: verdictDomain(shape.verdict.facts.map((fact) => fact.label)) };
|
||||
const labels = shape.verdict.facts.map((fact) => fact.label);
|
||||
const domain = verdictDomain(labels);
|
||||
if (!options.followUp && domain && domain !== "personality") return { required: true, reason: "first_turn", domain };
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* BUG-2336 (owner-approved spec 2026-11-24, 问答按天回答): a question whose time scale is days (this week, these few days,
|
||||
* which days of a month) is answered from the person's own calendar — the engine's `/api/personal_calendar`, the same
|
||||
* source as the 星历 page — for the range the writer asked for in its tool call (at most MAX_RANGE_DAYS). The words come
|
||||
* from the 星历 page's copy (ephemeris-month-copy.ts); nothing here is written by a model.
|
||||
*
|
||||
* - `clampDayRange`: the range the tool call names, checked and cut to 45 days.
|
||||
* - `dayCalendarFromEngine`: the engine's days for the range, as compact rows (level, lead theme, reasons).
|
||||
* - `dayCalendarRows`: one keyed row per day for the writer (〔C3〕12 月 4 日 星期五:吉,工作。…为什么:…).
|
||||
* - `dayMentions` / `checkDayCalendar`: the days the verdict and body name, and the sentences that call a day good or
|
||||
* bad against the calendar (flags for the existing repair call).
|
||||
* - `dayCalendarShape`: what the receipt carries for the page's calendar (the days, the ones the answer named, the best).
|
||||
*
|
||||
* No regex reads the user's words: the day scale is the writer's own request (`day_range` in the tool call).
|
||||
*/
|
||||
import { monthDayFromEngine } from "./ephemeris-month.ts";
|
||||
import { LEVEL_ZH, levelLine, THEME_LINE, THEME_NAME, weekdayZh } from "./ephemeris-month-copy.ts";
|
||||
import type { MonthDay, MonthReason, MonthTheme } from "./ephemeris-month-contract.ts";
|
||||
import { DAY_VERDICT_LABELS } from "./chat-answer-shape.ts";
|
||||
|
||||
/** The engine's own cap (scripts/personal_calendar.py MAX_RANGE_DAYS). */
|
||||
export const DAY_CALENDAR_MAX_DAYS = 45;
|
||||
/** A week answer (one row of seven cells); a longer range is a month grid. */
|
||||
export const DAY_CALENDAR_WEEK_DAYS = 7;
|
||||
|
||||
export type DayLevel = MonthDay["level"];
|
||||
export type DayCalendarReason = Pick<MonthReason, "code" | "weight"> & Partial<Pick<MonthReason, "transit" | "natal" | "vishti">>;
|
||||
export type DayCalendarDay = Readonly<{ date: string; level: DayLevel; theme: MonthTheme; reasons: readonly DayCalendarReason[] }>;
|
||||
export type DayCalendar = Readonly<{ start: string; end: string; days: readonly DayCalendarDay[] }>;
|
||||
export type DayRange = Readonly<{ start: string; end: string }>;
|
||||
|
||||
const ISO = /^(\d{4})-(\d{2})-(\d{2})$/u;
|
||||
|
||||
export function isoPlusDays(iso: string, days: number): string {
|
||||
const [year, month, day] = iso.split("-").map(Number);
|
||||
return new Date(Date.UTC(year!, month! - 1, day! + days)).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function daysBetween(a: string, b: string): number {
|
||||
return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);
|
||||
}
|
||||
|
||||
function validIso(value: unknown): value is string {
|
||||
if (typeof value !== "string" || !ISO.test(value)) return false;
|
||||
return new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool call's `day_range`, checked: two real dates, start not after end, the start within a week before today (a
|
||||
* week that began on Monday) and within a year after it; cut to 45 days. Null when it cannot be read.
|
||||
*/
|
||||
export function clampDayRange(range: unknown, today: string): DayRange | null {
|
||||
const value = range && typeof range === "object" ? range as Record<string, unknown> : null;
|
||||
if (!value || !validIso(value.start) || !validIso(value.end) || !validIso(today)) return null;
|
||||
const start = value.start;
|
||||
let end = value.end;
|
||||
if (end < start) return null;
|
||||
if (daysBetween(today, start) < -6 || daysBetween(today, start) > 366) return null;
|
||||
if (daysBetween(start, end) + 1 > DAY_CALENDAR_MAX_DAYS) end = isoPlusDays(start, DAY_CALENDAR_MAX_DAYS - 1);
|
||||
return { start, end };
|
||||
}
|
||||
|
||||
export function isWeekRange(range: DayRange): boolean {
|
||||
return daysBetween(range.start, range.end) + 1 <= DAY_CALENDAR_WEEK_DAYS;
|
||||
}
|
||||
|
||||
function compactReason(reason: MonthReason): DayCalendarReason {
|
||||
return {
|
||||
code: reason.code,
|
||||
weight: reason.weight,
|
||||
...(reason.transit ? { transit: reason.transit } : {}),
|
||||
...(reason.natal ? { natal: reason.natal } : {}),
|
||||
...(reason.vishti !== undefined ? { vishti: reason.vishti } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine's `/api/personal_calendar` reply for the range → compact rows. The day's theme is its first theme (the
|
||||
* Moon's house, as in the owner-approved design). Null when the reply is not usable or no day of the range is in it.
|
||||
*/
|
||||
export function dayCalendarFromEngine(raw: unknown, range: DayRange): DayCalendar | null {
|
||||
const row = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : null;
|
||||
if (!row || row.success !== true || !Array.isArray(row.days)) return null;
|
||||
// The same day parser as the 星历 month view (its month contract also asks for 28+ days, which a week is not).
|
||||
const days = row.days.map(monthDayFromEngine)
|
||||
.filter((day): day is MonthDay => day !== null && day.date >= range.start && day.date <= range.end)
|
||||
.slice(0, DAY_CALENDAR_MAX_DAYS)
|
||||
.map((day) => ({ date: day.date, level: day.level, theme: day.themes[0]!.theme, reasons: day.reasons.map(compactReason) }));
|
||||
return days.length ? { start: range.start, end: range.end, days } : null;
|
||||
}
|
||||
|
||||
/** 「12 月 4 日」. */
|
||||
export function dayLabel(iso: string): string {
|
||||
const [, month, day] = iso.split("-").map(Number);
|
||||
return `${month} 月 ${day} 日`;
|
||||
}
|
||||
|
||||
/** 「周五」 (the page's cells and titles use the short form). */
|
||||
export function weekdayShort(iso: string): string {
|
||||
return weekdayZh(iso).replace("星期", "周");
|
||||
}
|
||||
|
||||
/** What the day is like and what to do (the 星历 page's line for its theme and level). */
|
||||
export function dayLine(day: Pick<DayCalendarDay, "theme" | "level">): string {
|
||||
return THEME_LINE[day.theme][day.level];
|
||||
}
|
||||
|
||||
/** Why the day is 吉 / 平 / 凶 (the 星历 page's 「为什么」 wording). */
|
||||
export function dayWhy(day: Pick<DayCalendarDay, "level" | "reasons">): string {
|
||||
return levelLine({ level: day.level, reasons: day.reasons } as unknown as MonthDay);
|
||||
}
|
||||
|
||||
/** The writer's row for one day (also what 「判断依据」 prints for its key). */
|
||||
export function dayRowText(day: DayCalendarDay): string {
|
||||
return `${dayLabel(day.date)} ${weekdayZh(day.date)}:${LEVEL_ZH[day.level]},${THEME_NAME[day.theme]}。${dayLine(day)}为什么:${dayWhy(day).replace(/。$/u, "")}`;
|
||||
}
|
||||
|
||||
/** Keyed rows (C1 … Cn) in date order. */
|
||||
export function dayCalendarRows(calendar: DayCalendar): Array<{ key: string; date: string; text: string }> {
|
||||
return calendar.days.map((day, index) => ({ key: `C${index + 1}`, date: day.date, text: dayRowText(day) }));
|
||||
}
|
||||
|
||||
/** How the writer reads the table (BUG-2335 / 2336 writing rules carry the rest). */
|
||||
export const DAY_CALENDAR_READING =
|
||||
"这道题问的是具体哪几天:照 day_calendar 这张按天的表答,点出哪几天好、哪几天避开,各说一句为什么、那天做什么;每一天的吉、平、凶照表写,不改,不自己按运期另定;表外的日子不说好坏。点到的日子写成「12 月 4 日(周五)」或「周五」,句末写它的〔C 编号〕。这张表看的是每天月亮走到哪、和你出生时的月亮怎样,不受出生时间几分钟误差影响。";
|
||||
|
||||
// ---- the days an answer names ---------------------------------------------------------------------------------
|
||||
|
||||
const WEEKDAY_INDEX: Readonly<Record<string, number>> = { 日: 0, 天: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6 };
|
||||
const DATE_TOKEN = /(?:(\d{1,2})\s*月\s*)?(\d{1,2})\s*(?:日|号)/gu;
|
||||
const RANGE_JOIN = /^\s*(?:到|至|~|~|-|-|–|—)\s*$/u;
|
||||
const WEEKDAY_TOKEN = /(?:周|星期|礼拜)([一二三四五六日天])/gu;
|
||||
|
||||
function inRange(calendar: DayRange, iso: string): boolean {
|
||||
return iso >= calendar.start && iso <= calendar.end;
|
||||
}
|
||||
|
||||
/** The date of 「4 日」 in the range (the month named before it in the sentence, else the first month where it fits). */
|
||||
function resolveDay(range: DayRange, day: number, month: number | null): string | null {
|
||||
// A month outside the range names no calendar day (「5 月 4 日」 in a December answer).
|
||||
for (let offset = 0; offset <= daysBetween(range.start, range.end); offset += 1) {
|
||||
const iso = isoPlusDays(range.start, offset);
|
||||
if (Number(iso.slice(8, 10)) === day && (month === null || Number(iso.slice(5, 7)) === month)) return iso;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The calendar days one sentence names: dates, 「9 日到 11 日」 ranges and, in a week, weekdays. */
|
||||
export function sentenceDays(sentence: string, range: DayRange): string[] {
|
||||
const text = sentence.replace(/\*\*/gu, "");
|
||||
const hits: Array<{ iso: string; at: number }> = [];
|
||||
let at = 0;
|
||||
const add = (iso: string | null) => { if (iso && inRange(range, iso)) hits.push({ iso, at }); };
|
||||
let month: number | null = null;
|
||||
let last: { iso: string | null; end: number } | null = null;
|
||||
for (const hit of text.matchAll(DATE_TOKEN)) {
|
||||
at = hit.index ?? 0;
|
||||
// 「2027 年 5 月 4 日」: a year before it names a date of another year when it is not the range's.
|
||||
const before = text.slice(Math.max(0, at - 8), at);
|
||||
const year = /(\d{4})\s*年\s*$/u.exec(before)?.[1];
|
||||
if (hit[1]) month = Number(hit[1]);
|
||||
const iso = year && !range.start.startsWith(year) && !range.end.startsWith(year) ? null : resolveDay(range, Number(hit[2]), hit[1] ? Number(hit[1]) : month);
|
||||
if (last && last.iso && iso && RANGE_JOIN.test(text.slice(last.end, at))) {
|
||||
for (let offset = 1; offset < daysBetween(last.iso, iso); offset += 1) add(isoPlusDays(last.iso, offset));
|
||||
}
|
||||
add(iso);
|
||||
last = { iso, end: at + hit[0].length };
|
||||
}
|
||||
if (isWeekRange(range)) {
|
||||
const week: string[] = [];
|
||||
for (let offset = 0; offset <= daysBetween(range.start, range.end); offset += 1) week.push(isoPlusDays(range.start, offset));
|
||||
let previous: { iso: string; end: number } | null = null;
|
||||
for (const hit of text.matchAll(WEEKDAY_TOKEN)) {
|
||||
at = hit.index ?? 0;
|
||||
const iso = week.find((item) => new Date(`${item}T00:00:00Z`).getUTCDay() === WEEKDAY_INDEX[hit[1]!]) ?? null;
|
||||
if (!iso) { previous = null; continue; }
|
||||
if (previous && RANGE_JOIN.test(text.slice(previous.end, at)) && previous.iso < iso) {
|
||||
for (let offset = 1; offset < daysBetween(previous.iso, iso); offset += 1) add(isoPlusDays(previous.iso, offset));
|
||||
}
|
||||
add(iso);
|
||||
previous = { iso, end: at + hit[0].length };
|
||||
}
|
||||
}
|
||||
// In the order the sentence names them (the verdict's first 「最好的日子」 is the page's first pick).
|
||||
return [...new Set(hits.sort((a, b) => a.at - b.at).map((hit) => hit.iso))];
|
||||
}
|
||||
|
||||
/** The verdict and body of an answer (no 「判断依据」, 「接着问」 or 「问你一句」), line by line. */
|
||||
function answerLines(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
let skip = false;
|
||||
for (const line of text.split("\n")) {
|
||||
const heading = /^#{1,6}\s+(.+?)\s*$/u.exec(line)?.[1]?.replace(/\*\*/gu, "").trim();
|
||||
if (heading !== undefined) {
|
||||
skip = /^(?:判断依据|接着问|问你一句)/u.test(heading);
|
||||
continue;
|
||||
}
|
||||
if (!skip) out.push(line);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const SENTENCE = /[^。!?;\n]+[。!?;]?/gu;
|
||||
const TAGS = /\s*[〔【][^〔〕【】\n]{0,80}[〕】]/gu;
|
||||
|
||||
/** A verdict line 「- **最好的日子**:……」 / 「- **避开**:……」 names its days' side. */
|
||||
export const [DAY_VERDICT_PICK_LABEL, DAY_VERDICT_AVOID_LABEL] = DAY_VERDICT_LABELS;
|
||||
|
||||
const AVOID_WORDS = /避开|别(?:安排|排|做|碰|定|签|谈|急|冲动|开口)|不要|不宜|不适合|少(?:安排|做)|往后(?:放|挪)|挪开|小心|留神|躲|硬仗|最(?:累|容易累|容易急)|凶/u;
|
||||
const PICK_WORDS = /最好|最适合|适合|合适|挑(?:这|在|周|\d)|放在|安排在|好日子|宜|吉|顺手|开口|可以(?:谈|提|开口|安排|定|签)/u;
|
||||
|
||||
export type DayMention = Readonly<{ sentence: string; days: readonly string[]; side: "pick" | "avoid" | null }>;
|
||||
|
||||
/**
|
||||
* Every sentence of the verdict and body that names calendar days, with the side it puts them on: a verdict line by its
|
||||
* label; a body sentence by its words (both sides or neither → no side, never flagged).
|
||||
*/
|
||||
export function dayMentions(text: string, range: DayRange): DayMention[] {
|
||||
const out: DayMention[] = [];
|
||||
for (const line of answerLines(text)) {
|
||||
const label = /^\s*[-*]\s*\*\*([^*]{1,12})\*\*\s*[::]/u.exec(line)?.[1]?.trim();
|
||||
const sentences = label && (DAY_VERDICT_LABELS as readonly string[]).includes(label) ? [line] : line.match(SENTENCE) ?? [];
|
||||
for (const raw of sentences) {
|
||||
const sentence = raw.trim();
|
||||
if (!sentence) continue;
|
||||
const plainText = sentence.replace(TAGS, "");
|
||||
const days = sentenceDays(plainText, range);
|
||||
if (!days.length) continue;
|
||||
let side: DayMention["side"] = null;
|
||||
if (label === DAY_VERDICT_PICK_LABEL) side = "pick";
|
||||
else if (label === DAY_VERDICT_AVOID_LABEL) side = "avoid";
|
||||
else {
|
||||
const avoid = AVOID_WORDS.test(plainText);
|
||||
const pick = PICK_WORDS.test(plainText.replace(/不适合|不宜/gu, ""));
|
||||
side = avoid && !pick ? "avoid" : pick && !avoid ? "pick" : null;
|
||||
}
|
||||
out.push({ sentence, days, side });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export type DayFlag = { kind: "day_level"; sentence: string; card: string };
|
||||
|
||||
/**
|
||||
* BUG-2336 consistency check: a day the answer recommends must not be 凶 on the calendar, a day it says to avoid must
|
||||
* not be 吉; the verdict's 「最好的日子」 must be 吉 (平 only when the range has no 吉 day). Each flagged sentence goes to
|
||||
* the existing repair call with the calendar's rows.
|
||||
*/
|
||||
export function checkDayCalendar(text: string, calendar: DayCalendar | null | undefined): DayFlag[] {
|
||||
if (!calendar?.days.length) return [];
|
||||
const byDate = new Map(calendar.days.map((day) => [day.date, day]));
|
||||
const hasGood = calendar.days.some((day) => day.level === "good");
|
||||
const flags: DayFlag[] = [];
|
||||
for (const mention of dayMentions(text, calendar)) {
|
||||
if (!mention.side) continue;
|
||||
const verdict = /^\s*[-*]\s*\*\*/u.test(mention.sentence);
|
||||
const wrong = mention.days.map((date) => byDate.get(date)).filter((day): day is DayCalendarDay => {
|
||||
if (!day) return false;
|
||||
if (mention.side === "pick") return day.level === "bad" || (verdict && day.level === "mid" && hasGood);
|
||||
// Avoiding a 平 day is not calling it 凶 (a 平 day with 毗湿提 is one the old rule keeps big things off).
|
||||
return day.level === "good";
|
||||
});
|
||||
if (!wrong.length) continue;
|
||||
const side = mention.side === "pick" ? "写成了适合办事的日子" : "写成了要避开的日子";
|
||||
flags.push({
|
||||
kind: "day_level",
|
||||
sentence: mention.sentence,
|
||||
card: `${wrong.map((day) => `${dayLabel(day.date)}(${weekdayShort(day.date)})在日历上是${LEVEL_ZH[day.level]}:${dayLine(day)}`).join(";")}。这句话把它${side},改成和日历一致(换成日历上${mention.side === "pick" ? "吉" : "凶"}的日子,或照它的吉平凶改说法),日期照写。`,
|
||||
});
|
||||
}
|
||||
return flags;
|
||||
}
|
||||
|
||||
/** What the receipt carries for the page's calendar. */
|
||||
export type DayCalendarShape = Readonly<{
|
||||
start: string;
|
||||
end: string;
|
||||
days: readonly DayCalendarDay[];
|
||||
/** Days the verdict and body name, in date order. */
|
||||
mentioned: readonly string[];
|
||||
/** The day selected first: the verdict's first 「最好的日子」 that is 吉, else the first named 吉 day, else the first 吉 day. */
|
||||
best: string | null;
|
||||
}>;
|
||||
|
||||
export function dayCalendarShape(text: string, calendar: DayCalendar): DayCalendarShape {
|
||||
const mentions = dayMentions(text, calendar);
|
||||
const byDate = new Map(calendar.days.map((day) => [day.date, day]));
|
||||
const mentioned = [...new Set(mentions.flatMap((mention) => mention.days))].filter((date) => byDate.has(date)).sort();
|
||||
const good = (date: string) => byDate.get(date)?.level === "good";
|
||||
const verdictPick = mentions.filter((mention) => mention.side === "pick" && /^\s*[-*]\s*\*\*/u.test(mention.sentence)).flatMap((mention) => mention.days);
|
||||
const best = verdictPick.find(good)
|
||||
?? mentioned.find(good)
|
||||
?? calendar.days.find((day) => day.level === "good")?.date
|
||||
?? mentioned[0]
|
||||
?? null;
|
||||
return { start: calendar.start, end: calendar.end, days: calendar.days, mentioned, best };
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
* from the planets / houses they name, or are flagged); and the direction words of an item (适合 / 强 / 不适合 / 弱)
|
||||
* against the polarity of the rows it cites (logged only).
|
||||
*/
|
||||
import { DAY_CALENDAR_READING, dayCalendarRows } from "./chat-day-calendar.ts";
|
||||
import { evidenceCardKeyFacts, type EvidenceCard } from "./consultation-evidence-card.ts";
|
||||
import {
|
||||
domainBlock, functionalRole, lordshipTable, normalizeTableCard, otherDashaSystems, periodTable, planetTable,
|
||||
@@ -197,6 +198,8 @@ export function evidenceKeyRows(card: EvidenceCard): KeyRow[] {
|
||||
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" }));
|
||||
// BUG-2336: the day calendar for the range the writer asked for, one row per day (C keys), in the 星历 page's words.
|
||||
if (card.day_calendar) safe(() => dayCalendarRows(card.day_calendar!), []).forEach((row) => add({ key: row.key, label: row.text.split(":")[0]!, text: row.text, polarity: 0, table: "timing.day_calendar" }));
|
||||
cache.set(card, rows);
|
||||
return rows;
|
||||
}
|
||||
@@ -235,6 +238,7 @@ export function keyedPrecomputedTables(card: EvidenceCard, tables: { natal: J; t
|
||||
pressure_ranges: keyed("timing.pressure_ranges", tables.timing.pressure_ranges),
|
||||
double_transit: keyed("timing.double_transit", tables.timing.double_transit),
|
||||
transits: keyed("timing.transits", tables.timing.transits),
|
||||
...(byTable("timing.day_calendar").length ? { day_calendar: byTable("timing.day_calendar"), day_calendar_reading: DAY_CALENDAR_READING } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -563,6 +567,8 @@ export function checkBodyDirection(text: string, card: EvidenceCard | null): Pla
|
||||
* changing — or name a planet. Flagged for the sentence repair (a plain life-language reason or 「星盘上这一点很明确」).
|
||||
*/
|
||||
const MECHANISM = /主星|那颗[^,。;]{0,12}星|宫位|(?<!星)盘里|推(?:算)?时间的(?:方法|路子)|两(?:套|种)(?:推|方法|路子)|这颗[^,。;]{0,6}星|一颗[^,。;]{0,8}星|两颗[^,。;]{0,8}星|几颗[^,。;]{0,6}星|那个位置|那一处|这一处|那个点|点着|点到|照着(?!用|做|写|办|来|学|走|执行)|照过去|照向|落在[^,。;]{0,14}(?:那一块|那一处|位置|那一带|那一格)|分类表|那张表|那一层|这一层|走得慢的星|慢星|掌节奏|换了一颗星|换成[^,。;]{0,10}那颗|管[^,。;]{1,12}的那一路|管[^,。;]{1,12}的那[颗一个]|代表[^,。;]{1,12}的那[颗一个]|当值|大吉星|吉星|凶星|太阳|月亮|火星|水星|木星|金星|土星|罗睺|计都|那张盘|分盘|起算|位子上|落点|代表星|那一位|(?<!星)盘上(?!这一点|有几处)|星盘上(?!这一点|有几处)/u;
|
||||
/** BUG-2335: the one sentence that names the running periods (「现在走的是土星大运里的罗睺小运,到 2027 年 12 月」) is kept. */
|
||||
export const CURRENT_PERIOD_LINE = /现在(?:走的|正走|走在)[^。!?]{0,16}大运[^。!?]{0,16}(?:小运|子运)/u;
|
||||
const ASKED_BASIS = /依据|为什么|怎么看出|哪个宫|哪一宫|大运|小运|宫位|星盘上哪|技法|哪颗星/u;
|
||||
|
||||
// BUG-2281 review 原值:「那颗」后最多 8 个字、没有「盘里」「宫位」「推时间的方法 / 两套方法」;新值:「那颗」后最多 12 个字,加这几种说法;
|
||||
@@ -576,7 +582,7 @@ export function bodyMechanismSentences(text: string, userText = ""): string[] {
|
||||
// Units never cross a bold marker, so a rewrite keeps the bold lead intact.
|
||||
for (const match of line.replace(/^\s*[-*]\s+/u, "").matchAll(/(?:(?!\*\*)[^。!?])+[。!?]?/gu)) {
|
||||
const sentence = match[0].replace(/^[*::\s]+/u, "").replace(/\*+$/u, "").trim();
|
||||
if (sentence && MECHANISM.test(sentence) && !out.includes(sentence)) out.push(sentence);
|
||||
if (sentence && MECHANISM.test(sentence) && !CURRENT_PERIOD_LINE.test(sentence) && !out.includes(sentence)) out.push(sentence);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import { evidenceCardTimingHorizonYears } from "./consultation-evidence-card.ts";
|
||||
import { KP_WINDOW_DAYS } from "./chat-kp-timing.ts";
|
||||
import { dayCalendarFromEngine, type DayCalendar, type DayRange } from "./chat-day-calendar.ts";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const rec = (value: unknown): Json => (value && typeof value === "object" && !Array.isArray(value) ? value as Json : {});
|
||||
@@ -187,3 +188,34 @@ export async function attachKpTimingPacket(workflow: unknown, fetchImpl: typeof
|
||||
layers.kp_timing_packet = { calculation_status: "blocked", reason: error instanceof Error ? error.name : "fetch_failed" };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* BUG-2336: the person's day calendar for the range the writer asked for (`day_range` in its tool call), from the
|
||||
* engine's `/api/personal_calendar` — the 星历 page's source, with the birth place as the place, as the page sends it.
|
||||
* The engine caps the range at 45 days and caches per chart and range. A failure returns null (recorded by the caller)
|
||||
* and never stops the answer.
|
||||
*/
|
||||
export async function fetchDayCalendar(workflow: unknown, range: DayRange, fetchImpl: typeof fetch = fetch): Promise<{ calendar: DayCalendar | null; reason?: string; elapsedMs: number }> {
|
||||
const started = Date.now();
|
||||
const birth = birthFromChart(rec(rec(workflow).chart));
|
||||
if (!birth) return { calendar: 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/personal_calendar`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...birth,
|
||||
current_lat: birth.lat, current_lon: birth.lon, current_tz: birth.tz,
|
||||
start_date: range.start, end_date: range.end,
|
||||
}),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
if (!response.ok) return { calendar: null, reason: `http_${response.status}`, elapsedMs: Date.now() - started };
|
||||
const calendar = dayCalendarFromEngine(await response.json().catch(() => null), range);
|
||||
return { calendar, ...(calendar ? {} : { reason: "contract_failed" }), elapsedMs: Date.now() - started };
|
||||
} catch (error) {
|
||||
return { calendar: null, reason: error instanceof Error ? error.name : "fetch_failed", elapsedMs: Date.now() - started };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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 type { DayCalendar } from "./chat-day-calendar.ts";
|
||||
import { shadbalaMinimumRatio, shadbalaWithoutBand } from "./shadbala-minimum.ts";
|
||||
import { dashaEvidenceId, shadbalaEvidenceId, yogaEvidenceId } from "./evidence-ids.ts";
|
||||
import { evidenceBaseEdges, evidenceBaseStatuses, type EvidenceEdge, type EvidenceStatus } from "./card-evidence-index.ts";
|
||||
@@ -764,6 +765,8 @@ export type EvidenceCard = {
|
||||
parameters?: JsonRecord;
|
||||
};
|
||||
domain_sections: Partial<Record<ConsultationDomain, EvidenceCardDomainSection>>;
|
||||
/** BUG-2336: the person's day calendar for the range the writer asked for (`day_range`); absent otherwise. */
|
||||
day_calendar?: DayCalendar;
|
||||
meta: {
|
||||
backstage: typeof EVIDENCE_CARD_BACKSTAGE_LINE;
|
||||
/** BUG-1976: the calculation snapshot (birth input revision, date, rule versions) the evidence ids belong to. */
|
||||
|
||||
@@ -593,6 +593,12 @@ export const TIMING_FOCUS_RULE = "讲时间时最多说三件天象或运期变
|
||||
// 原因:负责人 2026-11-24:几乎每个回答都带一句问话,只在确实需要用户补一件事才能收窄时问。
|
||||
// BUG-2308 原值:「时间那一节(问题有时间的一面才写)」;新值:「时间那一节(性格题以外都写,照 strip_stretches 的几段)」;
|
||||
// 原因:负责人 11-24 的「我适合幕后还是台前?」首轮有「最好的时候」和带日期的几段,却判成没有时间的一面、没写时间条。
|
||||
/**
|
||||
* BUG-2335 / 2336 (owner 2026-11-24): a question about specific days is answered from the day calendar the writer asks
|
||||
* for (day_range in its tool call) — the shape's exception, carried in the turn for first turns and follow-ups alike.
|
||||
*/
|
||||
export const DAY_QUESTION_RULE =
|
||||
"问的是具体哪几天(这周、这几天、某一天、某个月里哪几天)时:调用工具带上 day_range,照卡上 day_calendar 直接点出日子;「## 结论」写一句话加「最好的日子」「避开」两行,不写时间那一节(页面在那里画日历),点到的日子句末写〔C 编号〕。";
|
||||
export const CHAT_FIRST_TURN_SHAPE =
|
||||
"这是本会话的首轮回答:按系统提示里 VISIBLE VOICE 的写法回答用户这句话,用它列的分节(## 标题)写完整,标题一字不改,按它的顺序写:## 结论(一句话加三行固定标签)、时间那一节(性格题以外都写,照 strip_stretches 的几段)、五块正文、## 问你一句(只在答案要看一件用户在对话里还没说过的事、按它分成明显不同的几条路时才写,多数回答没有)、## 接着问;正文写完后,最后写「## 判断依据」一节。正文写给没接触过占星的人,句子短,一句一件事,一句盘面上的理由都不写;从结论到「要留意的」大约 1,200 到 1,600 字,判断一条不少,写不下就把句子写短;用户说了要多长时按用户说的写。卡上为这个问题交付的层,和这件事有关的都要用进判断,正文只说结果,依据放进「判断依据」那一条的〔编号〕;正文每条判断和时间那一节每条末尾写〔编号〕。";
|
||||
|
||||
@@ -616,7 +622,7 @@ export function natalAnswerShapeBody(mode: ConsultationAnswerMode = DEFAULT_CONS
|
||||
// 原值:「这是本会话的首轮回答:……写成人话;标题和分节按本轮骨架写,一般问题不用标题。……每段的盘面原因只用一句;
|
||||
// 讲时间只说日期和那段时间会怎样,大运、小运、Narayana 这些名字只进判断依据。正文写完后,最后写「## 判断依据」一节。」;
|
||||
// 新值:CHAT_FIRST_TURN_SHAPE;原因:BUG-2229,负责人 2026-11-23 定按分节写完整、卡上每一层都用上。
|
||||
if (mode === "plain") return CHAT_FIRST_TURN_SHAPE;
|
||||
if (mode === "plain") return `${CHAT_FIRST_TURN_SHAPE}${DAY_QUESTION_RULE}`;
|
||||
return "这是本会话的首轮回答:按系统提示里 VISIBLE VOICE 的写法回答用户这句话——深度解读,按它的正文结构完整写,开头一节是简短的结论(第一句直接回答这个问题,时间范围紧随其后),然后证据,最后展开结论,Technique Audit Table 和参数写进正文。";
|
||||
}
|
||||
|
||||
@@ -667,6 +673,7 @@ export function followUpAnswerShapeInstruction(mode: ConsultationAnswerMode = DE
|
||||
? "这是追问轮:本会话前面已经写过完整解读。先写「## 结论」,第一句就回答用户这句话;再只写和这句话直接相关的几条(每条先一句加粗的结论,再两三句短句,段末写〔编号〕),讲清楚为准,不限字数,不重讲上一轮;正文的写法和首轮一样:写给没接触过占星的人,句子短,一句盘面上的理由都不写(不写星、宫、运期、分盘、方法名,也不写两种方法对没对上),这些都放进「判断依据」;只有用户问依据、为什么,或者自己用了专业词时,才照他的问法用这些词并解释。写法按系统提示里的 VISIBLE VOICE(追问轮写法)。问的是一段时间或什么时候、或者要分几段日期给建议时,写时间那一节(紧跟在「## 结论」后面,格式同首轮,每条末尾写〔编号〕);只有答案要看一件用户在对话里还没说过的事、按它分成明显不同的几条路时,才写「## 问你一句」(写法同首轮,用户说过的不再问);然后「## 接着问」三条;最后写「## 判断依据」,只列这一轮的判断,每条末尾写〔编号〕。用户明确换了领域或要求完整看一下时,按首轮写。"
|
||||
: "这是追问轮:本会话前面已经写过完整解读。先用一两句回答用户这句话,讲清楚为准,不限字数;再只写和这句话相关的技法路由、原始数据、Dasha 与证据等级,不重讲上一轮;冲突与阻塞项和 Technique Audit Table(列本轮用到的技法,加 Functional Benefic/Malefic、MEVG / Global Web Evidence、Real Case Calibration 三行)保留;写法按系统提示里的 VISIBLE VOICE。用户明确换了领域或要求完整看一下时,按首轮写。",
|
||||
CAREER_FOLLOW_UP_RULE,
|
||||
mode === "plain" ? DAY_QUESTION_RULE : "",
|
||||
// BUG-2229: a follow-up about time or a period names both timing methods; the card's main cause comes first.
|
||||
mode === "plain" ? FOLLOW_UP_TIMING_RULE : "",
|
||||
mode === "plain" ? FOLLOW_UP_MAIN_CAUSE_RULE : "",
|
||||
|
||||
@@ -95,7 +95,8 @@ function reason(raw: unknown): MonthReason | null {
|
||||
return parsed.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
function day(raw: unknown): MonthDay | null {
|
||||
/** One engine day → the page's day (null when unusable). BUG-2336: the chat's day calendar reads days the same way. */
|
||||
export function monthDayFromEngine(raw: unknown): MonthDay | null {
|
||||
const row = rec(raw);
|
||||
if (!row || typeof row.date !== "string") return null;
|
||||
const themes = list(row.themes).flatMap((item) => {
|
||||
@@ -161,7 +162,7 @@ export function ephemerisMonthFromEngine(raw: unknown, meta: { subjectId: string
|
||||
month: meta.month,
|
||||
today: meta.today,
|
||||
rulesVersion: typeof row.rules_version === "string" ? row.rules_version : "unknown",
|
||||
days: list(row.days).map(day).filter((d): d is MonthDay => d !== null),
|
||||
days: list(row.days).map(monthDayFromEngine).filter((d): d is MonthDay => d !== null),
|
||||
backdrop: backdrop(row.backdrop),
|
||||
};
|
||||
const parsed = ephemerisMonthResponseSchema.safeParse(candidate);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { attachFastTransits, attachKpTimingPacket, attachKpTransitLords } from "../lib/chat-transit-window.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";
|
||||
import { inheritFollowUpDomains } from "../lib/chat-followup-domains.ts";
|
||||
import { claimCardsWithTables } from "../lib/chat-answer-tables.ts";
|
||||
@@ -381,6 +382,11 @@ const domainPlanValueSchema = consultationDomainPlanValueSchema;
|
||||
const consultationToolInputSchema = z.object({
|
||||
question: z.string().trim().min(1).max(500),
|
||||
domains: z.array(domainPlanValueSchema).min(1).max(MAX_CONSULTATION_DOMAIN_PLAN_VALUES),
|
||||
// BUG-2336: the days the question is about, when its time scale is days (the writer's own judgment, never a word match).
|
||||
day_range: z.object({
|
||||
start: z.string().regex(/^\d{4}-\d{2}-\d{2}$/u),
|
||||
end: z.string().regex(/^\d{4}-\d{2}-\d{2}$/u),
|
||||
}).strict().optional(),
|
||||
}).strict();
|
||||
|
||||
const MAX_RECORDED_STEPS = 32;
|
||||
@@ -484,7 +490,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<string, number>; plainBody?: Record<string, unknown>; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record<string, unknown> };
|
||||
answerChecks?: { steps?: unknown; flags?: number; asked?: string[]; optionalNotMentioned?: string[]; repair?: Record<string, number>; plainBody?: Record<string, unknown>; directReply?: { restored: string[]; deletions: string[] }; timeline?: Record<string, unknown>; dayCalendar?: { mentioned: number; conflicts: string[] } };
|
||||
};
|
||||
|
||||
export function createConsultationRuntimeState(options: { plannedSteps?: number; reservedValidationSteps?: number } = {}): ConsultationRuntimeState {
|
||||
@@ -1630,7 +1636,7 @@ export function createConsultationTools(ctx: ConsultationAgentContext) {
|
||||
let lookupCache: EvidenceLookupCache | null = null;
|
||||
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.`,
|
||||
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.`,
|
||||
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.
|
||||
@@ -1646,6 +1652,9 @@ export function createConsultationTools(ctx: ConsultationAgentContext) {
|
||||
ctx.state.planOverrideIgnored = true;
|
||||
}
|
||||
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));
|
||||
const dayCalendar: { pending: ReturnType<typeof fetchDayCalendar> | 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
|
||||
// from about 111k to 255k input tokens). The first caller gets the result;
|
||||
@@ -1694,6 +1703,7 @@ 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.
|
||||
if (dayRange && !dayCalendar.pending) dayCalendar.pending = fetchDayCalendar(workflow, dayRange);
|
||||
await attachFastTransits(workflow, userIntent);
|
||||
// BUG-2325: the KP transit star / sub lords for career, money and relationship questions (bounded, cached).
|
||||
// BUG-2333: the astrologer's KP packet with the multi-system window (KP profile; the workflow's own periods reused).
|
||||
@@ -1839,6 +1849,11 @@ export function createConsultationTools(ctx: ConsultationAgentContext) {
|
||||
question: userIntent,
|
||||
requestTime: ctx.requestTime ?? new Date(),
|
||||
});
|
||||
if (dayCalendar.pending) {
|
||||
const day = await dayCalendar.pending;
|
||||
if (day.calendar) card.day_calendar = day.calendar;
|
||||
appendConsultationRuntimeStep(ctx.state, { kind: "tool", name: "day-calendar", status: day.calendar ? "completed" : "failed", durationMs: day.elapsedMs, ...(day.reason ? { failureCode: day.reason } : {}) });
|
||||
}
|
||||
const modelView = toModelEvidenceView(modelContext, card, userIntent);
|
||||
ctx.state.evidenceCard = card;
|
||||
ctx.state.evidenceCardChars = JSON.stringify({
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
// BUG-2336 (owner-approved spec 2026-11-24): a question about specific days is answered from the person's own day
|
||||
// calendar — the engine's /api/personal_calendar, the 星历 page's source — for the range the writer asks for in its tool
|
||||
// call (no word matching), in the 星历 page's words; every day the verdict and body name is checked against it and a
|
||||
// wrong one goes to the existing repair call.
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
|
||||
import { answerRepairPlan, withoutFailingFixes } from "../src/lib/chat-answer-repair.ts";
|
||||
import { parseAnswerShape } from "../src/lib/chat-answer-shape.ts";
|
||||
import { timelineRequirement } from "../src/lib/chat-answer-timeline.ts";
|
||||
import {
|
||||
checkDayCalendar,
|
||||
clampDayRange,
|
||||
DAY_CALENDAR_MAX_DAYS,
|
||||
dayCalendarFromEngine,
|
||||
dayCalendarRows,
|
||||
dayCalendarShape,
|
||||
dayMentions,
|
||||
type DayCalendar,
|
||||
} from "../src/lib/chat-day-calendar.ts";
|
||||
import { evidenceKeyRows, keyedPrecomputedTables } from "../src/lib/chat-evidence-keys.ts";
|
||||
import { fetchDayCalendar } from "../src/lib/chat-transit-window.ts";
|
||||
import { reduceWait, beginWait } from "../src/lib/chat-wait-progress.ts";
|
||||
import { agentExecutionReceiptSchema, consultationAgentPublicEventSchema } from "../src/lib/consultation-agent-events.ts";
|
||||
import type { EvidenceCard } from "../src/lib/consultation-evidence-card.ts";
|
||||
import { THEME_LINE } from "../src/lib/ephemeris-month-copy.ts";
|
||||
|
||||
/** The engine's own output for the public Obama chart, 2026-11-30 → 12-31 (the design's data), trimmed to what is read. */
|
||||
function engineDay(date: string, level: "good" | "mid" | "bad", theme: string, reasons: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
date, level, reasons,
|
||||
themes: [{ theme, sources: [{ kind: "moon_house", house: 1 }] }],
|
||||
activities: { marriage: { verdict: "neutral" }, business: { verdict: "neutral" }, travel: { verdict: "neutral" }, medical: { verdict: "neutral" }, education: { verdict: "neutral" } },
|
||||
};
|
||||
}
|
||||
const ENGINE = {
|
||||
success: true,
|
||||
rules_version: "personal_calendar_v1",
|
||||
backdrop: {},
|
||||
days: [
|
||||
engineDay("2026-11-30", "bad", "upheaval", [{ code: "tara_bad", weight: -1 }, { code: "sav_weak", weight: -1 }]),
|
||||
engineDay("2026-12-01", "mid", "upheaval", [{ code: "tara_good", weight: 1 }]),
|
||||
engineDay("2026-12-02", "good", "travel", [{ code: "tara_good", weight: 1 }, { code: "panchanga_good", weight: 1 }]),
|
||||
engineDay("2026-12-03", "mid", "travel", []),
|
||||
engineDay("2026-12-04", "good", "career", [{ code: "tara_good", weight: 1 }, { code: "sav_strong", weight: 1 }, { code: "panchanga_good", weight: 1 }]),
|
||||
engineDay("2026-12-05", "bad", "career", [{ code: "tara_bad", weight: -1 }, { code: "chandrabala_bad", weight: -1 }]),
|
||||
engineDay("2026-12-06", "mid", "talk", []),
|
||||
engineDay("2026-12-09", "bad", "rest", [{ code: "chandrashtama", weight: -2 }]),
|
||||
engineDay("2026-12-10", "bad", "rest", [{ code: "chandrashtama", weight: -2 }]),
|
||||
engineDay("2026-12-11", "bad", "rest", [{ code: "chandrashtama", weight: -2 }]),
|
||||
engineDay("2026-12-18", "good", "talk", [{ code: "tara_good", weight: 1 }, { code: "panchanga_good", weight: 1 }]),
|
||||
],
|
||||
};
|
||||
const WEEK = dayCalendarFromEngine(ENGINE, { start: "2026-11-30", end: "2026-12-06" })!;
|
||||
const MONTH = dayCalendarFromEngine(ENGINE, { start: "2026-12-01", end: "2026-12-31" })!;
|
||||
const cardWith = (calendar: DayCalendar) => ({ domains: ["timing"], base: { natal: {}, timing: {} }, domain_sections: {}, meta: { gaps: [] }, day_calendar: calendar }) as unknown as EvidenceCard;
|
||||
|
||||
test("BUG-2336 range: the writer's own day_range, checked and cut to the engine's 45 days", () => {
|
||||
assert.deepEqual(clampDayRange({ start: "2026-11-30", end: "2026-12-06" }, "2026-11-30"), { start: "2026-11-30", end: "2026-12-06" });
|
||||
// A week that began on Monday is still this week.
|
||||
assert.deepEqual(clampDayRange({ start: "2026-11-23", end: "2026-11-29" }, "2026-11-26"), { start: "2026-11-23", end: "2026-11-29" });
|
||||
assert.equal(clampDayRange({ start: "2026-12-01", end: "2027-03-01" }, "2026-11-30")!.end, "2027-01-14");
|
||||
assert.equal(DAY_CALENDAR_MAX_DAYS, 45);
|
||||
for (const bad of [null, { start: "2026-12-06", end: "2026-11-30" }, { start: "2026-02-30", end: "2026-03-01" }, { start: "2020-01-01", end: "2020-01-02" }, { start: "12月", end: "x" }]) {
|
||||
assert.equal(clampDayRange(bad, "2026-11-30"), null);
|
||||
}
|
||||
// No word matching on the user's question: the tool description asks the writer for the range.
|
||||
const tools = readFileSync(new URL("../src/mastra/consultation-tools.ts", import.meta.url), "utf8");
|
||||
assert.match(tools, /day_range: z\.object\(\{/u);
|
||||
assert.match(tools, /send day_range \{start, end\}/u);
|
||||
});
|
||||
|
||||
test("BUG-2336 the calendar call: the 星历 page's engine route, birth place as the place, the range; failures return null", async () => {
|
||||
const workflow = { chart: { birth: { date: "1961-08-04", hour: 19, minute: 24, lat: 21.3069, lon: -157.8583, tz: -10, ayanamsa_name: "raman", node_mode: "mean" } } };
|
||||
const calls: Array<{ url: string; body: Record<string, unknown> }> = [];
|
||||
const ok = (async (url: string, init: RequestInit) => {
|
||||
calls.push({ url, body: JSON.parse(String(init.body)) });
|
||||
return new Response(JSON.stringify(ENGINE), { status: 200 });
|
||||
}) as unknown as typeof fetch;
|
||||
const result = await fetchDayCalendar(workflow, { start: "2026-11-30", end: "2026-12-06" }, ok);
|
||||
assert.equal(result.calendar?.days.length, 7);
|
||||
assert.match(calls[0]!.url, /\/api\/personal_calendar$/u);
|
||||
assert.deepEqual(
|
||||
[calls[0]!.body.start_date, calls[0]!.body.end_date, calls[0]!.body.current_lat, calls[0]!.body.current_tz, calls[0]!.body.ayanamsa],
|
||||
["2026-11-30", "2026-12-06", 21.3069, -10, "raman"],
|
||||
);
|
||||
const failing = (async () => new Response("{}", { status: 503 })) as unknown as typeof fetch;
|
||||
assert.deepEqual((await fetchDayCalendar(workflow, { start: "2026-11-30", end: "2026-12-06" }, failing)).calendar, null);
|
||||
assert.equal((await fetchDayCalendar({}, { start: "2026-11-30", end: "2026-12-06" }, ok)).reason, "birth_fields_missing");
|
||||
});
|
||||
|
||||
test("BUG-2336 rows: one keyed row per day in the 星历 page's words, on the timing tables the writer reads", () => {
|
||||
const rows = dayCalendarRows(WEEK);
|
||||
assert.equal(rows.length, 7);
|
||||
assert.equal(rows[4]!.key, "C5");
|
||||
assert.equal(rows[4]!.text, `12 月 4 日 星期五:吉,工作。${THEME_LINE.career.good}为什么:这天的星宿和你合得来;月亮落的星座在你盘里有底子;这天的五要素大多是吉`);
|
||||
assert.doesNotMatch(rows.map((row) => row.text).join(""), /·|[A-Za-z]/u);
|
||||
const card = cardWith(WEEK);
|
||||
assert.ok(evidenceKeyRows(card).some((row) => row.key === "C5" && row.table === "timing.day_calendar"));
|
||||
const tables = keyedPrecomputedTables(card, { natal: {}, timing: {} });
|
||||
assert.equal((tables.timing.day_calendar as string[])[0]!.slice(0, 4), "〔C1〕");
|
||||
assert.match(String(tables.timing.day_calendar_reading), /吉、平、凶照表写,不改/u);
|
||||
});
|
||||
|
||||
test("BUG-2336 mentions: dates, 「9 日到 11 日」, weekdays in a week; 「判断依据」 and 「接着问」 are not read", () => {
|
||||
const answer = [
|
||||
"## 结论",
|
||||
"这周挑周三和周五办要紧的事。",
|
||||
"- **最好的日子**:周三 12 月 2 日、周五 12 月 4 日〔C3 C5〕",
|
||||
"- **避开**:周一 11 月 30 日",
|
||||
"## 接着问",
|
||||
"- 周六能不能谈?",
|
||||
"## 判断依据",
|
||||
"- **周六**:12 月 5 日好。",
|
||||
].join("\n");
|
||||
const mentions = dayMentions(answer, WEEK);
|
||||
assert.deepEqual(mentions.map((item) => [item.days, item.side]), [
|
||||
[["2026-12-02", "2026-12-04"], "pick"],
|
||||
[["2026-12-02", "2026-12-04"], "pick"],
|
||||
[["2026-11-30"], "avoid"],
|
||||
]);
|
||||
const month = dayMentions("12 月谈工作挑 4 日和 18 日;9 日到 11 日别安排硬仗。2027 年 5 月 4 日以后再说。", MONTH);
|
||||
assert.deepEqual(month.map((item) => item.days), [["2026-12-04", "2026-12-18"], ["2026-12-09", "2026-12-10", "2026-12-11"]]);
|
||||
});
|
||||
|
||||
test("BUG-2336 consistency: a recommended 凶 day, an avoided 吉 day or a verdict 平 day (when 吉 days exist) is flagged", () => {
|
||||
const wrong = [
|
||||
"## 结论",
|
||||
"这周挑周五。",
|
||||
"- **最好的日子**:周五 12 月 4 日、周日 12 月 6 日〔C5 C7〕",
|
||||
"- **避开**:周三 12 月 2 日、周日 12 月 6 日",
|
||||
"## 要留意的",
|
||||
"**周六最适合谈加薪。** 那天说的话有人听〔C6〕。",
|
||||
"**周二照常过。** 按部就班。",
|
||||
].join("\n");
|
||||
const flags = checkDayCalendar(wrong, WEEK);
|
||||
assert.deepEqual(flags.map((flag) => flag.sentence), [
|
||||
"- **最好的日子**:周五 12 月 4 日、周日 12 月 6 日〔C5 C7〕",
|
||||
"- **避开**:周三 12 月 2 日、周日 12 月 6 日",
|
||||
"**周六最适合谈加薪。",
|
||||
]);
|
||||
assert.match(flags[2]!.card, /12 月 5 日(周六)在日历上是凶/u);
|
||||
// Avoiding a 平 day (周日) is not calling it 凶: only the 吉 day 周三 is named in that flag (real Obama answer, 11-24).
|
||||
assert.match(flags[1]!.card, /12 月 2 日(周三)在日历上是吉/u);
|
||||
assert.doesNotMatch(flags[1]!.card, /12 月 6 日/u);
|
||||
assert.equal(flags[0]!.kind, "day_level");
|
||||
const right = "## 结论\n这周挑周三和周五。\n- **最好的日子**:周三 12 月 2 日、周五 12 月 4 日\n- **避开**:周一 11 月 30 日、周六 12 月 5 日";
|
||||
assert.deepEqual(checkDayCalendar(right, WEEK), []);
|
||||
assert.deepEqual(checkDayCalendar(wrong, null), []);
|
||||
});
|
||||
|
||||
test("BUG-2336 guard path: the flags go to the one repair call, and a rewrite that is still wrong is not used", () => {
|
||||
const card = cardWith(WEEK);
|
||||
const text = "## 结论\n这周挑周五。\n- **最好的日子**:周六 12 月 5 日\n\n## 判断依据\n\n- **好**:x。";
|
||||
const plan = answerRepairPlan(text, card, {});
|
||||
const flag = plan.flags.find((item) => item.kind === "day_level");
|
||||
assert.ok(flag);
|
||||
const kept = withoutFailingFixes({ layers: [], fixes: [{ id: flag.id, text: "- **最好的日子**:周五 12 月 4 日" }] }, card);
|
||||
assert.equal(kept.repair.fixes.length, 1);
|
||||
const refused = withoutFailingFixes({ layers: [], fixes: [{ id: flag.id, text: "- **最好的日子**:周一 11 月 30 日" }] }, card);
|
||||
assert.deepEqual(refused.rejected, [`fix#${flag.id}:day_level`]);
|
||||
});
|
||||
|
||||
test("BUG-2336 receipt: the days, the named ones and the best (the verdict's first 吉 day); no strip is required", () => {
|
||||
const text = "## 结论\n12 月谈工作挑 4 日和 18 日;9 日到 11 日别安排硬仗。\n- **最好的日子**:18 日(周五)谈加薪、4 日(周五)提方案\n- **避开**:9 日到 11 日";
|
||||
const shape = dayCalendarShape(text, MONTH);
|
||||
assert.deepEqual(shape.mentioned, ["2026-12-04", "2026-12-09", "2026-12-10", "2026-12-11", "2026-12-18"]);
|
||||
// The verdict names 18 日 first (real Obama answer 11-24 named 4 日 first and the page picked 2 日 by date order).
|
||||
assert.equal(shape.best, "2026-12-18");
|
||||
const parsed = parseAnswerShape(text);
|
||||
assert.deepEqual(parsed?.verdict.facts.map((fact) => fact.label), ["最好的日子", "避开"]);
|
||||
assert.equal(timelineRequirement(parsed, { followUp: false, dayCalendar: true }).required, false);
|
||||
// 原值: a first turn outside personality always required the strip; 新值: not when the answer has a day calendar; 原因: BUG-2337, the two never show together.
|
||||
assert.equal(timelineRequirement(parseAnswerShape("## 结论\n能。\n- **最适合**:写\n- **先别碰**:借\n- **最好的时候**:明年"), { followUp: false }).required, true);
|
||||
const receipt = agentExecutionReceiptSchema.shape.answerShape.unwrap().parse({ areas: [], tones: [], dayCalendar: { ...shape, days: shape.days.map((day) => ({ ...day, reasons: [...day.reasons] })), mentioned: [...shape.mentioned] } });
|
||||
assert.equal(receipt.dayCalendar?.days.length, MONTH.days.length);
|
||||
});
|
||||
|
||||
test("BUG-2336 stream: tool.started carries the writer's day range and the wait state keeps it", () => {
|
||||
const event = consultationAgentPublicEventSchema.parse({ type: "tool.started", callId: "c", tool: "run-jyotish-consultation", label: "正在计算个人星盘", domains: ["timing"], dayRange: { start: "2026-11-30", end: "2026-12-06" } });
|
||||
const state = reduceWait(beginWait(true), event);
|
||||
assert.deepEqual(state.dayRange, { start: "2026-11-30", end: "2026-12-06" });
|
||||
const stream = readFileSync(new URL("../src/lib/stream-agent-response.ts", import.meta.url), "utf8");
|
||||
assert.match(stream, /dayRange: range/u);
|
||||
assert.match(stream, /attachDayCalendarShape\(\);/u);
|
||||
});
|
||||
@@ -178,7 +178,8 @@ test("BUG-2287: the model must name the domains; one calculation per request", a
|
||||
const tool = tools["run-jyotish-consultation"];
|
||||
// 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.
|
||||
assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains"]);
|
||||
// 原值 ["question", "domains"];新值加可选的 day_range;原因:BUG-2336,按天的问题由写手在工具调用里给出日子范围(不按用户原话匹配)。
|
||||
assert.deepEqual(Object.keys((tool.inputSchema as unknown as { shape: object }).shape), ["question", "domains", "day_range"]);
|
||||
const execute = tool.execute!;
|
||||
const context = { observe: { span: async (_n: string, fn: () => Promise<unknown>) => fn(), log() {} } } as never;
|
||||
const schema = tool.inputSchema as unknown as { safeParse: (value: unknown) => { success: boolean } };
|
||||
|
||||
@@ -36,9 +36,13 @@ as supporting evidence only), VedAstro range scan (external, case-bound).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import OrderedDict
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
@@ -459,9 +463,40 @@ def day_themes(day: dict[str, Any], dasha_lords: set[str], limit: int = 3) -> li
|
||||
return themes
|
||||
|
||||
|
||||
# BUG-2336: the chat reads the same calendar as the 星历 page for a question's days (at most MAX_RANGE_DAYS). One result
|
||||
# per chart + range + place + profile, kept in process (LRU); a hit costs a deep copy, never a second calculation.
|
||||
CACHE_SIZE = 64
|
||||
_CACHE: "OrderedDict[str, dict[str, Any]]" = OrderedDict()
|
||||
_CACHE_LOCK = threading.Lock()
|
||||
_CACHE_FIELDS = (
|
||||
"year", "month", "day", "hour", "minute", "second", "lat", "lon", "tz", "ayanamsa", "node_mode",
|
||||
"current_lat", "current_lon", "current_tz", "start_date", "end_date",
|
||||
)
|
||||
|
||||
|
||||
def _cache_key(body: dict[str, Any]) -> str:
|
||||
return json.dumps([CALENDAR_RULES_VERSION, *[str(body.get(key)) for key in _CACHE_FIELDS]], ensure_ascii=True)
|
||||
|
||||
|
||||
def build_personal_calendar(body: dict[str, Any] | None) -> dict[str, Any]:
|
||||
if not isinstance(body, dict):
|
||||
raise PersonalCalendarError("JSON body must be an object")
|
||||
key = _cache_key(body)
|
||||
with _CACHE_LOCK:
|
||||
hit = _CACHE.get(key)
|
||||
if hit is not None:
|
||||
_CACHE.move_to_end(key)
|
||||
return deepcopy(hit)
|
||||
result = _build_personal_calendar(body)
|
||||
with _CACHE_LOCK:
|
||||
_CACHE[key] = deepcopy(result)
|
||||
_CACHE.move_to_end(key)
|
||||
while len(_CACHE) > CACHE_SIZE:
|
||||
_CACHE.popitem(last=False)
|
||||
return result
|
||||
|
||||
|
||||
def _build_personal_calendar(body: dict[str, Any]) -> dict[str, Any]:
|
||||
start = _parse_day(body.get("start_date"), "start_date")
|
||||
end = _parse_day(body.get("end_date"), "end_date")
|
||||
if end < start:
|
||||
|
||||
Reference in New Issue
Block a user