Skip to main content
Glama
README.md
# PainFree CareGraph

Local-first personal health journal and multi-hop memory graph powered by [Relate](https://github.com/relatedb/relate) (`relatedb/relate` v1.3.0), MCP, and zero-backend WebAssembly.

- **Demo Video (59s FHD):** https://youtu.be/m7ti620GTek
- **Zero-Install Live Demo (Relate WASM on GitHub Pages):** https://lainholic.github.io/painfree-caregraph/
- **Public Repository:** https://github.com/Lainholic/painfree-caregraph

## Use case

Everyday health logs fail when they stay as flat notes or isolated vector chunks: patients miss delayed next-day triggers (such as `<6h` sleep or late caffeine leading to next-day tinnitus), medication side-effect loops (such as frequent NSAIDs aggravating tinnitus or indigestion), and which care routines actually improve next-day recovery.

PainFree CareGraph turns a 10-second daily check-in (EN/KO) into a private on-device graph database that connects:
- **Temporal chains:** `(:Episode)-[:NEXT_DAY]->(:Episode)`
- **Delayed causes:** `(:Trigger)<-[:HAS_TRIGGER]-(prev)-[:NEXT_DAY]->(curr)-[:HAS_SYMPTOM]->(:Symptom)`
- **Sleep risk contrast:** `<6h` sleep vs `>=6h` sleep next-day symptom rates directly in Cypher
- **Safety & care guidance:** `(:Care|Trigger)-[:CAUTION_WITH]->(:Symptom)` and `(:Symptom)-[:ELIGIBLE_INFO]->(:SupportProgram)` (verified US/KR public assistance references with official URLs)
- **Cross-episode memory:** `(:Episode)-[:SIMILAR_TO]->(:Episode)` via Relate native vector search
- **Dual-audience UX (`Patient View` / `Full View` toggle):** Designed for both everyday patients (a calm 10-second check-in and color calendar) and judges/explorers (full Relate 1.3 multi-hop insights, Cypher traces, interactive memory graph, and Live Cypher Playground).

## How it uses Relate

- **Mode:** **Single file (`.rl`)** for the local Python + MCP + Web app, plus **in-browser WebAssembly (`@relate/relate-wasm` v1.3.0)** for the zero-install live demo.
- **Why this mode:** Personal health notes are deeply sensitive and belong on the user's own device with zero external database server or cloud signup. A single `.rl` file makes local persistence, portable backup/restore (`/api/export-rl`, `/api/import-rl`), and judge inspection trivial—while the WASM build lets anyone test Cypher queries and multi-hop graphs directly in a browser tab.
- **What the graph models:**
  - **Nodes:** `:Episode` (date, sleep_hours, fatigue, condition, mood, raw_note, search_terms, 32-dim `embedding`), `:Symptom`, `:Trigger`, `:State`, `:Care`, `:Tag`, `:SupportProgram`
  - **Relationships:** `:NEXT_DAY`, `:HAS_SYMPTOM {severity}`, `:HAS_TRIGGER {intensity}`, `:HAS_STATE {value}`, `:USED_CARE {note}`, `:HAS_TAG`, `:CAUTION_WITH {reason}`, `:SIMILAR_TO {score}`, `:ELIGIBLE_INFO`
  - **Relate 1.3.0 Native Capabilities:**
    - `CREATE FULLTEXT INDEX ep_ft` (`fulltext-2.0`) + `CREATE VECTOR INDEX ep_vec` (`vector-2026.08`, cosine) queried via Cypher 25 `SEARCH`
    - Engine-level `read_only=True` connections for all Web GET endpoints, `Ask CareGraph` agent traces, and MCP `run_readonly_cypher`
    - Browser-side `@relate/relate-wasm@1.3.0` with live `FULLTEXT INDEX` and an interactive Cypher Playground

## Live Screenshots

| 30-Day Heatmap & Multi-Hop Insights | Ask CareGraph Agent (3-Step Relate Cypher Trace) |
|---|---|
| ![Dashboard & Insights](docs/screenshots/01_dashboard_insights.png) | ![Ask CareGraph Agent](docs/screenshots/02_agent_cypher_trace.png) |

**Zero-Install Browser WASM Demo (`docs/index.html`) with Live Cypher Playground:**

![Browser WASM Demo & Cypher Playground](docs/screenshots/03_wasm_cypher_playground.png)

## Architecture

```
+--------------------------------------------+
|  Interactive Web UI (web/index.html)       |  <-- Zero-XSS DOM, 30-day Heatmap, Ask Agent, SVG Graph
|  Zero-Backend WASM UI (docs/index.html)    |  <-- @relate/relate-wasm@1.3.0 + Live Cypher Playground
+--------------------------------------------+
                    | HTTP (127.0.0.1:8787)
                    v
+--------------------------------------------+      +-----------------------------------+
| CareGraph Engine (src/caregraph/*.py)      | <--> | Local MCP Server (stdio)          |
|  - Bilingual EN/KO Parser & Negation Guard |      | - log_health_entry                |
|  - Relate FULLTEXT + VECTOR Hybrid SEARCH  |      | - search_health_memory            |
|  - Ask CareGraph 3-Step Cypher Trace       |      | - ask_caregraph_agent             |
|  - Multi-Hop NEXT_DAY & Recovery Cypher    |      | - trace_symptom / check_cautions  |
|  - 14-Day Clinician Doctor Brief           |      | - doctor_brief / readonly_cypher  |
+--------------------------------------------+      +-----------------------------------+
                    |
                    v
   [ data/local_caregraph.rl ]  (auto-seeded from committed data/sample_painfree_care.rl)
```

## Setup and run

**Prerequisites:** Python `>=3.10` (no external database server or API key required).

### Windows (PowerShell)
```powershell
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements.txt
.\.venv\Scripts\python.exe -m pip install -e .

# 1. Run automated test suite (verifies .rl persistence, native indexes, multi-hop Cypher, MCP, HTTP)
.\.venv\Scripts\python.exe -m pytest -v

# 2. Launch the interactive Web UI (http://127.0.0.1:8787 and /wasm)
.\.venv\Scripts\python.exe -m caregraph.web

# 3. (Optional) Regenerate the committed 30-day sample .rl graph
.\.venv\Scripts\python.exe -m caregraph.seed

# 4. Run the local MCP server (stdio)
.\.venv\Scripts\python.exe -m caregraph.mcp_server
```

### macOS / Linux
```bash
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
.venv/bin/pip install -e .
.venv/bin/pytest -v
.venv/bin/python -m caregraph.web
```

## Where the data lives

- **Committed inspectable Relate store:** `data/sample_painfree_care.rl` (30 days of multi-domain episodes, native `ep_ft` + `ep_vec` indexes, `NEXT_DAY` chains, `CAUTION_WITH` safety edges, and verified US/KR `SupportProgram` nodes).
- **Local runtime store (gitignored):** `data/local_caregraph.rl` (automatically copied from `data/sample_painfree_care.rl` on first launch; overridable via `CAREGRAPH_DB_PATH`).

Inspect the committed `.rl` file directly in Python:
```python
import relate
conn = relate.connect("data/sample_painfree_care.rl", read_only=True)
cur = conn.cursor()
cur.execute("MATCH (t:Trigger)<-[:HAS_TRIGGER]-(prev:Episode)-[:NEXT_DAY]->(curr:Episode)-[r:HAS_SYMPTOM]->(s:Symptom {name: 'Tinnitus'}) RETURN t.name AS trigger, count(DISTINCT curr) AS hits ORDER BY hits DESC")
print([dict(r) for r in cur.fetchall()])
conn.close()
```

## MCP Client Configuration (Claude Desktop / Cursor)

```json
{
  "mcpServers": {
    "painfree-caregraph": {
      "command": "/path/to/painfree-caregraph/.venv/bin/python",
      "args": ["-m", "caregraph.mcp_server"]
    }
  }
}
```

**Exposed MCP Tools (8):**
1. `log_health_entry(note, date?)` — Parse EN/KO free-text note and persist to `.rl`
2. `search_health_memory(query, limit?)` — Hybrid `FULLTEXT` + `VECTOR` `SEARCH` over health episodes
3. `ask_caregraph_agent(question)` — Answer EN/KO natural-language health questions with a 3-step Relate Cypher trace (`SEARCH` -> `NEXT_DAY` -> `CAUTION_WITH`)
4. `get_recorded_symptoms()` — List recorded symptoms with episode counts and severity stats
5. `trace_symptom(symptom_name)` — Multi-hop same-day, prior-day, sleep-contrast, and care-recovery insights
6. `check_cautions()` — Detect `CAUTION_WITH` medication/trigger interaction paths within a realistic window
7. `doctor_brief(days?)` — Clinician-ready summary scoped to the active calendar window with verified US/KR support links
8. `run_readonly_cypher(cypher)` — Arbitrary Cypher execution protected by Relate engine-level `read_only=True`

## Tech Stack Statement

- **Relate Capabilities (`relate-db` v1.3.0 & `@relate/relate-wasm` v1.3.0):** Single-file `.rl` store, `CREATE FULLTEXT INDEX`, `CREATE VECTOR INDEX`, Cypher 25 `SEARCH`, engine-level `read_only=True`, multi-hop temporal/safety traversals, browser WASM runtime.
- **Third-Party Libraries:** Python standard library (`http.server`, `re`, `json`, `urllib`), `mcp` (Model Context Protocol Python SDK), `pytest`.
- **AI Tools:** Runs **100% offline with zero API keys** via deterministic EN/KO parsing and local 32-dim concept embeddings. Optional opt-in Gemini extraction (`GEMINI_API_KEY`, default `gemini-4-hydrogen`, configurable via `CAREGRAPH_GEMINI_MODEL`) runs only if explicitly checked in the UI.

## License

MIT License — see [LICENSE](LICENSE).