> ## Documentation Index
> Fetch the complete documentation index at: https://docs.synheart.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Runtime FFI Surface

> The stable C ABI between the open-source Synheart SDKs and the runtime native binary

The Synheart SDKs (Dart, Swift, Kotlin) are thin shells over a native runtime binary. They communicate across a stable **C ABI** that is loaded at startup via `dlsym` (Apple platforms / Linux) or JNI (Android). This page documents the symbols your SDK actually calls.

<Note>
  Most apps never touch this layer directly — the SDK wraps it. This page is for: build-error diagnosis, custom integrations (CLIs, embedded hosts), or auditing what the SDK does on your behalf.
</Note>

## When you'd care

You see one of these:

* A linker error mentioning `libsynheart_core_runtime` or undefined `synheart_core_*` symbols.
* A `dlsym` / JNI error at runtime.
* You're embedding the runtime directly without using the SDK shells.
* You're writing platform glue code that calls the runtime from a non-mainstream language.

If none of these apply, [Architecture](/synheart-core/architecture) is the page you want.

## ABI rules

1. **C calling convention** — `extern "C"`, no name mangling, no exceptions across the boundary.
2. **Handle ownership** — `synheart_core_new` returns an opaque `*const SynheartCore` handle that the SDK owns and must free with `synheart_core_free`.
3. **Strings out of the runtime** are heap-allocated `*char` (UTF-8, null-terminated). Caller must release with `synheart_core_free_string`. Returning `NULL` means "no value" (not an error — check `last_error_code`).
4. **Strings into the runtime** are borrowed for the duration of the call. The runtime copies what it needs.
5. **Structured returns** are JSON strings. Lenient JSON parsing on both sides — unknown fields are tolerated.
6. **Error codes** are negative integers; success is `0` or a positive value (e.g. queue length).
7. **Thread safety** — the runtime is internally synchronised. Any thread can call any function on a handle. Callbacks (HSI, log, stream) fire on a runtime-owned thread; the SDK shell is responsible for re-dispatching to the host's UI/main thread.

## 1. Handle and lifecycle

| Symbol                                                  | Purpose                                                                                                               |
| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `synheart_core_new(config_json) -> *const SynheartCore` | Construct a runtime handle from a JSON config (subject id, data dir, cloud config, retention, etc.).                  |
| `synheart_core_free(handle)`                            | Destroy the handle. Idempotent on `NULL`.                                                                             |
| `synheart_core_is_runtime_available() -> bool`          | Returns `true` if the loaded shared library is the runtime. SDKs call this on startup to verify the binary is linked. |
| `synheart_core_last_error_code(handle) -> int32_t`      | Negative integer for the most recent error. Reset to `0` after read.                                                  |

## 2. Session lifecycle

| Symbol                                                                      | Purpose                                                                                                 |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `synheart_core_start_session(handle, session_kind, metadata_json) -> *char` | Open a session. Returns the session id as a JSON string (`{"session_id": "..."}`) or `NULL` on failure. |
| `synheart_core_stop_session(handle, session_id) -> int`                     | Close a session. Returns `0` on success.                                                                |
| `synheart_core_current_session(handle) -> *char`                            | Currently open session JSON, or `NULL` if no session is active.                                         |
| `synheart_core_is_running(handle) -> bool`                                  | Convenience flag — `true` when the engine pipeline is running.                                          |

## 3. HSI streaming

The runtime emits HSI 1.3 windows on a configurable cadence (default: 60s window, 5s step). Hosts subscribe via callback; the SDK exposes the stream as `Stream<HSIState>` / `AnyPublisher<...>` / `Flow<...>`.

| Symbol                                                            | Purpose                                                                                                        |
| ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `synheart_core_set_hsi_callback(handle, callback, user_data)`     | Register a callback `(user_data, json_ptr, json_len) -> void` invoked once per emitted HSI window.             |
| `synheart_core_clear_hsi_callback(handle)`                        | Unregister the callback. Called during SDK teardown.                                                           |
| `synheart_core_get_hsi_windows(handle, since_ms, limit) -> *char` | Replay recent HSI windows from local storage (JSON array).                                                     |
| `synheart_core_enqueue_hsi(handle, hsi_json) -> int`              | Enqueue an HSI window for cloud upload. Used when the SDK has the JSON in hand and wants to skip the listener. |

## 4. Sample ingest

The runtime accepts sensor samples through five push functions. All `ts_ms` parameters are device monotonic milliseconds.

