Metadata-Version: 2.4
Name: syntropy-lhm
Version: 0.2.0
Summary: LHM — Longevity Health Metrics SDK: chat-programmable, clinically-modelled n-of-1 personal metrics (correlation-not-causation by construction).
Author: Syntropy Health
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/Syntropy-Health/lhm
Project-URL: Repository, https://github.com/Syntropy-Health/lhm
Project-URL: Documentation, https://github.com/Syntropy-Health/lhm/tree/main/docs
Keywords: fhir,n-of-1,health-metrics,quantified-self
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3
Classifier: Intended Audience :: Developers
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: fhir.resources==8.3.0
Provides-Extra: units
Requires-Dist: pint<0.26,>=0.25; extra == "units"
Requires-Dist: ucumvert<0.4,>=0.3; extra == "units"
Provides-Extra: lhm-scoring
Requires-Dist: statsmodels<0.15,>=0.14; extra == "lhm-scoring"
Requires-Dist: scikit-learn<2,>=1.5; extra == "lhm-scoring"
Provides-Extra: publish
Requires-Dist: httpx<1,>=0.27; extra == "publish"
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.30; extra == "mcp"
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: pytest-asyncio>=0.23; extra == "test"
Dynamic: license-file

# LHM — Longevity Health Metrics SDK

**One plain-English question about your own health data → a claim-safe,
uncertainty-carrying personal metric → published to your dashboard.**

```python
from syntropy import lhm

result = await lhm.ask(
    "How does my magnesium intake relate to my sleep quality?",
    adapter=my_data,            # your data, your process — nothing leaves it
    interpreter=my_llm,         # bring your own LLM (or skip NL entirely)
)
result.suggestions                    # tiered candidates: low / mid / strong
await result.publish(my_dashboard)    # → your syntropy-journal dashboard
```

That's the whole loop: **language → analysis → metric suggestions →
publication**. Your inputs (supplements, food, regimen starts) and outcomes
(journal series, wearables, check-ins) are mapped onto standard FHIR
resources, analyzed as a single-subject observational series with named
statistical corrections, tiered, gated for claim-safety, and pushed to a
dashboard you own.

> **The honesty layer is structural, not prose.** Every metric is a personal
> correlation/trend — never a causal, treatment, or clinical claim. The
> claim-scope guard (`syntropy.lhm.metrics.claims.assert_claim_safe`) gates every
> persist, publish, and render: banned clinical-efficacy vocabulary fails
> loudly, and a metric cannot exist without its uncertainty caveats.

## Install

```bash
pip install syntropy-lhm                # core: clinical mapping + pipeline + contracts
pip install "syntropy-lhm[units]"       # + UCUM quantity validation (pint/ucumvert)
pip install "syntropy-lhm[publish]"     # + the HTTP publisher (httpx transport)
pip install "syntropy-lhm[mcp]"         # + lhm-mcp, the local MCP server

# pip install "syntropy-lhm[stats]"     # v2 — not yet published; the numerical-
#                              # estimator extra ships with the v2 estimators
#                              # (see the roadmap below). Installing it today
#                              # would fail: the extra does not exist yet.
```

Core stays lean by design: `fhir.resources` (typed FHIR R4B, pydantic v2) and
nothing else — no web framework, no ORM, no LLM, no network I/O.

## Use it from Claude, or any MCP client (`lhm-mcp`)

`lhm-mcp` is a local MCP server that offers three tools to an MCP client such
as Claude Desktop or Claude Code: `lhm_fetch`, `lhm_analyze` and `lhm_manage`.
It runs on your machine over stdio and reads only files you point it at. It
makes no network calls, and it writes nothing unless you name a `--store` file.

```bash
pip install "syntropy-lhm[mcp]"
lhm-mcp --demo                                       # synthetic data, zero setup
lhm-mcp --data ~/my-health                           # your own files
lhm-mcp --data ~/my-health --store ~/my-health/metrics.jsonl  # let lhm_manage keep metrics
```

