diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs index 181eef8..be2565b 100644 --- a/crates/analysis-prompt/src/lib.rs +++ b/crates/analysis-prompt/src/lib.rs @@ -9,7 +9,7 @@ use serde_json::{Value, json}; /// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key). -pub const PROMPT_VERSION: &str = "v2"; +pub const PROMPT_VERSION: &str = "v3"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { diff --git a/services/backend/README.md b/services/backend/README.md index b05f2c8..6c177f6 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -22,7 +22,7 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett | | `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket | | `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) | -| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) | +| `ANALYSIS_PROMPT_VERSION` | `v3` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) | | `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára | | `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | | diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 68a1146..57f012a 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -61,7 +61,7 @@ pub struct Config { /// `SUMMARY_MODEL`: writes the free short summary of every saved chart /// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each). pub summary_model: String, - /// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key. + /// `ANALYSIS_PROMPT_VERSION` (default `v3`); part of the analysis cache key. pub prompt_version: String, /// `MAX_CHARTS_PER_USER` (default 1000): a safety cap. pub max_charts_per_user: i64, @@ -121,7 +121,7 @@ impl Config { supported_locales, analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()), summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()), - prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()), + prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()), max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?, free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?, signup_mode: match var("SIGNUP_MODE").as_deref() { diff --git a/services/worker/README.md b/services/worker/README.md index 30b3059..082ab99 100644 --- a/services/worker/README.md +++ b/services/worker/README.md @@ -22,7 +22,8 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv **Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`) - A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül. - A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC. -- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v2`; ha a sor `prompt_version`-je `v2-r`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön): +- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra. +- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v3`; ha a sor `prompt_version`-je `v3-r`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön): - `title`, `summary`; - `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`; - `strengths`, `challenges`, `advice`; diff --git a/services/worker/src/analysis/compact.rs b/services/worker/src/analysis/compact.rs index 191f7d6..c612775 100644 --- a/services/worker/src/analysis/compact.rs +++ b/services/worker/src/analysis/compact.rs @@ -75,12 +75,49 @@ fn names(list: &Value) -> String { list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::>().join(", ") } +/// A point at most this far before the next house cusp is read in that house, +/// as astrologers do (the "5° rule"). The calculation keeps the exact house. +const CUSP_ORB: f64 = 5.0; + +/// "2°05'" +fn degrees(x: f64) -> String { + let minutes = (x * 60.0).round() as i64; + format!("{}°{:02}'", minutes / 60, minutes % 60) +} + +fn point_longitude(chart: &Value, id: &str) -> Option { + points(chart).find(|p| p["id"] == id)?["longitude"].as_f64() +} + +/// The house a point is read in: its own, or the next one when that cusp is +/// at most [`CUSP_ORB`] ahead, with how far ahead it is. +fn read_house(longitude: Option, house: i64, cusps: &Value) -> (i64, Option) { + let next = house % 12 + 1; + let cusp = cusps.as_array().into_iter().flatten().find(|c| c["house"].as_i64() == Some(next)); + match (longitude, cusp.and_then(|c| c["longitude"].as_f64())) { + (Some(lon), Some(cusp)) if (cusp - lon).rem_euclid(360.0) <= CUSP_ORB => { + (next, Some((cusp - lon).rem_euclid(360.0))) + } + _ => (house, None), + } +} + +/// "house 11 (on the cusp: 2°05' before it, formally house 10)" or "house 10". +fn house_text(longitude: Option, house: i64, cusps: &Value) -> String { + match read_house(longitude, house, cusps) { + (read, Some(before)) => { + format!("house {read} (on the cusp: {} before it, formally house {house})", degrees(before)) + } + (read, None) => format!("house {read}"), + } +} + /// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile". fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) { for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) { let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p)); if houses && let Some(h) = p["house"].as_i64() { - let _ = write!(line, ", house {h}"); + let _ = write!(line, ", {}", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"])); } if p["retrograde"].as_bool() == Some(true) { line.push_str(", retrograde"); @@ -97,7 +134,10 @@ fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) { .filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or(""))) .map(|p| { let house = if houses { - p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default() + p["house"] + .as_i64() + .map(|h| format!(" ({})", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"]))) + .unwrap_or_default() } else { String::new() }; @@ -155,12 +195,15 @@ pub fn natal(chart: &Value) -> String { if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] { continue; } + let house = r["house"].as_i64().map_or_else( + || "house ?".to_string(), + |h| house_text(point_longitude(chart, planet), h, &chart["houses"]["cusps"]), + ); let _ = writeln!( out, - "- Chart ruler ({kind}): {} in {}, house {}", + "- Chart ruler ({kind}): {} in {}, {house}", point_name(planet), capitalize(r["sign"].as_str().unwrap_or("?")), - r["house"] ); } } @@ -199,7 +242,10 @@ pub fn natal(chart: &Value) -> String { } if known && let Some(fortune) = chart["lots"]["fortune"].as_object() { let fortune = Value::Object(fortune.clone()); - let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]); + if let Some(h) = fortune["house"].as_i64() { + let house = house_text(fortune["longitude"].as_f64(), h, &chart["houses"]["cusps"]); + let _ = writeln!(out, "- Part of Fortune: {}, {house}", position(&fortune)); + } } out } @@ -251,16 +297,23 @@ pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String { } let overlays = &result["house_overlays"]; - for (key, label) in [ - ("person1_in_person2", "Person 1's planets in Person 2's houses"), - ("person2_in_person1", "Person 2's planets in Person 1's houses"), + for (key, label, own, other) in [ + ("person1_in_person2", "Person 1's planets in Person 2's houses", chart1, chart2), + ("person2_in_person1", "Person 2's planets in Person 1's houses", chart2, chart1), ] { let list: Vec = overlays[key] .as_array() .into_iter() .flatten() .filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or(""))) - .filter_map(|o| Some(format!("{} {}", point_name(o["point"].as_str()?), o["house"].as_i64()?))) + .filter_map(|o| { + let point = o["point"].as_str()?; + let house = o["house"].as_i64()?; + Some(match read_house(point_longitude(own, point), house, &other["houses"]["cusps"]) { + (read, Some(_)) => format!("{} {read} (on the cusp, formally {house})", point_name(point)), + (read, None) => format!("{} {read}", point_name(point)), + }) + }) .collect(); if !list.is_empty() { let _ = writeln!(out, "\n{label}: {}", list.join(", ")); @@ -357,7 +410,12 @@ pub fn forecast(chart: &Value, result: &Value) -> String { out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n"); angle_lines(&mut out, sr, ""); if let Some(h) = sr["natal_house_of_ascendant"].as_i64() { - let _ = writeln!(out, "- The solar return Ascendant falls in natal house {h}."); + let asc = sr["angles"]["ascendant"]["longitude"].as_f64(); + let _ = writeln!( + out, + "- The solar return Ascendant falls in natal {}.", + house_text(asc, h, &chart["houses"]["cusps"]) + ); } point_lines(&mut out, sr, "", true); aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15); @@ -370,13 +428,16 @@ pub fn forecast(chart: &Value, result: &Value) -> String { let planets = names(&p["planets_in_sign"]); let _ = writeln!( out, - "\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, house {}).{}", + "\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, {}).{}", p["house"], capitalize(p["sign"].as_str().unwrap_or("?")), point_name(p["lord"].as_str().unwrap_or("?")), point_name(p["lord"].as_str().unwrap_or("?")), capitalize(p["lord_sign"].as_str().unwrap_or("?")), - p["lord_house"], + p["lord_house"].as_i64().map_or_else( + || "house ?".to_string(), + |h| house_text(point_longitude(chart, p["lord"].as_str().unwrap_or("")), h, &chart["houses"]["cusps"]) + ), if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") } ); } @@ -466,7 +527,7 @@ pub fn forecast(chart: &Value, result: &Value) -> String { position(e) ); if let Some(h) = e["house"].as_i64() { - let _ = write!(line, ", natal house {h}"); + let _ = write!(line, ", natal {}", house_text(e["longitude"].as_f64(), h, &chart["houses"]["cusps"])); } let hits: Vec = e["contacts"] .as_array() @@ -525,6 +586,7 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize) #[cfg(test)] mod tests { use super::*; + use serde_json::json; fn fixture(name: &str) -> Value { let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR")); @@ -539,6 +601,19 @@ mod tests { } } + #[test] + fn points_just_before_a_cusp_are_read_in_the_next_house() { + let cusps = json!([{"house": 10, "longitude": 300.0}, {"house": 11, "longitude": 319.0}]); + // Moon at 17° with the 11th cusp at 19°: an astrologer reads it in the 11th. + assert_eq!(read_house(Some(317.0), 10, &cusps), (11, Some(2.0))); + assert_eq!(house_text(Some(317.0), 10, &cusps), "house 11 (on the cusp: 2°00' before it, formally house 10)"); + assert_eq!(read_house(Some(313.0), 10, &cusps), (10, None)); + assert_eq!(read_house(None, 10, &cusps), (10, None)); + // across 0° Aries, and from the 12th to the 1st + let cusps = json!([{"house": 1, "longitude": 2.0}]); + assert_eq!(read_house(Some(358.5), 12, &cusps), (1, Some(3.5))); + } + #[test] fn natal_with_birth_time() { let text = natal(&fixture("natal-1990-03-15.json")); @@ -553,7 +628,8 @@ mod tests { "House cusps: 1 Leo 19°23' | 2 Virgo 9°35'", "- Moon trine Chiron (orb 0.1°, applying)", "- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;", - "- Part of Fortune: Aries 5°10', house 8", + // 4' before the 9th cusp: read in the 9th + "- Part of Fortune: Aries 5°10', house 9 (on the cusp: 0°04' before it, formally house 8)", ] { assert!(text.contains(expected), "missing '{expected}' in:\n{text}"); }