| Symbol                                                                        | Purpose                                                                                |
| ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `synheart_core_push_hr(handle, ts_ms, bpm, source) -> int`                    | Heart-rate sample. `source` is a string id (`"apple_healthkit"`, `"ble_hrm"`, etc.).   |
| `synheart_core_push_rr(handle, ts_ms, rr_ms, source) -> int`                  | RR-interval sample (raw beat-to-beat). Highest fidelity input.                         |
| `synheart_core_push_accel(handle, ts_ms, x, y, z) -> int`                     | Accelerometer sample (m/s²). Drives motion-state head.                                 |
| `synheart_core_push_behavior(handle, ts_ms, event_type, payload_json) -> int` | Behavior event (tap, scroll, swipe, app\_switch, …). Payload is content-free metadata. |
| `synheart_core_push_sleep_stages(handle, stages_json) -> int`                 | Per-window sleep stages (REM/NREM/wake/awake) from a wearable.                         |
| `synheart_core_ingest_batch(handle, samples_json) -> int`                     | Bulk-ingest multiple samples in one call. Used during catch-up after backgrounding.    |

## 5. Cloud upload

The runtime owns a persistent SQLite upload queue. The SDK observes it; the runtime drains it.

| Symbol                                                       | Purpose                                                                                                                          |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `synheart_core_flush_uploads(handle) -> *char`               | Force-flush the queue if eligible (consent + reachability). Returns a JSON result `{"uploaded": n, "failed": n, "requeued": n}`. |
| `synheart_core_upload_queue_length(handle) -> int32_t`       | Current queue depth.                                                                                                             |
| `synheart_core_last_ingest_success_at_ms(handle) -> int64_t` | Epoch-ms of the last successful upload, or `0` if never.                                                                         |
| `synheart_core_is_network_reachable(handle) -> bool`         | Cached reachability flag (the runtime monitors `<api_base>/health`).                                                             |
| `synheart_core_upload_metadata(handle) -> *char`             | Diagnostic JSON: queue depth, last error, last attempt, backoff state.                                                           |

See [Cloud Protocol](/synheart-core/cloud-protocol) for the wire shape.

## 6. Consent and capability

| Symbol                                                          | Purpose                                                                                                            |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `synheart_core_grant_consent(handle, snapshot_json) -> int`     | Grant consent for one or more types. Snapshot JSON has boolean fields per consent type.                            |
| `synheart_core_revoke_consent(handle, type_or_null) -> int`     | Revoke a single consent type, or all if `type_or_null` is `NULL`.                                                  |
| `synheart_core_has_consent(handle, consent_type) -> int`        | `1` if granted, `0` if denied, negative on error.                                                                  |
| `synheart_core_current_consent(handle) -> *char`                | Full consent snapshot as JSON.                                                                                     |
| `synheart_core_load_capability_token(handle, token_jwt) -> int` | Install a capability token. The token determines which features the SDK can activate (core / extended / research). |

See [Consent System](/synheart-core/consent-system) and [Capability System](/synheart-core/capability-system) for the model.

## 7. Sessions and local storage

The runtime owns local persistence (SQLite plus encrypted preference storage on Apple/Android).

| Symbol                                                           | Purpose                                                                                                      |
| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `synheart_core_list_sessions(handle, since_ms, limit) -> *char`  | JSON array of historical session metadata.                                                                   |
| `synheart_core_get_session_summary(handle, session_id) -> *char` | Per-session aggregate (HR mean/std, HRV, duration, etc.).                                                    |
| `synheart_core_delete_session(handle, session_id) -> int`        | Delete one session and its windows.                                                                          |
| `synheart_core_wipe_local_data(handle) -> int`                   | Clear all local stores: queue, history, sessions, HSI windows, SRM snapshot. Does **not** affect cloud data. |
| `synheart_core_set_retention_days(handle, days) -> int`          | Configure rolling-window retention for HSI history.                                                          |
| `synheart_core_get_storage_usage(handle) -> *char`               | JSON breakdown of bytes used per store.                                                                      |
| `synheart_core_record_metric(handle, name, value_json) -> int`   | Append an app-defined metric to the active session.                                                          |

## 8. SRM and baselines

The [Self-Reference Model](/synheart-core/srm) maintains longitudinal baselines per subject.