Claude Desktop (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "lhm": { "command": "lhm-mcp", "args": ["--data", "/Users/you/my-health"] }
  }
}
```

Claude Code: `claude mcp add lhm -- lhm-mcp --data ~/my-health`

**Your data directory.** `orders.json` holds what you took or bought, and
`regimen_starts.json` (optional) holds when you started something. Each
outcome you track is a CSV in `series/` with the columns `observed_at,value`;
the file name is the outcome's name.

```json
[{"item_display": "Magnesium glycinate", "occurred_at": "2026-01-15"}]
```

```csv
observed_at,value
2026-01-01,6.5
2026-01-02,7.0
```

Timestamps need a timezone (`2026-01-05T08:00:00Z`). A bare date is read as
midnight UTC. The full format is a JSON schema in the package:
`syntropy/lhm/contracts/lhm-local-data.v1.schema.json`.

Every result is a personal association in your own data, with its
uncertainty, never a causal finding. The candidate labels `lhm_analyze`
returns pass the SDK's claim check; a label that fails it is withheld. Names
taken from your files (items, outcomes) are passed through as data: control
characters are removed, each is cut to 200 characters, and every result has a
size limit. Log lines carry counts and timings only, never your values.

## How it works

```
"How does my magnesium relate to my sleep?"
      │
      ▼  Interpreter (BYO-LLM — optional; every step below is typed & callable directly)
MetricIntent(input="magnesium", outcome="sleep quality", window=90d)
      │
      ▼  fetch(adapter, user)         # your data → FHIR-mapped, time-aligned series
AlignedData(regimen start marked, rx-tier flagged)
      │
      ▼  analyze(aligned)             # six named n-of-1 corrections, tier surface
CandidateSignal(tier=mid, interval, corrections, caveats)
      │
      ▼  manage("add", candidate)     # the R10 claim gate — banned lexicon fails here
MetricSpec + VizPayload               # the persistence + render contracts
      │
      ▼  publish(target)              # self-hosted journals, or cloud w/ API key
your dashboard
```

**The NL layer is sugar, never load-bearing.** Every stage consumes and
returns typed models you can construct by hand — `syntropy.lhm.ask()` is a
convenience composition, not a magic box. The LLM only narrows language to a
`MetricIntent`; the SDK binds it to your actual data deterministically, so a
hallucinated column can't silently become a metric.

## Bring your own data (the only required integration)

Implement three async readers — that's the whole adapter contract:

```python
class MyAdapter:
    async def read_orders(self, user_scope): ...          # → [OrderRecord]
    async def read_regimen_starts(self, user_scope): ...  # → [RegimenStartRecord]
    async def read_outcome_series(self, user_scope): ...  # → [SeriesRecord]
```

CSV, SQLite, a wearable export, a full app backend — anything that can fill
those records. `user_scope` is an opaque token you choose; LHM never sees a
name, email, or free-text note (check-in notes reach it only as an
in-boundary sentiment float you derive).

## Publish: self-hosted first, cloud by API key

The publish contract (`lhm-publish/v1`) is ONE versioned envelope —
`MetricSpec` + `VizPayload` + an idempotency key — POSTed to a
syntropy-journal backend:

```python
from syntropy.lhm import SyntropyTarget

# Self-hosted: your own syntropy-journal instance
target = SyntropyTarget(base_url="https://journal.my-lab.dev")

# Cloud (commercial): the SAME contract — an API key is the only delta
target = SyntropyTarget(
    base_url="https://app.syntropyhealth.bio",
    api_key=os.environ["SYNTROPY_API_KEY"],     # never persisted by the SDK
)

receipt = await result.publish(target)
receipt.dashboard_url                            # deep link to the rendered card
```

Publishing is idempotent (at-least-once safe), claim-gated *before*
transport, and Rx-tier metrics structurally refuse public surfaces. The SDK
never stores your key (it is held as a `SecretStr` — masked in `repr` and
every `model_dump`).

Targets must be `https://` — the API key rides a header, and plain `http`
would send it in cleartext. Plain `http` is accepted only for loopback dev
hosts (`localhost` / `127.0.0.1` / `[::1]`); anything else needs an explicit
`SyntropyTarget(..., allow_insecure=True)` opt-in. If you publish in-process
instead of over HTTP, `InProcessPublisher(callback, public_surface=...)`
requires the surface declaration — there is no default.

## Status & roadmap

