tirtho149 commited on
Commit
34d29ef
·
verified ·
1 Parent(s): 70b98f2

Deploy SyndemicGPS HealthBot — geography-conditioned syndemic reasoning

Browse files
Files changed (5) hide show
  1. README.md +3 -2
  2. app.py +2 -1
  3. syndemic/engine.py +27 -110
  4. syndemic/llm.py +32 -17
  5. syndemic/ops.py +39 -18
README.md CHANGED
@@ -150,8 +150,9 @@ Evidence scores are derived from the reporting year, so an old series is penalis
150
 
151
  **What is deliberately NOT fetched.** Mental-health workforce, depression prevalence, extreme-heat days, campus
152
  services and verified crisis lines have no World Bank indicator. The system does **not** substitute a proxy for
153
- them — it abstains, and says so. A handful of city-level rows on the five seeded cities remain illustrative
154
- placeholders and are labelled `illustrative global baseline` in the provenance panel.
 
155
 
156
  **Describing yourself works too.** First-person messages ("I live in Iowa, I have gained weight, I don't sleep
157
  well") are recognised as case descriptions, not questions.
 
150
 
151
  **What is deliberately NOT fetched.** Mental-health workforce, depression prevalence, extreme-heat days, campus
152
  services and verified crisis lines have no World Bank indicator. The system does **not** substitute a proxy for
153
+ them — it abstains, and says so. Every seeded placeholder has now been removed: all
154
+ contextual values come from a live source or the factor abstains. Only the last-resort global fallback rows
155
+ remain illustrative, and they are labelled `illustrative global baseline` in the provenance panel.
156
 
157
  **Describing yourself works too.** First-person messages ("I live in Iowa, I have gained weight, I don't sleep
158
  well") are recognised as case descriptions, not questions.
app.py CHANGED
@@ -239,7 +239,8 @@ CHIPS = [
239
  ]
240
 
241
  DISCLAIMER = ("Research prototype. Support and hypothesis generation only — not diagnosis or treatment. "
242
- "Contextual values are illustrative placeholders, not retrieved statistics.")
 
243
 
244
 
245
  # --------------------------------------------------------------------------- #
 
239
  ]
240
 
241
  DISCLAIMER = ("Research prototype. Support and hypothesis generation only — not diagnosis or treatment. "
242
+ "Place data is retrieved live from the World Bank, Open-Meteo and Wikipedia; where no source "
243
+ "exists the system abstains rather than estimating.")
244
 
245
 
246
  # --------------------------------------------------------------------------- #
syndemic/engine.py CHANGED
@@ -233,104 +233,14 @@ GLOBAL_BASE = {
233
  }
234
 
235
  LOCS: Dict[str, Dict[str, Any]] = {
236
- "dhaka": dict(lat=23.777, lon=90.399, iso3="BGD", name="Dhaka, Bangladesh", short="Dhaka", lang="Bengali / English", neighbors=[], obs={
237
- "pm25": [dict(res="city", v=78, ev=.82, yr=2025, src="Urban reference monitors")],
238
- "heat_days": [dict(res="city", v=34, ev=.60, yr=2024, src="Station + reanalysis blend")],
239
- "wash": [dict(res="national", v=39, ev=.70, yr=2022, src="WASH monitoring series")],
240
- "primary_care": [dict(res="national", v=42, ev=.60, yr=2023, src="Service-coverage index")],
241
- "mh_workforce": [dict(res="national", v=0.5, ev=.55, yr=2020, src="Mental-health atlas class")],
242
- "referral": [dict(res="national", v=38, ev=.50, yr=2021, src="Facility-density composite")],
243
- "oop": [dict(res="national", v=73, ev=.75, yr=2022, src="National health accounts class")],
244
- "food_insec": [dict(res="national", v=31, ev=.68, yr=2023, src="Food-security survey class")],
245
- "poverty": [dict(res="national", v=30, ev=.70, yr=2022, src="Poverty platform class")],
246
- "youth_unemp": [dict(res="national", v=12, ev=.60, yr=2023, src="Labour force survey class")],
247
- "cd_burden": [dict(res="national", v=68, ev=.62, yr=2022, src="Burden-of-disease study class")],
248
- "dm_prev": [dict(res="national", v=14, ev=.72, yr=2021, src="Diabetes atlas class")],
249
- "dep_prev": [dict(res="national", v=4.4, ev=.55, yr=2019, src="Mental-disorder burden estimates")],
250
- "campus_svc": [dict(res="city", v=25, ev=.40, yr=2024, src="Institutional self-report")],
251
- "crisis": [dict(res="national", v=1, ev=.70, yr=2025, src="National emotional-support line (verified listing)",
252
- note="national emotional-support line")],
253
- }),
254
- "stockholm": dict(lat=59.329, lon=18.069, iso3="SWE", name="Stockholm, Sweden", short="Stockholm", lang="Swedish / English", neighbors=[], obs={
255
- "pm25": [dict(res="city", v=6, ev=.93, yr=2025, src="Urban reference monitors")],
256
- "heat_days": [dict(res="city", v=1, ev=.80, yr=2024, src="Station record")],
257
- "wash": [dict(res="national", v=99, ev=.90, yr=2022, src="WASH monitoring series")],
258
- "primary_care": [dict(res="national", v=88, ev=.85, yr=2023, src="Service-coverage index")],
259
- "mh_workforce": [dict(res="national", v=22, ev=.80, yr=2023, src="Mental-health atlas class")],
260
- "referral": [dict(res="national", v=84, ev=.80, yr=2023, src="Facility-density composite")],
261
- "oop": [dict(res="national", v=14, ev=.85, yr=2022, src="National health accounts class")],
262
- "food_insec": [dict(res="national", v=4, ev=.80, yr=2023, src="Food-security survey class")],
263
- "poverty": [dict(res="national", v=1, ev=.85, yr=2022, src="Poverty platform class")],
264
- "youth_unemp": [dict(res="national", v=20, ev=.75, yr=2023, src="Labour force survey class")],
265
- "cd_burden": [dict(res="national", v=22, ev=.80, yr=2023, src="Burden-of-disease study class")],
266
- "dm_prev": [dict(res="national", v=5.5, ev=.82, yr=2023, src="Diabetes atlas class")],
267
- "dep_prev": [dict(res="national", v=6.2, ev=.78, yr=2023, src="Mental-disorder burden estimates")],
268
- "campus_svc": [dict(res="city", v=78, ev=.62, yr=2025, src="University service directory")],
269
- "crisis": [dict(res="national", v=1, ev=.88, yr=2026, src="Emergency + national health line (verified)",
270
- note="emergency number + national health line")],
271
- }),
272
- "nairobi": dict(lat=-1.286, lon=36.817, iso3="KEN", name="Nairobi, Kenya", short="Nairobi", lang="Swahili / English", neighbors=[], obs={
273
- "pm25": [dict(res="city", v=26, ev=.60, yr=2024, src="Low-cost sensor network")],
274
- "heat_days": [dict(res="city", v=3, ev=.65, yr=2024, src="Station record")],
275
- "wash": [dict(res="national", v=34, ev=.66, yr=2022, src="WASH monitoring series")],
276
- "primary_care": [dict(res="national", v=46, ev=.60, yr=2023, src="Service-coverage index")],
277
- "mh_workforce": [dict(res="national", v=0.3, ev=.50, yr=2020, src="Mental-health atlas class")],
278
- "referral": [dict(res="national", v=41, ev=.50, yr=2021, src="Facility-density composite")],
279
- "oop": [dict(res="national", v=24, ev=.70, yr=2022, src="National health accounts class")],
280
- "food_insec": [dict(res="national", v=47, ev=.70, yr=2023, src="Food-security survey class")],
281
- "poverty": [dict(res="national", v=55, ev=.72, yr=2021, src="Poverty platform class")],
282
- "youth_unemp": [dict(res="national", v=14, ev=.60, yr=2023, src="Labour force survey class")],
283
- "cd_burden": [dict(res="national", v=72, ev=.65, yr=2022, src="Burden-of-disease study class")],
284
- "dm_prev": [dict(res="national", v=3.3, ev=.60, yr=2021, src="Diabetes atlas class")],
285
- "dep_prev": [dict(res="national", v=4.9, ev=.50, yr=2019, src="Mental-disorder burden estimates")],
286
- "campus_svc": [dict(res="city", v=34, ev=.35, yr=2023, src="Institutional self-report")],
287
- "crisis": [dict(res="national", v=1, ev=.30, yr=2022, src="Unconfirmed directory entry",
288
- note="listing could not be re-verified")],
289
- }),
290
- "chicago": dict(lat=41.878, lon=-87.63, iso3="USA", name="Chicago, United States", short="Chicago", lang="English / Spanish", neighbors=[], obs={
291
- "pm25": [dict(res="city", v=11, ev=.90, yr=2025, src="Regulatory monitor network")],
292
- "heat_days": [dict(res="city", v=8, ev=.80, yr=2024, src="Station record")],
293
- "wash": [dict(res="national", v=99, ev=.90, yr=2022, src="WASH monitoring series")],
294
- "primary_care": [dict(res="national", v=74, ev=.80, yr=2023, src="Service-coverage index",
295
- note="access varies sharply by insurance status")],
296
- "mh_workforce": [dict(res="national", v=15, ev=.75, yr=2023, src="Mental-health atlas class")],
297
- "referral": [dict(res="national", v=80, ev=.75, yr=2023, src="Facility-density composite")],
298
- "oop": [dict(res="national", v=11, ev=.80, yr=2022, src="National health accounts class",
299
- note="low mean OOP hides coverage-dependent exposure")],
300
- "food_insec": [dict(res="national", v=11, ev=.75, yr=2023, src="Food-security survey class")],
301
- "poverty": [dict(res="national", v=2, ev=.80, yr=2022, src="Poverty platform class")],
302
- "youth_unemp": [dict(res="national", v=9, ev=.75, yr=2023, src="Labour force survey class")],
303
- "cd_burden": [dict(res="national", v=31, ev=.78, yr=2023, src="Burden-of-disease study class")],
304
- "dm_prev": [dict(res="national", v=11, ev=.80, yr=2023, src="Diabetes atlas class")],
305
- "dep_prev": [dict(res="national", v=8.3, ev=.75, yr=2023, src="Mental-disorder burden estimates")],
306
- "campus_svc": [dict(res="city", v=71, ev=.60, yr=2025, src="University service directory")],
307
- "crisis": [dict(res="national", v=1, ev=.90, yr=2026, src="National crisis lifeline (verified)",
308
- note="national 3-digit crisis lifeline")],
309
- }),
310
  "coxs": dict(lat=21.427, lon=92.005, iso3="BGD", name="Cox's Bazar, Bangladesh (border region)", short="Cox's Bazar",
311
  lang="Bengali / Chittagonian / English",
312
  neighbors=[dict(n="Teknaf sub-district (BD)", d=42, x=False),
313
- dict(n="Maungdaw, Rakhine (MM)", d=78, x=True)], obs={
314
- "pm25": [dict(res="city", v=41, ev=.45, yr=2024, src="Single low-cost sensor")],
315
- "heat_days": [dict(res="subnational", v=29, ev=.58, yr=2024, src="Regional reanalysis")],
316
- "wash": [dict(res="subnational", v=26, ev=.58, yr=2023, src="Humanitarian WASH assessment"),
317
- dict(res="national", v=39, ev=.70, yr=2022, src="WASH monitoring series")],
318
- "primary_care": [dict(res="national", v=42, ev=.60, yr=2023, src="Service-coverage index")],
319
- "mh_workforce": [dict(res="national", v=0.5, ev=.55, yr=2020, src="Mental-health atlas class")],
320
- "referral": [dict(res="national", v=38, ev=.50, yr=2021, src="Facility-density composite")],
321
- "oop": [dict(res="national", v=73, ev=.75, yr=2022, src="National health accounts class")],
322
- "food_insec": [dict(res="subnational", v=52, ev=.60, yr=2023, src="Regional food-security assessment"),
323
- dict(res="national", v=31, ev=.68, yr=2023, src="Food-security survey class")],
324
- "poverty": [dict(res="national", v=30, ev=.70, yr=2022, src="Poverty platform class")],
325
- "youth_unemp": [dict(res="national", v=12, ev=.60, yr=2023, src="Labour force survey class")],
326
- "cd_burden": [dict(res="subnational", v=81, ev=.50, yr=2023, src="District surveillance (single sentinel site)"),
327
- dict(res="region", v=85, ev=.62, yr=2024, src="Cross-border regional surveillance (N_r, r=150 km)")],
328
- "dm_prev": [dict(res="national", v=14, ev=.72, yr=2021, src="Diabetes atlas class")],
329
- "dep_prev": [dict(res="national", v=4.4, ev=.55, yr=2019, src="Mental-disorder burden estimates")],
330
- "campus_svc": [dict(res="subnational", v=18, ev=.32, yr=2023, src="Institutional self-report")],
331
- "crisis": [dict(res="national", v=1, ev=.70, yr=2025, src="National emotional-support line (verified listing)",
332
- note="national line; no verified local service")],
333
- }),
334
  "global": dict(name="Global baseline (no locality)", short="Global", lang="varies", neighbors=[], obs={}),
335
  }
336
 
@@ -539,15 +449,15 @@ def fmt(v: Any, key: str) -> str:
539
  # --------------------------------------------------------------------------- #
540
 
541
  ACTIONS: List[Dict[str, Any]] = [
542
- dict(id="crisis", lab="Verified crisis pathway and immediate safety planning", tier="red",
543
  base=lambda s: 100.0 if s.get("si_flag", 0) > 0 else 0.0, drivers=["si_flag"], mods=[]),
544
- dict(id="sleep", lab="Sleep stabilisation paired with academic-load planning", tier="green",
545
  base=lambda s: 1.2 * max(s.get("academic_stress", 0), s.get("work_stress", 0), s.get("burnout", 0))
546
  + 1.4 * s.get("sleep_short", 0) + .4 * s.get("headache", 0),
547
  drivers=["academic_stress", "work_stress", "burnout", "sleep_short", "headache"],
548
  mods=[dict(k="heat_days", cmp=">=", th=20, d=.5, why="sustained heat exposure degrades sleep consolidation"),
549
  dict(k="campus_svc", cmp=">=", th=60, d=.4, why="campus study-support services exist to absorb load")]),
550
- dict(id="depression", lab="Structured depression follow-up with specialist referral", tier="amber",
551
  base=lambda s: 2.0 * s.get("depressive_sx", 0) + 1.4 * s.get("anxiety_sx", 0)
552
  + .6 * s.get("sleep_short", 0) + .5 * s.get("prior_trauma", 0),
553
  drivers=["depressive_sx", "anxiety_sx", "sleep_short", "prior_trauma"],
@@ -556,12 +466,12 @@ ACTIONS: List[Dict[str, Any]] = [
556
  feas=dict(k="mh_workforce", cmp=">=", th=3,
557
  alt="Stepped non-specialist-first support with explicit escalation triggers",
558
  msg="specialist mental-health capacity is thin; the specialist-referral route is not assumed")),
559
- dict(id="food", lab="Food-safety and low-cost nutrition planning", tier="green",
560
  base=lambda s: 1.3 * s.get("food_insecurity", 0) + .8 * s.get("gi_symptoms", 0),
561
  drivers=["food_insecurity", "gi_symptoms"],
562
  mods=[dict(k="food_insec", cmp=">=", th=25, d=.9, why="population-level food insecurity is high here"),
563
  dict(k="wash", cmp="<=", th=55, d=.8, why="weak sanitation coverage raises food-borne risk")]),
564
- dict(id="metabolic", lab="Early metabolic screening (HbA1c, blood pressure)", tier="amber",
565
  base=lambda s: .9 * s.get("fam_hx", 0) + .7 * s.get("food_insecurity", 0) + .5 * s.get("poor_diet", 0)
566
  + .5 * s.get("sedentary", 0) + .4 * s.get("metabolic_vuln", 0),
567
  drivers=["fam_hx", "food_insecurity", "poor_diet", "sedentary", "metabolic_vuln"],
@@ -571,54 +481,54 @@ ACTIONS: List[Dict[str, Any]] = [
571
  feas=dict(k="primary_care", cmp=">=", th=45,
572
  alt="Opportunistic screening via campus clinic or subsidised programme",
573
  msg="routine primary-care screening cannot be assumed at this access level")),
574
- dict(id="resp", lab="Respiratory infection reduction (ventilation, hygiene, vaccination)", tier="green",
575
  base=lambda s: 1.1 * s.get("recurrent_uri", 0) + .9 * s.get("crowded_housing", 0)
576
  + .7 * s.get("asthma", 0),
577
  drivers=["recurrent_uri", "crowded_housing", "asthma"],
578
  mods=[dict(k="cd_burden", cmp=">=", th=60, d=1.0, why="high communicable-disease background burden"),
579
  dict(k="pm25", cmp=">=", th=35, d=.6, why="particulate exposure compounds airway irritation")]),
580
- dict(id="air", lab="Air-quality exposure management", tier="green",
581
  requires=dict(k="pm25", cmp=">=", th=25),
582
  base=lambda s: .5 * s.get("recurrent_uri", 0) + .3 * s.get("crowded_housing", 0)
583
  + .8 * s.get("asthma", 0),
584
  drivers=["recurrent_uri", "asthma"],
585
  mods=[dict(k="pm25", cmp=">=", th=50, d=2.4, why="PM2.5 is far above guideline levels"),
586
  dict(k="pm25", cmp=">=", th=25, d=.8, why="PM2.5 exceeds guideline levels")]),
587
- dict(id="finance", lab="Financial-aid and student-support navigation", tier="green",
588
  base=lambda s: .9 * s.get("food_insecurity", 0) + 1.0 * s.get("financial_strain", 0)
589
  + .4 * s.get("displacement", 0),
590
  drivers=["food_insecurity", "financial_strain", "displacement"],
591
  mods=[dict(k="poverty", cmp=">=", th=20, d=.6, why="structural poverty context"),
592
  dict(k="youth_unemp", cmp=">=", th=15, d=.3, why="constrained student labour market"),
593
  dict(k="campus_svc", cmp=">=", th=60, d=.6, why="an institutional aid pathway is documented")]),
594
- dict(id="continuity", lab="Care-continuity plan to replace self-medication", tier="amber",
595
  base=lambda s: 1.2 * s.get("self_medication", 0), drivers=["self_medication"],
596
  mods=[dict(k="primary_care", cmp="<=", th=50, d=.5, why="weak first contact makes explicit navigation more important"),
597
  dict(k="referral", cmp="<=", th=50, d=.4, why="thin referral capacity requires a planned route"),
598
  dict(k="oop", cmp=">=", th=50, d=.4, why="cost exposure drives informal self-treatment")]),
599
- dict(id="heat", lab="Heat-exposure planning", tier="green",
600
  requires=dict(k="heat_days", cmp=">=", th=15),
601
  base=lambda s: .3 + .2 * s.get("sleep_short", 0), drivers=["sleep_short"],
602
  mods=[dict(k="heat_days", cmp=">=", th=30, d=1.0, why="prolonged extreme-heat season")]),
603
- dict(id="social", lab="Social connection and peer-support planning", tier="green",
604
  base=lambda s: 1.2 * s.get("isolation", 0) + .8 * s.get("displacement", 0)
605
  + .5 * s.get("depressive_sx", 0),
606
  drivers=["isolation", "displacement", "depressive_sx"],
607
  mods=[dict(k="campus_svc", cmp=">=", th=60, d=.7, why="community or campus groups are documented here"),
608
  dict(k="youth_unemp", cmp=">=", th=15, d=.3, why="a thin labour market narrows everyday contact")]),
609
- dict(id="substance", lab="Substance-use conversation and harm reduction", tier="amber",
610
  base=lambda s: 1.6 * s.get("substance_use", 0),
611
  drivers=["substance_use"],
612
  mods=[dict(k="primary_care", cmp=">=", th=60, d=.4, why="a first-contact route for this exists")],
613
  feas=dict(k="referral", cmp=">=", th=45,
614
  alt="Self-directed harm-reduction guidance with an explicit escalation trigger",
615
  msg="referral capacity is thin; a specialist route is not assumed")),
616
- dict(id="fatigue", lab="Fatigue review — sleep, mood and infection burden together", tier="amber",
617
  base=lambda s: 1.3 * s.get("chronic_fatigue", 0) + .4 * s.get("back_pain", 0),
618
  drivers=["chronic_fatigue", "back_pain"],
619
  mods=[dict(k="cd_burden", cmp=">=", th=60, d=.5, why="recurrent infection is a plausible contributor here"),
620
  dict(k="primary_care", cmp=">=", th=60, d=.4, why="workup is realistically reachable")]),
621
- dict(id="gi", lab="GI symptom review and rehydration guidance", tier="green",
622
  base=lambda s: 1.0 * s.get("gi_symptoms", 0) + 1.2 * s.get("diarrhoeal", 0),
623
  drivers=["gi_symptoms", "diarrhoeal"],
624
  mods=[dict(k="wash", cmp="<=", th=45, d=.9, why="sanitation coverage is low"),
@@ -668,7 +578,13 @@ def plan(state: State, ctx: Dict[str, Any], geo_off: bool) -> List[Dict[str, Any
668
  geo_why.append(f"{m['why']} - {FACTORS[m['k']]['short']} {fmt(c['v'], m['k'])} "
669
  f"({RES_LAB[c['res']]} {c['yr']}"
670
  f"{', counterfactual' if c.get('cf') else ''})")
671
- label, feas_note = a["lab"], None
 
 
 
 
 
 
672
  if a.get("feas") and not geo_off:
673
  c = ctx.get(a["feas"]["k"])
674
  if c and c["ok"] and not _test(c["v"], a["feas"]["cmp"], a["feas"]["th"]):
@@ -682,6 +598,7 @@ def plan(state: State, ctx: Dict[str, Any], geo_off: bool) -> List[Dict[str, Any
682
  for k in a["drivers"] if s.get(k, 0) > 0]
683
  conf = min(1.0, max(0.0, (sum(evs) / len(evs) if evs else .70) * (.8 if geo_off else 1.0)))
684
  items.append(dict(id=a["id"], lab=label, base=a["lab"], tier=a["tier"], score=score, why=why,
 
685
  geo_why=geo_why, abstained=abstained, feas_note=feas_note, conf=conf,
686
  resource=crisis_resource(ctx, geo_off) if a["id"] == "crisis" else None))
687
  items.sort(key=lambda x: -x["score"])
 
233
  }
234
 
235
  LOCS: Dict[str, Dict[str, Any]] = {
236
+ "dhaka": dict(lat=23.777, lon=90.399, iso3="BGD", name="Dhaka, Bangladesh", short="Dhaka", lang="Bengali / English", neighbors=[], obs={}),
237
+ "stockholm": dict(lat=59.329, lon=18.069, iso3="SWE", name="Stockholm, Sweden", short="Stockholm", lang="Swedish / English", neighbors=[], obs={}),
238
+ "nairobi": dict(lat=-1.286, lon=36.817, iso3="KEN", name="Nairobi, Kenya", short="Nairobi", lang="Swahili / English", neighbors=[], obs={}),
239
+ "chicago": dict(lat=41.878, lon=-87.63, iso3="USA", name="Chicago, United States", short="Chicago", lang="English / Spanish", neighbors=[], obs={}),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  "coxs": dict(lat=21.427, lon=92.005, iso3="BGD", name="Cox's Bazar, Bangladesh (border region)", short="Cox's Bazar",
241
  lang="Bengali / Chittagonian / English",
242
  neighbors=[dict(n="Teknaf sub-district (BD)", d=42, x=False),
243
+ dict(n="Maungdaw, Rakhine (MM)", d=78, x=True)], obs={}),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  "global": dict(name="Global baseline (no locality)", short="Global", lang="varies", neighbors=[], obs={}),
245
  }
246
 
 
449
  # --------------------------------------------------------------------------- #
450
 
451
  ACTIONS: List[Dict[str, Any]] = [
452
+ dict(id="crisis", says="Talk to someone today rather than sitting with it alone. A named line or a trusted person, now, not later.", lab="Verified crisis pathway and immediate safety planning", tier="red",
453
  base=lambda s: 100.0 if s.get("si_flag", 0) > 0 else 0.0, drivers=["si_flag"], mods=[]),
454
+ dict(id="sleep", says="Anchor the wake time first, even on bad nights, and protect the hour before bed. Sleep debt is usually the cheapest thing to move and it lifts mood and appetite with it.", label_fn=lambda s: "Sleep stabilisation with " + ("study-load planning" if s.get("academic_stress") else "work-load planning" if s.get("work_stress") else "a review of what is keeping you up"), lab="Sleep stabilisation paired with academic-load planning", tier="green",
455
  base=lambda s: 1.2 * max(s.get("academic_stress", 0), s.get("work_stress", 0), s.get("burnout", 0))
456
  + 1.4 * s.get("sleep_short", 0) + .4 * s.get("headache", 0),
457
  drivers=["academic_stress", "work_stress", "burnout", "sleep_short", "headache"],
458
  mods=[dict(k="heat_days", cmp=">=", th=20, d=.5, why="sustained heat exposure degrades sleep consolidation"),
459
  dict(k="campus_svc", cmp=">=", th=60, d=.4, why="campus study-support services exist to absorb load")]),
460
+ dict(id="depression", says="Low mood that has lasted weeks is worth naming to a professional, not managing alone. Ask specifically for an assessment, not just reassurance.", lab="Structured depression follow-up with specialist referral", tier="amber",
461
  base=lambda s: 2.0 * s.get("depressive_sx", 0) + 1.4 * s.get("anxiety_sx", 0)
462
  + .6 * s.get("sleep_short", 0) + .5 * s.get("prior_trauma", 0),
463
  drivers=["depressive_sx", "anxiety_sx", "sleep_short", "prior_trauma"],
 
466
  feas=dict(k="mh_workforce", cmp=">=", th=3,
467
  alt="Stepped non-specialist-first support with explicit escalation triggers",
468
  msg="specialist mental-health capacity is thin; the specialist-referral route is not assumed")),
469
+ dict(id="food", says="Aim for reliable, cheap, safe calories on a fixed schedule rather than perfect nutrition. Skipped meals drive both the stomach symptoms and the mood dip.", lab="Food-safety and low-cost nutrition planning", tier="green",
470
  base=lambda s: 1.3 * s.get("food_insecurity", 0) + .8 * s.get("gi_symptoms", 0),
471
  drivers=["food_insecurity", "gi_symptoms"],
472
  mods=[dict(k="food_insec", cmp=">=", th=25, d=.9, why="population-level food insecurity is high here"),
473
  dict(k="wash", cmp="<=", th=55, d=.8, why="weak sanitation coverage raises food-borne risk")]),
474
+ dict(id="metabolic", says="Ask for a blood-sugar and blood-pressure check. With family history and disrupted sleep this is a measurement question, not a lifestyle lecture.", lab="Early metabolic screening (HbA1c, blood pressure)", tier="amber",
475
  base=lambda s: .9 * s.get("fam_hx", 0) + .7 * s.get("food_insecurity", 0) + .5 * s.get("poor_diet", 0)
476
  + .5 * s.get("sedentary", 0) + .4 * s.get("metabolic_vuln", 0),
477
  drivers=["fam_hx", "food_insecurity", "poor_diet", "sedentary", "metabolic_vuln"],
 
481
  feas=dict(k="primary_care", cmp=">=", th=45,
482
  alt="Opportunistic screening via campus clinic or subsidised programme",
483
  msg="routine primary-care screening cannot be assumed at this access level")),
484
+ dict(id="resp", says="Ventilation, hand hygiene and being current on seasonal vaccination cut repeat infections more than anything else available to you.", lab="Respiratory infection reduction (ventilation, hygiene, vaccination)", tier="green",
485
  base=lambda s: 1.1 * s.get("recurrent_uri", 0) + .9 * s.get("crowded_housing", 0)
486
  + .7 * s.get("asthma", 0),
487
  drivers=["recurrent_uri", "crowded_housing", "asthma"],
488
  mods=[dict(k="cd_burden", cmp=">=", th=60, d=1.0, why="high communicable-disease background burden"),
489
  dict(k="pm25", cmp=">=", th=35, d=.6, why="particulate exposure compounds airway irritation")]),
490
+ dict(id="air", says="On high-pollution days, shift exertion indoors and keep windows shut at peak traffic hours.", lab="Air-quality exposure management", tier="green",
491
  requires=dict(k="pm25", cmp=">=", th=25),
492
  base=lambda s: .5 * s.get("recurrent_uri", 0) + .3 * s.get("crowded_housing", 0)
493
  + .8 * s.get("asthma", 0),
494
  drivers=["recurrent_uri", "asthma"],
495
  mods=[dict(k="pm25", cmp=">=", th=50, d=2.4, why="PM2.5 is far above guideline levels"),
496
  dict(k="pm25", cmp=">=", th=25, d=.8, why="PM2.5 exceeds guideline levels")]),
497
+ dict(id="finance", says="Money pressure is upstream of the food and the sleep here. A hardship fund, payment plan or benefits check often moves more than any health advice.", lab="Financial-aid and student-support navigation", tier="green",
498
  base=lambda s: .9 * s.get("food_insecurity", 0) + 1.0 * s.get("financial_strain", 0)
499
  + .4 * s.get("displacement", 0),
500
  drivers=["food_insecurity", "financial_strain", "displacement"],
501
  mods=[dict(k="poverty", cmp=">=", th=20, d=.6, why="structural poverty context"),
502
  dict(k="youth_unemp", cmp=">=", th=15, d=.3, why="constrained student labour market"),
503
  dict(k="campus_svc", cmp=">=", th=60, d=.6, why="an institutional aid pathway is documented")]),
504
+ dict(id="continuity", says="Pick one place to go back to, so someone sees the whole picture instead of one symptom at a time.", lab="Care-continuity plan to replace self-medication", tier="amber",
505
  base=lambda s: 1.2 * s.get("self_medication", 0), drivers=["self_medication"],
506
  mods=[dict(k="primary_care", cmp="<=", th=50, d=.5, why="weak first contact makes explicit navigation more important"),
507
  dict(k="referral", cmp="<=", th=50, d=.4, why="thin referral capacity requires a planned route"),
508
  dict(k="oop", cmp=">=", th=50, d=.4, why="cost exposure drives informal self-treatment")]),
509
+ dict(id="heat", says="Plan effort and sleep around the heat: hydration, shade in peak hours, and a cooler sleeping setup.", lab="Heat-exposure planning", tier="green",
510
  requires=dict(k="heat_days", cmp=">=", th=15),
511
  base=lambda s: .3 + .2 * s.get("sleep_short", 0), drivers=["sleep_short"],
512
  mods=[dict(k="heat_days", cmp=">=", th=30, d=1.0, why="prolonged extreme-heat season")]),
513
+ dict(id="social", says="One recurring, low-effort contact beats an ambitious plan. Isolation feeds the mood symptoms directly.", lab="Social connection and peer-support planning", tier="green",
514
  base=lambda s: 1.2 * s.get("isolation", 0) + .8 * s.get("displacement", 0)
515
  + .5 * s.get("depressive_sx", 0),
516
  drivers=["isolation", "displacement", "depressive_sx"],
517
  mods=[dict(k="campus_svc", cmp=">=", th=60, d=.7, why="community or campus groups are documented here"),
518
  dict(k="youth_unemp", cmp=">=", th=15, d=.3, why="a thin labour market narrows everyday contact")]),
519
+ dict(id="substance", says="Look at what the drinking or use is doing for you before trying to cut it. Sleep and mood usually improve first.", lab="Substance-use conversation and harm reduction", tier="amber",
520
  base=lambda s: 1.6 * s.get("substance_use", 0),
521
  drivers=["substance_use"],
522
  mods=[dict(k="primary_care", cmp=">=", th=60, d=.4, why="a first-contact route for this exists")],
523
  feas=dict(k="referral", cmp=">=", th=45,
524
  alt="Self-directed harm-reduction guidance with an explicit escalation trigger",
525
  msg="referral capacity is thin; a specialist route is not assumed")),
526
+ dict(id="fatigue", says="Fatigue with disrupted sleep and repeat infection deserves one joined-up review rather than three separate ones.", lab="Fatigue review — sleep, mood and infection burden together", tier="amber",
527
  base=lambda s: 1.3 * s.get("chronic_fatigue", 0) + .4 * s.get("back_pain", 0),
528
  drivers=["chronic_fatigue", "back_pain"],
529
  mods=[dict(k="cd_burden", cmp=">=", th=60, d=.5, why="recurrent infection is a plausible contributor here"),
530
  dict(k="primary_care", cmp=">=", th=60, d=.4, why="workup is realistically reachable")]),
531
+ dict(id="gi", says="Track what precedes the episodes and keep oral rehydration to hand. Persistent or bloody symptoms need review, not self-management.", lab="GI symptom review and rehydration guidance", tier="green",
532
  base=lambda s: 1.0 * s.get("gi_symptoms", 0) + 1.2 * s.get("diarrhoeal", 0),
533
  drivers=["gi_symptoms", "diarrhoeal"],
534
  mods=[dict(k="wash", cmp="<=", th=45, d=.9, why="sanitation coverage is low"),
 
578
  geo_why.append(f"{m['why']} - {FACTORS[m['k']]['short']} {fmt(c['v'], m['k'])} "
579
  f"({RES_LAB[c['res']]} {c['yr']}"
580
  f"{', counterfactual' if c.get('cf') else ''})")
581
+ label = a["lab"]
582
+ if a.get("label_fn"):
583
+ try:
584
+ label = a["label_fn"](s)
585
+ except Exception:
586
+ pass
587
+ feas_note = None
588
  if a.get("feas") and not geo_off:
589
  c = ctx.get(a["feas"]["k"])
590
  if c and c["ok"] and not _test(c["v"], a["feas"]["cmp"], a["feas"]["th"]):
 
598
  for k in a["drivers"] if s.get(k, 0) > 0]
599
  conf = min(1.0, max(0.0, (sum(evs) / len(evs) if evs else .70) * (.8 if geo_off else 1.0)))
600
  items.append(dict(id=a["id"], lab=label, base=a["lab"], tier=a["tier"], score=score, why=why,
601
+ says=a.get("says", ""),
602
  geo_why=geo_why, abstained=abstained, feas_note=feas_note, conf=conf,
603
  resource=crisis_resource(ctx, geo_off) if a["id"] == "crisis" else None))
604
  items.sort(key=lambda x: -x["score"])
syndemic/llm.py CHANGED
@@ -137,25 +137,40 @@ Operation meanings:
137
  If the user names one place for a move, put it in place_b and leave place_a null.
138
  Output JSON only."""
139
 
140
- ANSWER_SYSTEM = """You are SyndemicGPS, a geography-conditioned syndemic health reasoning assistant.
141
-
142
- ABSOLUTE RULES
143
- 1. Every number, prevalence, service name, year and resolution level you state MUST appear verbatim in the
144
- FACTS block. Never estimate, round differently, extrapolate, or add a statistic of your own.
145
- 2. If FACTS says a factor was abstained on or gated out, say the system is not using it. Never fill the gap.
146
- 3. Never claim a local service exists unless FACTS names it as verified.
147
- 4. Never diagnose, never prescribe, never claim clinical efficacy or causal effect. Structural counterfactuals
148
- are reasoning probes, not forecasts.
149
- 5. Population statistics are evidence about the PLACE, never facts about the PERSON. Never infer anything about
150
- the person from their country, and never let a country name alone justify a recommendation.
151
- 6. Keep the safety tier exactly as FACTS states it. Geography may change which resource is named; it never moves
152
- the threshold.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  STYLE
155
- Address the user directly and plainly. 90-170 words unless the FACTS block is a comparison, in which case up to
156
- 220. No headings, no bullet lists of more than four items, no emoji. Lead with the answer, then the reason it
157
- holds, then the one thing that would change it. Name the mechanism, not just the outcome: say which contextual
158
- factor moved the pathway and at what resolution level and year it was observed."""
159
 
160
  SAFETY_ANSWER = """A person may be at risk. Respond with warmth and brevity. Do not analyse the syndemic graph,
161
  do not rank interventions, do not mention rankings or scores. Acknowledge, encourage contact with the named
 
137
  If the user names one place for a move, put it in place_b and leave place_a null.
138
  Output JSON only."""
139
 
140
+ ANSWER_SYSTEM = """You are SyndemicGPS. You are talking to a person, not narrating a system.
141
+
142
+ WHO YOU ADDRESS
143
+ If the case is the user's own ("I live in...", "I have..."), say "you". If they described someone else, say
144
+ "they". Never switch mid-answer.
145
+
146
+ NEVER SAY THESE WORDS
147
+ node, severity, graph, G_I, G_S, X_u, gate, threshold, tau, rank, score, pathway number, "the system",
148
+ "I extracted", "was gated", "interacting pairs". The machinery is shown separately; your job is the meaning.
149
+ Say "what you told me", "what stands out", "the thing I'd move first".
150
+
151
+ WHAT AN ANSWER CONTAINS, IN THIS ORDER
152
+ 1. What is going on, in one or two sentences, and — this is the point of the whole tool — what is feeding
153
+ what. Name the loop: short sleep and low mood push on each other; money pressure is upstream of the food.
154
+ If nothing links, say the picture is still thin rather than inventing a connection.
155
+ 2. The one thing worth moving first, and the concrete line for it from SUPPORT in the FACTS block. Use that
156
+ wording — it is the substance of the answer, not decoration.
157
+ 3. What would change your answer: the local fact you do not have, or the thing you would need to ask them.
158
+
159
+ ABSOLUTE RULES ON FACTS
160
+ · Every number, prevalence, service name, year and place fact MUST appear verbatim in the FACTS block. Never
161
+ estimate, extrapolate, or round differently. Never take a figure from a retrieved passage.
162
+ · Where FACTS says a factor was abstained on, say so in plain words — "I don't have trustworthy local data on
163
+ mental-health services there, so I'm not going to guess what's available" — never fill the gap.
164
+ · Never claim a local service exists unless FACTS names it as verified.
165
+ · Never diagnose, never prescribe, never promise an outcome. Counterfactuals are thought experiments.
166
+ · A population statistic describes a place, never the person in front of you. Never reason from someone's
167
+ country to their behaviour, diet, beliefs or character.
168
+ · Keep the safety tier exactly as FACTS states it.
169
 
170
  STYLE
171
+ Plain, warm, direct. 90-160 words; up to 200 for a place comparison. No headings. At most three sentences
172
+ before you get to something useful. Retrieved passages may be paraphrased for local colour and attributed by
173
+ title, but they can never supply a number."""
 
174
 
175
  SAFETY_ANSWER = """A person may be at risk. Respond with warmth and brevity. Do not analyse the syndemic graph,
176
  do not rank interventions, do not mention rankings or scores. Acknowledge, encourage contact with the named
syndemic/ops.py CHANGED
@@ -299,6 +299,8 @@ def _plan_lines(items: List[Dict[str, Any]]) -> str:
299
  rows.append(f" {i+1}. {it['lab']} [{it['tier']}] confidence {it['conf']*100:.0f}%")
300
  for w in it["why"][:2]:
301
  rows.append(f" driven by: {w}")
 
 
302
  for g in it["geo_why"][:2]:
303
  rows.append(f" context: {g}")
304
  if it["feas_note"]:
@@ -375,7 +377,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
375
  facts = (f"OPERATION: safety\nSAFETY TIER: RED\nPLACE: {E.LOCS[st.a]['name']}\n"
376
  f"VERIFIED RESOURCE: {res['txt']}\nRESOURCE RESOLUTION LEVEL: {res['lvl']}\n"
377
  "The syndemic ranking is suspended for this turn.")
378
- return Result(op="Safety", title="Safety-first handling", badges=["red tier"], safety=True,
379
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], expl="safety template, no ranking"),
380
  facts=facts,
381
  body=f"**{res['txt']}**\n\nIf there is immediate danger, contact local emergency services now.",
@@ -399,7 +401,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
399
  if not extracted.get("summary"):
400
  extracted = dict(extracted, summary=fallback["summary"])
401
  if not nodes:
402
- return Result(op="New case", title="I could not find a case in that",
403
  trace=E.trace(st, None, None, gate=False, expl="no nodes extracted"),
404
  facts=("OPERATION: set_case FAILED. Nothing in the message mapped to the factor "
405
  "catalogue. Ask the user to describe the person's situation, symptoms, sleep, "
@@ -419,6 +421,24 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
419
  inferred = [v["lab"] for v in prof.values() if v["st"] == "inferred"]
420
  edges = [f"{prof[a]['lab']} {'<->' if k == 'bi' else '->'} {prof[b]['lab']}"
421
  for a, b, k, strength in E.EDGES_I if a in prof and b in prof and strength != "weak"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
422
  facts = (f"OPERATION: build a new individual syndemic graph from the user's description\n"
423
  f"CASE: {st.summary}\n"
424
  f"NODES EXTRACTED ({len(prof)}): "
@@ -429,21 +449,22 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
429
  f"SAFETY TIER: {st.tier().upper()}\n"
430
  f"PLACE CURRENTLY APPLIED: {E.LOCS[st.a]['name']}\n"
431
  f"PATHWAY UNDER THAT PLACE:\n{_plan_lines(p)}\n"
432
- "Confirm what you took from their description, name anything you inferred rather than were "
433
- "told, and invite them to correct it or move the person to another place.")
434
  body = ("**X_u — " + st.summary + "**\n\n"
435
  + "\n".join(f"- **{v['lab']}** severity {v['sev']} `{v['st']}`"
436
  + (f" — {v['sub']}" if v['sub'] else "") for v in prof.values()))
437
- return Result(op="New case", title="Individual syndemic graph rebuilt",
438
- badges=[f"{len(prof)} nodes", f"{len(edges)} interactions"],
439
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], plan_n=len(p),
440
  expl="case parsed into X_u"),
441
  facts=facts, body=body,
442
- followups=["How does living in Dhaka affect this case?",
443
- "Move this person to Sweden.", "What do you not know?"])
 
444
 
445
  if op == "help":
446
- return Result(op="Help", title="Seven supported operations",
447
  trace=E.trace(st, None, None, gate=False, expl="capability listing"),
448
  facts=("OPERATION: help\nThe system supports EXACTLY these seven operations and no others. "
449
  "Name only these:\n"
@@ -471,7 +492,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
471
  p = E.plan(st, ctx, True)
472
  facts = ("OPERATION: remove geography (ablation)\nC_g* IS EMPTY - no contextual factor entered G_S.\n"
473
  f"SAFETY TIER: {st.tier().upper()}\nINDIVIDUAL-ONLY PATHWAY:\n{_plan_lines(p)}")
474
- return Result(op="Remove geography", title="Geography-ablated reasoning view", badges=["C_g* = empty"],
475
  trace=E.trace(st, ctx, None, gate=False, plan_n=len(p), expl="individual-only ranking"),
476
  facts=facts, body=_md_plan(p, "Individual-only pathway", None),
477
  followups=["Move this person to Sweden.", "How does living in Dhaka affect this case?"])
@@ -486,7 +507,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
486
  f"INFERRED (not reported) NODES: poor diet, metabolic vulnerability\n"
487
  f"EVIDENCE THRESHOLD tau = {st.tau:.2f}\nCONTEXT:\n{_ctx_lines(ctx)}")
488
  bars = "\n".join(f"- `{k}` {v*100:.0f}%" for k, v in u.items())
489
- return Result(op="Uncertainty", title=f"What I do not know about {E.LOCS[st.a]['short']}",
490
  badges=[f"{len(out)} abstentions"],
491
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], expl="uncertainty decomposition"),
492
  facts=facts, body=bars + "\n\n" + _md_prov(ctx, E.LOCS[st.a]["short"]),
@@ -495,7 +516,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
495
  if op == "counterfactual":
496
  cfd = next((c for c in E.CFS if c["k"] == factor), None)
497
  if not cfd:
498
- return Result(op="Counterfactual", title="Which structural variable should move?",
499
  trace=E.trace(st, None, E.LOCS[st.a]["short"], gate=False, expl="clarification"),
500
  facts="OPERATION: counterfactual, target not identified. Ask which variable to move. "
501
  "No statistics.",
@@ -539,7 +560,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
539
  f"FLIPS:\n" + "\n".join(f" {f['t']}: " + re.sub(r"[*]+", "", f["d"]) for f in flips))
540
  docs = retrieve_for(st, st.b)
541
  facts += ("\n" + retrieval.as_facts(docs)) if docs else ""
542
- return Result(passages=docs, op="Compare", title=f"Same person, {na} → {nb}",
543
  badges=[f"{len(flips)} flips", "G_I identical"],
544
  trace=E.trace(st, c2, f"{na} + {nb}", plan_n=len(p2), expl="flip taxonomy"),
545
  facts=facts,
@@ -567,7 +588,7 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
567
  docs = retrieve_for(st, st.a)
568
  facts += ("\n" + retrieval.as_facts(docs)) if docs else ""
569
  return Result(passages=docs, op="Contextualize",
570
- title=f"Geographic context applied — {E.LOCS[st.a]['short']}",
571
  badges=[f"{len(used)}/{len(E.FACTORS)} factors",
572
  f"{len(back)} backed off" if back else "no backoff"],
573
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], plan_n=len(p),
@@ -594,8 +615,8 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
594
  body = "\n".join(f"- **{E.FACTORS[k]['lab']}** — {E.fmt(c1[k]['v'], k)} in {na} vs "
595
  f"{E.fmt(c2[k]['v'], k)} in {nb} `{E.RES_LAB[c1[k]['res']]} {c1[k]['yr']}`"
596
  for k in drivers) or "_No single contextual factor differs enough to drive a change._"
597
- return Result(op="Explain", title=f"What made the {na} → {nb} answer differ",
598
- badges=[f"{len(drivers)} driving nodes"],
599
  trace=E.trace(st, c2, f"{na} + {nb}", plan_n=len(p2), expl="attribution to gated nodes"),
600
  facts=facts, body=body + "\n\n" + _md_flips(flips),
601
  followups=["Keep them here but improve healthcare access.",
@@ -614,8 +635,8 @@ def execute(st: E.State, intent: Dict[str, Any], text: str) -> Result:
614
  f"INFERRED NODES (not reported by the person): "
615
  f"{', '.join(v['lab'] for v in prof.values() if v['st'] == 'inferred') or 'none'}\n"
616
  f"SAFETY TIER: {st.tier().upper()}\nNo place has been applied in this operation.")
617
- return Result(op="Analyze", title="Individual syndemic graph G_I",
618
- badges=[f"{sum(1 for v in st.sev.values() if v > 0)} active nodes"],
619
  trace=E.trace(st, ctx, None, plan_n=len(p), expl="graph description"),
620
  facts=facts, body="\n".join(f"- {x}" for x in inter[:5]),
621
  followups=["How does living in Dhaka affect this case?",
 
299
  rows.append(f" {i+1}. {it['lab']} [{it['tier']}] confidence {it['conf']*100:.0f}%")
300
  for w in it["why"][:2]:
301
  rows.append(f" driven by: {w}")
302
+ if it.get("says"):
303
+ rows.append(f" SUPPORT (use this wording): {it['says']}")
304
  for g in it["geo_why"][:2]:
305
  rows.append(f" context: {g}")
306
  if it["feas_note"]:
 
377
  facts = (f"OPERATION: safety\nSAFETY TIER: RED\nPLACE: {E.LOCS[st.a]['name']}\n"
378
  f"VERIFIED RESOURCE: {res['txt']}\nRESOURCE RESOLUTION LEVEL: {res['lvl']}\n"
379
  "The syndemic ranking is suspended for this turn.")
380
+ return Result(op="Safety", title="Please read this first", badges=["red tier"], safety=True,
381
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], expl="safety template, no ranking"),
382
  facts=facts,
383
  body=f"**{res['txt']}**\n\nIf there is immediate danger, contact local emergency services now.",
 
401
  if not extracted.get("summary"):
402
  extracted = dict(extracted, summary=fallback["summary"])
403
  if not nodes:
404
+ return Result(op="New case", title="Tell me a bit more",
405
  trace=E.trace(st, None, None, gate=False, expl="no nodes extracted"),
406
  facts=("OPERATION: set_case FAILED. Nothing in the message mapped to the factor "
407
  "catalogue. Ask the user to describe the person's situation, symptoms, sleep, "
 
421
  inferred = [v["lab"] for v in prof.values() if v["st"] == "inferred"]
422
  edges = [f"{prof[a]['lab']} {'<->' if k == 'bi' else '->'} {prof[b]['lab']}"
423
  for a, b, k, strength in E.EDGES_I if a in prof and b in prof and strength != "weak"]
424
+ domains = {v["col"] for v in prof.values()}
425
+ missing = [d for d in E.COLUMNS if d not in domains]
426
+ thin = len(prof) < 4 or len(missing) >= 2
427
+ ask = []
428
+ if "mental" in missing:
429
+ ask.append("how their mood and stress have been over the last couple of weeks")
430
+ if "social" in missing:
431
+ ask.append("whether money, food or housing is under pressure")
432
+ if "body" in missing:
433
+ ask.append("whether anything physical is going on - stomach, infections, pain, energy")
434
+ if "sleep_short" not in prof:
435
+ ask.append("how many hours they actually sleep and whether it is broken")
436
+ if "self_medication" not in prof:
437
+ ask.append("whether they have anyone they see about this already")
438
+ intake = ("\nTHE PICTURE IS STILL THIN. Do NOT present a confident plan. Confirm what you heard in one "
439
+ "sentence, say plainly that this is not yet enough to see how things interact, then ask "
440
+ "EXACTLY TWO short questions, chosen from: " + "; ".join(ask[:4]) + ". "
441
+ "Ask them as a person would, not as a form.") if thin else ""
442
  facts = (f"OPERATION: build a new individual syndemic graph from the user's description\n"
443
  f"CASE: {st.summary}\n"
444
  f"NODES EXTRACTED ({len(prof)}): "
 
449
  f"SAFETY TIER: {st.tier().upper()}\n"
450
  f"PLACE CURRENTLY APPLIED: {E.LOCS[st.a]['name']}\n"
451
  f"PATHWAY UNDER THAT PLACE:\n{_plan_lines(p)}\n"
452
+ "Confirm what you took from their description and name anything you inferred rather than "
453
+ "were told." + intake)
454
  body = ("**X_u — " + st.summary + "**\n\n"
455
  + "\n".join(f"- **{v['lab']}** severity {v['sev']} `{v['st']}`"
456
  + (f" — {v['sub']}" if v['sub'] else "") for v in prof.values()))
457
+ return Result(op="New case", title="What I heard",
458
+ badges=[f"{len(prof)} factors", f"{len(edges)} interactions"],
459
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], plan_n=len(p),
460
  expl="case parsed into X_u"),
461
  facts=facts, body=body,
462
+ followups=(["What should I do first?", "What else do you need to know?"] if thin
463
+ else ["What should I do first?", "How does living here change this?",
464
+ "What do you not know?"]))
465
 
466
  if op == "help":
467
+ return Result(op="Help", title="What I can do",
468
  trace=E.trace(st, None, None, gate=False, expl="capability listing"),
469
  facts=("OPERATION: help\nThe system supports EXACTLY these seven operations and no others. "
470
  "Name only these:\n"
 
492
  p = E.plan(st, ctx, True)
493
  facts = ("OPERATION: remove geography (ablation)\nC_g* IS EMPTY - no contextual factor entered G_S.\n"
494
  f"SAFETY TIER: {st.tier().upper()}\nINDIVIDUAL-ONLY PATHWAY:\n{_plan_lines(p)}")
495
+ return Result(op="Remove geography", title="Ignoring where you live", badges=["C_g* = empty"],
496
  trace=E.trace(st, ctx, None, gate=False, plan_n=len(p), expl="individual-only ranking"),
497
  facts=facts, body=_md_plan(p, "Individual-only pathway", None),
498
  followups=["Move this person to Sweden.", "How does living in Dhaka affect this case?"])
 
507
  f"INFERRED (not reported) NODES: poor diet, metabolic vulnerability\n"
508
  f"EVIDENCE THRESHOLD tau = {st.tau:.2f}\nCONTEXT:\n{_ctx_lines(ctx)}")
509
  bars = "\n".join(f"- `{k}` {v*100:.0f}%" for k, v in u.items())
510
+ return Result(op="Uncertainty", title=f"What I don't know about {E.LOCS[st.a]['short']}",
511
  badges=[f"{len(out)} abstentions"],
512
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], expl="uncertainty decomposition"),
513
  facts=facts, body=bars + "\n\n" + _md_prov(ctx, E.LOCS[st.a]["short"]),
 
516
  if op == "counterfactual":
517
  cfd = next((c for c in E.CFS if c["k"] == factor), None)
518
  if not cfd:
519
+ return Result(op="Counterfactual", title="Which one thing should change?",
520
  trace=E.trace(st, None, E.LOCS[st.a]["short"], gate=False, expl="clarification"),
521
  facts="OPERATION: counterfactual, target not identified. Ask which variable to move. "
522
  "No statistics.",
 
560
  f"FLIPS:\n" + "\n".join(f" {f['t']}: " + re.sub(r"[*]+", "", f["d"]) for f in flips))
561
  docs = retrieve_for(st, st.b)
562
  facts += ("\n" + retrieval.as_facts(docs)) if docs else ""
563
+ return Result(passages=docs, op="Compare", title=f"The same person, in {nb}",
564
  badges=[f"{len(flips)} flips", "G_I identical"],
565
  trace=E.trace(st, c2, f"{na} + {nb}", plan_n=len(p2), expl="flip taxonomy"),
566
  facts=facts,
 
588
  docs = retrieve_for(st, st.a)
589
  facts += ("\n" + retrieval.as_facts(docs)) if docs else ""
590
  return Result(passages=docs, op="Contextualize",
591
+ title=f"Living in {E.LOCS[st.a]['short']}",
592
  badges=[f"{len(used)}/{len(E.FACTORS)} factors",
593
  f"{len(back)} backed off" if back else "no backoff"],
594
  trace=E.trace(st, ctx, E.LOCS[st.a]["short"], plan_n=len(p),
 
615
  body = "\n".join(f"- **{E.FACTORS[k]['lab']}** — {E.fmt(c1[k]['v'], k)} in {na} vs "
616
  f"{E.fmt(c2[k]['v'], k)} in {nb} `{E.RES_LAB[c1[k]['res']]} {c1[k]['yr']}`"
617
  for k in drivers) or "_No single contextual factor differs enough to drive a change._"
618
+ return Result(op="Explain", title="Why the answer changed",
619
+ badges=[f"{len(drivers)} local differences"],
620
  trace=E.trace(st, c2, f"{na} + {nb}", plan_n=len(p2), expl="attribution to gated nodes"),
621
  facts=facts, body=body + "\n\n" + _md_flips(flips),
622
  followups=["Keep them here but improve healthcare access.",
 
635
  f"INFERRED NODES (not reported by the person): "
636
  f"{', '.join(v['lab'] for v in prof.values() if v['st'] == 'inferred') or 'none'}\n"
637
  f"SAFETY TIER: {st.tier().upper()}\nNo place has been applied in this operation.")
638
+ return Result(op="Analyze", title="What stands out",
639
+ badges=[f"{len(prof)} factors"],
640
  trace=E.trace(st, ctx, None, plan_n=len(p), expl="graph description"),
641
  facts=facts, body="\n".join(f"- {x}" for x in inter[:5]),
642
  followups=["How does living in Dhaka affect this case?",