fix(yoga): astrologer 11-25 review items 4–8 — Raja structure formed with modifiers, exchange recall by houses, actual vs illustrated diagrams (BUG-2392)

Owner approved the yoga_engine.py change for items 4, 5, 6 and 8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
This commit is contained in:
2026-11-25 20:22:29 +08:00
co-authored by Claude Opus 5.5
parent e54db1a756
commit c34ffc855e
8 changed files with 333 additions and 12 deletions
+17
View File
@@ -32439,3 +32439,20 @@
- **防复发**:`tests/test_parivartana_classes_2388.py`、`frontend/tests/chart-yoga-parivartana-2388.test.ts`。
- **关联记录**:BUG-2387(同一张盘的落陷卡)、BUG-1572(王者互换此前从未触发)、BUG-1975 / BUG-2218(规则级主题映射冻结)。
- **修复版本**:1.4(staging)。
## BUG-2392 | 占星师 2026-11-25 九项复核第四至八项:Raja 结构满足仍显示候选、互换不按实际宫位召回领域、示意图冒充本盘实际图
- **状态**:resolved(本地提交,staging 待推)
- **现象**:负责人转来占星师对九项的复核(`/workspace/eval-read-1116/astrologer-replies/yoga-kp-9items-20261125.md`)。①角宫主与三方宫主互换等 Raja 结构在盘上满足,引擎一律给 `candidate`(`source_definition_not_reviewed`),星盘页不显示、问答卡读作候选;②三类互换没有领域归属(主题表 unmapped),问答按领域召回不到;③约 90 条自定义规则不记录参与星,星盘页按规则句子推断出的图看起来像本盘实际成立的配置;④她担心月亮自身落陷时的有效缓解被当成自我参照排除。
- **触发条件**:任一盘上 kendra–trikona 宫主关系的 Raja 规则命中;问婚恋/事业/财富等领域时盘上有互换;自定义规则命中而无参与星。
- **根因**:①`assess_yoga_formation` 只有带审过定义的规则才能 `formed_under_source`,Raja 结构类规则没有合同;②领域召回只有关键词主题表,互换没有按交换宫位的检索规则;③自定义表达式命中后不写 `participants_expr` 时引擎不记参与星,前端用 BUG-2387 的推断画图,未标明是示意;④核查后引擎本身已按她的定义处理(只有见证星与参照点都是月亮才算 `self_reference`),月亮落天蝎、火星在月亮起第四宫是有效缓解——没有排除,补回归测试锁住。
- **修复**:
- `scripts/yoga_engine.py`(冻结文件,负责人 2026-11-25 逐项批准第四、五、六、八项):新增 `RAJA_STRUCTURAL_RULES`(11 条角宫主/三方宫主结构规则)的产品成立合同 `kendra_trikona_lord_structure`:D1、几何一致、`lord_structure`(参与星各管至少一个角宫或三方宫)满足即 `formed_under_source`;参与宫主兼管第 6/8/12 宫写进 `formation_modifiers` 与 `formation_note_zh`(「实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。」),不降级、不写待核。`_assess_product_contract` 允许合同以规则自身的执行定义为定义(`definition: None`)。
- `references/yoga_rules.json`:dhana_yoga、grahi_dhana、vipreet_pairs、bvr_bahu_sthree_yoga 加 `participants_expr`,写明实际命中分支的参与星。
- 星盘页 `chart-yoga-groups.ts`:成立卡读 `formation_note_zh` 接在条件句后;引擎没给参与星、靠规则句子推断出的图,图注前加「示意:」,引擎给了参与星的画本盘实际配置(整盘类分布图、宫主链不加)。
- 问答卡 `consultation-evidence-card.ts`:新召回理由 `exchange_houses`——按实际交换的两宫召回领域(事业 10 + 6/7/2/11;财富 2、11 + 8/12;婚恋 5、7 + 2/8;健康 1/6/8/12;家庭 4、3;父母 4;学业 5/9;迁移 9/12;一宫是核心宫或两宫都在核心+辅助宫内),是检索规则不是结论;同一对互换星的第二条规则标 `same_exchange_as`,不算多一份支持;模型可见的选取说明补了这两项。
- **验证**:Python 新测 `tests/test_yoga_review_2392.py` 5 条;yoga/neecha/parivartana/formation 全部 Python 测试 667 通过;2324 英文泄漏测试 3 条通过;前端新测 `frontend/tests/yoga-review-2392.test.ts` 5 条;consult/chart/yoga/evidence 前端测试 1399 通过;tsc 无错;改动文件 ESLint 0 错。
- **防复发**:`test_yoga_instances_gana_2075` 参与星规则计数 32 → 36(原值/新值/原因已注);新测试锁住 Raja 成立与修正句、月亮落陷缓解不被排除、只有月亮自参照才算恒真、互换按两宫召回且同一互换只算一份、示意图标注。
- **未做(如实)**:其余约 140 条自定义规则仍没有 `participants_expr`,它们的图继续按句子推断并标「示意」;报告端(jyotisha-10)未读 `formation_note_zh`,需要报告窗口决定是否展示。
- **关联记录**:BUG-2387、BUG-2388、BUG-2353/2354(第九项,问答窗口)、BUG-2027、BUG-2301。
- **修复版本**:1.5(待发)。
+17 -2
View File
@@ -318,6 +318,18 @@ function ruleDiagram(id: string, bodies: Record<string, Body>, rules: Record<str
return found.length ? { kind: "set", bodies: found.slice(0, 4), label: found.map(zh).join("、") } : null;
}
/**
* BUG-2392 (占星师 11-25 第八项): the engine's matched participants draw this chart's actual configuration.
* When the engine names none, the diagram is read from the rule's sentence (BUG-2387) and its caption says
* it is an illustration of the rule, not the matched branch.
*/
function actualOrIllustration(row: Row, bound: string[], bodies: Record<string, Body>, rules: Record<string, number[]>): YogaDiagram {
const diagram = rowDiagram(row, bound, bodies, rules);
const wholeChart = diagram.kind === "spread" || diagram.kind === "chain" || diagram.kind === "none";
if (bound.length || wholeChart) return diagram;
return { ...diagram, label: `示意:${diagram.label}` };
}
function rowDiagram(row: Row, bound: string[], bodies: Record<string, Body>, rules: Record<string, number[]> = {}): YogaDiagram {
const category = String(row.category ?? "");
const id = String(row.rule_id ?? "");
@@ -436,8 +448,11 @@ export function buildYogaGroups(input: Readonly<{
// A one-body yoga and a one-body structure on that body are the same fact (萨萨 and 7th lord in its own sign).
if (planets.length === 1 && !formedPlanets.has(planets[0]!)) formedPlanets.set(planets[0]!, name);
categories.set(id, String(row.category ?? ""));
// BUG-2392 (占星师 11-25 第五项): a formed kendra–trikona Raja yoga keeps its modifier in plain words.
const note = text(row.formation_note_zh);
formed.push({
id, group: "formed", name, alias, text: sentence, tags, same: false, planets, diagram: rowDiagram(row, planets, bodies, rules),
id, group: "formed", name, alias, text: note ? `${sentence}。${note}`.replace(/。。/gu, "。") : sentence, tags, same: false, planets,
diagram: actualOrIllustration(row, planets, bodies, rules),
...(MINOR_CATEGORIES.has(String(row.category ?? "")) ? { minor: true } : {}),
});
}
@@ -508,7 +523,7 @@ export function buildYogaGroups(input: Readonly<{
id: `adverse:${key}`, group: "adverse", name, alias: null,
text: `${conditionText(first)}${merged ? `。${merged}` : ""}`.replace(/。。/gu, "。"),
tags: mitigations, same: false, planets,
diagram: rowDiagram(first, planets, bodies, rules),
diagram: actualOrIllustration(first, planets, bodies, rules),
});
}
return { formed: [...formed.filter((card) => !card.minor), ...formed.filter((card) => card.minor)], support, adverse };
+62 -3
View File
@@ -3370,7 +3370,9 @@ export const EVIDENCE_CARD_YOGA_SELECTION_RULE = (
"selection_reasons keeps every recall reason. direct: route_packet, domain_named, packet_domain, rule_topic (topic map "
+ "pending the astrologer's review). dependency: an exchange or debilitation cancellation sharing a planet with a direct "
+ "row (dependency_of); unrelated ones do not enter. weak: category alone, or a planet ruling a recall house "
+ "(domain_house_lord; not used on whole-chart cards). Rows without a mapped topic are unmapped_rule_ids, never dropped."
+ "(domain_house_lord; not used on whole-chart cards). Rows without a mapped topic are unmapped_rule_ids, never dropped. "
+ "exchange_houses: a sign exchange recalled by the two houses it exchanges (exchanged_houses) — a recall rule, not a "
+ "conclusion; same_exchange_as marks another rule on the same exchange, which is one piece of evidence, not extra support."
);
export const EVIDENCE_CARD_YOGA_FIELD_RULE = (
@@ -3388,7 +3390,45 @@ export const EVIDENCE_CARD_YOGA_COUNTS_RULE = (
+ "hit_count > 1 is the same rule matched again, not independent support."
);
const YOGA_DIRECT_REASONS = ["route_packet", "domain_named", "packet_domain", "rule_topic"] as const;
const YOGA_DIRECT_REASONS = ["route_packet", "domain_named", "packet_domain", "rule_topic", "exchange_houses"] as const;
/**
* BUG-2392 (占星师 2026-11-25 复核第四项): a sign-exchange row is retrieved for a domain by the two houses
* actually exchanged on this chart — a retrieval rule, not a conclusion. 事业 10 + 6/7/2/11;财富 2、11 + 8/12;
* 婚恋 5、7(+2/8);健康 1/6/8/12;居住 4;学习远行 5/9;手足沟通 3. One exchange is one row of evidence:
* other rows on the same two planets are marked `same_exchange_as`, never counted as extra support.
*/
export const EXCHANGE_DOMAIN_HOUSES: Readonly<Partial<Record<ConsultationDomain, Readonly<{ core: readonly number[]; extra: readonly number[] }>>>> = {
career: { core: [10], extra: [6, 7, 2, 11] },
wealth: { core: [2, 11], extra: [8, 12] },
marriage: { core: [5, 7], extra: [2, 8] },
health: { core: [1, 6, 8, 12], extra: [] },
family: { core: [4, 3], extra: [] },
parents: { core: [4], extra: [] },
education: { core: [5, 9], extra: [] },
migration: { core: [9, 12], extra: [] },
};
/** A domain recalls an exchange when one exchanged house is its core house, or both are among its core and extra houses. */
export function exchangeRecalledFor(domain: ConsultationDomain, houses: readonly number[]): boolean {
const spec = EXCHANGE_DOMAIN_HOUSES[domain];
if (!spec || houses.length !== 2) return false;
const all = [...spec.core, ...spec.extra];
return houses.some((house) => spec.core.includes(house)) || houses.every((house) => all.includes(house));
}
/** The two houses a sign-exchange row exchanges: the engine's house_class check, else its `exchange` places. */
export function exchangedHouses(row: Record<string, unknown>): number[] {
for (const check of Array.isArray(row.formation_checks) ? row.formation_checks as Json[] : []) {
const value = record(check);
if (value.id === "house_class") {
const houses = record(value.witness).houses;
if (Array.isArray(houses)) return houses.filter((h): h is number => typeof h === "number");
}
}
const places = Object.values(record(row.exchange)).map((place) => record(place).house).filter((h): h is number => typeof h === "number");
return places.length === 2 ? places : [];
}
type YogaReason = typeof YOGA_DIRECT_REASONS[number] | "dependency" | "category" | "domain_house_lord";
function yogaCategory(row: Record<string, unknown>): string | undefined {
@@ -3468,6 +3508,11 @@ export function selectEvidenceCardYogaDetail(
if (typeof row.name === "string" && named.has(row.name)) out.push("domain_named");
if (typeof row.packet_domain === "string" && tags.has(row.packet_domain)) out.push("packet_domain");
if (stringList(row.rule_topics).some((topic) => topics.has(topic))) out.push("rule_topic");
const exchanged = exchangedHouses(row);
if (!whole && exchanged.length === 2
&& scope.domains.some((domain) => exchangeRecalledFor(domain, exchanged))) {
out.push("exchange_houses");
}
return out;
};
const rows = [...unique.values()];
@@ -3518,7 +3563,18 @@ export function selectEvidenceCardYogaDetail(
chosen.sort((a, b) => rank[a.relevance] - rank[b.relevance] || String(a.row.rule_id).localeCompare(String(b.row.rule_id)));
let detailCount = 0;
let indexCount = 0;
// BUG-2392: one exchange (two planets in each other's signs) is one piece of evidence however many rules name it.
const exchangeFirst = new Map<string, string>();
const exchangeKey = (row: Record<string, unknown>) => {
const pair = Object.keys(record(row.exchange));
const bound = pair.length === 2 ? pair : exchangedHouses(row).length === 2
? (Array.isArray(row.planets) ? stringList(row.planets) : Object.keys(record(row.planets))) : [];
return bound.length === 2 ? [...bound].sort().join(":") : "";
};
const outRows: Json[] = chosen.map(({ row, reasons, relevance, dependencyOf }) => {
const exchangeOf = exchangeKey(row);
const sameExchange = exchangeOf && exchangeFirst.has(exchangeOf) ? exchangeFirst.get(exchangeOf) : undefined;
if (exchangeOf && !exchangeFirst.has(exchangeOf)) exchangeFirst.set(exchangeOf, String(row.rule_id));
const common: JsonRecord = {
// BUG-1976 / BUG-1978: rule id + layer; the method version is the snapshot's (yoga_id on the Python side).
// BUG-1988: a per-planet rule (Neecha Bhanga main detector) keeps one row and one id per planet.
@@ -3533,12 +3589,15 @@ export function selectEvidenceCardYogaDetail(
...(dependencyOf ? { dependency_of: dependencyOf } : {}),
...yogaTemporal(row),
...(Number(row.hit_count ?? 1) > 1 ? { hit_count: Number(row.hit_count) } : {}),
...(reasons.includes("exchange_houses") ? { exchanged_houses: exchangedHouses(row) as unknown as Json } : {}),
...(sameExchange ? { same_exchange_as: sameExchange } : {}),
};
// Detail when the row bears on this question: a route packet, a domain section or the packet names it,
// a dependency of such a row, or (single-domain cards) the rule's own topic. On a whole-chart card a
// topic match alone is an index unless a participating planet runs a current period.
const strong = reasons.some((r) => r === "route_packet" || r === "domain_named" || r === "packet_domain");
const topicDetail = reasons.includes("rule_topic") && (!whole || stringList(row.running_dasha_levels).length > 0);
const topicDetail = (reasons.includes("rule_topic") || reasons.includes("exchange_houses"))
&& (!whole || stringList(row.running_dasha_levels).length > 0);
const asIndex = relevance === "weak" || (relevance === "direct" && !strong && !topicDetail);
if (asIndex) {
indexCount += 1;
+98
View File
@@ -0,0 +1,98 @@
// BUG-2392(占星师 2026-11-25 九项复核第四至八项):互换按实际交换的两宫召回领域、Raja 结构满足显示成立并写明修正、
// 月亮落陷的有效缓解出卡、见证条件分开写、示意图与本盘实际图分开。合成盘,无出生资料。
import assert from "node:assert/strict";
import test from "node:test";
import { buildYogaGroups } from "../src/lib/chart-yoga-groups.ts";
import { exchangeRecalledFor, exchangedHouses, selectEvidenceCardYogaDetail } from "../src/lib/consultation-evidence-card.ts";
import type { ConsultationDomain } from "../src/lib/consultation-domain-registry.ts";
type Json = Record<string, unknown>;
const planets = [
{ name: "Sun", sign: "Cancer", house: 1 }, { name: "Moon", sign: "Virgo", house: 3 },
{ name: "Mars", sign: "Libra", house: 4 }, { name: "Mercury", sign: "Leo", house: 2 },
{ name: "Jupiter", sign: "Capricorn", house: 7 }, { name: "Venus", sign: "Gemini", house: 12 },
{ name: "Saturn", sign: "Pisces", house: 9 },
];
test("item 4: an exchange is recalled by the two houses it exchanges, never by every house a lord rules", () => {
// 7 and 9: marriage (7 core) and education (9 core); not career (only 7 is a career extra house), not wealth.
assert.equal(exchangeRecalledFor("marriage", [7, 9]), true);
assert.equal(exchangeRecalledFor("education", [7, 9]), true);
assert.equal(exchangeRecalledFor("career", [7, 9]), false);
assert.equal(exchangeRecalledFor("wealth", [7, 9]), false);
// Two career extra houses together (2 and 11) are recalled for career; 10 alone is enough.
assert.equal(exchangeRecalledFor("career", [2, 11]), true);
assert.equal(exchangeRecalledFor("career", [10, 3]), true);
assert.equal(exchangeRecalledFor("health", [6, 9]), true);
});
const row = (id: string, extra: Json = {}): Json => ({
name: `Yoga ${id}`, rule_id: id, status: "computed", rule_state: "formed", method_version: "m",
instance_key: `${id}|m|D1`, condition: "c", topic_mapping: "unmapped", rule_topics: [], ...extra,
});
const select = (rows: Json[], domains: ConsultationDomain[]) =>
selectEvidenceCardYogaDetail({ rows } as never, domains, [])!;
test("item 4: the evidence card recalls the exchange for marriage and marks the second rule on it as the same exchange", () => {
const maha = row("maha_parivartana_yoga", { planets: ["Jupiter", "Saturn"],
formation_checks: [{ id: "house_class", passed: true, witness: { houses: [7, 9], class: "maha" } }] });
const raja = row("raja_yoga_parivartana", {
exchange: { Jupiter: { sign: "Capricorn", house: 7 }, Saturn: { sign: "Pisces", house: 9 } } });
assert.deepEqual(exchangedHouses(maha), [7, 9]);
assert.deepEqual(exchangedHouses(raja).sort(), [7, 9]);
const out = select([maha, raja], ["marriage"]);
const rows = out.rows as Json[];
assert.deepEqual(rows.map((r) => r.rule_id).sort(), ["maha_parivartana_yoga", "raja_yoga_parivartana"]);
for (const r of rows) assert.ok((r.selection_reasons as string[]).includes("exchange_houses"));
const marked = rows.filter((r) => typeof r.same_exchange_as === "string");
assert.equal(marked.length, 1, "one exchange is one piece of evidence");
// A career card does not recall a 7–9 exchange.
assert.equal((select([maha], ["career"]).rows as Json[]).length, 0);
});
test("item 5: a formed Raja yoga card keeps its dusthana modifier in plain words", () => {
const raja = {
rule_id: "raja_yoga_parivartana", name: "Raja Yoga", name_cn: "王者互换格局", category: "raja",
planets: ["Jupiter", "Saturn"], reader_condition_zh: "木星与土星互换星座",
formation_assessment: { status: "formed_under_source" },
formation_note_zh: "实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。",
};
const groups = buildYogaGroups({ rows: [raja], planets, ascendant: "Cancer" })!;
const card = groups.formed.find((c) => c.id === "raja_yoga_parivartana")!;
assert.ok(card, "formed, not a candidate");
assert.equal(card.text, "木星与土星互换星座。实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。");
assert.doesNotMatch(card.text, /待核|候选|不能据此/u);
});
test("items 6 and 7: a debilitated Moon with Mars in a kendra from the Moon gets its card; conditions stay separate", () => {
const moonChart = [
{ name: "Moon", sign: "Scorpio", house: 8 }, { name: "Mars", sign: "Aquarius", house: 11 },
{ name: "Venus", sign: "Leo", house: 5 }, { name: "Sun", sign: "Aries", house: 1 },
];
const row = {
rule_id: "neechabhanga_basic", name: "Neecha Bhanga", name_cn: "落陷取消", category: "nicha_bhanga",
planets: ["Moon", "Mars", "Venus"],
combination: "月亮落陷于天蝎座;成立条件:落陷星座主星火星在月亮起第4宫(角宫);该星入旺星座的主星金星在月亮起第10宫(角宫)",
formation_evidence: { planet: "Moon", self_reference_only: false,
cancellation_reasons: [{ condition: "dispositor_kendra_from_moon", planet: "Mars", reference: "Moon", self_reference: false }] },
formation_assessment: { status: "formed_under_source" },
};
const groups = buildYogaGroups({ rows: [row], planets: moonChart, ascendant: "Aries" })!;
const cards = groups.support.filter((c) => c.id.startsWith("neecha:"));
assert.deepEqual(cards.map((c) => c.id), ["neecha:Moon"]);
assert.match(cards[0]!.text, /缓解来自:落陷星座主星火星在月亮起第4宫(角宫);该星入旺星座的主星金星在月亮起第10宫(角宫)/u);
assert.doesNotMatch(cards[0]!.text, /%/u);
});
test("item 8: engine participants draw the actual chart; an inferred diagram is captioned as an illustration", () => {
const withParticipants = { rule_id: "dhana_yoga", name: "Dhana Yoga", name_cn: "财富格局", category: "dhana",
planets: ["Jupiter", "Saturn"], reader_condition_zh: "财富宫主星落入财富宫", formation_assessment: { status: "formed_under_source" } };
const inferred = { rule_id: "bvr_sumukha_precise", name: "Sumukha", name_cn: "善面瑜伽", category: "special",
planets: [], reader_condition_zh: "2宫主在角宫", formation_assessment: { status: "formed_under_source" } };
const groups = buildYogaGroups({ rows: [withParticipants, inferred], planets, ascendant: "Cancer" })!;
const actual = groups.formed.find((c) => c.id === "dhana_yoga")!;
const sketch = groups.formed.find((c) => c.id === "bvr_sumukha_precise")!;
assert.doesNotMatch(actual.diagram.label, /^示意/u);
assert.match(sketch.diagram.label, /^示意:/u);
});
+8 -4
View File
@@ -1073,7 +1073,8 @@
"combo_template": "财富宫主星落入财富宫",
"combo_template_en": "Lords of wealth houses placed in wealth houses",
"strength": "中",
"strength_en": "moderate"
"strength_en": "moderate",
"participants_expr": "[w for w in sorted(wl) if w in ctx.planets and house_of(w) in wh]"
},
"effects": [
"财富积累",
@@ -1104,7 +1105,8 @@
"combo_template": "财富宫主星聚宫",
"combo_template_en": "Lords of wealth houses conjoined",
"strength": "强",
"strength_en": "strong"
"strength_en": "strong",
"participants_expr": "[lp for h, lp in lords.items() if lp in ctx.planets and house_of(lp) in (2, 11) and sum(1 for q in lords.values() if q in ctx.planets and house_of(q) == house_of(lp)) >= 2]"
},
"effects": [
"财运亨通",
@@ -1565,7 +1567,8 @@
"type": "custom",
"expr": "\npairs = [(6,8), (6,12), (8,12)]\nmatched = []\nfor h1, h2 in pairs:\n l1 = lord(h1)\n l2 = lord(h2)\n if l1 in ctx.planets and l2 in ctx.planets:\n if house_of(l1) == h2 and house_of(l2) == h1:\n matched.append((h1, h2, l1, l2))\nmatched\n",
"combo_template": "凶宫主星互落",
"combo_template_en": "Dusthana lords placed in each other's houses"
"combo_template_en": "Dusthana lords placed in each other's houses",
"participants_expr": "[p for m in matched for p in m[2:]]"
},
"effects": [
"因祸得福",
@@ -12483,7 +12486,8 @@
"logic": {
"type": "custom",
"expr": "\n# PyJHora/BVR-238: Lords of Lagna and 7th in conjunction or mutual graha aspect.\nl1 = lord(1)\nl7 = lord(7)\nif l1 not in ctx.planets or l7 not in ctx.planets:\n False\nelse:\n same_house(l1, l7) or (aspect(l1, l7) and aspect(l7, l1))\n",
"combo_template": "PyJHora aligned source logic"
"combo_template": "PyJHora aligned source logic",
"participants_expr": "[l1, l7]"
},
"effects": [
"既有规则的传统描述(非个人事实或结果保证):与多位女性交往"
+40 -2
View File
@@ -349,7 +349,28 @@ def parivartana_class(house_a: int, house_b: int) -> Optional[str]:
return 'maha'
# BUG-2392 (占星师 2026-11-25 复核第五项; owner approved this frozen-file change): a kendra–trikona lord
# Raja yoga whose structure is satisfied on the chart is formed (「成立」). Was: no reviewed contract,
# so every hit stayed `candidate` (`source_definition_not_reviewed`). A lord that also rules the
# 6th, 8th or 12th is a modifier written beside it (`formation_modifiers`), not a reason to withhold it.
RAJA_STRUCTURAL_RULES = frozenset({
'raja_yoga', 'raja_yoga_parivartana', 'dharma_karmadhipati', 'dharma_karmadhipati_parivartana',
'raja_yoga_1_4', 'raja_yoga_5_9', 'raja_yoga_4_9', 'raja_yoga_mutual_aspect', 'raja_yoga_1_10',
'raja_yoga_7_9', 'raja_yoga_5_10_lord',
})
RAJA_STRUCTURAL_PROFILE = 'kendra_trikona_lord_structure'
def _product_formation_contract(rule_id: str) -> Optional[dict[str, Any]]:
if rule_id in RAJA_STRUCTURAL_RULES:
return {
'profile': RAJA_STRUCTURAL_PROFILE, 'name': None,
'source': {'title': 'BPHS', 'section': 'Raja yoga (kendra and trikona lords)'},
# The rule's own executed definition is the definition (no second detector).
'definition': None,
'required': ['d1_scope', 'consistent_geometry', 'lord_structure'],
'variant_boundary': '角宫主与三方宫主按本条规则结合;兼管第 6、8、12 宫的宫主写在修正里。',
}
for kind in PARIVARTANA_CLASSES:
if rule_id == f'{kind}_parivartana_yoga':
return {
@@ -379,7 +400,8 @@ def _assess_product_contract(row: dict[str, Any], contract: dict[str, Any]) -> d
missing = [key for key in required if key not in satisfied and key not in failed]
issues = []
if (row.get('formation_source_profile') != contract['profile'] or
evidence.get('definition') != contract['definition']):
(evidence.get('definition') != contract['definition'] if contract['definition'] is not None
else not evidence.get('definition'))):
issues.append('source_definition_mismatch')
if len(by_id) != len(checks):
issues.append('duplicate_condition_evidence')
@@ -393,7 +415,7 @@ def _assess_product_contract(row: dict[str, Any], contract: dict[str, Any]) -> d
formed = not issues and not missing and not failed
return {
'status': 'formed_under_source' if formed else 'conditions_not_met' if failed else 'candidate',
'name': contract['name'], 'source_profile': contract['profile'], 'source': dict(contract['source']),
'name': contract['name'] or row.get('name'), 'source_profile': contract['profile'], 'source': dict(contract['source']),
'required_conditions': list(required), 'satisfied_conditions': satisfied,
'missing_conditions': missing, 'failed_conditions': failed,
'review_issues': issues, 'checks': checks, 'variant_boundary': contract['variant_boundary'],
@@ -1892,6 +1914,22 @@ class YogaEngine:
ctx.is_own_sign('Jupiter') or ctx.is_exalted('Jupiter') or
SIGN_LORDS.get(sign) in FRIENDLY_PLANETS['Jupiter'],
{'planet': 'Jupiter', 'sign': sign, 'friendship': 'natural'})
elif contract.get('profile') == RAJA_STRUCTURAL_PROFILE:
# BUG-2392: the bound lords and the houses each rules; any 6/8/12 lordship is a modifier.
lordships = {p: [h for h in range(1, 13) if ctx.lord_of_house(h) == p] for p in planets_bound}
royal = {p: [h for h in houses if h in (1, 4, 5, 7, 9, 10)] for p, houses in lordships.items()}
check('lord_structure', None if len(planets_bound) < 2 else
len(set(planets_bound)) >= 2 and all(royal.values()),
{'lordships': lordships} if len(planets_bound) >= 2 else None)
modifiers = [{'planet': p, 'houses': [h for h in houses if h in (6, 8, 12)]}
for p, houses in lordships.items() if any(h in (6, 8, 12) for h in houses)]
if modifiers:
entry['formation_modifiers'] = modifiers
entry['formation_note_zh'] = '实际作用有利有弊:' + ','.join(
f"{PLANET_ZH.get(m['planet'], m['planet'])}同时管第 {'、'.join(map(str, m['houses']))} 宫"
for m in modifiers) + '。'
entry['formation_note_en'] = 'Mixed in effect: ' + '; '.join(
f"{m['planet']} also rules house {', '.join(map(str, m['houses']))}" for m in modifiers) + '.'
elif contract.get('profile') == 'phaladeepika_6_parivartana_houses':
# BUG-2388: the two lords sit in each other's signs, and the two houses decide the kind.
pair = [p for p in planets_bound if p in SIGN_LORDS.values()][:2]
+4 -1
View File
@@ -75,7 +75,10 @@ def test_synced_rules_carry_participants_expr_and_name_their_planets():
# 原值:34
# 新值:32
# 原因:BUG-2301 照上游 58f37ee5b,她从 daridra_2、daridra_yoga_combined 去掉了 participants_expr(两条改为取法待核、不给作用)
assert len(carrying) == 32
# 原值:32 / 新值:36 / 原因:BUG-2392(占星师 11-25 第八项)dhana_yoga、grahi_dhana、vipreet_pairs、
# bvr_bahu_sthree_yoga 写明实际命中分支的参与星(产品自加,不是上游同步)
assert len(carrying) == 36
assert {"dhana_yoga", "grahi_dhana", "vipreet_pairs", "bvr_bahu_sthree_yoga"} <= carrying
# Her expression for this rule belongs to a different condition text than ours; not copied.
assert "bvr_matrunasa_precise" not in carrying
+87
View File
@@ -0,0 +1,87 @@
"""BUG-2392: the astrologer's 2026-11-25 review, items 5, 6 and 8 on the engine side (synthetic charts only).
Item 5: a kendra–trikona Raja yoga whose structure holds is formed; a lord that also rules a dusthana is
written as a modifier. Item 6: Neecha Bhanga self-reference is only the Moon measured from itself; a
debilitated Moon with its dispositor in a kendra from the Moon is a real mitigation. Item 8: a custom rule
names the planets of the branch that matched.
"""
from pathlib import Path
import pytest
from scripts.yoga_engine import RAJA_STRUCTURAL_RULES, SIGNS, YogaEngine
RULES = Path(__file__).resolve().parents[1] / "references" / "yoga_rules.json"
@pytest.fixture(scope="module")
def engine():
return YogaEngine(str(RULES))
def chart(ascendant, signs):
asc = SIGNS.index(ascendant)
return {p: {"sign": s, "house": (SIGNS.index(s) - asc) % 12 + 1} for p, s in signs.items()}
def run(engine, ascendant, signs, ids=None):
rows = engine.detect(chart(ascendant, signs), ascendant, context={"chart_type": "D1"})
return [r for r in rows if ids is None or r["rule_id"] in ids]
CANCER = {"Jupiter": "Capricorn", "Saturn": "Pisces", "Sun": "Cancer", "Moon": "Virgo",
"Mars": "Libra", "Mercury": "Leo", "Venus": "Gemini"}
def test_raja_exchange_is_formed_with_its_dusthana_modifier(engine):
rows = {r["rule_id"]: r for r in run(engine, "Cancer", CANCER, RAJA_STRUCTURAL_RULES)}
row = rows["raja_yoga_parivartana"]
assert row["formation_assessment"]["status"] == "formed_under_source"
assert row["formation_assessment"]["review_issues"] == []
checks = {c["id"]: c for c in row["formation_checks"]}
assert checks["lord_structure"]["passed"] is True
assert checks["lord_structure"]["witness"]["lordships"] == {"Jupiter": [6, 9], "Saturn": [7, 8]}
assert row["formation_note_zh"] == "实际作用有利有弊:木星同时管第 6 宫,土星同时管第 8 宫。"
assert "待核" not in row["formation_note_zh"]
def test_a_raja_rule_without_a_second_royal_lord_is_not_formed(engine):
# Aries: Sun (lord of 5) with Moon (lord of 4) in the 4th — formed; the check names both royal lords.
rows = {r["rule_id"]: r for r in run(engine, "Aries", {
"Sun": "Cancer", "Moon": "Cancer", "Mars": "Aries", "Mercury": "Gemini", "Jupiter": "Libra",
"Venus": "Virgo", "Saturn": "Scorpio"}, RAJA_STRUCTURAL_RULES)}
assert rows, "expected a Raja row"
for row in rows.values():
assert row["formation_assessment"]["status"] == "formed_under_source", row["rule_id"]
lordships = {c["id"]: c for c in row["formation_checks"]}["lord_structure"]["witness"]["lordships"]
assert all(any(h in (1, 4, 5, 7, 9, 10) for h in houses) for houses in lordships.values())
def test_debilitated_moon_with_its_dispositor_in_a_kendra_from_the_moon_is_mitigated(engine):
rows = run(engine, "Aries", {"Moon": "Scorpio", "Mars": "Aquarius", "Sun": "Aries", "Jupiter": "Pisces",
"Saturn": "Gemini", "Mercury": "Taurus", "Venus": "Leo"}, {"neechabhanga_basic"})
evidence = rows[0]["formation_evidence"]
assert evidence["planet"] == "Moon"
assert evidence["self_reference_only"] is False
mars = [r for r in evidence["cancellation_reasons"] if r["planet"] == "Mars"]
assert mars and mars[0]["reference"] == "Moon" and mars[0]["self_reference"] is False
assert rows[0]["formation_assessment"]["status"] == "formed_under_source"
assert "火星在月亮起第4宫" in str(rows[0]["combination"])
def test_only_the_moon_measured_from_itself_is_self_reference(engine):
# Jupiter in Capricorn: Moon (lord of Jupiter's exaltation sign Cancer) "in a kendra from the Moon" is the
# tautology; Saturn (lord of Capricorn) in the 7th from the Moon is a separate, real condition.
rows = run(engine, "Cancer", CANCER, {"neechabhanga_basic"})
reasons = rows[0]["formation_evidence"]["cancellation_reasons"]
by = {(r["planet"], r["condition"]): r for r in reasons}
assert by[("Moon", "exaltation_sign_lord_kendra_from_moon")]["self_reference"] is True
assert by[("Saturn", "dispositor_kendra_from_moon")]["self_reference"] is False
assert rows[0]["formation_evidence"]["self_reference_only"] is False
def test_custom_rules_name_the_planets_of_the_matched_branch(engine):
# Aries: lords of 2/5/9/11 are Venus, Sun, Jupiter, Saturn; Jupiter in the 2nd and Venus in the 5th.
rows = run(engine, "Aries", {"Jupiter": "Taurus", "Venus": "Leo", "Sun": "Capricorn", "Saturn": "Gemini",
"Moon": "Aries", "Mars": "Virgo", "Mercury": "Sagittarius"}, {"dhana_yoga"})
assert rows and sorted(rows[0]["planets"]) == ["Jupiter", "Venus"]