| Layer | What | Status |
|---|---|---|
| **L0** — contracts | `MetricSpec`, `lhm-viz/v1` schema, claim-scope guard | ✅ shipped |
| **L1** — clinical mapping | orders/regimens/series → FHIR R4B; synthetic fixtures; PHI/secret gates | ✅ shipped |
| **L2** — pipeline v0.1 | `fetch → analyze → manage`; six correction hooks (contract-tested stubs); tier surface | ✅ shipped |
| **L3** — journals adoption | reference adapters, dashboard binding, the `/api/lhm/v1/metrics` route | ✅ shipped |
| **L4** — NL + publish | `syntropy.lhm.nl` (`MetricIntent`, `Interpreter`, `resolve_intent`), `syntropy.lhm.publish` (envelope, targets, publishers), `syntropy.lhm.ask` | ✅ shipped — [design 0001](docs/design/0001-nl-to-publish-pipeline.md) |
| **L4** — docs pillar | app-independent guide tree ([docs/](docs/README.md)), execution-verified examples | ✅ shipped |
| **L4** — packaging | the D13 repo split + PyPI publish | 🔜 next |
| **v2** — real estimators | `syntropy-lhm[stats]`: AR(1)/detrend/ITS/posterior + FDR in the six hooks; ratified tier cutoffs | 📐 hooks in place |
| **cloud** — hosted dashboard | API-key issuance, workspaces, the commercial surface | 🗺 vision |

**Packaging:** LHM lives in the syntropy-journal repo through L3 (maximum-
coupling build phase), then splits to its own repo + PyPI at L4 so
`pip install syntropy-lhm` is real and the app consumes it like any dependency —
decision record: [design 0002](docs/design/0002-packaging-strategy.md).

v0.1 proves shapes and plumbing; the deterministic stubs make every contract
testable today. The full design for the NL→publish pipeline — use cases,
dependency tiers (numerical / clinical / models), the publish data models,
and the API-key semantics — lives in
[`docs/design/0001-nl-to-publish-pipeline.md`](docs/design/0001-nl-to-publish-pipeline.md).
Full guides — quickstart, adapters, NL & `syntropy.lhm.ask`, publishing, the honesty
layer, and the error reference — live at [`docs/README.md`](docs/README.md).

## Design principles

- **App-independent**: bring your own adapter, LLM, and render surface.
  (Syntropy's journal app is the first consumer, not a dependency.)
- **Clinical models, not bespoke schemas**: FHIR R4B via
  [`fhir.resources`](https://pypi.org/project/fhir.resources/).
- **Versioned contracts**: `lhm-viz/v1` (render) and `lhm-publish/v1`
  (transport) — additive-only within a version; JSON schemas ship in the
  package.
- **Privacy-blind by construction**: in-process data only; no payload
  logging; opaque subject tokens; all bundled fixtures synthetic
  (scan-gated in CI).
- **Honest by construction**: correlation language, uncertainty intervals,
  verbatim caveats, and a lexicon gate that fails the build — not a
  disclaimer paragraph.

## Quickstart (v0.1 — the shapes that already run)

```python
from syntropy.lhm import InputRef, MetricSpec, OutcomeRef, to_viz_payload, VizPoint

spec = MetricSpec(
    metric_key="mag_sleep",
    label="Magnesium intake and sleep quality — personal trend",
    inputs=(InputRef(resource="NutritionOrder", code="supplement-order",
                     display="Magnesium glycinate"),),
    outcome=OutcomeRef(kind="journal_series", series_key="sleep_quality"),
    confidence="mid",
    caveats=(
        "Personal n-of-1 association from your own records — observational, not causal.",
        "Estimates carry an uncertainty interval and may not generalize.",
    ),
    rx_input=False,
)
payload = to_viz_payload(spec, series=[VizPoint(ts=..., value=...)])  # render-gated
```

And the L2 pipeline end-to-end against synthetic data:

```python
from syntropy.lhm.fixtures import synthetic_order, synthetic_regimen_start, synthetic_series
from syntropy.lhm.tools import analyze, fetch, manage

aligned = await fetch(my_adapter, "subject-001")
signals = await analyze(aligned)                  # tiered, corrections-threaded
outcome = await manage("add", signals[0])         # claim-gated, persistence-ready
outcome.parameterization                          # the C4 JSONB your store persists
```

## Running the shipped tests

The test suite ships in the source distribution. Several suites are async, so
install the `test` extra first: a bare `pytest` without `pytest-asyncio`
reports them as failures. The configuration (`asyncio_mode = "auto"`) is in
`pyproject.toml`, and some tests read `LICENSE` and `pyproject.toml`, so run
from the unpacked source root.

```bash
pip download --no-deps --no-binary :all: syntropy-lhm==0.2.0
tar xzf syntropy_lhm-0.2.0.tar.gz && cd syntropy_lhm-0.2.0
pip install ".[test,mcp,units,lhm-scoring]"
pytest
```

Tests for an extra you did not install are skipped, not failed.

## License

Apache-2.0. Runtime dependencies are BSD/MIT-family only (attributions in
[`NOTICE`](NOTICE)); no copyleft in the graph, re-verified at every release.
All example data is synthetic.