| Symbol                                                          | Purpose                                                                                                                         |
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `synheart_core_export_srm_snapshot(handle) -> *char`            | Serialise the current SRM snapshot as JSON. Hosts persist this through their own secure store.                                  |
| `synheart_core_load_srm_snapshot(handle, snapshot_json) -> int` | Restore a snapshot on cold start. Caller must invoke `recompute()` afterward — load alone does not emit a fresh reference view. |
| `synheart_core_baselines_json(handle) -> *char`                 | Current per-dimension baselines (mean / std / sample count).                                                                    |
| `synheart_core_wellness_json(handle) -> *char`                  | Wellness derivatives (recovery, strain, readiness inputs) keyed by date.                                                        |
| `synheart_core_srm_overall_status(handle) -> *char`             | Overall maturity status: `EMPTY`, `WARMING`, `READY`, or `STALE`. See [maturity states](/synheart-core/srm#maturity-states).    |

## 9. Sync

| Symbol                                                   | Purpose                                                              |
| -------------------------------------------------------- | -------------------------------------------------------------------- |
| `synheart_core_sync_now(handle) -> *char`                | Trigger an immediate device-first sync cycle. Returns a JSON result. |
| `synheart_core_set_sync_enabled(handle, enabled) -> int` | Enable or disable the background sync layer.                         |

## 10. Account deletion

| Symbol                                                    | Purpose                                                                                                    |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `synheart_core_request_account_deletion(handle) -> *char` | Enter wind-down mode and signal the platform to delete cloud data. Returns a `DeletionRequestResult` JSON. |
| `synheart_core_cancel_account_deletion(handle) -> *char`  | Undo the deletion request before the platform confirms.                                                    |

## 11. Multi-source priority resolver

When multiple wearables / vendors push the same metric, the runtime de-duplicates via a priority resolver. SDKs configure it so the SDK consumer's source preferences flow into the runtime gate.

| Symbol                                                                        | Purpose                                                                   |
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| `synheart_core_priority_set_provider(handle, metric, provider, rank) -> int`  | Assign a priority rank for a given metric/provider pair. Lower rank wins. |
| `synheart_core_priority_set_metric_override(handle, metric, provider) -> int` | Force a specific provider to win for a metric, regardless of rank.        |
| `synheart_core_priority_resolve(handle, metric) -> *char`                     | Resolve which provider currently owns this metric.                        |
| `synheart_core_priority_effective_rank(handle, metric, provider) -> int`      | Effective rank after override / fallback rules.                           |

## 12. Stateless score computation

These are stateless utility calls — they don't read or mutate the handle's state, just compute a result from the input JSON. The `_handle` parameter is unused; pass `NULL`.

| Symbol                                                                                  | Purpose                                                                      |
| --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `synheart_core_recovery_score_compute_json(_, input_json) -> *char`                     | Daily 0–100 recovery score from sleep + overnight HR/HRV.                    |
| `synheart_core_readiness_score_compute_json(_, input_json) -> *char`                    | Daily 0–100 readiness score combining recovery, workload, and trend signals. |
| `synheart_core_resilience_compute_v1(samples_json, windows_json, config_json) -> *char` | HRV-CV resilience score over a multi-day window.                             |

## 13. Apple Health backfill

When a user exports `export.zip` from the iOS Health app, the SDK feeds it back into the runtime via this batch path. Idempotency keys ensure repeated imports don't duplicate samples.

| Symbol                                                                        | Purpose                                                 |
| ----------------------------------------------------------------------------- | ------------------------------------------------------- |
| `synheart_core_backfill_open(handle, db_path, import_id) -> int`              | Open a backfill session.                                |
| `synheart_core_backfill_insert_batch(handle, import_id, samples_json) -> int` | Insert a batch of samples.                              |
| `synheart_core_backfill_finalize(handle, import_id) -> int`                   | Commit and aggregate the import; updates SRM baselines. |

## 14. Diagnostics

| Symbol                                       | Purpose                                                                                                                                                         |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `synheart_core_diagnostics(handle) -> *char` | JSON dump of runtime state: availability, version, frame count, last quality, queue stats, last error. The SDK exposes this as `Synheart.runtimeDiagnostics()`. |

## 15. Memory management

| Symbol                           | Purpose                                                                             |
| -------------------------------- | ----------------------------------------------------------------------------------- |
| `synheart_core_free_string(ptr)` | Release a `*char` returned by any of the calls above. Calling on `NULL` is a no-op. |

Forgetting to call this on returned strings leaks memory. SDK shells handle it automatically; custom integrations must call it themselves.

## Symbols this page does not document

The runtime exports more than what's listed here. Those undocumented symbols are either:

* **Tracing variants** (`*_traced` with a correlation id parameter) — useful for runtime debugging only.
* **Vendor event ingestion** (`*_vendor_*`) — internal to the cloud connector seam.
* **Internal counters** (`frame_count`, `last_features`, `last_quality`) — diagnostic-only, may change.

Treat anything not on this page as unstable. If you find yourself needing one of these, file an issue against the relevant SDK repo at [github.com/synheart-ai](https://github.com/synheart-ai).

## Related

* [Architecture](/synheart-core/architecture) — how the SDK composes around the FFI.
* [Cloud Protocol](/synheart-core/cloud-protocol) — what HSI windows look like on the wire.
* [HSV Specification](/synheart-core/hsv-specification) — the typed inference output the runtime emits.
* [HSI Specification](/synheart-core/hsi-specification) — the public wire format.
