sovana-solver 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dag.js CHANGED
@@ -1,13 +1,9 @@
1
1
  import { floorMod } from 'sovana-geo-time';
2
+ import { castZiweiChart, detectPalaceTuHoa, findZiweiPalace, getPalaceGroup, normalizePalaceKey, resolveLaiNhanCung, resolveSihuaPlacements, } from 'sovana-kernel';
2
3
  import { loadSampleRules } from './store.js';
3
- function cmpStr(a, b) {
4
- return a < b ? -1 : a > b ? 1 : 0;
5
- }
4
+ const cmpStr = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
6
5
  function sortedUnique(items) {
7
- if (items.length === 0)
8
- return [];
9
- const set = new Set(items);
10
- return Array.from(set).sort(cmpStr);
6
+ return items.length === 0 ? [] : Array.from(new Set(items)).sort(cmpStr);
11
7
  }
12
8
  const ELEMENT_INDEX = {
13
9
  Mộc: 0,
@@ -16,21 +12,7 @@ const ELEMENT_INDEX = {
16
12
  Kim: 3,
17
13
  Thủy: 4,
18
14
  };
19
- // Branch 0=Tý .. 11=Hợi -> Five Element index (Mộc=0, Hỏa=1, Thổ=2, Kim=3, Thủy=4)
20
- const BRANCH_ELEMENT_INDEX = [
21
- 4, // 0 Tý: Thủy
22
- 2, // 1 Sửu: Thổ
23
- 0, // 2 Dần: Mộc
24
- 0, // 3 Mão: Mộc
25
- 2, // 4 Thìn: Thổ
26
- 1, // 5 Tỵ: Hỏa
27
- 1, // 6 Ngọ: Hỏa
28
- 2, // 7 Mùi: Thổ
29
- 3, // 8 Thân: Kim
30
- 3, // 9 Dậu: Kim
31
- 2, // 10 Tuất: Thổ
32
- 4, // 11 Hợi: Thủy
33
- ];
15
+ const BRANCH_ELEMENT_INDEX = [4, 2, 0, 0, 2, 1, 1, 2, 3, 3, 2, 4];
34
16
  const TIEN_THAN_PAIRS = new Set([
35
17
  '11->0',
36
18
  '2->3',
@@ -49,23 +31,10 @@ const THOAI_THAN_PAIRS = new Set([
49
31
  '7->4',
50
32
  '10->7',
51
33
  ]);
52
- function normalizePalaceKey(name) {
53
- const trimmed = name.trim();
54
- if (trimmed === 'Giao Hữu' || trimmed === 'Nô Bộc')
55
- return 'Nô Bộc';
56
- return trimmed;
57
- }
58
- function findPalace(ziwei, palaceQuery) {
59
- const target = normalizePalaceKey(palaceQuery);
60
- if (target === 'Thân') {
61
- return ziwei.palaces.find((p) => p.isThan || p.branchIndex === ziwei.thanBranch);
62
- }
63
- return ziwei.palaces.find((p) => normalizePalaceKey(p.palaceName) === target);
64
- }
65
- function findPalaceByBranch(ziwei, branchIndex) {
34
+ const findPalaceByBranch = (ziwei, branchIndex) => {
66
35
  const b = floorMod(branchIndex, 12);
67
36
  return ziwei.palaces.find((p) => p.branchIndex === b);
68
- }
37
+ };
69
38
  function palaceHasStarOrTransform(palace, starOrTransform) {
70
39
  for (const s of palace.majorStars) {
71
40
  if (s.name === starOrTransform || s.sihuaTransform === starOrTransform)
@@ -75,39 +44,43 @@ function palaceHasStarOrTransform(palace, starOrTransform) {
75
44
  if (s.name === starOrTransform || s.sihuaTransform === starOrTransform)
76
45
  return true;
77
46
  }
78
- if (palace.thaiTueStar === starOrTransform ||
47
+ return (palace.thaiTueStar === starOrTransform ||
79
48
  palace.trangSinhStar === starOrTransform ||
80
- palace.bacSyStar === starOrTransform) {
81
- return true;
82
- }
83
- return false;
49
+ palace.bacSyStar === starOrTransform);
84
50
  }
51
+ const bacPhaiCache = new WeakMap();
85
52
  function selectZiweiChart(chart, ruleSilo, explicitSilo) {
86
- const siloId = explicitSilo !== undefined ? explicitSilo : ruleSilo === 'toan-thu' ? 'toan-thu' : 'nam-phai';
87
- return {
88
- siloId,
89
- ziwei: siloId === 'toan-thu' ? chart.ziweiToanThu : chart.ziweiNamPhai,
90
- };
53
+ const siloId = explicitSilo ||
54
+ (ruleSilo === 'toan-thu' || ruleSilo === 'bac-phai-phi-tinh' ? ruleSilo : 'nam-phai');
55
+ if (siloId === 'toan-thu')
56
+ return { siloId, ziwei: chart.ziweiToanThu };
57
+ if (siloId === 'bac-phai-phi-tinh') {
58
+ let ziwei = chart.ziweiBacPhaiPhiTinh ?? bacPhaiCache.get(chart);
59
+ if (!ziwei) {
60
+ ziwei = castZiweiChart(chart.temporal, chart.gender, 'bac-phai-phi-tinh', chart.ziweiNamPhai.luuNien?.targetYear);
61
+ bacPhaiCache.set(chart, ziwei);
62
+ }
63
+ return { siloId, ziwei };
64
+ }
65
+ return { siloId, ziwei: chart.ziweiNamPhai };
91
66
  }
92
67
  function baziHasTenGod(chart, tenGod) {
93
- const pillars = [
94
- chart.bazi.yearPillar,
95
- chart.bazi.monthPillar,
96
- chart.bazi.dayPillar,
97
- chart.bazi.hourPillar,
98
- ];
99
- for (const p of pillars) {
100
- if (p.position !== 'day' && p.stemTenGod === tenGod) {
68
+ const { yearPillar, monthPillar, dayPillar, hourPillar } = chart.bazi;
69
+ for (const p of [yearPillar, monthPillar, dayPillar, hourPillar]) {
70
+ if (p.position !== 'day' && p.stemTenGod === tenGod)
71
+ return true;
72
+ if (p.hiddenStems.some((hs) => hs.tenGod === tenGod))
101
73
  return true;
102
- }
103
- for (const hs of p.hiddenStems) {
104
- if (hs.tenGod === tenGod) {
105
- return true;
106
- }
107
- }
108
74
  }
109
75
  return false;
110
76
  }
77
+ const elStep = (fromEl, toEl, step) => {
78
+ if (!fromEl || !toEl)
79
+ return false;
80
+ const a = ELEMENT_INDEX[fromEl];
81
+ const b = ELEMENT_INDEX[toEl];
82
+ return a !== undefined && b !== undefined && (a + step) % 5 === b;
83
+ };
111
84
  function computeTheUngRelation(chart) {
112
85
  const ly = chart.liuyao;
113
86
  if (!ly)
@@ -136,6 +109,13 @@ function evalLiuyaoFlag(chart, flag) {
136
109
  return false;
137
110
  const theLine = ly.lines.find((l) => l.isThe);
138
111
  const ungLine = ly.lines.find((l) => l.isUng);
112
+ const isTheVT = () => {
113
+ if (!theLine)
114
+ return false;
115
+ const eThe = ELEMENT_INDEX[theLine.elementVi];
116
+ const eMonth = BRANCH_ELEMENT_INDEX[floorMod(ly.monthBranchIndex, 12)];
117
+ return eThe !== undefined && eMonth !== undefined && (eThe === eMonth || (eMonth + 1) % 5 === eThe);
118
+ };
139
119
  switch (flag) {
140
120
  case 'theTuanKhong':
141
121
  return Boolean(theLine?.isTuanKhong);
@@ -150,211 +130,234 @@ function evalLiuyaoFlag(chart, flag) {
150
130
  case 'ungDong':
151
131
  return Boolean(ungLine?.isMoving);
152
132
  case 'hoaTienThan':
153
- return ly.lines.some((l) => l.isMoving &&
154
- l.transformedBranchIndex !== null &&
155
- TIEN_THAN_PAIRS.has(`${l.branchIndex}->${l.transformedBranchIndex}`));
156
- case 'hoaThoaiThan':
157
- return ly.lines.some((l) => l.isMoving &&
158
- l.transformedBranchIndex !== null &&
159
- THOAI_THAN_PAIRS.has(`${l.branchIndex}->${l.transformedBranchIndex}`));
133
+ case 'hoaThoaiThan': {
134
+ const pairs = flag === 'hoaTienThan' ? TIEN_THAN_PAIRS : THOAI_THAN_PAIRS;
135
+ return ly.lines.some((l) => l.isMoving && l.transformedBranchIndex !== null && pairs.has(`${l.branchIndex}->${l.transformedBranchIndex}`));
136
+ }
160
137
  case 'hoaHoiDauSinh':
161
- return ly.lines.some((l) => {
162
- if (!l.isMoving || l.transformedElementVi === null)
163
- return false;
164
- const ePrim = ELEMENT_INDEX[l.elementVi];
165
- const eTrans = ELEMENT_INDEX[l.transformedElementVi];
166
- return ePrim !== undefined && eTrans !== undefined && (eTrans + 1) % 5 === ePrim;
167
- });
168
- case 'hoaHoiDauKhac':
169
- return ly.lines.some((l) => {
170
- if (!l.isMoving || l.transformedElementVi === null)
171
- return false;
172
- const ePrim = ELEMENT_INDEX[l.elementVi];
173
- const eTrans = ELEMENT_INDEX[l.transformedElementVi];
174
- return ePrim !== undefined && eTrans !== undefined && (eTrans + 2) % 5 === ePrim;
175
- });
138
+ case 'hoaHoiDauKhac': {
139
+ const step = flag === 'hoaHoiDauSinh' ? 1 : 2;
140
+ return ly.lines.some((l) => l.isMoving && elStep(l.transformedElementVi, l.elementVi, step));
141
+ }
176
142
  case 'theVuongTuong':
143
+ return Boolean(theLine && isTheVT());
177
144
  case 'theHuuTu': {
178
145
  if (!theLine)
179
146
  return false;
180
147
  const eThe = ELEMENT_INDEX[theLine.elementVi];
181
148
  const eMonth = BRANCH_ELEMENT_INDEX[floorMod(ly.monthBranchIndex, 12)];
182
- if (eThe === undefined || eMonth === undefined)
183
- return false;
184
- const isVT = eThe === eMonth || (eMonth + 1) % 5 === eThe;
185
- return flag === 'theVuongTuong' ? isVT : !isVT;
149
+ return eThe !== undefined && eMonth !== undefined && !(eThe === eMonth || (eMonth + 1) % 5 === eThe);
186
150
  }
187
151
  case 'hasPhucThan':
188
152
  return ly.phucThan.length > 0;
189
153
  case 'phiSinhPhuc':
190
- return ly.phucThan.some((p) => {
191
- const a = ELEMENT_INDEX[p.phiThanElementVi];
192
- const b = ELEMENT_INDEX[p.elementVi];
193
- return a !== undefined && b !== undefined && (a + 1) % 5 === b;
194
- });
154
+ return ly.phucThan.some((p) => elStep(p.phiThanElementVi, p.elementVi, 1));
195
155
  case 'phiKhacPhuc':
196
- return ly.phucThan.some((p) => {
197
- const a = ELEMENT_INDEX[p.phiThanElementVi];
198
- const b = ELEMENT_INDEX[p.elementVi];
199
- return a !== undefined && b !== undefined && (a + 2) % 5 === b;
200
- });
156
+ return ly.phucThan.some((p) => elStep(p.phiThanElementVi, p.elementVi, 2));
201
157
  case 'phiLamKhongPha':
202
158
  return ly.phucThan.some((p) => {
203
159
  const line = ly.lines[p.lineNumber - 1];
204
160
  return line !== undefined && (line.isTuanKhong || line.isNguyetPha);
205
161
  });
206
- case 'theAmDong': {
207
- if (!theLine || theLine.isMoving)
208
- return false;
209
- const eThe = ELEMENT_INDEX[theLine.elementVi];
210
- const eMonth = BRANCH_ELEMENT_INDEX[floorMod(ly.monthBranchIndex, 12)];
211
- if (eThe === undefined || eMonth === undefined)
212
- return false;
213
- const isVT = eThe === eMonth || (eMonth + 1) % 5 === eThe;
214
- return isVT && floorMod(ly.nhatThanBranch + 6, 12) === theLine.branchIndex;
215
- }
162
+ case 'theAmDong':
163
+ return Boolean(theLine && !theLine.isMoving && isTheVT() && floorMod(ly.nhatThanBranch + 6, 12) === theLine.branchIndex);
216
164
  }
217
165
  }
218
- const UNMATCHED = {
219
- matched: false,
220
- cost: 0,
221
- parents: [],
222
- facts: [],
223
- };
166
+ const UNMATCHED = { matched: false, cost: 0, parents: [], facts: [] };
167
+ const ok = (fact, cost = 0, parents = []) => ({
168
+ matched: true,
169
+ cost,
170
+ parents,
171
+ facts: [fact],
172
+ });
224
173
  function evaluateCondition(cond, chart, ruleSilo, derivedMap) {
225
174
  switch (cond.op) {
226
- case 'star_in_palace': {
227
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
228
- const p = findPalace(ziwei, cond.palace);
229
- if (!p || !palaceHasStarOrTransform(p, cond.star))
175
+ case 'year_stem_in': {
176
+ const yStem = ruleSilo === 'bazi'
177
+ ? chart.temporal.pillars.baziYearPillar.stemIndex
178
+ : chart.temporal.pillars.lunarYearPillar.stemIndex;
179
+ return cond.stems.includes(yStem) ? ok(`stem:year:${yStem}`) : UNMATCHED;
180
+ }
181
+ case 'bazi_strength_is':
182
+ return chart.bazi.strengthClass === cond.value ? ok(`bazi:strength:${cond.value}`) : UNMATCHED;
183
+ case 'day_stem_in': {
184
+ const dStem = chart.temporal.pillars.dayPillar.stemIndex;
185
+ return cond.stems.includes(dStem) ? ok(`bazi:day_stem:${dStem}`) : UNMATCHED;
186
+ }
187
+ case 'month_branch_in': {
188
+ const mBranch = chart.temporal.pillars.baziMonthPillar.branchIndex;
189
+ return cond.branches.includes(mBranch) ? ok(`bazi:month_branch:${mBranch}`) : UNMATCHED;
190
+ }
191
+ case 'bazi_has_ten_god':
192
+ return baziHasTenGod(chart, cond.tenGod) ? ok(`bazi:ten_god:${cond.tenGod}`) : UNMATCHED;
193
+ case 'liuyao_has_moving':
194
+ return chart.liuyao && (chart.liuyao.movingLines.length > 0) === cond.value
195
+ ? ok(`liuyao:has_moving:${String(cond.value)}`)
196
+ : UNMATCHED;
197
+ case 'liuyao_the_ung_relation':
198
+ return computeTheUngRelation(chart) === cond.relation
199
+ ? ok(`liuyao:the_ung:${cond.relation}`)
200
+ : UNMATCHED;
201
+ case 'liuyao_state_flag':
202
+ return evalLiuyaoFlag(chart, cond.flag) ? ok(`liuyao:flag:${cond.flag}`) : UNMATCHED;
203
+ case 'derived_node': {
204
+ const parent = derivedMap.get(cond.nodeId);
205
+ return parent ? ok(`derived:${cond.nodeId}`, parent.proofDepth, [cond.nodeId]) : UNMATCHED;
206
+ }
207
+ case 'and': {
208
+ if (cond.args.length === 0)
209
+ return { matched: true, cost: 0, parents: [], facts: [] };
210
+ let maxCost = 0;
211
+ const allParents = [];
212
+ const allFacts = [];
213
+ for (const arg of cond.args) {
214
+ const sub = evaluateCondition(arg, chart, ruleSilo, derivedMap);
215
+ if (!sub.matched)
216
+ return UNMATCHED;
217
+ if (sub.cost > maxCost)
218
+ maxCost = sub.cost;
219
+ allParents.push(...sub.parents);
220
+ allFacts.push(...sub.facts);
221
+ }
222
+ return { matched: true, cost: maxCost, parents: sortedUnique(allParents), facts: sortedUnique(allFacts) };
223
+ }
224
+ case 'or': {
225
+ const matchedSubs = [];
226
+ for (const arg of cond.args) {
227
+ const sub = evaluateCondition(arg, chart, ruleSilo, derivedMap);
228
+ if (sub.matched)
229
+ matchedSubs.push(sub);
230
+ }
231
+ if (matchedSubs.length === 0)
232
+ return UNMATCHED;
233
+ let minCost = matchedSubs[0].cost;
234
+ for (const sub of matchedSubs)
235
+ if (sub.cost < minCost)
236
+ minCost = sub.cost;
237
+ const bestParents = [];
238
+ const bestFacts = [];
239
+ for (const sub of matchedSubs) {
240
+ if (sub.cost === minCost) {
241
+ bestParents.push(...sub.parents);
242
+ bestFacts.push(...sub.facts);
243
+ }
244
+ }
245
+ return { matched: true, cost: minCost, parents: sortedUnique(bestParents), facts: sortedUnique(bestFacts) };
246
+ }
247
+ case 'not':
248
+ return evaluateCondition(cond.arg, chart, ruleSilo, derivedMap).matched
249
+ ? UNMATCHED
250
+ : ok(`not:${cond.arg.op}`);
251
+ }
252
+ const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
253
+ switch (cond.op) {
254
+ case 'palace_flies_sihua_to': {
255
+ const src = findZiweiPalace(ziwei, cond.fromPalace);
256
+ const dst = findZiweiPalace(ziwei, cond.toPalace);
257
+ const hit = src && dst ? resolveSihuaPlacements(ziwei, src.stemIndex).find((p) => p.transform === cond.transform) : undefined;
258
+ if (!hit || !dst)
259
+ return UNMATCHED;
260
+ const mode = cond.mode || 'NHAP_CUNG';
261
+ const isNhap = hit.branchIndex === dst.branchIndex;
262
+ const isXung = (hit.branchIndex + 6) % 12 === dst.branchIndex;
263
+ return (mode === 'NHAP_CUNG' ? isNhap : mode === 'XUNG_CHIEU' ? isXung : isNhap || isXung)
264
+ ? ok(`ziwei:${siloId}:${cond.op}:${cond.fromPalace}:${cond.toPalace}:${cond.transform}:${mode}`)
265
+ : UNMATCHED;
266
+ }
267
+ case 'palace_has_tu_hoa': {
268
+ const pal = findZiweiPalace(ziwei, cond.palace);
269
+ if (!pal)
230
270
  return UNMATCHED;
231
- return {
232
- matched: true,
233
- cost: 0,
234
- parents: [],
235
- facts: [`ziwei:${siloId}:star_in_palace:${cond.palace}:${cond.star}`],
236
- };
271
+ const th = detectPalaceTuHoa(ziwei, pal.branchIndex);
272
+ const dir = cond.direction || 'ANY';
273
+ const tr = cond.transform;
274
+ const hit = (es) => es.some((e) => !tr || e.transform === tr);
275
+ const matched = dir === 'LY_TAM'
276
+ ? hit(th.selfTransforms)
277
+ : dir === 'HUONG_TAM'
278
+ ? hit(th.centripetalTransforms)
279
+ : dir === 'SONG_TU_HOA'
280
+ ? th.hasSongTuHoa && (!tr || hit(th.selfTransforms) || hit(th.centripetalTransforms))
281
+ : hit(th.selfTransforms) || hit(th.centripetalTransforms);
282
+ return matched ? ok(`ziwei:${siloId}:${cond.op}:${cond.palace}:${dir}:${tr || '*'}`) : UNMATCHED;
283
+ }
284
+ case 'lai_nhan_cung_in': {
285
+ const ln = resolveLaiNhanCung(ziwei, chart.temporal.pillars.lunarYearPillar.stemIndex);
286
+ const pal = ziwei.palaces[ln.primaryBranchIndex];
287
+ const group = getPalaceGroup(pal.palaceName);
288
+ if (cond.palaceGroup != null && group !== cond.palaceGroup)
289
+ return UNMATCHED;
290
+ if (cond.palaces != null &&
291
+ !cond.palaces.some((q) => normalizePalaceKey(q) === 'Thân' ? pal.isThan : normalizePalaceKey(q) === normalizePalaceKey(pal.palaceName))) {
292
+ return UNMATCHED;
293
+ }
294
+ return ok(`ziwei:${siloId}:${cond.op}:${pal.palaceName}:${group}`);
295
+ }
296
+ case 'star_in_palace': {
297
+ const p = findZiweiPalace(ziwei, cond.palace);
298
+ return p && palaceHasStarOrTransform(p, cond.star)
299
+ ? ok(`ziwei:${siloId}:star_in_palace:${cond.palace}:${cond.star}`)
300
+ : UNMATCHED;
237
301
  }
238
302
  case 'star_in_tam_phuong': {
239
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
240
- const basePalace = findPalace(ziwei, cond.palace);
241
- if (!basePalace)
303
+ const base = findZiweiPalace(ziwei, cond.palace);
304
+ if (!base)
242
305
  return UNMATCHED;
243
- const b = basePalace.branchIndex;
244
- const branches = [b, (b + 4) % 12, (b + 8) % 12, (b + 6) % 12];
245
- const hit = branches.some((br) => {
306
+ const b = base.branchIndex;
307
+ const hit = [b, (b + 4) % 12, (b + 8) % 12, (b + 6) % 12].some((br) => {
246
308
  const pal = findPalaceByBranch(ziwei, br);
247
309
  return pal !== undefined && palaceHasStarOrTransform(pal, cond.star);
248
310
  });
249
- if (!hit)
250
- return UNMATCHED;
251
- return {
252
- matched: true,
253
- cost: 0,
254
- parents: [],
255
- facts: [`ziwei:${siloId}:star_in_tam_phuong:${cond.palace}:${cond.star}`],
256
- };
311
+ return hit ? ok(`ziwei:${siloId}:star_in_tam_phuong:${cond.palace}:${cond.star}`) : UNMATCHED;
257
312
  }
258
313
  case 'star_brightness_in': {
259
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
260
- const searchPalaces = cond.palace !== undefined && cond.palace.length > 0
314
+ const pal = cond.palace != null && cond.palace.length > 0 ? cond.palace : null;
315
+ const searchPalaces = pal
261
316
  ? (() => {
262
- const p = findPalace(ziwei, cond.palace);
317
+ const p = findZiweiPalace(ziwei, pal);
263
318
  return p ? [p] : [];
264
319
  })()
265
320
  : ziwei.palaces;
266
321
  for (const p of searchPalaces) {
267
- const allStars = [...p.majorStars, ...p.minorStars];
268
- for (const s of allStars) {
269
- if (s.name === cond.star || s.sihuaTransform === cond.star) {
270
- if (s.brightness !== null && cond.levels.includes(s.brightness)) {
271
- const palLabel = cond.palace !== undefined && cond.palace.length > 0 ? cond.palace : '*';
272
- return {
273
- matched: true,
274
- cost: 0,
275
- parents: [],
276
- facts: [`ziwei:${siloId}:star_brightness_in:${palLabel}:${cond.star}:${s.brightness}`],
277
- };
278
- }
322
+ for (const s of [...p.majorStars, ...p.minorStars]) {
323
+ if ((s.name === cond.star || s.sihuaTransform === cond.star) && s.brightness !== null && cond.levels.includes(s.brightness)) {
324
+ return ok(`ziwei:${siloId}:star_brightness_in:${pal ?? '*'}:${cond.star}:${s.brightness}`);
279
325
  }
280
326
  }
281
327
  }
282
328
  return UNMATCHED;
283
329
  }
284
330
  case 'sihua_in_palace': {
285
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
286
- const p = findPalace(ziwei, cond.palace);
287
- if (!p || !palaceHasStarOrTransform(p, cond.transform))
288
- return UNMATCHED;
289
- return {
290
- matched: true,
291
- cost: 0,
292
- parents: [],
293
- facts: [`ziwei:${siloId}:sihua_in_palace:${cond.palace}:${cond.transform}`],
294
- };
331
+ const p = findZiweiPalace(ziwei, cond.palace);
332
+ return p && palaceHasStarOrTransform(p, cond.transform)
333
+ ? ok(`ziwei:${siloId}:sihua_in_palace:${cond.palace}:${cond.transform}`)
334
+ : UNMATCHED;
295
335
  }
296
336
  case 'palace_has_flag': {
297
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
298
- const p = findPalace(ziwei, cond.palace);
299
- if (!p)
300
- return UNMATCHED;
301
- const flagVal = cond.flag === 'tuanTrung' ? p.tuanTrung : p.trietLo;
302
- if (!flagVal)
303
- return UNMATCHED;
304
- return {
305
- matched: true,
306
- cost: 0,
307
- parents: [],
308
- facts: [`ziwei:${siloId}:palace_has_flag:${cond.palace}:${cond.flag}`],
309
- };
337
+ const p = findZiweiPalace(ziwei, cond.palace);
338
+ return p && (cond.flag === 'tuanTrung' ? p.tuanTrung : p.trietLo)
339
+ ? ok(`ziwei:${siloId}:palace_has_flag:${cond.palace}:${cond.flag}`)
340
+ : UNMATCHED;
310
341
  }
311
342
  case 'palace_branch_in': {
312
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
313
- const p = findPalace(ziwei, cond.palace);
314
- if (!p || !cond.branches.includes(p.branchIndex))
315
- return UNMATCHED;
316
- return {
317
- matched: true,
318
- cost: 0,
319
- parents: [],
320
- facts: [`ziwei:${siloId}:palace_branch_in:${cond.palace}:${p.branchIndex}`],
321
- };
343
+ const p = findZiweiPalace(ziwei, cond.palace);
344
+ return p && cond.branches.includes(p.branchIndex)
345
+ ? ok(`ziwei:${siloId}:palace_branch_in:${cond.palace}:${p.branchIndex}`)
346
+ : UNMATCHED;
322
347
  }
323
348
  case 'star_in_relative_palace': {
324
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
325
- const basePalace = findPalace(ziwei, cond.palace);
326
- if (!basePalace)
327
- return UNMATCHED;
328
- const b = basePalace.branchIndex;
329
- let targetBranch;
330
- switch (cond.relation) {
331
- case 'opposite':
332
- targetBranch = (b + 6) % 12;
333
- break;
334
- case 'prev':
335
- targetBranch = (b + 11) % 12;
336
- break;
337
- case 'next':
338
- targetBranch = (b + 1) % 12;
339
- break;
340
- case 'nhi_hop':
341
- targetBranch = (13 - b) % 12;
342
- break;
343
- }
344
- const targetPalace = findPalaceByBranch(ziwei, targetBranch);
345
- if (!targetPalace || !palaceHasStarOrTransform(targetPalace, cond.star)) {
349
+ const base = findZiweiPalace(ziwei, cond.palace);
350
+ if (!base)
346
351
  return UNMATCHED;
347
- }
348
- return {
349
- matched: true,
350
- cost: 0,
351
- parents: [],
352
- facts: [`ziwei:${siloId}:star_in_relative_palace:${cond.palace}:${cond.relation}:${cond.star}`],
353
- };
352
+ const b = base.branchIndex;
353
+ const off = { opposite: b + 6, prev: b + 11, next: b + 1, nhi_hop: 13 - b }[cond.relation];
354
+ const target = findPalaceByBranch(ziwei, off % 12);
355
+ return target && palaceHasStarOrTransform(target, cond.star)
356
+ ? ok(`ziwei:${siloId}:star_in_relative_palace:${cond.palace}:${cond.relation}:${cond.star}`)
357
+ : UNMATCHED;
354
358
  }
355
359
  case 'palace_major_count': {
356
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
357
- const p = findPalace(ziwei, cond.palace);
360
+ const p = findZiweiPalace(ziwei, cond.palace);
358
361
  if (!p)
359
362
  return UNMATCHED;
360
363
  const count = p.majorStars.length;
@@ -363,316 +366,90 @@ function evaluateCondition(cond, chart, ruleSilo, derivedMap) {
363
366
  (cond.max != null && count > cond.max)) {
364
367
  return UNMATCHED;
365
368
  }
366
- return {
367
- matched: true,
368
- cost: 0,
369
- parents: [],
370
- facts: [`ziwei:${siloId}:palace_major_count:${cond.palace}:${count}`],
371
- };
369
+ return ok(`ziwei:${siloId}:palace_major_count:${cond.palace}:${count}`);
372
370
  }
373
371
  case 'palace_star_count_in': {
374
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
375
- const p = findPalace(ziwei, cond.palace);
372
+ const p = findZiweiPalace(ziwei, cond.palace);
376
373
  if (!p)
377
374
  return UNMATCHED;
378
375
  let count = 0;
379
- for (const s of new Set(cond.stars)) {
376
+ for (const s of new Set(cond.stars))
380
377
  if (palaceHasStarOrTransform(p, s))
381
378
  count++;
382
- }
383
- if (count < cond.min || (cond.max != null && count > cond.max)) {
384
- return UNMATCHED;
385
- }
386
- return {
387
- matched: true,
388
- cost: 0,
389
- parents: [],
390
- facts: [`ziwei:${siloId}:palace_star_count_in:${cond.palace}:${count}`],
391
- };
379
+ return count < cond.min || (cond.max != null && count > cond.max)
380
+ ? UNMATCHED
381
+ : ok(`ziwei:${siloId}:palace_star_count_in:${cond.palace}:${count}`);
392
382
  }
393
383
  case 'star_co_located': {
394
384
  const uniq = sortedUnique(cond.stars);
395
385
  if (uniq.length === 0)
396
386
  return UNMATCHED;
397
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
398
- const sortedJoined = uniq.join('+');
387
+ const joined = uniq.join('+');
399
388
  if (cond.palace != null && cond.palace.length > 0) {
400
- const p = findPalace(ziwei, cond.palace);
401
- if (!p || !uniq.every((s) => palaceHasStarOrTransform(p, s)))
402
- return UNMATCHED;
403
- return {
404
- matched: true,
405
- cost: 0,
406
- parents: [],
407
- facts: [`ziwei:${siloId}:star_co_located:${cond.palace}:${sortedJoined}`],
408
- };
389
+ const p = findZiweiPalace(ziwei, cond.palace);
390
+ return p && uniq.every((s) => palaceHasStarOrTransform(p, s))
391
+ ? ok(`ziwei:${siloId}:star_co_located:${cond.palace}:${joined}`)
392
+ : UNMATCHED;
409
393
  }
410
- const sortedPalaces = [...ziwei.palaces].sort((a, b) => a.branchIndex - b.branchIndex);
411
- const hit = sortedPalaces.find((p) => uniq.every((s) => palaceHasStarOrTransform(p, s)));
412
- if (!hit)
413
- return UNMATCHED;
414
- return {
415
- matched: true,
416
- cost: 0,
417
- parents: [],
418
- facts: [`ziwei:${siloId}:star_co_located:palace_${hit.branchIndex}:${sortedJoined}`],
419
- };
394
+ const hit = [...ziwei.palaces]
395
+ .sort((a, b) => a.branchIndex - b.branchIndex)
396
+ .find((p) => uniq.every((s) => palaceHasStarOrTransform(p, s)));
397
+ return hit ? ok(`ziwei:${siloId}:star_co_located:palace_${hit.branchIndex}:${joined}`) : UNMATCHED;
420
398
  }
421
399
  case 'vo_chinh_dieu': {
422
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
423
- const p = findPalace(ziwei, cond.palace);
424
- if (!p || p.voChinhDieu !== cond.value)
425
- return UNMATCHED;
426
- return {
427
- matched: true,
428
- cost: 0,
429
- parents: [],
430
- facts: [`ziwei:${siloId}:vo_chinh_dieu:${cond.palace}:${String(cond.value)}`],
431
- };
400
+ const p = findZiweiPalace(ziwei, cond.palace);
401
+ return p && p.voChinhDieu === cond.value
402
+ ? ok(`ziwei:${siloId}:vo_chinh_dieu:${cond.palace}:${String(cond.value)}`)
403
+ : UNMATCHED;
432
404
  }
433
405
  case 'tam_khong_in_tam_phuong': {
434
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
435
- const basePalace = findPalace(ziwei, cond.palace);
436
- if (!basePalace)
406
+ const base = findZiweiPalace(ziwei, cond.palace);
407
+ if (!base)
437
408
  return UNMATCHED;
438
- const b = basePalace.branchIndex;
409
+ const b = base.branchIndex;
439
410
  const found = new Set();
440
411
  for (const br of [b, (b + 4) % 12, (b + 8) % 12, (b + 6) % 12]) {
441
412
  const pal = findPalaceByBranch(ziwei, br);
442
- if (pal) {
443
- for (const tok of pal.tamKhongTypes) {
413
+ if (pal)
414
+ for (const tok of pal.tamKhongTypes)
444
415
  found.add(tok);
445
- }
446
- }
447
416
  }
448
- const count = found.size;
449
- if (count < cond.minCount)
450
- return UNMATCHED;
451
- return {
452
- matched: true,
453
- cost: 0,
454
- parents: [],
455
- facts: [`ziwei:${siloId}:tam_khong_in_tam_phuong:${cond.palace}:${count}`],
456
- };
417
+ return found.size < cond.minCount
418
+ ? UNMATCHED
419
+ : ok(`ziwei:${siloId}:tam_khong_in_tam_phuong:${cond.palace}:${found.size}`);
457
420
  }
458
421
  case 'thai_tue_tu_linh': {
459
- const { siloId, ziwei } = selectZiweiChart(chart, ruleSilo, cond.silo);
460
422
  const tt = ziwei.thaiTueTamHopTuLinh;
461
423
  const hasTuLinh = cond.scope === 'tam_hop' ? tt.hasFullTuLinhInMenhTamHop : tt.hasFullTuLinhInMenhTamPhuong;
462
- if (!tt.menhInThaiTueTamHop || !hasTuLinh)
463
- return UNMATCHED;
464
- return {
465
- matched: true,
466
- cost: 0,
467
- parents: [],
468
- facts: [`ziwei:${siloId}:thai_tue_tu_linh:${cond.scope}`],
469
- };
470
- }
471
- case 'year_stem_in': {
472
- const yStem = ruleSilo === 'bazi'
473
- ? chart.temporal.pillars.baziYearPillar.stemIndex
474
- : chart.temporal.pillars.lunarYearPillar.stemIndex;
475
- if (!cond.stems.includes(yStem))
476
- return UNMATCHED;
477
- return {
478
- matched: true,
479
- cost: 0,
480
- parents: [],
481
- facts: [`stem:year:${yStem}`],
482
- };
483
- }
484
- case 'bazi_strength_is': {
485
- if (chart.bazi.strengthClass !== cond.value)
486
- return UNMATCHED;
487
- return {
488
- matched: true,
489
- cost: 0,
490
- parents: [],
491
- facts: [`bazi:strength:${cond.value}`],
492
- };
493
- }
494
- case 'day_stem_in': {
495
- const dStem = chart.temporal.pillars.dayPillar.stemIndex;
496
- if (!cond.stems.includes(dStem))
497
- return UNMATCHED;
498
- return {
499
- matched: true,
500
- cost: 0,
501
- parents: [],
502
- facts: [`bazi:day_stem:${dStem}`],
503
- };
504
- }
505
- case 'month_branch_in': {
506
- const mBranch = chart.temporal.pillars.baziMonthPillar.branchIndex;
507
- if (!cond.branches.includes(mBranch))
508
- return UNMATCHED;
509
- return {
510
- matched: true,
511
- cost: 0,
512
- parents: [],
513
- facts: [`bazi:month_branch:${mBranch}`],
514
- };
515
- }
516
- case 'bazi_has_ten_god': {
517
- if (!baziHasTenGod(chart, cond.tenGod))
518
- return UNMATCHED;
519
- return {
520
- matched: true,
521
- cost: 0,
522
- parents: [],
523
- facts: [`bazi:ten_god:${cond.tenGod}`],
524
- };
525
- }
526
- case 'liuyao_has_moving': {
527
- if (!chart.liuyao)
528
- return UNMATCHED;
529
- const hasMoving = chart.liuyao.movingLines.length > 0;
530
- if (hasMoving !== cond.value)
531
- return UNMATCHED;
532
- return {
533
- matched: true,
534
- cost: 0,
535
- parents: [],
536
- facts: [`liuyao:has_moving:${String(cond.value)}`],
537
- };
538
- }
539
- case 'liuyao_the_ung_relation': {
540
- const rel = computeTheUngRelation(chart);
541
- if (rel !== cond.relation)
542
- return UNMATCHED;
543
- return {
544
- matched: true,
545
- cost: 0,
546
- parents: [],
547
- facts: [`liuyao:the_ung:${cond.relation}`],
548
- };
549
- }
550
- case 'liuyao_state_flag': {
551
- if (!evalLiuyaoFlag(chart, cond.flag))
552
- return UNMATCHED;
553
- return {
554
- matched: true,
555
- cost: 0,
556
- parents: [],
557
- facts: [`liuyao:flag:${cond.flag}`],
558
- };
559
- }
560
- case 'derived_node': {
561
- const parent = derivedMap.get(cond.nodeId);
562
- if (!parent)
563
- return UNMATCHED;
564
- return {
565
- matched: true,
566
- cost: parent.proofDepth,
567
- parents: [cond.nodeId],
568
- facts: [`derived:${cond.nodeId}`],
569
- };
570
- }
571
- case 'and': {
572
- if (cond.args.length === 0) {
573
- return { matched: true, cost: 0, parents: [], facts: [] };
574
- }
575
- let maxCost = 0;
576
- const allParents = [];
577
- const allFacts = [];
578
- for (const arg of cond.args) {
579
- const sub = evaluateCondition(arg, chart, ruleSilo, derivedMap);
580
- if (!sub.matched)
581
- return UNMATCHED;
582
- if (sub.cost > maxCost)
583
- maxCost = sub.cost;
584
- allParents.push(...sub.parents);
585
- allFacts.push(...sub.facts);
586
- }
587
- return {
588
- matched: true,
589
- cost: maxCost,
590
- parents: sortedUnique(allParents),
591
- facts: sortedUnique(allFacts),
592
- };
593
- }
594
- case 'or': {
595
- const matchedSubs = [];
596
- for (const arg of cond.args) {
597
- const sub = evaluateCondition(arg, chart, ruleSilo, derivedMap);
598
- if (sub.matched)
599
- matchedSubs.push(sub);
600
- }
601
- if (matchedSubs.length === 0)
602
- return UNMATCHED;
603
- let minCost = matchedSubs[0].cost;
604
- for (const sub of matchedSubs) {
605
- if (sub.cost < minCost)
606
- minCost = sub.cost;
607
- }
608
- const bestParents = [];
609
- const bestFacts = [];
610
- for (const sub of matchedSubs) {
611
- if (sub.cost === minCost) {
612
- bestParents.push(...sub.parents);
613
- bestFacts.push(...sub.facts);
614
- }
615
- }
616
- return {
617
- matched: true,
618
- cost: minCost,
619
- parents: sortedUnique(bestParents),
620
- facts: sortedUnique(bestFacts),
621
- };
622
- }
623
- case 'not': {
624
- const sub = evaluateCondition(cond.arg, chart, ruleSilo, derivedMap);
625
- if (sub.matched)
626
- return UNMATCHED;
627
- return {
628
- matched: true,
629
- cost: 0,
630
- parents: [],
631
- facts: [`not:${cond.arg.op}`],
632
- };
424
+ return tt.menhInThaiTueTamHop && hasTuLinh
425
+ ? ok(`ziwei:${siloId}:thai_tue_tu_linh:${cond.scope}`)
426
+ : UNMATCHED;
633
427
  }
634
428
  }
635
429
  }
636
430
  function passesContextFilter(rule, filter) {
637
431
  if (!filter)
638
432
  return true;
639
- if (filter.careerCategory !== undefined && filter.careerCategory !== null) {
640
- if (rule.careerCategory !== undefined && rule.careerCategory !== null) {
641
- if (rule.careerCategory !== filter.careerCategory)
642
- return false;
643
- }
644
- if (rule.careerCategories !== undefined && rule.careerCategories !== null && rule.careerCategories.length > 0) {
645
- if (!rule.careerCategories.includes(filter.careerCategory))
646
- return false;
647
- }
648
- }
649
- if (filter.setting !== undefined && filter.setting !== null) {
650
- if (rule.setting !== undefined && rule.setting !== null) {
651
- if (rule.setting !== filter.setting)
652
- return false;
653
- }
654
- if (rule.settings !== undefined && rule.settings !== null && rule.settings.length > 0) {
655
- if (!rule.settings.includes(filter.setting))
656
- return false;
657
- }
433
+ if (filter.careerCategory != null) {
434
+ if (rule.careerCategory != null && rule.careerCategory !== filter.careerCategory)
435
+ return false;
436
+ if (rule.careerCategories?.length && !rule.careerCategories.includes(filter.careerCategory))
437
+ return false;
658
438
  }
659
- return true;
660
- }
661
- function arraysEqual(a, b) {
662
- if (a.length !== b.length)
663
- return false;
664
- for (let i = 0; i < a.length; i++) {
665
- if (a[i] !== b[i])
439
+ if (filter.setting != null) {
440
+ if (rule.setting != null && rule.setting !== filter.setting)
441
+ return false;
442
+ if (rule.settings?.length && !rule.settings.includes(filter.setting))
666
443
  return false;
667
444
  }
668
445
  return true;
669
446
  }
447
+ const arraysEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
670
448
  function detectParaconsistentConflicts(nodes) {
671
449
  const domains = sortedUnique(nodes.map((n) => n.domain));
672
450
  const conflicts = [];
673
451
  for (const domain of domains) {
674
452
  const domNodes = nodes.filter((n) => n.domain === domain);
675
- // 1. Cross-Silo opposition (opposing polarities CAT vs HUNG across distinct silos, or nam-phai vs toan-thu fork)
676
453
  const crossPosSet = new Set();
677
454
  const crossNegSet = new Set();
678
455
  let hasNamPhaiToanThuPair = false;
@@ -702,17 +479,9 @@ function detectParaconsistentConflicts(nodes) {
702
479
  : `Đối lập Cát/Hung liên hệ thống tại lĩnh vực '${domain}': bảo toàn cả hai mệnh đề và đối chiếu Dụng Thần Bát Tự cùng Đại Hạn Tử Vi trước khi kết luận.`,
703
480
  });
704
481
  }
705
- // 2. Intra-Silo paraconsistent coexistence (CAT and HUNG within the same silo & domain)
706
- const silos = sortedUnique(domNodes.map((n) => n.silo));
707
- for (const silo of silos) {
708
- const posIds = domNodes
709
- .filter((n) => n.silo === silo && n.polarity === 'CAT')
710
- .map((n) => n.nodeId)
711
- .sort(cmpStr);
712
- const negIds = domNodes
713
- .filter((n) => n.silo === silo && n.polarity === 'HUNG')
714
- .map((n) => n.nodeId)
715
- .sort(cmpStr);
482
+ for (const silo of sortedUnique(domNodes.map((n) => n.silo))) {
483
+ const posIds = domNodes.filter((n) => n.silo === silo && n.polarity === 'CAT').map((n) => n.nodeId).sort(cmpStr);
484
+ const negIds = domNodes.filter((n) => n.silo === silo && n.polarity === 'HUNG').map((n) => n.nodeId).sort(cmpStr);
716
485
  if (posIds.length > 0 && negIds.length > 0) {
717
486
  conflicts.push({
718
487
  conflictId: `conflict:${domain}:INTRA_SILO_PARACONSISTENT:${silo}`,
@@ -731,22 +500,16 @@ function detectParaconsistentConflicts(nodes) {
731
500
  export function evaluateRulesDAG(chart, rules, contextFilter) {
732
501
  const sourceRules = rules ?? loadSampleRules();
733
502
  const activeRules = sourceRules.filter((r) => passesContextFilter(r, contextFilter));
734
- // Deduplicate by rule.id deterministically and group by topological stratum
735
503
  const byId = new Map();
736
504
  for (const r of activeRules) {
737
505
  if (!Number.isInteger(r.stratum) || r.stratum < 1) {
738
506
  throw new Error(`Invalid rule stratum for '${r.id}': ${r.stratum} (must be integer >= 1)`);
739
507
  }
740
- if (!byId.has(r.id)) {
508
+ if (!byId.has(r.id))
741
509
  byId.set(r.id, r);
742
- }
743
510
  }
744
511
  const canonicalRules = Array.from(byId.values()).sort((a, b) => a.stratum !== b.stratum ? a.stratum - b.stratum : cmpStr(a.id, b.id));
745
- const strataSet = new Set();
746
- for (const r of canonicalRules) {
747
- strataSet.add(r.stratum);
748
- }
749
- const strataEvaluated = Array.from(strataSet).sort((a, b) => a - b);
512
+ const strataEvaluated = Array.from(new Set(canonicalRules.map((r) => r.stratum))).sort((a, b) => a - b);
750
513
  const derivedMap = new Map();
751
514
  for (const stratum of strataEvaluated) {
752
515
  const stratumRules = canonicalRules.filter((r) => r.stratum === stratum);
@@ -801,12 +564,8 @@ export function evaluateRulesDAG(chart, rules, contextFilter) {
801
564
  }
802
565
  }
803
566
  const nodes = Array.from(derivedMap.values()).sort((a, b) => a.stratum !== b.stratum ? a.stratum - b.stratum : cmpStr(a.nodeId, b.nodeId));
804
- const conflicts = detectParaconsistentConflicts(nodes);
805
- const normalizedContextFilter = contextFilter !== undefined
806
- ? {
807
- careerCategory: contextFilter.careerCategory ?? null,
808
- setting: contextFilter.setting ?? null,
809
- }
567
+ const normalizedContextFilter = contextFilter != null
568
+ ? { careerCategory: contextFilter.careerCategory ?? null, setting: contextFilter.setting ?? null }
810
569
  : null;
811
570
  return {
812
571
  schemaVersion: '1.0.0',
@@ -814,7 +573,7 @@ export function evaluateRulesDAG(chart, rules, contextFilter) {
814
573
  strataEvaluated,
815
574
  contextFilter: normalizedContextFilter,
816
575
  nodes,
817
- conflicts,
576
+ conflicts: detectParaconsistentConflicts(nodes),
818
577
  };
819
578
  }
820
579
  //# sourceMappingURL=dag.js.map