Files
Jyotisha/frontend/src/lib/chat-basis-completeness.ts
T
ClaudeandClaude Opus 5.5 bbdb274931
Independent Staging Quality Gate / validate-python (push) Successful in 10m15s
Independent Staging Quality Gate / validate-frontend (push) Successful in 14m5s
Independent Staging Quality Gate / publish (push) Successful in 3m26s
fix(report,chat): reading facts and the chat card follow the astrologer's D/E/G states; chat basis reads the shared topic chart table (BUG-2163)
- Debilitation: verified reads 「落陷;另有缓解条件,不代表困难全部消失」, a candidate (neecha_states)
  reads 「落陷;缓解条件待核」, uncomputed / not met / self-reference only stay 「落陷」; the
  chat card, evidence pack, computed fallback and writer rule R-06 follow.
- Connections: plain words for pd_range_split / pd_stability_not_assessed and for a truncated or
  missing chain; an unassessed topic chart no longer hides an undetermined house; the use rule says
  unfinished or unassessed is never 'no connection'.
- Chat basis completion reads references/topic_varga_routes.json (parents D12 only, children D7,
  siblings D3, residence D4, education D24; D9 never a career chart).
- test_reading_facts_2126 follows the BUG-2151 wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-22 12:46:35 +08:00

218 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* BUG-2151 (产品负责人 2026-11-22, follow-up to BUG-2150): the 「判断依据」 block is checked against the
* computed card after the answer is written. When the card has a layer the question's route needs —
* Narayana's current period, the route's Jaimini karaka (MK / PiK / DK / PK / AmK) or the route's
* divisional chart — and the block never mentions it, the program appends one item per group, written
* from the card's own values. The body is never touched.
*
* Deterministic on purpose: the BUG-2150 eval showed the model adds these layers in some answers and
* drops them in others under the same instruction; a second model pass would add latency and could
* misstate a value (one answer wrote longitude as 「纬度」). The card already holds the exact sentences
* (key_facts.<domain>.reading, the same text the model reads) and the Narayana periods.
*/
import { splitJudgmentBasis } from "./consult-judgment-basis.ts";
import { evidenceCardKeyFacts, EVIDENCE_CARD_LABELS, type EvidenceCard } from "./consultation-evidence-card.ts";
import { planetZh, signZh } from "./chart-view-labels.ts";
import topicVargaRoutes from "../../../references/topic_varga_routes.json";
type Json = unknown;
const record = (value: Json): Record<string, Json> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, Json> : {};
/** Karakas the route can ask for, with the words an answer uses when it names them without the code. */
const KARAKA_WORDS: Readonly<Record<string, RegExp>> = {
MK: /(?<![A-Za-z])MK(?![A-Za-z])|母亲(?:的)?代表星|代表母亲的星/u,
PiK: /(?<![A-Za-z])PiK(?![A-Za-z])|父亲(?:的)?代表星|代表父亲的星/u,
DK: /(?<![A-Za-z])DK(?![A-Za-z])|伴侣(?:的)?代表星|代表伴侣的星|配偶(?:的)?代表星/u,
PK: /(?<![A-Za-z])PK(?![A-Za-z])|子女(?:的)?代表星|代表子女的星/u,
AmK: /(?<![A-Za-z])AmK(?![A-Za-z])|事业(?:的)?代表星|代表事业的星/u,
};
/** What each divisional chart is read for, in the words the basis already uses. */
const VARGA_USE: Readonly<Record<string, string>> = {
D2: "钱财", D3: "兄弟姐妹", D4: "住处", D6: "健康", D7: "子女", D8: "健康", D9: "婚姻",
D10: "事业", D11: "收益", D12: "父母", D16: "车与安逸", D20: "修行", D24: "学业", D30: "健康",
};
const NARAYANA_RE = /Narayana|纳拉亚纳/u;
const vargaRe = (code: string) => new RegExp(`(?<![A-Za-z0-9])${code}(?!\\d)`, "u");
export type BasisCompletion = Readonly<{ output: string; added: readonly string[] }>;
/** What the check reads: each route's item statuses, the key block, and the Narayana periods. */
export type BasisSources = Readonly<{
routes: readonly Record<string, Json>[];
/** The domain of each route, same order (BUG-2152). */
routeDomains?: readonly string[];
keyFacts: Record<string, Json>;
narayana: Record<string, Json>;
}>;
/** From the server's card (stream-agent-response). */
export function basisSourcesFromCard(card: EvidenceCard): BasisSources {
return {
routes: card.domains.map((domain) => record(card.domain_sections[domain]?.route)),
routeDomains: [...card.domains],
keyFacts: record(evidenceCardKeyFacts(card)),
narayana: record(card.base.timing.narayana),
};
}
/** From the model's view of the card (the tool result the research script saves as *.card.json). */
export function basisSourcesFromModelView(view: Json): BasisSources {
const cards = Array.isArray(record(view).claim_cards) ? record(view).claim_cards as Json[] : [];
const routes: Record<string, Json>[] = [];
const routeDomains: string[] = [];
let narayana: Record<string, Json> = {};
for (const card of cards) {
const evidence = record(record(card).evidence);
if (record(card).category === "timing") narayana = record(evidence.narayana);
for (const [domain, value] of Object.entries(evidence)) {
if (!record(value).route) continue;
routes.push(record(record(value).route));
routeDomains.push(domain);
}
}
return { routes, routeDomains, keyFacts: record(record(view).key_facts), narayana };
}
/**
* BUG-2152 (测试环境复测第三十轮:问父母时「相关分盘」补了 D7(看子女)): a question about parents also carries the
* engine's wider family route (D3 / D7 / D12), and a broad route such as general carries D9 / D10 / D2. When the
* card has a specific topic domain, only that domain's routes count; family counts only when no narrower family
* topic (parents, children) is on the card, and the broad domains only when nothing else is.
* 原值:卡上所有领域的路由都算。
*/
const BROAD_DOMAINS = new Set(["general", "annual", "timing"]);
const NARROWER: Readonly<Record<string, readonly string[]>> = { family: ["parents", "children"] };
export function questionRoutes(sources: BasisSources): readonly Record<string, Json>[] {
const domains = sources.routeDomains;
if (!domains || domains.length !== sources.routes.length) return sources.routes;
const present = new Set(domains);
const specific = domains.filter((domain) => !BROAD_DOMAINS.has(domain));
const keep = (domain: string) => specific.length
? !BROAD_DOMAINS.has(domain) && !(NARROWER[domain] ?? []).some((narrower) => present.has(narrower))
: true;
return sources.routes.filter((_, index) => keep(domains[index]!));
}
/**
* BUG-2163 (占星师 2026-11-22 §6.4, G3; shared with the report through references/topic_varga_routes.json):
* the divisional charts a question's topic reads. A card domain with a topic in the table only adds that
* topic's charts (D1 excluded; a chart in not_unconditional for the topic is never added for it); a domain
* without a table topic (health, family, ...) keeps its route's charts as before (BUG-2151 / BUG-2152).
* 原值:卡上路由列出的所有分盘都补。
*/
type TopicRoute = Readonly<{ topic: string; charts: readonly string[] }>;
type TopicTable = Readonly<{ topics: readonly TopicRoute[]; not_unconditional?: readonly Readonly<{ chart: string; topic: string }>[] }>;
const TOPIC_TABLE = topicVargaRoutes as unknown as TopicTable;
/** Card domains whose table topic has another name. */
const DOMAIN_TOPIC: Readonly<Record<string, string>> = { migration: "home" };
export function topicCharts(domain: string): ReadonlySet<string> | null {
const topic = DOMAIN_TOPIC[domain] ?? domain;
const row = TOPIC_TABLE.topics.find((item) => item.topic === topic);
if (!row) return null;
const barred = new Set((TOPIC_TABLE.not_unconditional ?? []).filter((item) => item.topic === topic).map((item) => item.chart));
return new Set(row.charts.filter((chart) => chart !== "D1" && !barred.has(chart)));
}
/** The divisional chart codes the question's routes ask for, limited by the shared topic table. */
export function questionVargaCodes(sources: BasisSources): string[] {
const routes = questionRoutes(sources);
const domains = sources.routeDomains && sources.routeDomains.length === sources.routes.length ? sources.routeDomains : null;
const kept = domains ? sources.routes.map((route, index) => [route, domains[index]!] as const).filter(([route]) => routes.includes(route)) : routes.map((route) => [route, ""] as const);
const codes: string[] = [];
for (const [route, domain] of kept) {
const allowed = domain ? topicCharts(domain) : null;
for (const code of Object.keys(route)) {
if (!/^D\d+$/u.test(code) || code === "D1" || (allowed && !allowed.has(code)) || codes.includes(code)) continue;
codes.push(code);
}
}
return codes;
}
function onCard(sources: BasisSources, item: string): boolean {
return questionRoutes(sources).some((route) => route[item] === EVIDENCE_CARD_LABELS.routeStatus.onCard);
}
/** 「D4 第 4 宫摩羯,……」 segments of the key block's reading sentence that start with `code`. */
function readingSegments(sources: BasisSources, code: string, lead: RegExp): string[] {
const out: string[] = [];
for (const facts of Object.values(sources.keyFacts)) {
const reading = record(facts).reading;
if (typeof reading !== "string") continue;
const text = reading.startsWith(EVIDENCE_CARD_LABELS.keyFactsReading) ? reading.slice(EVIDENCE_CARD_LABELS.keyFactsReading.length) : reading;
for (const segment of text.replace(/。$/u, "").split(";")) {
const trimmed = segment.trim();
if (lead.test(trimmed) && !out.includes(trimmed)) out.push(trimmed);
}
}
return out;
}
const age = (value: Json) => typeof value === "number" && Number.isFinite(value) ? String(Math.round(value * 100) / 100) : null;
function narayanaLine(sources: BasisSources): string | null {
const narayana = sources.narayana;
const md = record(narayana.md);
if (typeof md.sign !== "string" || age(md.start_age) === null || age(md.end_age) === null) return null;
const period = (row: Record<string, Json>) => {
const lord = typeof row.lord === "string" ? `、主星${planetZh(row.lord)}` : "";
const from = age(row.start_age), to = age(row.end_age);
return `${signZh(String(row.sign))}${lord}${from !== null && to !== null ? `(${from}–${to} 岁)` : ""}`;
};
const parts = [`当前主运${period(md)}`];
const ad = record(narayana.ad);
if (typeof ad.sign === "string") parts.push(`子运${period(ad)}`);
const next = Array.isArray(narayana.next) ? record(narayana.next[0]) : {};
if (typeof next.sign === "string") parts.push(`下一段主运${period(next)}`);
return `Narayana(按星座排的运势分段)${parts.join(",")}。`;
}
/** The items to append, in order; empty when nothing the route needs is missing. */
export function missingBasisItems(output: string, sources: BasisSources | null | undefined): string[] {
if (!sources) return [];
const { basis } = splitJudgmentBasis(output);
if (basis === null) return [];
const items: string[] = [];
if (onCard(sources, "Narayana") && !NARAYANA_RE.test(basis)) {
const line = narayanaLine(sources);
if (line) items.push(`- **第二套运程**:${line}`);
}
const karakas: string[] = [];
for (const code of Object.keys(KARAKA_WORDS)) {
if (!onCard(sources, code) || KARAKA_WORDS[code]!.test(basis)) continue;
karakas.push(...readingSegments(sources, code, new RegExp(`^${code} 是`, "u")));
}
if (karakas.length) items.push(`- **代表星**:${karakas.join(";")}。`);
const vargas: string[] = [];
for (const code of questionVargaCodes(sources)) {
if (!onCard(sources, code) || vargaRe(code).test(basis)) continue;
const segments = readingSegments(sources, code, new RegExp(`^${code} 第`, "u"));
if (segments.length) vargas.push(`${VARGA_USE[code] ? `${code}(看${VARGA_USE[code]})` : code}:${segments.map((segment) => segment.replace(new RegExp(`^${code} `, "u"), "")).join(";")}`);
}
if (vargas.length) items.push(`- **相关分盘**:${vargas.join("。")}。`);
return items;
}
/** The answer with the missing items appended to the end of 「判断依据」. */
export function withCompletedBasis(output: string, sources: BasisSources | null | undefined): BasisCompletion {
const items = missingBasisItems(output, sources);
if (!items.length) return { output, added: [] };
// The block ends the answer, except when the model wrote it twice (BUG-2150): append after the first copy.
const trimmed = output.replace(/\s+$/u, "");
const firstEnd = (() => {
const split = splitJudgmentBasis(trimmed);
if (split.basis === null) return trimmed.length;
const index = trimmed.indexOf(split.basis);
return index < 0 ? trimmed.length : index + split.basis.length;
})();
const head = trimmed.slice(0, firstEnd).replace(/\s+$/u, "");
const tail = trimmed.slice(firstEnd);
return { output: `${head}\n${items.join("\n")}${tail}`, added: items };
}