# Use the CLI from AI agents Source: https://docs.synheart.ai/cli/agents Agent mode, machine-readable output, exit codes, the command map and the MCP server, so coding agents can drive synheart without surprises. The CLI is built to be driven by AI coding agents and scripts. In agent mode it prints JSON, never opens the interactive UI, never prompts and never animates. Every failure has a stable error code and a semantic exit code. ## Agent mode Agent mode turns on automatically when the CLI sees that a coding agent started it. It checks these environment variables, in this order: | Variable | Set by | | - | - | | `SYNHEART_AGENT=1` | You, to opt in explicitly | | `CLAUDECODE` | Claude Code, in the shells it spawns | | `CLAUDE_CODE_ENTRYPOINT` | Claude Code, to say how it was launched | | `CURSOR_AGENT` | Cursor's agent terminal | | `CODEX_SANDBOX` | OpenAI Codex, when it runs commands in its sandbox | | `GEMINI_CLI` | Gemini CLI's shell tool | | `COPILOT_AGENT` | GitHub Copilot's coding agent | Any of these counts when it is set to a value other than empty, `0`, `false`, `no` or `off`. Set `SYNHEART_AGENT=0` to force agent mode off, even inside an agent's shell. This is useful when you run the CLI by hand in a terminal that an agent also uses. In agent mode: * The output format defaults to JSON. An explicit `--format text` still wins, also on errors raised before flags are parsed (`synheart mock strt --format text` prints the text error). * The interactive UI never opens. Bare `synheart` and `synheart --help` print a compact [command index](#command-map) instead. * There are no spinners, no colour and no passive update notices. * Nothing prompts. A command that would prompt fails at once with `SH-AGENT-001`, and the `hint` names the flag to pass. For example, `synheart login` needs `--ci-token ` or `SYNHEART_CI_TOKEN`. `synheart update` does not prompt either: without `--yes` it only reports whether a newer version exists (a result with `up_to_date`, `current` and `latest`, and exit code 1 when there is one), and `--yes` applies it. `synheart local --https` and `synheart local cleanup` need sudo to trust the certificate and edit `/etc/hosts`; when sudo would ask for a password they fail with `SH-AGENT-001` instead. Run `sudo -v` first, or run the command yourself with `SYNHEART_AGENT=0`. > [!NOTE] > > `synheart guard`, which holds coding agents to rules you set, ignores `SYNHEART_AGENT=0`. An agent cannot switch detection off to get around a rule, and only a person at a terminal can grant an exception. See [AI & agents](/cli/reference/ai-and-agents#synheart-guard). ## Ask for JSON Pass `--json` or `--format json` on any command that supports it. The [command reference](/cli/reference/index) marks each command, and `supports_json` in the [command map](#command-map) says the same thing for scripts. `--json` together with `--format text` is a usage error. `synheart install` and `synheart sync` count too: under `--json` they print one result object. A few commands have no JSON form, such as `guard allow`, `guard init`, `guard install`, `guard sync`, `guard team join` and `guard team leave`. An explicit `--json` on one of them is a usage error (exit 2) instead of silently printing text. `guard rules`, `guard report`, `guard check`, `guard team status` and `explain` do print JSON. ```bash theme={null} synheart whoami --json synheart mock list-scenarios --json synheart env --json ``` ### JSON conventions Every JSON body follows the same rules, so scripts and agents can rely on it. * **Names use `snake_case`.** Common fields keep the same spelling everywhere: `id`, `name`, `description`, `created_at`, `error_code`, `logged_in`, `next_cursor`. * **Lists are objects with an `items` array**, even when there is only one page. This leaves room for `next_cursor` later without a breaking change. ```json theme={null} {"items": [{"name": "baseline", "description": "..."}]} ``` * **Platform commands follow the same shape.** `org`, `project` and `api-key` lists print `{"items": [...]}`, plus `next_cursor` and `pagination` when the platform sends them. A `show` prints the object itself. The platform's `success` and `message` wrapper is dropped. A command with nothing to return, such as a delete or a revoke, keeps the platform's body. * **Timestamps are RFC 3339**, such as `2026-05-06T18:42:11Z`, never Unix integers. Time zone offsets are kept as given. * **Durations are integers** with a `_ms` (milliseconds) or `_s` (seconds) suffix. * **Required fields are always present**, even when empty. Optional fields are left out when they have no value. * **Adding a field is not a breaking change.** Removing or renaming one, or changing its type, is. Array order is only stable when the field name says so. ### Errors in JSON When a command fails in JSON mode, it still prints a valid JSON body and exits with a non-zero code. You never have to choose between the exit code and the body. ```json theme={null} { "class": "user", "detail": "No Synheart credentials found in the keyring or config file.", "error_code": "SH-AUTH-001", "exit_code": 3, "fix": { "command": "synheart login", "safe_to_run": false, "needs_human": true }, "message": "Not signed in." } ``` Every failure carries `error_code`, `class`, `exit_code` and `message`. The other fields appear only when they have something to say. | Field | Present | Meaning | | - | - | - | | `error_code` | Always | The stable code. See [Errors and environment](/cli/errors). | | `class` | Always | `user` (fix it locally), `server`, `transient` (retrying may work), `usage` or `unknown`. | | `exit_code` | Always | The process exit code, in case a consumer lost the status. | | `message` | Always | One line saying what went wrong. | | `detail` | When non-empty | Why, in a sentence or two. | | `hint` | When non-empty and not just `fix.command` | The next step for a person: prose, several lines, or a command with context. | | `fix` | When the hint is a runnable `synheart` command | `{"command", "safe_to_run", "needs_human"}`. | | `did_you_mean` | When a name was mistyped | The closest subcommands, flags, scenarios or `explain` topics. | | `valid_values` | When the input must be one of a known set | The full set, such as every scenario name. | | `upstream` | When the platform answered with its own error | `{"status", "code", "message", "trace_id"}`. `detail` is then the platform's message. | An agent can act on `fix` without parsing text. `fix.command` is the first line of the hint when that line is a complete `synheart` command; a hint that is an example rather than a command gives no `fix`, so you never run it with made-up values. That means a placeholder (``, `[name]`, `prj_…`), a quoted example string, a shell variable such as `$TOKEN`, `[…]`, `...`, or a word like `your-…` or `*.example`. `safe_to_run` is `true` when the command writes no files, is not destructive, does not run until stopped and is not interactive. Reading the network or your account is fine, so you may run it unprompted. That covers `--help` and `help`, `version`, `whoami`, `auth status`, `doctor`, `explain`, `env`, `config show` and `config path`, `completion`, `mcp`, `mock`, `mock list-scenarios` and `mock describe`, `org`, `project` and `api-key` `list` and `show`, `usage`, `syni personas`, `syni personas show`, `syni sessions show`, `syni version`, `guard check`, `guard rules` and `guard report`, `guard team status`, `runtime current`, and `update --check`. `needs_human` is `true` when a person has to take part: `synheart login` without `--ci-token`, `synheart update` without `--yes`, `guard allow`, `local --https`, `syni chat` (the REPL), and `ui` or anything else that opens the interactive UI. A command that is neither, such as `synheart install runtime`, is one you may run once you have decided to. `synheart mock describe workout --json` prints the scenario's own keys, here trimmed: ```json theme={null} { "name": "workout", "description": "Cardio workout with warmup, run, cooldown (HR up, HRV down, EDA up)", "duration": "30m", "default_rate": "50hz", "signals": { "ppg.hr_bpm": {"baseline": 72, "noise": 3, "rate": "1hz", "unit": "bpm"} }, "phases": [ { "name": "warmup", "duration": "5m", "overrides": { "ppg.hr_bpm": {"add": 18}, "ppg.hrv_rmssd_ms": {"multiply": 0.85}, "motion.activity": {"value": "walk"} } } ] } ``` A mistyped name comes back with the candidates. This is `synheart mock describe stres --json`, which exits 4: ```json theme={null} { "class": "user", "detail": "Scenarios: baseline, focus_session, stress_spike, workout.", "did_you_mean": ["stress_spike"], "error_code": "SH-MOCK-NOTFOUND", "exit_code": 4, "fix": { "command": "synheart mock list-scenarios", "safe_to_run": true, "needs_human": false }, "message": "There is no scenario called \"stres\".", "valid_values": ["baseline", "focus_session", "stress_spike", "workout"] } ``` > [!WARNING] > > **Changed in 0.20 (breaking).** `message` replaces both `title` and `error`, which are gone. `detail` and `hint` are left out when empty instead of being `""`, and `hint` is also left out when it is only the command already in `fix.command`. `fix`, `did_you_mean` and `valid_values` are new. Readers of `title` or `error` should read `message`. Readers that tested `detail == ""` should test for its absence. When the platform API answered with its own error, the body adds `upstream`, for example: ```json theme={null} { "error_code": "SH-PLATFORM-403", "upstream": {"status": 403, "code": "...", "message": "...", "trace_id": "..."} } ``` When the platform cannot be reached at all (connection refused, DNS, timeout), the error is `SH-NET-004` with `class: "transient"` and exit code 5, so a script can retry. A command that reports status, such as `whoami`, `auth status`, `auth refresh`, `runtime current` and `config path`, keeps its own fields and adds the error fields beside them. For example, `whoami` signed out still has `logged_in: false`, and its `message` is `Not signed in.`. Its exit code follows the table below. A mistake in how you called the CLI, such as an unknown flag, uses `error_code: "SH-CLI-USAGE"` and exits 2. It is a JSON body whenever `--json` or `--format json` appears anywhere on the line, even after the bad flag. In text mode the usage pointer goes to stderr. An unknown scenario name is `SH-MOCK-NOTFOUND` and exits 4. An unknown flag on a group is reported as that flag, not as an unknown command: `synheart mock --scenario baseline` is `unknown flag: --scenario`, with close flag names in `did_you_mean`. An unknown subcommand is a usage error too. `synheart mock strt`, `synheart org lst`, `synheart help ` and `synheart --help` all exit 2 with `did_you_mean`, instead of printing help and exiting 0. A bare group such as `synheart mock` still prints its help and exits 0. This is `synheart mock strt --json`: ```json theme={null} { "class": "usage", "did_you_mean": ["start"], "error_code": "SH-CLI-USAGE", "exit_code": 2, "message": "unknown command \"strt\" for \"synheart mock\"" } ``` Mistyped flags, scenarios and `explain` topics suggest the closest names the same way. A missing argument says what is missing rather than printing cobra's `accepts 1 arg(s), received 0`: `synheart mock describe` with no name is `Name a scenario`, with `valid_values` listing the scenarios and a `fix` that runs `synheart mock list-scenarios`. In a stream, the `error` event carries the same fields plus `ok: false`. `syni version --json` prints `spec`, `runtime` and `source`. `source` is `vendor` when it read the installed files. With no vendored copy it falls back to what `synheart.lock` pins and reports `"source": "lockfile"`. `whoami --json` and `usage --json` include `claims_refreshed`. It is `true` when that run refreshed a stale access token first, so a recent plan change is already reflected in the result. ## Follow long-running commands (NDJSON) Installs, servers and recordings can be followed line by line. Each line on **stdout** is one JSON object, flushed immediately. Progress bars, spinners and banners are off, and stderr carries only genuine warnings. ### Which flag gives what | Command kind | `--format text` | `--json` or agent mode | `--format ndjson` | | - | - | - | - | | One-shot: `install`, `sync` | Human text | **One result object** | Event stream, ending in `done` | | Servers: `mock start`, `mock record`, `mock replay`, `local`, `receiver` | Human text | **Event stream** | Event stream (same) | A command that prints one final object keeps doing so under `--json`, so existing scripts do not break. Streaming is opt-in with `--format ndjson`. A server has no single result, so `--json` and agent mode already mean the stream. `--json` together with `--format ndjson` is a usage error (exit 2). ### The envelope Every event starts with the same three fields: ```json theme={null} {"event": "ready", "ts": "2026-05-06T18:42:11.123Z", "command": "synheart mock start", "...": "..."} ``` `ts` is RFC 3339 with milliseconds. Other fields are `snake_case` and sorted alphabetically; do not rely on their order. Ignore unknown fields and unknown event names, because new ones can be added. ### Events | Event | When | Fields | | - | - | - | | `started` | Once, first | The inputs the command accepted | | `progress` | Repeatedly while work runs | `package`, `artifact`, `bytes_done`, and `bytes_total` and `percent` when known | | `ready` | Servers only, once, after every listener is bound | `url`, `ws_url`, `port`, and per-command URLs | | `item` | One result per artifact, file or received export | `kind`, `status`, plus per-command fields | | `warning` | A non-fatal condition | `message`, `kind`, plus context | | `done` | Terminal, success | `ok: true` and a summary | | `error` | Terminal, failure | `ok: false` and the error fields above: `error_code`, `exit_code`, `class`, `message`, plus `detail`, `hint`, `fix`, `did_you_mean`, `valid_values` and `upstream` when present | Exactly one terminal event (`done` or `error`) ends a run, and nothing follows it. The process exit code matches `exit_code`. A server stops on SIGINT or SIGTERM by emitting `done` with `"interrupted": true` and exits 0. A failure before the stream starts, such as a bad flag, is a single `error` event. ### Receiver exports In event mode `synheart receiver` writes only events to stdout. Each received export is an `item` event with `kind: "export"` and an `export_id`. The export is in `payload` (one compact line) when you pass no `--out`, or `path` is the file written when you do. `--output-format` then only affects the files under `--out`. The `ready` event carries `endpoint` and `token`, and `done` carries `received`, `duplicates` and `errors`. ### Recipe: start the mock server and connect ```bash theme={null} synheart mock start --json | while read -r line; do [ "$(echo "$line" | jq -r .event)" = "ready" ] || continue ws_url=$(echo "$line" | jq -r .ws_url) echo "connect to $ws_url" break done ``` 1. Start `synheart mock start --json` and read stdout line by line. 2. Wait for the `ready` event. Do not connect before it, because the listeners are not bound until then. A port already in use produces an `error` event instead. 3. Read `ws_url` (also `sse_url` and `udp_url`) and connect. `dashboard_url` is in the event only when you started the server with `--web`. 4. Stop the server with SIGINT and read the final `done` event for counts. ## Exit codes Branch on the exit code instead of parsing messages. | Code | Meaning | | - | - | | `0` | Success. | | `1` | General failure. | | `2` | Usage error: bad flags or arguments, an unknown command or subcommand (the body has `did_you_mean`), or `--json` with a different `--format`. | | `3` | Authentication required or forbidden (`SH-AUTH-*`, and any `-403` such as `SH-PLATFORM-403`). | | `4` | The requested resource was not found. | | `5` | Transient failure (network or timing). Retrying may work. | ## Command map The full map is over 100 KB, so bare `synheart` and `synheart --help` in agent mode print a compact index instead (about 10 KB). `synheart help --json` prints the full machine-readable map of every public command and flag. For one command, run `synheart --help --json` or `synheart help --json`. It prints just that command's entry, the same object as one element of `commands`. In agent mode `--help` defaults to JSON; pass `--format text` to get the text back. ### The command index Start here. It lists every command's path and one-line summary, grouped the way `synheart --help` groups them (`build`, `run`, `account`, `cloud`, `ai`, `tools` and `other`), plus the exit codes and environment variables. ```json theme={null} { "name": "synheart", "version": "0.20.0", "groups": [ {"id": "build", "name": "Build", "commands": [ {"path": "synheart init", "short": "Set up this directory as a Synheart app project"}, {"path": "synheart install", "short": "Install SDK artifacts into your app project"} ]} ], "next": "synheart help --json", "full": "synheart help --json", "exit_codes": {"0": "success", "...": "..."}, "env": [{"name": "SYNHEART_AGENT", "description": "..."}] } ``` A group lists its top-level commands, each followed by its subcommands. Use `next` for one command's detail and `full` for the whole map. ### The full map ```bash theme={null} synheart help --json ``` ```json theme={null} { "name": "synheart", "version": "0.20.0", "commands": [ { "path": "synheart mock start", "short": "Stream mock wearable data to your app", "long": "...", "usage": "synheart mock start [flags]", "aliases": [], "flags": [ {"name": "scenario", "shorthand": "", "type": "string", "default": "baseline", "usage": "...", "required": false} ], "examples": [ {"description": "Stream the baseline scenario on 127.0.0.1:8787", "command": "synheart mock start"} ], "supports_json": false, "hidden": false, "subcommands": [], "group": "", "formats": ["text", "ndjson"], "requires_auth": false, "network": false, "writes_files": false, "destructive": false, "long_running": true, "interactive": false } ], "global_flags": [{"name": "format", "shorthand": "", "type": "string", "default": "text", "usage": "...", "required": false}], "exit_codes": {"0": "success", "2": "usage error: ..."}, "env": [{"name": "SYNHEART_AGENT", "description": "..."}] } ``` * Commands are sorted by `path`. Hidden commands and flags are left out. * `flags` holds a command's own flags. `global_flags` holds the flags every command inherits. * `subcommands` lists the paths of a command's visible direct subcommands. * `supports_json` is derived from the commands themselves, so it is `true` for every command that prints a single JSON body, including `install` and `sync`. It is `false` for the streaming commands (`mock start`, `mock record`, `mock replay`, `local`, `receiver`): their `--json` emits an [NDJSON](#follow-long-running-commands-ndjson) event stream instead of one object. * `examples` is a list of `{"description", "command"}` objects: the `# comment` above the example in the text help (`""` when there is none) and the command. Independent `synheart` commands under one comment are separate entries that share the description; lines that only work together (an `export` before `synheart login`, a `cd`, a pipe) stay one entry, joined by `\n`. * `group` is the section a top-level command appears under in `synheart --help`. It is empty for subcommands. * `formats` lists the `--format` values the command honours: always `text`, `json` when it prints a single JSON body, `ndjson` when it takes part in the event stream. A server (`mock start`, `mock record`, `mock replay`, `local`, `receiver`) lists `["text", "ndjson"]`, and `install` and `sync` list all three. * `requires_auth`, `network`, `writes_files`, `destructive`, `long_running` and `interactive` say what running the command involves, so an agent can decide before it runs. `requires_auth` means an account. `network` means a call to Synheart's servers or the internet (local listeners do not count). `writes_files` means files are created or changed (the CLI's own caches, such as the credential refresh `whoami` may do, do not count). `destructive` means something is deleted or revoked for good. `long_running` means it runs until stopped. `interactive` means a person at the keyboard: a browser sign-in, a confirmation, sudo, `guard allow` or the interactive UI, which agent mode fails on instead of prompting. A parent group that only prints help has all six `false`. * `exit_codes` and `env` list the exit codes and the environment variables the CLI reads. An agent that has not seen the CLI before can read the index once, then ask for the commands it needs. ## Check the setup with doctor `synheart doctor --json` reports each check as an entry in `checks[]`: ```json theme={null} { "ok": false, "summary": {"passed": 4, "warnings": 1, "errors": 1}, "checks": [ { "id": "runtime.files", "status": "error", "subject": "synheart-core-runtime-edge", "message": "synheart-core-runtime-edge v1.2.3 · 2 files missing", "missing_files": ["synheart/vendor/runtime/..."], "error_code": "SH-RT-FILES", "fix": {"command": "synheart sync", "safe_to_run": false, "needs_human": false, "requires": ["synheart login"]} } ] } ``` * `ok` is `true` when no check has status `error`. `summary` counts the checks by status. * `scenarios_dir` is left out when there is no local scenarios directory. * `status` is `ok`, `warn` or `error`. * `fix.command` is the exact command that resolves the check. * `safe_to_run` follows the same rule as the error envelope's `fix`: it is `true` when the command writes no files, is not destructive, exits by itself and needs no person. An account or network read is fine. It comes from the command's traits in the [command map](#command-map), so `synheart install runtime`, `synheart sync` and `synheart mock start --port …` are `false`. When it is `false`, ask a person before running it, or run it once you have decided to. * `needs_human` is `true` when a person has to take part, such as `synheart login`, which opens a browser. * `fix.requires` lists fixes that must succeed first. While you are signed out, a fix that needs an account has `"requires": ["synheart login"]`. The text report's TRY list is in that order. * `notes[]` holds facts that are not verdicts. Outside an app project (no `Package.swift`, `build.gradle` or `pubspec.yaml`, and no `.synheart/` here or above) a missing `synheart.lock` is not a warning. The report notes `Not in an app project · cd into your app, or run synheart init` instead. * `doctor` exits 1 only when your app cannot work: the runtime is missing or incompatible, or its files are missing or modified. Warnings do not change the exit code. > [!WARNING] > > **Changed in 0.21 (breaking).** > > * Index group ids and names changed. Ids are now `build`, `run`, `account`, `cloud`, `ai`, `tools` and `other`; they were `build`, `simulate`, `platform`, `ai`, `troubleshoot` and `other`. Names are Build, Run locally, Account, Cloud, AI & agents, Tools and Other. Platform is split into Account (`login`, `logout`, `whoami`, `auth`, `usage`) and Cloud (`org`, `project`, `api-key`). The command map's `group` uses the same ids. > * `help --json` `examples` are objects, `{"description", "command"}`, not strings. > * `synheart mock describe --json` keys are `snake_case`. Signals and phase overrides use the scenario file's keys (`baseline`, `noise`, `rate`, `unit`, `add`, `multiply`, `value`, `ramp`, `ramp_to_baseline`) and list only the keys that are set. Phases are `{"name", "duration", "overrides"}`, and `phases` is `[]`, never `null`. > [!NOTE] > > In agent mode, `synheart login` fails fast with `SH-AGENT-001` instead of opening a browser. Pass `--ci-token ` or set `SYNHEART_CI_TOKEN` for unattended sign-in. ## MCP server `synheart mcp serve` runs an MCP (Model Context Protocol) server on stdin and stdout, so an agent in Claude Code, Cursor or Claude Desktop can do its first hour on an app without a shell. It has 15 tools. Nothing in the server signs in, opens a browser, copies to the clipboard or prompts. ### Set it up > [tab] Claude Code > > ```bash theme={null} > claude mcp add --scope user synheart "$(which synheart)" mcp serve > ``` > [tab] Cursor / Claude Desktop > > Add this to the client's MCP config. The file path depends on the client: Cursor's MCP settings, or `~/Library/Application Support/Claude/claude_desktop_config.json` for Claude Desktop on macOS. > > ```json theme={null} > { > "mcpServers": { > "synheart": { > "command": "synheart", > "args": ["mcp", "serve"] > } > } > } > ``` The client starts the server as a subprocess. Relative paths in tool arguments resolve against its working directory, normally the app project you opened. If the agent cannot find `synheart`, give the client the absolute path from `which synheart`, because client subprocesses often inherit a minimal `PATH`. ### The tools "Safe" says whether an agent may call the tool unprompted. "CLI" is the command it stands for. | Tool | What it does | Safe | CLI | | - | - | - | - | | `synheart_init` | Writes `.synheart/config.yaml` in `dir`, detects the app type, lists next steps | No (writes files) | `init` | | `synheart_doctor` | Checks scenarios, the installed runtime, sign-in and the mock port | Yes | `doctor` | | `synheart_env` | Paths, app type and app IDs, account, pinned runtime | Yes | `env` | | `synheart_connect_info` | Mock endpoints and client snippets (JavaScript, Python, Go) | Yes | `doctor --examples` | | `synheart_explain` | A primer on a concept, or the topic list | Yes | `explain` | | `synheart_config_show` | The resolved app project config | Yes | `config show` | | `synheart_auth_status` | Where credentials load from, and expiry | Yes | `auth status` | | `synheart_whoami` | The signed-in user (refreshes stale plan claims first) | Yes | `whoami` | | `synheart_version` | CLI version, commit, channel, Go, OS and architecture | Yes | `version` | | `synheart_mock_list_scenarios` | The mock scenarios, as `{"items": [...]}` | Yes | `mock list-scenarios` | | `synheart_list_scenarios` | Deprecated name of `synheart_mock_list_scenarios`. It still works. | Yes | `mock list-scenarios` | | `synheart_mock_describe` | One scenario's signals and phases | Yes | `mock describe` | | `synheart_mock_start` | Starts a mock stream in the background | No (keeps running) | `mock start` | | `synheart_mock_status` | The stream's state, endpoints, events and clients | Yes | MCP only | | `synheart_mock_stop` | Stops the stream | Yes | MCP only | Every tool's `inputSchema` has `additionalProperties: false`. An unknown argument, a value of the wrong type, a port out of range or a value outside an enum fails with `SH-CLI-USAGE` (exit 2), with `did_you_mean` and `valid_values`. The full argument list for each tool is in `tools/list`. ### Safety comes from command traits A tool's safe verdict is not a separate list. It comes from the traits of the CLI command the tool stands for, the same ones `synheart help --json` reports and `fix.safe_to_run` uses: a tool is safe when its command writes no files, deletes nothing, exits by itself and needs no person. Reading the network or the account is fine. The same traits give each tool in `tools/list` its MCP `annotations` (`readOnlyHint`, `destructiveHint`, `openWorldHint`), and each tool's description says what it does, its side effects and whether it is safe to call unprompted. ### The first hour A typical run for an agent on a new app: 1. `synheart_init` sets up the app project. It refuses your home directory (`SH-CFG-006`) and never overwrites a backup. 2. `synheart_doctor` checks the setup. Each check's `fix` says what to run next. 3. `synheart_mock_list_scenarios` and `synheart_mock_describe` pick a scenario. 4. `synheart_mock_start` streams mock data and returns its endpoints. 5. `synheart_connect_info` gives the WebSocket, SSE, UDP and control URLs and a client snippet for the app. 6. `synheart_mock_status` shows whether the app has connected (`clients`, `ever_connected`). 7. `synheart_mock_stop` ends the stream. To check it, ask the agent: "Set this app up for Synheart and stream some mock data I can connect to." It should call `synheart_init`, then `synheart_mock_start`, then `synheart_connect_info`. ### The mock stream `synheart_mock_start` does what `synheart mock start` does, without blocking. It returns once the WebSocket (`port`), SSE (`port+1`) and UDP (`port+2`) listeners are bound, and the stream keeps running inside the MCP server. It writes no files and opens no browser, so `--out` and `--web` are not arguments. * **One stream per server.** While one runs, another `synheart_mock_start` fails with `SH-MOCK-005` (usage, exit 2). Stop it first, or keep using it. * **It ends** on `synheart_mock_stop`, when its `duration` runs out, or when the MCP server exits because the client disconnects or closes stdin. Its ports are free again when it ends. * **A port in use** fails with `SH-MOCK-004` (transient, exit 5), as the CLI does. `fix.command` suggests another port. `synheart_mock_start`, `synheart_mock_status` and `synheart_mock_stop` return the stream's status: `running`, `state` (`none`, `running`, `stopping`, `finished`, `stopped` or `failed`), `scenario`, `vendor`, `rate`, `host`, `port`, `seed`, `endpoints` (`ws_url`, `sse_url`, `udp_url`, `control_url`), `events`, `events_per_s`, `clients` (`ws`, `sse`, `udp`) and `ever_connected`. `synheart_mock_stop` adds `was_running`, and with nothing running it does nothing and says `"was_running": false`. If the stream has not shut down within 10 seconds, `synheart_mock_stop` fails with `SH-MOCK-007` and the state stays `stopping` until it has. ### Errors When a tool fails, the reply sets MCP's `isError: true` flag instead of a JSON-RPC error, so the conversation does not abort. The text is the CLI's [JSON error envelope](#errors-in-json): `error_code`, `class`, `exit_code` and `message`, plus `detail`, `hint`, `fix`, `did_you_mean` and `valid_values` when present. `fix.command` is a CLI command line; an agent on MCP calls the matching tool when there is one. `synheart_auth_status`, `synheart_whoami` and `synheart_doctor` (when the app cannot work) report a status, so they fail with that body and the envelope merged in, as `--json` does. Signed out, `synheart_whoami` returns: ```json theme={null} { "claims_refreshed": false, "class": "user", "detail": "No Synheart credentials found in the keyring or config file.", "error_code": "SH-AUTH-001", "exit_code": 3, "fix": {"command": "synheart login", "safe_to_run": false, "needs_human": true}, "logged_in": false, "message": "Not signed in." } ``` ### What is not a tool The server mirrors what an agent can do on its own. These stay with the person at the terminal: * **Interactive commands**: `login` (a browser sign-in), `guard allow` (only a person may approve), `update` (it confirms and replaces the binary), `local --https` and `local cleanup` (sudo), and `ui` and `syni` (a terminal UI or chat). * **Commands that install or fetch artifacts**: `install`, `sync`, `runtime install` and `runtime upgrade`, and `guard sync`. They write into the app project from the registry and need an account. An agent runs them in a shell when you ask; `synheart_doctor` names them as fixes. * **Other long-running servers**: `mock record`, `mock replay`, `local` and `receiver`. They write files or serve a platform. `synheart_mock_start` covers building against mock data. * **Platform commands** (`org`, `project`, `api-key`, `usage`) and `logout`: account-level changes outside the first-hour loop. * Resources, prompts and sampling are not offered, and the transport is stdio only. To check the server from a shell, without any client: ```bash theme={null} echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | synheart mcp serve ``` The reply lists every tool, sorted by name. > [!WARNING] > > **Changed in 0.21.** The server grew from 7 read-only tools to 15, and it now includes tools that write files (`synheart_init`) or keep running (`synheart_mock_start`). `synheart_list_scenarios` is deprecated in favour of `synheart_mock_list_scenarios`; it still works. `synheart_auth_status` and `synheart_whoami` signed out, and `synheart_doctor` when the app cannot work, now come back with `isError: true`, as `--json` exits non-zero. ## Recipes ### Bootstrap an app project An agent sets up a Flutter or native app project from a clean checkout: ```bash theme={null} # 1. Read the setup. Nothing here changes anything. synheart doctor --json # 2. For each check with status "warn" or "error", read fix.command. Run it # unprompted only when fix.safe_to_run is true. Fixes that install or sync # are false: they need an account and the network, and they write files. # fix.requires says what must come first ("synheart login"). # 3. If there is no runtime or lockfile yet, sign in and install it. SYNHEART_CI_TOKEN=... synheart login synheart install runtime # 4. Start mock data for the app to connect to. synheart mock start --scenario baseline --duration 5m ``` Run `synheart doctor --json` again at the end. `"ok": true` means the app can run. ### Branch on failure ```bash theme={null} synheart sync case $? in 0) echo "synced" ;; 3) echo "sign in first" ;; # SH-AUTH-* 5) sleep 5 && synheart sync ;; # transient, retry *) echo "failed; read error_code in the JSON error body" ;; esac ``` ### Run the CLI unattended ```bash theme={null} export SYNHEART_AGENT=1 # explicit, in case detection misses your tool export SYNHEART_NO_UPDATE_CHECK=1 export SYNHEART_CI_TOKEN="$TOKEN" # prefer the variable over --ci-token synheart login synheart update --check --json # exit 1 means a newer version exists ``` # Errors and environment Source: https://docs.synheart.ai/cli/errors Synheart CLI error codes, the environment variables it reads, and fixes for common problems. When a command fails, the CLI prints a typed error. In JSON mode the same information is a JSON body with `error_code`, `class`, `exit_code` and `message`, plus `detail`, `hint`, `fix`, `did_you_mean` and `valid_values` when they apply, so scripts and agents can branch on it. See [Use the CLI from AI agents](/cli/agents#errors-in-json). ```text theme={null} ✗ Not signed in SH-AUTH-001 No Synheart credentials found in the keyring or config file. TRY synheart login ``` Codes follow `SH--`. They are stable: search for them in your shell history, put them in support tickets, and branch on them in scripts. A code is never reassigned to a different meaning. ## Error codes ### Command line | Code | Meaning | What to do | | - | - | - | | `SH-CLI-USAGE` | You called the CLI wrong: a bad flag or argument, an unknown command or subcommand (`did_you_mean` names the closest), or `--json` with a different `--format`. Also raised when you pass `--json` to a command with no JSON form, such as `guard allow`. Exit code 2. | Read the usage line the CLI prints (on stderr), or run the command with `--help`. | | `SH-MOCK-NOTFOUND` | You named a mock scenario that does not exist. Exit code 4. | Run `synheart mock list-scenarios`. | | `SH-EXPLAIN-NOTFOUND` | `synheart explain` has no primer for that topic. Exit code 4. | The error lists the topics, and the hint suggests the closest one. | | `SH-MOCK-004` | `synheart mock start` could not bind: the port, port+1 or port+2 is already in use. A transient error, exit code 5, because the port frees up when the other process stops. The `fix` suggests another port. | Pass another `--port`, or stop whatever holds the port. | | `SH-MOCK-005` | A mock stream is already running, or still shutting down, in this MCP server. A usage error, exit code 2. Only `synheart_mock_start` raises it. | Stop the running stream with `synheart_mock_stop`, or wait until `synheart_mock_status` says `stopped`. | | `SH-MOCK-007` | `synheart_mock_stop` timed out: the stream is still shutting down and its ports may still be bound. A transient error, exit code 5. | Call `synheart_mock_status` until it says `stopped`, then start again. | | `SH-MOCK-006` | The mock stream started through the MCP server did not bind its listeners in time. A transient error, exit code 5. | Call `synheart_mock_start` again, or pass another `port`. | | `SH-MOCK-003` | The rate you typed is not valid. Seen when you change the rate on the interactive mock screen. | Use a frequency like `10hz` or an interval like `100ms`. | | `SH-FLAG-REMOVED` | You passed a flag that no longer exists. Exit code 2. | The error names the flag and what replaces it. | | `SH-AGENT-001` | The step is interactive, and [agent mode](/cli/agents#agent-mode) never prompts. | Re-run with the flag in the hint, such as `--yes` or `--ci-token`. Set `SYNHEART_AGENT=0` if a person is running the command. | | `SH-TUI-001` | `synheart ui` needs a terminal. It does not open in CI, in a pipe, or when `SYNHEART_NO_TUI=1` is set. | Use the ordinary commands, or run it from a terminal. | | `SH-TUI-002` | `synheart ui` is off in agent mode. It is a usage error (exit 2) whose detail says how to open it yourself: set `SYNHEART_AGENT=0`. | Use the ordinary commands with `--json`, or `synheart help --json` for the command map. | Any failure that is not a typed error has the code `SH-UNKNOWN` and exits 1. If you see one, the message is the underlying error text. `synheart ui` with `--json`, `--format json` or `--quiet` fails with a plain error instead of a code: `TUI is not available with --format json` (or `--quiet`). ### Sign-in | Code | Meaning | What to do | | - | - | - | | `SH-AUTH-001` | Not signed in. | `synheart login` | | `SH-AUTH-002` | The CLI could not fetch your account info. | Retry. If it persists, run `synheart auth status`. | | `SH-AUTH-003` | The credentials file is unreadable. | `synheart auth status` shows the path and permissions. | | `SH-AUTH-004` | The CLI could not use the system keyring. | Unlock the OS keyring and retry, or set `SYNHEART_DISABLE_KEYRING`. | | `SH-AUTH-005` | You denied the authorization in the browser. | Run `synheart login` again and approve it. | | `SH-AUTH-006` | The device code expired before you finished. | Run `synheart login` again. | | `SH-AUTH-007` | The CLI could not save your credentials locally. | Check the permissions of `~/.synheart`. | | `SH-AUTH-008` | Authorization failed. | Run `synheart login` again. | | `SH-AUTH-009` | The refresh token is expired or invalid. Retrying will not help. | `synheart login` | | `SH-AUTH-010` | The CLI could not refresh your session, for a temporary reason. | Retry once. If it persists, run `synheart auth status`. | | `SH-AUTH-011` | No CI token was supplied. | Set `SYNHEART_CI_TOKEN` or pass `--ci-token`. | | `SH-AUTH-012` | The CLI could not save the CI token locally. | Check the permissions of `~/.synheart`. | | `SH-AUTH-099` | Sign-in failed for another reason. | Run `synheart auth status`, then `synheart login` again. | ### Install, sync and runtime | Code | Meaning | What to do | | - | - | - | | `SH-INST-001` | A package argument is missing, or there are too many. | `synheart install --help` | | `SH-INST-002` | There is no `synheart.lock` in the project. | `synheart install runtime` | | `SH-INST-003` | The CLI could not read the lockfile. | Check the file, or reinstall with `synheart install runtime`. | | `SH-INST-004` | Lockfile drift: the lockfile names an artifact the current manifest no longer has. | Re-pin with the command in the hint, such as `synheart install runtime --version `. | | `SH-INST-005` | An artifact's SHA-256 does not match the lockfile. | Do not use the file. Re-pin with `synheart install`. | | `SH-INST-PROJECT` | The CLI could not resolve the project directory. | Check `--project-dir`. | | `SH-INST-VARIANT` | The variant is unknown, or `--variant` was used on something that is not a runtime. | Use `edge`, `stable` or `lab` with `install runtime`. | | `SH-INST-FORBIDDEN` | Your account is not entitled to that runtime variant. | Install without `--variant`, or check your plan with `synheart usage`. | | `SH-INST-EMPTY` | Nothing was installed. | Check that your plan includes the package. | | `SH-RT-NOLOCK` | No runtime is installed in this app project. | `synheart install runtime` | | `SH-RT-INCOMPATIBLE` | The installed runtime does not work with this project's `synheart_core` version. | Follow the hint, usually `synheart runtime upgrade`. | | `SH-RT-FILES` | Runtime files are missing or modified compared with `synheart.lock`. | `synheart sync` | | `SH-RT-SYMBOLS` | A runtime library lacks functions its variant must export. | Reinstall the variant: `synheart install runtime`. | ### Network and registry | Code | Meaning | What to do | | - | - | - | | `SH-NET-001` | The CLI could not reach the auth service. | Check your connection and retry. | | `SH-NET-002` | The CLI could not reach the release manifest. | Check your connection and retry. | | `SH-NET-003` | The CLI could not reach the artifact registry, or a download failed. | Check your connection and retry. | | `SH-NET-004` | The CLI could not reach the platform API, or it did not answer in time. Exit code 5, so it is safe to retry. | Check your connection and `SYNHEART_API_URL`, then retry. `synheart doctor` checks connectivity. | | `SH-REG-404` | The interactive install screen could not find the package. | Try the latest channel, and set a platform if the package is platform-specific. | | `SH-REG-429` | The registry is rate limiting the interactive install screen. | Wait a moment and try again. | | `SH-REG-000` | The interactive install screen hit another registry error. | Retry. The message carries the registry's reason. | | `SH-SUPPLY-001` | This CLI build does not trust the registry signing key. | Update the CLI: `synheart update`. | | `SH-SUPPLY-002` | The registry manifest is not signed. | Do not continue. Contact support. | | `SH-SUPPLY-003` | The registry manifest signature is invalid, or could not be verified. | Do not continue. Contact support. | | `SH-SUPPLY-004` | The registry manifest is outside its validity window. | Check your system clock, then retry. | | `SH-PLATFORM-400` | The platform rejected the request. | Check the arguments. | | `SH-PLATFORM-403` | Forbidden. Exit code 3. | Check `--org`, `--tenant`, or `SYNHEART_ORG_ID`. | | `SH-PLATFORM-404` | Not found. | `synheart org list` to confirm the resource exists. | | `SH-PLATFORM-429` | The platform is rate limiting you. Exit code 5. | Wait a moment and retry. | | `SH-PLATFORM-500` | The platform service had an error. | Retry later, or contact support. | The `synheart org`, `project` and `api-key` commands return `SH-AUTH-001` for an HTTP 401. ### Config, update, usage and Syni | Code | Meaning | What to do | | - | - | - | | `SH-CFG-002` | No project config was found. | Run `synheart init`, or create `.synheart/config.yaml`. See [project settings](/cli/overview#settings-precedence). | | `SH-CFG-003` | The theme name is unknown. The error names where it was set, and the JSON body has `did_you_mean` and `valid_values`. | Use `tide`, `ember`, `signal` or `mono`. | | `SH-CFG-004` | `SYNHEART_THEME_MODE` (or `ui.mode`) is not `auto`, `light` or `dark`. The JSON body has `valid_values`, and `did_you_mean` when the value is close to one. | Set it to `auto`, `light` or `dark`, or unset it. | | `SH-CFG-005` | `synheart init` could not run: there is no directory at the path you gave, or it could not write `.synheart/config.yaml`. | Check `--project-dir` and that you can write to the directory. | | `SH-CFG-007` | `synheart init` won't write through a symlink: `.synheart`, `.synheart/config.yaml` or a backup path is a symbolic link. A usage error, exit code 2. | Replace the link with a real directory or file, then run `synheart init` again. | | `SH-CFG-006` | `synheart init` ran in your home directory. `~/.synheart/config.yaml` holds your personal settings, so init refuses to touch it. A usage error, exit code 2. | `cd` into your app, then run `synheart init` again, or pass `--project-dir `. | | `SH-CFG-HOME` | The CLI could not find your home directory. | Set `HOME` (or `USERPROFILE` on Windows). | | `SH-LOCAL-ADMIN` | On Windows, the interactive local platform screen needs Administrator rights to edit the hosts file for HTTPS mode. | Reopen the terminal with Run as administrator and try again. | | `SH-LOCAL-SUDO` | The interactive local platform screen needs administrator rights, and `sudo` cannot prompt inside the full-screen UI. | Quit the UI (`q`) and run the command from a shell, or run `sudo -v` first and try again. | | `SH-UPD-MANAGED` | A package manager manages this binary. | Update with the package manager, or pass `--force`. | | `SH-UPD-APPLY` | The update failed to apply. The existing binary is untouched. | Retry. | | `SH-UPD-ROLLBACK` | The rollback failed. | Reinstall with the installer script. | | `SH-UPD-NOPREV` | There is no previous binary to roll back to. | Nothing to do. | | `SH-UPD-NOPLATFORM` | The latest manifest has no binary for your OS and architecture. | Check the release page. | | `SH-UPD-EXEC` | The CLI could not find its own binary path. | Reinstall with the installer script. | | `SH-UPD-ABORT` | You declined the update prompt. | Run `synheart update --yes` to skip the prompt. | | `SH-USAGE-001` | There is no organization on this session. | Pass `--org`, or set `SYNHEART_ORG_ID`. | | `SH-USAGE-002` | The billing API request failed. | Retry later. | | `SH-USAGE-403` | You are not allowed to read usage for this org. Exit code 3. | Check your role. | | `SH-USAGE-404` | The usage endpoint was not found. | Check `--org`. | | `SH-SYNI-001` | A Syni message is required. | Pass a message to `synheart syni chat`. | | `SH-SYNI-002` | A project ID is required to list personas. | Pass `--project`, set `SYNHEART_PROJECT_ID`, or add `project:` under `platform:` in `.synheart/config.yaml`. `synheart project list` shows the ids. | | `SH-SYNI-403` | Syni cloud chat is not allowed for this org. Exit code 3. | Check your plan. | | `SH-SYNI-404` | The persona or session does not exist. Exit code 4. | `synheart syni personas`, and check the `--session` ID. | | `SH-SYNI-429` | You are over your Syni quota. | Wait, or check `synheart usage`. | | `SH-SYNI-500` | The Syni API request failed. | Retry later. | ## Environment variables The CLI reads these variables. Each is checked against the CLI source. | Variable | Purpose | | - | - | | `SYNHEART_AGENT` | `1` forces [agent mode](/cli/agents#agent-mode) on. `0` forces it off. | | `CLAUDECODE`, `CLAUDE_CODE_ENTRYPOINT`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `GEMINI_CLI`, `COPILOT_AGENT` | Set by coding agents. Any of them turns agent mode on. | | `SYNHEART_NO_TUI` | `1` stops the interactive UI from opening. | | `SYNHEART_MOUSE` | `0` leaves the mouse to your terminal: plain click-drag selects text, but the wheel scrolls the terminal instead of the interactive UI. | | `SYNHEART_NO_UPDATE_CHECK` | `1` turns off the passive update notice. | | `SYNHEART_THEME` | Colour theme: `tide`, `ember`, `signal` or `mono`. Same as `--theme`. | | `SYNHEART_THEME_MODE` | `auto` (the default), `light` or `dark`. `light` and `dark` skip the terminal background check. | | `SYNHEART_REDUCED_MOTION` | A truthy value, such as `1`, turns off animation. | | `SYNHEART_API_URL` | Overrides the platform API base URL. The default is `https://api.synheart.ai`. | | `SYNHEART_DIST_URL` | Overrides the distribution URL. The default is `https://dist.synheart.ai`. | | `SYNHEART_UPDATE_MANIFEST_URL` | Overrides the manifest URL that `synheart update` reads. | | `SYNHEART_CI_TOKEN` | A long-lived token for non-interactive `synheart login`. Prefer it over `--ci-token`, because flags show up in process lists and shell history. | | `SYNHEART_DISABLE_KEYRING` | Stores credentials in `~/.synheart/credentials.enc` instead of the system keyring. | | `SYNHEART_ORG_ID` | Default organization ID for `usage`, `syni`, and the `org`, `project` and `api-key` commands. | | `SYNHEART_TENANT_ID` | Default tenant ID for `syni` and the platform commands. | | `SYNHEART_PROJECT_ID` | Default project ID for `syni`. Overrides `platform.project` in `.synheart/config.yaml`. | | `SYNHEART_INSTALL_JOBS` | Number of parallel downloads for `install` and `sync`, from 1 to 16. | | `SYNHEART_ALLOW_ALL_ORIGINS` | `1` lets the mock servers accept browser requests from any origin. By default only non-browser clients, `file://` pages and loopback origins are accepted. | | `SYNHEART_INSTALL_DIR` | Read by the installer scripts, not by the CLI. Sets where `synheart` is installed. | | `NO_COLOR` | Any value turns off colour. See [no-color.org](https://no-color.org). | | `CI` | Any value turns off the interactive UI and update notices. | Two further variables, `SYNHEART_INSECURE_SKIP_MANIFEST_VERIFY` and `SYNHEART_REGISTRY_PINNED_KEYS_FILE`, exist only for CLI developers testing against an unsigned or local registry. Never set them in a real environment. ## Troubleshooting > [accordion] Install or sync asks me to sign in > > Run `synheart login`. Artifact commands need a valid session. If you keep getting sent back to login, run `synheart auth status` to see where the CLI loads credentials from and when they expire. Then `synheart logout` and `synheart login` again. > [accordion] Sign-in does not work in CI or in an agent > > The browser flow needs a person. Create a CI token in the dashboard, set `SYNHEART_CI_TOKEN`, and run `synheart login`. > [accordion] Mock stream port already in use > > Pass `--port` to `synheart mock start`, or check a port with `synheart doctor --port 8787`. The defaults are 8787 (WebSocket), 8788 (SSE) and 8789 (UDP). `--port N` moves all three together: WebSocket on N, SSE on N+1, UDP on N+2. If any of the three is taken, the command fails with `SH-MOCK-004` (exit 5). > [accordion] I need the same runtime version in CI > > Commit `synheart.lock`, and run `synheart sync` in CI. If the lockfile no longer matches the registry, `sync` fails with `SH-INST-004` or `SH-INST-005` instead of installing something different. `synheart doctor` also reports modified runtime files (`SH-RT-FILES`). > [accordion] synheart local --https fails to write /etc/hosts > > The HTTPS mode adds an `/etc/hosts` entry and trusts a local certificate, which can need administrator rights. Run it with the permissions the error asks for, or use plain HTTP (`synheart local`). Undo the changes with `synheart local cleanup --remove-certs`. > [accordion] The receiver cannot be reached from my phone > > Check that your phone and computer are on the same network, and that your firewall allows the receiver's port (default 8787). The receiver listens on every interface unless you pass `--host`. `synheart doctor --port 8787` checks that the port is free. > [accordion] SYNHEART\_API\_URL is not picked up > > The CLI reads environment variables on every run. Check that the variable is exported in the shell that runs the CLI, and run `synheart env` to confirm. > [accordion] The colours look wrong on my terminal > > Set `SYNHEART_THEME_MODE=light` or `dark` if the CLI guessed your background wrongly. Pick another theme with `--theme`, or turn colour off with `NO_COLOR=1`. For anything else, run `synheart doctor`, and include the output of `synheart version --build` when you ask for help. # CLI overview Source: https://docs.synheart.ai/cli/overview What the synheart CLI does, how to open its interactive UI, and the flags and settings every command shares. `synheart` is the command-line tool for building on the Human State Interface (HSI). Use it to: * Set up an app project with `synheart init`, install the Synheart runtime and SDK packages into your app, and pin their versions. * Stream mock wearable data to your app while you build. * Run a local copy of the platform for consent and ingest testing. * Receive HSI exports from a Synheart mobile client over your local network. * Manage your account, organizations, projects and API keys. * Let AI coding agents use all of the above safely. See [Use the CLI from AI agents](/cli/agents). > [!NOTE] > > To install the CLI, see [Install the CLI](/setup/install-cli). For the full onboarding flow (account, sign-in, runtime), see the [Setup overview](/setup/overview). ## Workflows > [card] SDK artifact install > > Sign in, install the runtime, and pin exact versions in `synheart.lock` so every machine and CI run matches. > [card] Local app testing > > Stream mock Whoop or Garmin data over WebSocket, SSE and UDP, and record or replay sessions. > [card] Offline platform > > Run local consent and ingest endpoints, and receive HSI exports from mobile apps. Commands are grouped the way `synheart --help` groups them. Each group has a generated reference page. | Group | Commands | Reference | | - | - | - | | Build | `init`, `install`, `sync`, `runtime` | [Build](/cli/reference/build-your-app) | | Run locally | `mock`, `local`, `receiver` | [Run locally](/cli/reference/simulate-and-serve) | | Account | `login`, `logout`, `whoami`, `auth`, `usage` | [Account & cloud](/cli/reference/platform) | | Cloud | `org`, `project`, `api-key` | [Account & cloud](/cli/reference/platform) | | AI & agents | `syni`, `mcp`, `guard` | [AI & agents](/cli/reference/ai-and-agents) | | Tools | `doctor`, `env`, `config`, `explain`, `version`, `update` | [Tools](/cli/reference/troubleshoot) | | Other | `completion`, `ui` | [Other](/cli/reference/other) | ## The interactive UI Run `synheart` with no arguments in a terminal to open the interactive UI. `synheart ui` (alias `synheart tui`) does the same. The home menu lists every guided flow, grouped as Build, Run locally, Account, Cloud and Tools. Cloud holds orgs, projects, API keys, Syni and Synapse; Synapse (`g`) opens a hub with Guard status, Guard report, Set up guard, Team rules and the Dashboard. The home screen reads your app project without going online: * **Next** beside the logo suggests the one thing to do now. Missing runtime files come first, then a missing lockfile, then signing in; on a healthy project it suggests starting mock data. The cursor starts on that item, so Enter runs it. * Menu items carry their state: Sync shows how many runtime files are missing, Doctor how many problems it found, Update an arrow when a release is waiting, and Mock data a dot while something listens on its port. * A Get Started checklist on a new project walks through starting mock data, connecting an app and installing the runtime. The Connect an app step ticks once an app connects to the mock. * In a terminal at least about 110 columns wide, a panel beside the menu describes the focused item and shows the project at a glance: its runtime packages, mock data and your account. These are the same checks [`synheart doctor`](/cli/reference/troubleshoot) runs, so the two never disagree. Move with the arrow keys or `h` `j` `k` `l`, and press Enter to open an item. Each item also has a one-key shortcut: | Key | Opens | | - | - | | `n` | Connect an app: the mock's WebSocket, SSE and UDP URLs, client snippets (`1` to `3` copy one) and where the SDKs come from | | `i` | Install: what this project has, add packages, reinstall, upgrade, or use a local runtime build | | `s` | Sync | | `e` | Env | | `m` | Mock data | | `p` | Local platform | | `v` | HSI receiver | | `y` | Syni | | `a` | Sign in (or Sign out when you are signed in) | | `$` | Usage & plan | | `d` | Doctor | | `x` | Explain | | `c` | Config | | `,` | Settings: `↑` `↓` move between Theme, Mode and Motion, `←` `→` change the one you are on, Enter saves and Esc cancels | | `u` | Update | | `?` | Help (keyboard shortcuts and tips) | | `q` | Quit | ### Downloads Install and Sync show overall progress and a bar for each file still downloading. Press `p` to pause and `r` to resume. Files already downloaded are kept, and the rest continues from where it stopped, including after you quit and run the same install again. A stalled or dropped download is retried automatically. ### Copying text Click and drag to select text on any screen, as in any other terminal program. Inside a screen, `y` copies the most useful thing on it: the highlighted ID in a list, the stream URL or API key on a live view, or the whole page as plain text on results, Doctor, Help and Explain. Over SSH, copying uses your terminal's clipboard support (OSC 52). The scroll wheel scrolls the UI itself, not your terminal's history, and `PgUp`/`PgDn` scroll every page. To select text, hold Shift (Option in macOS terminals) while you drag. Set `SYNHEART_MOUSE=0` to leave the mouse to your terminal instead: plain click-drag selects, but the wheel then scrolls the terminal's own scrollback. The UI does not open in CI, in a pipe, in [agent mode](/cli/agents), with `--json` or `--quiet`, or when `SYNHEART_NO_TUI=1` is set. In those cases bare `synheart` does not open the UI (in agent and JSON mode it prints the command map instead). `synheart ui` refuses with an error: `TUI is not available with --format json` or `--quiet` for those flags, `SH-TUI-002` in agent mode, and `SH-TUI-001` when there is no terminal, in CI, or when `SYNHEART_NO_TUI=1` is set. Use the ordinary commands in scripts. ## Themes The CLI and the UI share one colour theme. Pick one with `--theme`, with the `SYNHEART_THEME` environment variable, or with `ui.theme` in `.synheart/config.yaml`. The flag wins over the variable, and the variable wins over the config file. | Theme | Look | | - | - | | `tide` | The orange-to-teal brand gradient: teal structure, orange for the next action. This is the default. | | `ember` | Warm graphite with a single orange accent. | | `signal` | Near-monochrome. Orange appears only where you act. | | `mono` | No colour; bold and dim only. | ```yaml theme={null} # .synheart/config.yaml ui: theme: tide ``` ```bash theme={null} synheart --theme signal doctor SYNHEART_THEME=tide synheart ``` An unknown theme name fails with `SH-CFG-003`. Each theme has a dark and a light variant. The CLI detects your terminal background and picks the matching one. To force a variant, set `SYNHEART_THEME_MODE=light` or `SYNHEART_THEME_MODE=dark`. `auto`, the default, detects the background. In the interactive UI, choosing Mode `auto` in Settings after a saved light or dark mode follows the terminal from the next launch; it does not preview a mode until then. Any other value fails with `SH-CFG-004`. Colour turns off when you pass `--no-color`, when `NO_COLOR` is set, when `TERM=dumb`, or when output is not a terminal. In those cases the CLI uses `mono`. ## Motion The UI plays short animations. They are off in CI, in [agent mode](/cli/agents), and whenever `SYNHEART_REDUCED_MOTION` is set to a truthy value such as `1`. ```bash theme={null} SYNHEART_REDUCED_MOTION=1 synheart ``` ## Global flags These flags work on every command. They are also listed, with their defaults, on the [command reference](/cli/reference/index#global-flags) page. | Flag | Purpose | | - | - | | `--format text\|json\|ndjson` | Output format. `ndjson` is an event stream, for commands that stream. Agent mode defaults to `json`. | | `--json` | Shorthand for `--format json`. Combining it with `--format text` is a usage error (exit code 2). | | `--theme ` | Colour theme: `tide`, `ember`, `signal` or `mono`. | | `--no-color` | Turn off coloured output. | | `-q`, `--quiet` | Hide non-essential output. | | `-v`, `--verbose` | Print extra diagnostic output. It also shows the underlying cause on typed errors. | ### Settings precedence Commands that read project settings resolve each value in this order, highest first: 1. A command-line flag, such as `--port 9000`. 2. An environment variable. 3. The project config, `.synheart/config.yaml` in the current directory or a parent. 4. The built-in default. ```yaml theme={null} # .synheart/config.yaml mock: port: 9000 host: 127.0.0.1 scenario: workout vendor: garmin local: port: 8090 domain: api.synheart.local receiver: port: 7777 host: 127.0.0.1 out: ./exports scenarios: dir: ./my-scenarios ui: theme: tide mode: auto # auto, light or dark motion: on # on or reduced platform: org: tenant: project: ``` ```bash theme={null} synheart config show # the resolved settings and the file in use synheart config path # the config file path; exits 1 when there is none ``` `mock`, `local` and `receiver` read their matching section, and `doctor` reads the `mock` section for the port it checks. The `ui` section sets the theme, the light or dark mode and the motion. The `platform` section sets the default organization, tenant and project for `syni` and the `org`, `project`, `api-key` and `usage` commands; the matching `SYNHEART_ORG_ID`, `SYNHEART_TENANT_ID` and `SYNHEART_PROJECT_ID` variables override it. A user config at `~/.synheart/config.yaml` holds the same `ui` and `platform` settings for every project on your machine. A project config overrides it value by value. ## Mock data `synheart mock` generates synthetic vendor streams so you can build and test without a wearable. It streams raw vendor-format JSON, the same shape WHOOP and Garmin send. The SDK runtime in your app turns it into HSI. ```bash theme={null} synheart mock start # whoop, baseline scenario synheart mock start --vendor garmin --scenario workout synheart mock start --rate 100hz --duration 5m synheart mock start --seed 42 # repeatable output ``` By default `mock start` serves three transports from one port setting: | Transport | Address | | - | - | | WebSocket | `ws://127.0.0.1:8787/hsi` (`--port`) | | Server-Sent Events | `http://127.0.0.1:8788/hsi/sse` (`--port` plus 1) | | UDP | `udp://127.0.0.1:8789` (`--port` plus 2) | All three carry the same payload. Add `--web` to open a live dashboard on `--web-port` (default `8790`). ### Record and replay Record a session to an NDJSON file, then replay it later with the same timing. This is useful for regression tests that need a fixed stream. ```bash theme={null} synheart mock record --out session.ndjson --vendor whoop --duration 15m --seed 42 synheart mock replay --in session.ndjson --speed 2 --loop ``` `mock start --out ` records while it streams. `mock replay` serves over WebSocket on `--port`. ### Choose a scenario ```bash theme={null} synheart mock list-scenarios synheart mock describe baseline ``` A scenario is a named time-series profile. `describe` prints its duration, default rate, signals and phases. ## Local platform server `synheart local` runs a local copy of the platform endpoints your SDK calls, so you can build without network access or platform quota. It needs no login. | Setting | Default | | - | - | | Port | `8083` (`--port`) | | API key | `mock-dev-api-key-2026` (`--api-key`) | | HMAC secret | `mock-dev-hmac-secret-2026` (`--hmac-secret`) | | Consent profiles | `profiles.json` from `--data-dir` (default: auto-detected) | | Saved ingests | `~/.synheart/local/ingested/` | ```bash theme={null} synheart local # plain HTTP on 127.0.0.1:8083 synheart local --port 9000 --api-key my-key # custom credentials synheart local --https # HTTPS on api.synheart.local synheart local --web --web-port 8791 # live dashboard synheart local cleanup # remove the /etc/hosts entries synheart local cleanup --remove-certs # also remove the local certificates ``` With `--https`, the CLI creates a locally trusted certificate, adds an `/etc/hosts` entry for `--domain` (default `api.synheart.local`) and serves HTTPS on `--https-port` (default `8443`). That step may ask for your password. Undo it with `synheart local cleanup`. > [!NOTE] > > `--host` defaults to `127.0.0.1`. Pass `--host 0.0.0.0` only when you want other devices on your network to reach the server. ## HSI export receiver `synheart receiver` accepts HSI export payloads that a Synheart mobile client POSTs to `/v1/hsi/import`, for example from the Synheart Life app over your local network. It checks each payload against the HSI Export Schema v1, ignores duplicates, and writes the data to stdout or, with `--out`, to files. ```bash theme={null} synheart receiver # port 8787, random token synheart receiver --port 9000 --token my-token synheart receiver --out ./exports --output-format ndjson --gzip ``` Senders must present the bearer token. Pass `--token`, or let the CLI generate one. The receiver listens on every network interface by default; pass `--host 127.0.0.1` to keep it on your machine. > [!NOTE] > > The payload format flag is `--output-format json|ndjson`. The old `--format ndjson` on `receiver` still works and prints a deprecation note, but `--format` is now the global output flag. ## Debugging the CLI The CLI has hidden developer flags for profiling itself (`--pprof` and the `--cpu-profile`, `--mem-profile` and `--trace-profile` family). They do not appear in `--help` or `synheart help --json`. You only need them if you are reporting a performance problem with the CLI. ## Where to go next > [card] [Use the CLI from AI agents](/cli/agents) > > Agent mode, JSON output, exit codes and the MCP server. > [card] [Command reference](/cli/reference/index) > > Every command, flag and example, generated from the CLI. > [card] [Errors and environment](/cli/errors) > > Error codes, environment variables and troubleshooting. > [card] [Install the CLI](/setup/install-cli) > > Install on macOS, Linux or Windows. # AI & agents Source: https://docs.synheart.ai/cli/reference/ai-and-agents Reference for the synheart commands in the AI & agents group. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart guard` Hold your coding agents to rules you set Checks what a coding agent is about to do (push, merge, delete, deploy, edit a protected file) against rules you wrote, before it runs. A rule either asks you or stops the agent. Exceptions are scoped to a repository, branch or path, expire after the time you set, and can only be granted by you at a terminal. Everything stays on this machine: your rules in \~/.synheart/guard/rules.yaml, a repository's own rules in .synheart/guard.yaml, and a local log of which rules fired (never the commands themselves). Start with synheart guard init, then synheart guard install to hook it into Claude Code. **Usage** ```bash theme={null} synheart guard ``` **Subcommands** * `synheart guard allow`: Allow a blocked action for a limited time * `synheart guard check`: Test a shell command against your guard rules * `synheart guard init`: Create your guard rules file * `synheart guard install`: Hook the guard into Claude Code * `synheart guard report`: Summarise what the guard stopped, asked and allowed * `synheart guard rules`: List the guard rules in force here * `synheart guard sync`: Refresh team rules and upload day totals now * `synheart guard team`: Use your organization's guard rules **Examples** ```bash theme={null} # Create your rules file, then hook the guard into Claude Code synheart guard init synheart guard install --write # Test a command against your rules synheart guard check git push --force origin main # See what the guard did this week synheart guard report ``` ### `synheart guard allow` Allow a blocked action for a limited time Lets what a rule stops or asks about through, in the scope you give and only until the time you set (default 1h, at most 168h). Use it when you know a one-off action is fine. Only you can run it, at a terminal; an agent cannot. Find rule IDs with synheart guard rules. Scope the exception with --repo, \--branch or --path; without them it applies everywhere. **Usage** ```bash theme={null} synheart guard allow [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--branch` | `string` | - | Limit the exception to this branch | | `--for` | `duration` | `1h0m0s` | How long the exception lasts, up to 168h (for example 30m or 2h) | | `--note` | `string` | - | Reason for the exception, kept in your local record | | `--path` | `string` | - | Limit the exception to paths matching this glob | | `--repo` | `string` | - | Limit the exception to this repository (owner/name) | **Examples** ```bash theme={null} # Allow a force-push on one branch for two hours synheart guard allow no-force-push --branch feat/rewrite --for 2h # Allow pushes to protected branches in one repository for a hotfix synheart guard allow no-push-protected --repo synheart-ai/synheart-cloud --for 30m --note "hotfix" ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard check` Test a shell command against your guard rules Shows what the guard would do with a shell command in the current directory, without running it: stop, ask, or let it through, and which rule decided. Everything after 'check' is the command to test, flags included, except a trailing --json, which prints the actions, verdict and matching rules as an object. Needs no login and no network. **Usage** ```bash theme={null} synheart guard check ``` **Examples** ```bash theme={null} # Would this force-push be stopped? synheart guard check git push --force origin main # Quote compound commands synheart guard check 'cd ../web && gh pr create --base dev' # The same answer for a script synheart guard check git push --force origin main --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart guard init` Create your guard rules file Writes \~/.synheart/guard/rules.yaml, from a starter set or from a file you give with --from, and checks that it loads. Refuses to overwrite an existing file. Only you can run it, at a terminal. Next step: synheart guard install. **Usage** ```bash theme={null} synheart guard init [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--from` | `string` | - | Start from this rules file instead of the starter set | **Examples** ```bash theme={null} # Start from the built-in rules synheart guard init # Start from your team's file synheart guard init --from ./team-rules.yaml ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard install` Hook the guard into Claude Code Without flags, prints the Claude Code settings that run the guard before and after each action. With --write, merges them into \~/.claude/settings.json, or into .claude/settings.local.json in this directory with --project. It keeps every other setting and hook, saves a backup first, and changes nothing when run again. **Usage** ```bash theme={null} synheart guard install [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--project` | `bool` | `false` | With --write, use this directory's .claude/settings.local.json instead of \~/.claude/settings.json | | `--write` | `bool` | `false` | Add the hook to Claude Code's settings instead of printing it | **Examples** ```bash theme={null} # Preview the settings synheart guard install # Add the hook for all your projects synheart guard install --write # Add it for this directory only synheart guard install --write --project ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard report` Summarise what the guard stopped, asked and allowed Counts how often each rule fired over a period: stopped, asked, or let through. It reads the local log, which never holds commands or file paths. With \--json it prints the counts as an object. Needs no login and no network. **Usage** ```bash theme={null} synheart guard report [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--since` | `duration` | `168h0m0s` | How far back to report, as a duration (for example 24h) | **Examples** ```bash theme={null} # The last seven days synheart guard report # The last day synheart guard report --since 24h ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart guard rules` List the guard rules in force here Lists the rules that apply in the current directory, merged from your rules file, the repository's .synheart/guard.yaml and your team's rules, each with its verdict (stop or ask; "shadow" means it only logs). Active exceptions follow. With --json it prints an object with the rules under "items" and the active exceptions under "exceptions". Needs no login and no network. **Usage** ```bash theme={null} synheart guard rules ``` **Examples** ```bash theme={null} # List the rules and exceptions that apply here synheart guard rules # As JSON synheart guard rules --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart guard sync` Refresh team rules and upload day totals now Fetches your organization's current rules from Synapse and uploads the day totals of which rules fired, never commands, paths or prompts. The guard does this in the background about every 15 minutes; run it to do it now. Needs: you joined a team (synheart guard team join) and network access. **Usage** ```bash theme={null} synheart guard sync [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--quiet` | `bool` | `false` | Print nothing (used by the hook) | **Examples** ```bash theme={null} # Sync now synheart guard sync ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard team` Use your organization's guard rules Applies your organization's rules from Synapse on this machine, ahead of your own, and shares day totals of which rules fired with your team. Never a command, a file path or a prompt. Use synheart guard team join to start, synheart guard team status to check, and synheart guard team leave to stop. **Usage** ```bash theme={null} synheart guard team ``` **Subcommands** * `synheart guard team join`: Enforce your organization's agent rules here * `synheart guard team leave`: Stop using your organization's rules here * `synheart guard team status`: Show your guard team and last sync **Examples** ```bash theme={null} # Start using your organization's rules synheart guard team join # Check the team and last sync synheart guard team status ``` ### `synheart guard team join` Enforce your organization's agent rules here Fetches your organization's rules from Synapse and enforces them ahead of your own, then runs a first sync. Day totals of which rule fired (stopped, asked, let through) are shared with your team, never a command, a file path or a prompt. Only you can run it, at a terminal. Needs: you are signed in (synheart login) and network access. The organization comes from your sign-in unless you pass --org. **Usage** ```bash theme={null} synheart guard team join [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Organization ID (default: the org from your sign-in) | **Examples** ```bash theme={null} # Join the team for your organization synheart guard team join # Join a specific organization synheart guard team join --org org_acme_xyz ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard team leave` Stop using your organization's rules here Removes your organization's rules and the team link from this machine. Your own rules keep applying. Only you can run it, at a terminal. Needs no network. **Usage** ```bash theme={null} synheart guard team leave ``` **Examples** ```bash theme={null} # Leave the team synheart guard team leave ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart guard team status` Show your guard team and last sync Shows the organization this machine takes rules from, the policy version, when it last synced, and the last sync error if there was one. Says "not in a team" when you have not joined. With --json it prints the same as an object. Reads local state only. **Usage** ```bash theme={null} synheart guard team status ``` **Examples** ```bash theme={null} # Show the team and last sync synheart guard team status ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart mcp` Connect AI agents through the MCP server Exposes the Synheart CLI to AI agents (Claude Code, Cursor, Claude Desktop) through the Model Context Protocol, so they can call its commands as tools: set up an app project, check it, stream mock data and get connection snippets. Each tool says whether it is safe to call unprompted. On its own, synheart mcp prints this help. Add synheart mcp serve to your agent's MCP server list to use it. See docs/cli-mcp.md for the setup of each client. **Usage** ```bash theme={null} synheart mcp ``` **Subcommands** * `synheart mcp serve`: Run the MCP server on stdin and stdout **Examples** ```bash theme={null} # Start the server (your agent's MCP client runs this) synheart mcp serve # Check it responds, without an agent echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | synheart mcp serve ``` ### `synheart mcp serve` Run the MCP server on stdin and stdout Reads JSON-RPC 2.0 messages from stdin, one per line, and writes responses to stdout. Its tools mirror init, doctor, env, explain, config show, auth status, whoami, version and the mock commands; synheart\_mock\_start runs the stream inside this process until synheart\_mock\_stop or the client disconnects. Nothing signs in, opens a browser or prompts: login, guard allow and update stay with the person at the terminal. An MCP client starts this command; it prints nothing until the client sends a request. Needs no network of its own. **Usage** ```bash theme={null} synheart mcp serve ``` **Examples** ```bash theme={null} # Start the server (your agent's MCP client runs this) synheart mcp serve # List its tools from a shell echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | synheart mcp serve ``` **JSON output:** not supported. This command does not print a JSON body. ## `synheart syni` Chat with Syni, Synheart's state-aware assistant Syni is Synheart's state-aware assistant. Run synheart syni in a terminal to chat interactively; use the subcommands for one-shot messages, personas and past sessions. Cloud chat needs you to be signed in and a plan that includes it (see synheart usage). Without a terminal, or with --json or --no-repl, running synheart syni prints this help instead. Pass --org, --tenant or --project (or the matching SYNHEART\_\*\_ID variables) to choose the scope. **Usage** ```bash theme={null} synheart syni ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Organization ID (env: SYNHEART\_ORG\_ID) | | `--project` | `string` | - | Project ID (env: SYNHEART\_PROJECT\_ID) | | `--tenant` | `string` | - | Tenant ID (env: SYNHEART\_TENANT\_ID) | **Subcommands** * `synheart syni chat`: Send a message to Syni * `synheart syni personas`: List Syni personas * `synheart syni sessions`: Inspect Syni chat sessions * `synheart syni version`: Show installed syni-spec and syni-runtime versions **Examples** ```bash theme={null} # Chat interactively synheart syni # Ask one question and get the answer synheart syni chat "How is my recovery?" # See the available personas synheart syni personas ``` ### `synheart syni chat` Send a message to Syni Sends a message to Syni in the cloud and prints the reply. With a message it runs once and exits; with none, in a terminal, it opens an interactive chat. Pass a persona ID first to talk to a specific persona, and --session to continue an earlier conversation. Use --no-repl to require a message. Needs: you are signed in, a plan that includes cloud chat, and network access. With --json it prints the reply as an object. **Usage** ```bash theme={null} synheart syni chat [persona] [message] [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--mode` | `string` | `cloud_only` | Execution mode: cloud\_only, local\_first or local\_only | | `--model` | `string` | - | Model ID (from GET /v1/models) | | `--no-repl` | `bool` | `false` | Require a message instead of opening the interactive REPL | | `--persona` | `string` | - | Persona ID or legacy key | | `--session` | `string` | - | Continue this session (ID from an earlier chat) | **Examples** ```bash theme={null} # Ask one question synheart syni chat "Why is my HRV down?" # Ask a specific persona synheart syni chat focus.coach.v1 "Help me focus" # Continue a session and get JSON synheart syni chat --session sess_abc "Continue" --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart syni personas` List Syni personas Lists the personas you can chat with, each with its ID. Use an ID with synheart syni chat \. Needs: you are signed in, network access and a project ID (--project, SYNHEART\_PROJECT\_ID, or platform.project in .synheart/config.yaml). With --json it prints the list. **Usage** ```bash theme={null} synheart syni personas ``` **Subcommands** * `synheart syni personas show`: Show one Syni persona **Examples** ```bash theme={null} # List personas for a project synheart syni personas --project prj_123 # As JSON synheart syni personas --project prj_123 --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart syni personas show` Show one Syni persona Prints the details of the persona with the given ID. Needs you to be signed in and network access. With --json it prints the persona as an object. **Usage** ```bash theme={null} synheart syni personas show ``` **Examples** ```bash theme={null} # Show a persona synheart syni personas show focus.coach.v1 # As JSON synheart syni personas show focus.coach.v1 --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart syni sessions` Inspect Syni chat sessions Work with your Syni chat sessions. Use synheart syni sessions show to read one, and pass its ID to synheart syni chat --session to continue it. **Usage** ```bash theme={null} synheart syni sessions ``` **Subcommands** * `synheart syni sessions show`: Show a Syni session and its messages **Examples** ```bash theme={null} # Read a session synheart syni sessions show sess_abc123 ``` ### `synheart syni sessions show` Show a Syni session and its messages Prints a chat session and its messages. Needs you to be signed in and network access. With --json it prints the session as an object. **Usage** ```bash theme={null} synheart syni sessions show ``` **Examples** ```bash theme={null} # Read a session synheart syni sessions show sess_abc123 # As JSON synheart syni sessions show sess_abc123 --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart syni version` Show installed syni-spec and syni-runtime versions Prints the versions of the syni-spec and syni-runtime packages installed in the current project. It reads the vendored packages, or the pins in synheart.lock when they are not vendored yet; "source" in the JSON says which. Reads local files only, so it needs no login and no network. **Usage** ```bash theme={null} synheart syni version ``` **Examples** ```bash theme={null} # Show the installed versions synheart syni version # As JSON synheart syni version --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. # Build Source: https://docs.synheart.ai/cli/reference/build-your-app Reference for the synheart commands in the Build group. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart init` Set up this directory as a Synheart app project Creates .synheart/config.yaml in the current directory (or --project-dir) with every setting the CLI reads from it, commented out at its default: mock, local, receiver, ui and platform. Uncomment a line to change that default for everyone working on the app project; flags and environment variables still win. It also detects the kind of app in the directory (ios, android, flutter, multi or none), the same way synheart env does, and prints what to do next. Running it again is safe: an existing config is left alone and reported, and the command exits 0. --force rewrites it, keeping the old file as config.yaml.bak (or config.yaml.bak.1, .2, ... when that exists, so no backup is ever overwritten). Run it inside your app's folder, not your home directory: \~/.synheart/config.yaml holds your personal settings, and init refuses to touch it. Needs no login and no network, and never prompts. With \--json it prints created, path, project\_type and the next steps as an object. **Usage** ```bash theme={null} synheart init [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--force` | `bool` | `false` | Rewrite an existing .synheart/config.yaml, keeping the old one as config.yaml.bak (never overwriting an older backup) | | `--project-dir` | `string` | `.` | Directory to set up | **Examples** ```bash theme={null} # Set up the app in this directory synheart init # Set up another directory, as JSON synheart init --project-dir ../my-app --json # Start over from the defaults (the old file is kept as config.yaml.bak) synheart init --force ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart install` Install SDK artifacts into your app project Downloads Synheart SDK artifacts from the Artifact Registry into your project's synheart/vendor directory and records them in synheart.lock. Use it to add the runtime or the Syni packages to an app, or to change runtime variant. Needs: you are signed in (synheart login), network access, and a project directory (default: the current directory). For a guided install, open synheart ui. Products are syni and core; components are runtime and spec. A product installs every component of it that your plan includes. A component installs across every product that ships it. Two arguments, in either order, pin one package. Files go to synheart/vendor/runtime/ for the core runtime and to synheart/vendor/\/ for everything else. **Usage** ```bash theme={null} synheart install [component|product] [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--cache-dir` | `string` | - | Download cache directory (default: \~/.synheart/cache) | | `--channel` | `string` | `latest` | Release channel to install from: latest or stable (stable may not be published yet) | | `--platform` | `string` | - | Install for one platform only: ios or android (default: all platforms) | | `--project-dir` | `string` | `.` | Project directory to install into | | `--variant` | `string` | - | Runtime variant: edge, stable or lab (default: the server picks one based on your plan) | | `--version` | `string` | - | Exact version to install, such as v1.2.3 or stable; overrides --channel | **Examples** ```bash theme={null} # Install the Syni packages your plan includes synheart install syni # Install the core runtime synheart install core # Install one component for every product that ships it synheart install runtime # Pin one package to a variant or version synheart install runtime --variant edge synheart install runtime syni --version v0.2.0 ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart runtime` Manage the synheart-core-runtime library Inspect, upgrade, or install the native synheart-core-runtime library in a project. The runtime is what your app's Synheart SDK loads at launch. To fetch the runtime from the registry the first time, use synheart install runtime. The subcommands here work on a runtime that is already pinned in synheart.lock, or on a local build. **Usage** ```bash theme={null} synheart runtime ``` **Subcommands** * `synheart runtime current`: Show the runtime pinned in synheart.lock * `synheart runtime install`: Install runtime artifacts from a local build * `synheart runtime upgrade`: Fetch the latest runtime for your variant **Examples** ```bash theme={null} # Show which runtime this project is on synheart runtime current # Move to the latest runtime for the same variant synheart runtime upgrade # Install a runtime you built locally synheart runtime install --from ../synheart-core-runtime/build/dist/core ``` ### `synheart runtime current` Show the runtime pinned in synheart.lock Prints the runtime package, variant and version recorded in the project's synheart.lock. It makes no network call, so it is a quick way to answer "what am I on?". Needs a project directory containing synheart.lock (default: the current directory). Exits 1 with SH-RT-NOLOCK when there is no lockfile yet. With \--json it prints the same fields as an object. **Usage** ```bash theme={null} synheart runtime current [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--project` | `string` | `.` | Project directory containing synheart.lock | **Examples** ```bash theme={null} # In a project with a runtime installed synheart runtime current # Another project, as JSON synheart runtime current --project ../my-app --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart runtime install` Install runtime artifacts from a local build Copies pre-built synheart-core-runtime artifacts from a local build directory into \/synheart/vendor/runtime/, in the same layout that synheart install runtime produces from the registry. Use it to test a runtime you built yourself. No login or network needed. \--from points at the build output, typically from make dist-core in the synheart-core-runtime repository. Everything at the top level of that directory is copied as is. **Usage** ```bash theme={null} synheart runtime install [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--from` | `string` | - | Directory of built runtime artifacts (required) | | `--project` | `string` | `.` | Project directory to install into | **Examples** ```bash theme={null} # Install a local build into the current project synheart runtime install --from ../synheart-core-runtime/build/dist/core # Install into another project synheart runtime install --from ./build/dist/core --project ../my-flutter-app ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart runtime upgrade` Fetch the latest runtime for your variant Reads the variant (edge, stable or lab) from synheart.lock and runs synheart install runtime against the latest release of that variant. A project on lab stays on lab; a project on edge stays on edge. With no lockfile it installs without a variant, so the server picks one from your plan. Needs: you are signed in and network access. **Usage** ```bash theme={null} synheart runtime upgrade [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--platform` | `string` | - | Upgrade one platform only: ios or android (default: all platforms) | | `--project` | `string` | `.` | Project directory containing synheart.lock | **Examples** ```bash theme={null} # Upgrade the runtime in this app project synheart runtime upgrade # Upgrade a project in another directory synheart runtime upgrade --project ../my-app # Upgrade for one platform only synheart runtime upgrade --platform ios ``` **JSON output:** not supported. This command does not print a JSON body. ## `synheart sync` Reinstall exactly what synheart.lock pins Reads synheart.lock in the project directory and installs the versions it pins, so every machine and CI run gets the same artifacts. Use it after cloning a project or pulling a lockfile change. It works with single-package and multi-package lockfiles. Needs: you are signed in, network access, and a synheart.lock (created by synheart install). **Usage** ```bash theme={null} synheart sync [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--project-dir` | `string` | `.` | Project directory containing synheart.lock | **Examples** ```bash theme={null} # Restore the artifacts pinned in this project synheart sync # Restore them for a project in another directory synheart sync --project-dir ../my-app ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. # Command reference Source: https://docs.synheart.ai/cli/reference/index Every synheart command, grouped the way `synheart --help` groups them. This reference is generated from synheart 0.21.0. For a machine-readable version, run `synheart help --json`. ## Command groups ### [Build](/cli/reference/build-your-app) * `synheart init`: Set up this directory as a Synheart app project * `synheart install`: Install SDK artifacts into your app project * `synheart runtime`: Manage the synheart-core-runtime library * `synheart sync`: Reinstall exactly what synheart.lock pins ### [Run locally](/cli/reference/simulate-and-serve) * `synheart local`: Run a local copy of the Synheart platform * `synheart mock`: Generate and replay mock wearable data * `synheart receiver`: Receive HSI export payloads over HTTP ### [Account](/cli/reference/platform) * `synheart auth`: Sign in, sign out and inspect credentials * `synheart login`: Sign in to your Synheart account * `synheart logout`: Sign out and remove stored credentials * `synheart usage`: Show plan usage, limits and Syni meters * `synheart whoami`: Show the account you are signed in as ### [Cloud](/cli/reference/platform) * `synheart api-key`: List and manage API keys * `synheart org`: List and manage your organizations * `synheart project`: List and manage your projects ### [AI & agents](/cli/reference/ai-and-agents) * `synheart guard`: Hold your coding agents to rules you set * `synheart mcp`: Connect AI agents through the MCP server * `synheart syni`: Chat with Syni, Synheart's state-aware assistant ### [Tools](/cli/reference/troubleshoot) * `synheart config`: Show how the CLI resolves its settings * `synheart doctor`: Check your Synheart setup for problems * `synheart env`: Show paths, account and app type * `synheart explain`: Read a plain-language primer on a concept * `synheart update`: Update the CLI to the latest release * `synheart version`: Show the CLI version ### [Other](/cli/reference/other) * `synheart completion`: Generate a shell completion script * `synheart ui`: Open the interactive terminal UI ## Global flags Every command accepts these flags. | Flag | Type | Default | Description | | - | - | - | - | | `--format` | `string` | `text` | Output format: text, json or ndjson (event stream, on commands that stream); agent mode defaults to json | | `--json` | `bool` | `false` | Shorthand for --format json | | `--no-color` | `bool` | `false` | Turn off coloured output | | `-q`, `--quiet` | `bool` | `false` | Hide non-essential output | | `--theme` | `string` | - | Colour theme: tide\|ember\|signal\|mono (default tide; also SYNHEART\_THEME) | | `-v`, `--verbose` | `bool` | `false` | Print extra diagnostic output | ## Exit codes | Code | Meaning | | - | - | | `0` | success | | `1` | general failure | | `2` | usage error: bad flags or arguments, unknown command | | `3` | authentication required or forbidden (SH-AUTH-\*) | | `4` | the requested resource was not found | | `5` | transient failure (network, timing); retrying may work | ## Environment variables | Variable | Description | | - | - | | `SYNHEART_AGENT` | 1 forces agent mode on, 0 forces it off | | `CLAUDECODE` | agent mode: set to 1 by Claude Code in the shells it spawns | | `CLAUDE_CODE_ENTRYPOINT` | agent mode: set by Claude Code to how it was launched | | `CURSOR_AGENT` | agent mode: set to 1 by Cursor's agent terminal | | `CODEX_SANDBOX` | agent mode: set by OpenAI Codex when it runs commands in its sandbox | | `GEMINI_CLI` | agent mode: set to 1 by Gemini CLI's shell tool | | `COPILOT_AGENT` | agent mode: set by GitHub Copilot's coding agent | | `SYNHEART_NO_TUI` | 1 disables the interactive TUI | | `SYNHEART_MOUSE` | 0 leaves the mouse to the terminal: native click-drag selection, but the wheel scrolls the terminal, not the TUI | | `SYNHEART_NO_UPDATE_CHECK` | 1 disables the passive update notice | | `SYNHEART_THEME` | colour theme (same as --theme) | | `SYNHEART_API_URL` | override the platform API base URL | | `SYNHEART_CI_TOKEN` | long-lived token for non-interactive login | | `NO_COLOR` | any value disables colour | | `CI` | any value disables the TUI and update notices | # Other Source: https://docs.synheart.ai/cli/reference/other Reference for the synheart commands in the Other group. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart completion` Generate a shell completion script Prints a completion script for your shell to stdout. Load it once per shell, or save it where your shell reads completions, to complete commands, flags and arguments. Supports bash, zsh, fish and powershell. Needs no login and no network. **Usage** ```bash theme={null} synheart completion [bash|zsh|fish|powershell] ``` **Examples** ```bash theme={null} # Load completions in the current zsh session source <(synheart completion zsh) # Install them for bash on Linux synheart completion bash | sudo tee /etc/bash_completion.d/synheart # fish synheart completion fish > ~/.config/fish/completions/synheart.fish ``` **JSON output:** not supported. This command does not print a JSON body. ## `synheart ui` Open the interactive terminal UI Opens the full-screen Synheart terminal UI: the home screen plus guided flows for sign-in, mock data, local server, receiver, install, sync, doctor, usage, Syni chat, runtime, orgs, projects, API keys, env, update and config. Running synheart with no arguments in a terminal does the same. synheart tui is an alias. It does not open in CI, in pipes, in agent mode, with --json or --quiet, or when SYNHEART\_NO\_TUI=1 is set. Use the ordinary commands in scripts. **Usage** ```bash theme={null} synheart ui ``` **Aliases:** `tui` **Examples** ```bash theme={null} # Open the UI synheart ui # The same, from a bare command synheart ``` **JSON output:** not supported. This command does not print a JSON body. # Account & cloud Source: https://docs.synheart.ai/cli/reference/platform Reference for the synheart commands in the Account and Cloud groups. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart auth` Sign in, sign out and inspect credentials Manage how the CLI authenticates to Synheart. login, logout and whoami are also available at the top level (synheart login), because you will use them most; status and refresh are for troubleshooting sign-in. **Usage** ```bash theme={null} synheart auth ``` **Subcommands** * `synheart auth refresh`: Refresh your token to pick up plan changes * `synheart auth status`: Show where credentials are stored and if they load **Examples** ```bash theme={null} # Why does the CLI think I am signed out? synheart auth status # Pick up a plan change without signing in again synheart auth refresh ``` ### `synheart auth refresh` Refresh your token to pick up plan changes Exchanges your stored refresh token for a new access token, even if the current one is still valid. Prints the organization and plan from the new token. Rarely needed: whoami, usage and the TUI refresh your plan claims automatically when they are older than 5 minutes, so an upgrade shows up without signing out and in again. Needs: you are signed in and network access. With --json it prints the result as an object. **Usage** ```bash theme={null} synheart auth refresh ``` **Examples** ```bash theme={null} # Refresh and show the new plan synheart auth refresh # As JSON synheart auth refresh --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart auth status` Show where credentials are stored and if they load Reports whether the CLI can load your credentials and from where (file or keyring), when they expire, and whether a refresh token is present. Use it to debug "not signed in" problems. Reads local state only; no network call. Exits 1 when no usable credentials are found. With --json it prints the same fields as an object. **Usage** ```bash theme={null} synheart auth status ``` **Examples** ```bash theme={null} # Check stored credentials synheart auth status # As JSON synheart auth status --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart login` Sign in to your Synheart account Signs you in with the OAuth 2.0 device flow. The CLI prints a URL and a code, opens your browser (unless you pass --no-browser), and waits while you approve it. Tokens are stored in your system keychain, or in \~/.synheart/credentials.enc when no keychain is available. For CI and agents, which cannot use a browser, set SYNHEART\_CI\_TOKEN (or pass \--ci-token) to store a long-lived token from the dashboard instead. Prefer the environment variable: a flag is visible in process listings and shell history. With --json the CI-token sign-in prints "logged\_in", "method", "storage" and "credentials\_path" as an object. Needs network access. synheart auth login does the same; synheart ui has a sign-in screen too. **Usage** ```bash theme={null} synheart login [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--ci-token` | `string` | - | Long-lived CI bearer token (overrides \$SYNHEART\_CI\_TOKEN) | | `--no-browser` | `bool` | `false` | Print the sign-in URL without opening a browser | **Examples** ```bash theme={null} # Sign in with your browser synheart login # Sign in from CI with a token from the environment export SYNHEART_CI_TOKEN=sht_ci_abc123 synheart login # Print the sign-in URL instead of opening a browser synheart login --no-browser ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart logout` Sign out and remove stored credentials Removes the credentials stored on this machine. Add --revoke to also revoke the tokens on the server, which is the right choice on a shared or lost device. Says "Not signed in" and does nothing when you are already signed out. Needs network access only with --revoke. With --json it prints "logged\_out", "was\_logged\_in" and "revoke\_requested" as an object. **Usage** ```bash theme={null} synheart logout [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--revoke` | `bool` | `false` | Also revoke the tokens on the server | **Examples** ```bash theme={null} # Sign out of this machine synheart logout # Also revoke the tokens on the server synheart logout --revoke ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart usage` Show plan usage, limits and Syni meters Shows the current billing period for your organization: plan, cost, limits on projects, apps and seats, Syni entitlements, and Syni cloud chat meters. Use it to see how close you are to a limit. Your plan claims are refreshed automatically first when they are older than 5 minutes, so a recent upgrade shows up. Needs: you are signed in and network access. The organization comes from your sign-in; override it with --org or SYNHEART\_ORG\_ID. With --json it prints the report as an object. **Usage** ```bash theme={null} synheart usage [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Organization ID (env: SYNHEART\_ORG\_ID; default: the org in your sign-in) | | `--period` | `string` | - | Billing period for the Syni meters (default: the current period) | **Examples** ```bash theme={null} # Show usage for your organization synheart usage # As JSON synheart usage --json # For a specific organization synheart usage --org org_acme_xyz ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart whoami` Show the account you are signed in as Prints the signed-in account: ID, email, name, organization, plan and the runtime variants your plan includes. Use it to confirm which account the CLI will act as. If your sign-in is older than 5 minutes it is refreshed first, so a recent plan change shows up. Needs you to be signed in; exits 1 with SH-AUTH-001 otherwise. With --json it prints the account as an object with "logged\_in" and "claims\_refreshed". **Usage** ```bash theme={null} synheart whoami ``` **Examples** ```bash theme={null} # Show the current account synheart whoami # As JSON synheart whoami --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart api-key` List and manage API keys Work with the API keys in your organization. Each subcommand calls the Synheart platform API, so you must be signed in. synheart api-key list prints a table (JSON with --json); the other subcommands print the result as JSON. Use synheart api-key revoke to turn a key off and synheart api-key delete to remove it. To browse keys interactively, open synheart ui. **Usage** ```bash theme={null} synheart api-key ``` **Subcommands** * `synheart api-key delete`: Delete an API key * `synheart api-key list`: List your API keys * `synheart api-key revoke`: Revoke an API key * `synheart api-key show`: Show one API key **Examples** ```bash theme={null} # List keys synheart api-key list # Revoke one synheart api-key revoke key_123 ``` ### `synheart api-key delete` Delete an API key Deletes the API key with the given ID through the platform API. It does not ask for confirmation, so check the ID first with synheart api-key show. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart api-key delete [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Check what you are about to delete synheart api-key show key_123 # Delete it synheart api-key delete key_123 ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart api-key list` List your API keys Lists the API keys in your organization as a table. Needs you to be signed in and network access. With --json it prints the result as JSON. **Usage** ```bash theme={null} synheart api-key list [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # List keys synheart api-key list # As JSON synheart api-key list --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart api-key revoke` Revoke an API key Revokes the API key with the given ID so it stops working. It does not ask for confirmation. Use it when a key may have leaked. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart api-key revoke [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Revoke a key synheart api-key revoke key_123 ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart api-key show` Show one API key Prints the details of the API key with the given ID. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart api-key show [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Show a key synheart api-key show key_123 # Compact JSON for scripts synheart api-key show key_123 --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart org` List and manage your organizations Work with the organizations your account belongs to. Each subcommand calls the Synheart platform API, so you must be signed in. synheart org list prints a table (JSON with --json); the other subcommands print the result as JSON. Pass --org or set SYNHEART\_ORG\_ID to act on a specific organization. To browse them interactively, open synheart ui. **Usage** ```bash theme={null} synheart org ``` **Subcommands** * `synheart org delete`: Delete an organization * `synheart org list`: List your organizations * `synheart org show`: Show one organization **Examples** ```bash theme={null} # List your organizations synheart org list # Show one synheart org show org_acme_xyz --json ``` ### `synheart org delete` Delete an organization Deletes the organization with the given ID through the platform API. It does not ask for confirmation, so check the ID first with synheart org show. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart org delete [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Check what you are about to delete synheart org show org_acme_xyz # Delete it synheart org delete org_acme_xyz ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart org list` List your organizations Lists the organizations your account belongs to as a table. Needs you to be signed in and network access. With --json it prints the result as JSON. **Usage** ```bash theme={null} synheart org list [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # List organizations synheart org list # Pipe the JSON to another tool synheart org list --json | jq '.' ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart org show` Show one organization Prints the details of the organization with the given ID. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart org show [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Show an organization synheart org show org_acme_xyz # Compact JSON for scripts synheart org show org_acme_xyz --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart project` List and manage your projects Work with the projects in your organization. Each subcommand calls the Synheart platform API, so you must be signed in. synheart project list prints a table (JSON with --json); the other subcommands print the result as JSON. Pass --org and --tenant (or set SYNHEART\_ORG\_ID and SYNHEART\_TENANT\_ID) to choose the scope. To browse them interactively, open synheart ui. **Usage** ```bash theme={null} synheart project ``` **Subcommands** * `synheart project delete`: Delete a project * `synheart project list`: List your projects * `synheart project show`: Show one project **Examples** ```bash theme={null} # List projects synheart project list # Show one synheart project show proj_123 --json ``` ### `synheart project delete` Delete a project Deletes the project with the given ID through the platform API. It does not ask for confirmation, so check the ID first with synheart project show. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart project delete [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Check what you are about to delete synheart project show proj_123 # Delete it synheart project delete proj_123 ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart project list` List your projects Lists the projects for your tenant as a table. Needs you to be signed in and network access. With --json it prints the result as JSON. **Usage** ```bash theme={null} synheart project list [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # List projects synheart project list # List projects of another organization, as JSON synheart project list --org org_acme_xyz --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart project show` Show one project Prints the details of the project with the given ID. Needs you to be signed in and network access. Prints the result as JSON. **Usage** ```bash theme={null} synheart project show [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--org` | `string` | - | Sent as X-Org-ID header (env: SYNHEART\_ORG\_ID) | | `--tenant` | `string` | - | Sent as X-Tenant-ID header (env: SYNHEART\_TENANT\_ID) | **Examples** ```bash theme={null} # Show a project synheart project show proj_123 # Compact JSON for scripts synheart project show proj_123 --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. # Run locally Source: https://docs.synheart.ai/cli/reference/simulate-and-serve Reference for the synheart commands in the Run locally group. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart local` Run a local copy of the Synheart platform Starts an HTTP server on your machine that answers the platform endpoints your SDK calls, so you can develop and test without network access: ```text theme={null} GET /api/v1/apps/{id}/consent-profiles POST /api/v1/sdk/consent-token POST /api/v1/sdk/consent-revoke POST /v1/ingest/hsi POST /v1/platform/session/ingest POST /v1/platform/metadata/ingest GET /status ``` Runs until you press Ctrl+C. Pass --https to serve HTTPS on a local domain with a locally trusted certificate; that adds an /etc/hosts entry and may ask for your password. Undo it with synheart local cleanup. Port, host and domain fall back to the local section of .synheart/config.yaml. Needs no login. **Usage** ```bash theme={null} synheart local [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--api-key` | `string` | `mock-dev-api-key-2026` | API key the consent endpoints accept | | `--data-dir` | `string` | - | Directory containing profiles.json (default: auto-detected) | | `--domain` | `string` | `api.synheart.local` | Local domain name for HTTPS mode | | `--hmac-secret` | `string` | `mock-dev-hmac-secret-2026` | Secret used to verify ingest signatures (HMAC) | | `--host` | `string` | `127.0.0.1` | Address to bind to; 0.0.0.0 exposes the server on your network | | `--https` | `bool` | `false` | Serve HTTPS with a locally trusted certificate and an /etc/hosts entry | | `--https-port` | `int` | `8443` | Port for the HTTPS reverse proxy | | `--port` | `int` | `8083` | Port to listen on | | `--web` | `bool` | `false` | Serve the web dashboard for real-time visualization | | `--web-port` | `int` | `8790` | Port for the web dashboard | **Subcommands** * `synheart local cleanup`: Undo the setup that local --https made **Examples** ```bash theme={null} # Start on 127.0.0.1:8083 synheart local # Use another port and open the live dashboard synheart local --port 9000 --web # Serve HTTPS on api.synheart.local synheart local --https ``` ### `synheart local cleanup` Undo the setup that local --https made Removes the "# synheart" entries that synheart local --https added to /etc/hosts. Add --remove-certs to also delete the locally generated certificates and stop trusting the local CA. Removing hosts entries may need elevated permissions. Needs no login and no network. Progress goes to stderr. **Usage** ```bash theme={null} synheart local cleanup [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--remove-certs` | `bool` | `false` | Also remove certificates and untrust the local CA | **Examples** ```bash theme={null} # Remove the hosts entries synheart local cleanup # Remove certificates and the CA trust as well synheart local cleanup --remove-certs ``` **JSON output:** not supported. This command does not print a JSON body. ## `synheart mock` Generate and replay mock wearable data Generates, records and replays mock HSI sensor data, so you can build against the Human State Interface without a wearable. Needs no login and no network. synheart mock on its own prints this help; use the subcommands to run it. For the guided mock flow, open synheart ui. **Usage** ```bash theme={null} synheart mock ``` **Subcommands** * `synheart mock describe`: Show a scenario's signals and phases * `synheart mock list-scenarios`: List the available mock scenarios * `synheart mock record`: Record mock wearable data to a file * `synheart mock replay`: Replay a recorded mock session * `synheart mock start`: Stream mock wearable data to your app **Examples** ```bash theme={null} # Stream the baseline scenario to your app synheart mock start # See which scenarios exist, then inspect one synheart mock list-scenarios synheart mock describe baseline # Record a session, then play it back synheart mock record --out session.ndjson synheart mock replay --in session.ndjson ``` ### `synheart mock describe` Show a scenario's signals and phases Prints one scenario in detail: its duration, default rate, the signals it generates with their baselines, noise and units, and its phases with any overrides. Use it to choose a scenario before you run it. Needs no login and no network. With --json it prints the same details as an object. **Usage** ```bash theme={null} synheart mock describe ``` **Aliases:** `scenario`, `scen` **Examples** ```bash theme={null} # Describe a scenario synheart mock describe baseline # As JSON synheart mock describe baseline --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart mock list-scenarios` List the available mock scenarios Lists every scenario that synheart mock start and synheart mock record can run, each with a one-line description. Use it to find a scenario name. Needs no login and no network. With --json it prints an object with an "items" array of name and description. **Usage** ```bash theme={null} synheart mock list-scenarios ``` **Aliases:** `scenarios`, `ls` **Examples** ```bash theme={null} # List scenarios synheart mock list-scenarios # As JSON synheart mock list-scenarios --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart mock record` Record mock wearable data to a file Generates sensor events for a scenario and writes them to an NDJSON file without serving them, so you can replay the same session later with synheart mock replay. Pass --seed to get the same data every time. Needs no login and no network. Scenario and vendor fall back to the mock section of .synheart/config.yaml when you do not pass them. **Usage** ```bash theme={null} synheart mock record [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--duration` | `string` | `5m` | How long to record, such as 30s or 5m | | `--out` | `string` | - | File to write the NDJSON recording to (required) | | `--rate` | `string` | `50hz` | Tick rate for the generated signals, such as 50hz | | `--scenario` | `string` | `baseline` | Scenario to record; list them with synheart mock list-scenarios | | `--seed` | `int64` | `0` | Seed for repeatable output; 0 or unset picks a random one each run | | `--vendor` | `string` | `whoop` | Vendor data format: whoop or garmin | **Examples** ```bash theme={null} # Record five minutes of the baseline scenario synheart mock record --out baseline.ndjson # Record half an hour of Garmin data, repeatably synheart mock record --out run.ndjson --scenario workout --vendor garmin --duration 30m --seed 42 ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart mock replay` Replay a recorded mock session Reads a recording made with synheart mock record (or synheart mock start --out) and serves its events over WebSocket on --port, with the original timing scaled by --speed. Use it to run the same session against your app again and again. Needs no login and no network. Press Ctrl+C to stop. Host and port fall back to the mock section of .synheart/config.yaml when you do not pass them. **Usage** ```bash theme={null} synheart mock replay [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--host` | `string` | `127.0.0.1` | Address to bind to | | `--in` | `string` | - | Recorded NDJSON file to replay (required) | | `--loop` | `bool` | `false` | Restart from the beginning when the recording ends | | `--port` | `int` | `8787` | Port to listen on | | `--speed` | `float64` | `1` | Playback speed multiplier (2 is twice as fast) | **Examples** ```bash theme={null} # Replay a recording once synheart mock replay --in workout.ndjson # Replay at double speed, forever synheart mock replay --in workout.ndjson --speed 2 --loop ``` **JSON output:** not supported. This command does not print a JSON body. ### `synheart mock start` Stream mock wearable data to your app Generates sensor events for a scenario and serves them over WebSocket (on \--port), Server-Sent Events (--port plus 1) and UDP (--port plus 2) until you press Ctrl+C or --duration ends. Connect your app's SDK to one of them. Use --vendor garmin for Garmin-format payloads (the default is whoop), --out to record the stream as NDJSON, and --web to open a live dashboard in your browser. Port, host, scenario and vendor fall back to the mock section of .synheart/config.yaml when you do not pass them. Needs no login and no network. **Usage** ```bash theme={null} synheart mock start [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--duration` | `string` | - | How long to run, such as 5m or 1h (default: the scenario's own duration) | | `--host` | `string` | `127.0.0.1` | Address to bind to | | `--out` | `string` | - | Also record events to this file | | `--port` | `int` | `8787` | Port to listen on | | `--rate` | `string` | `50hz` | Tick rate for the generated signals, such as 50hz | | `--scenario` | `string` | `baseline` | Scenario to run; list them with synheart mock list-scenarios | | `--seed` | `int64` | `0` | Seed for repeatable output; 0 or unset picks a random one each run | | `--vendor` | `string` | `whoop` | Vendor data format: whoop or garmin | | `--web` | `bool` | `false` | Serve the web dashboard for real-time visualization | | `--web-port` | `int` | `8790` | Port for the web dashboard (the SSE stream uses --port plus 1) | **Examples** ```bash theme={null} # Stream the baseline scenario on 127.0.0.1:8787 synheart mock start # Open the live dashboard as well synheart mock start --web # A stressful hour of Garmin-format data, recorded to a file synheart mock start --scenario stress_spike --vendor garmin --duration 1h --out stress.ndjson ``` **JSON output:** not supported. This command does not print a JSON body. ## `synheart receiver` Receive HSI export payloads over HTTP Starts an HTTP server that accepts HSI export payloads POSTed to /v1/hsi/import, for example from the Synheart Life app over your local network. Each payload is checked against the HSI Export Schema v1, duplicates are ignored, and the data is written to stdout or, with --out, to files. Runs until you press Ctrl+C. Senders must present a bearer token: pass --token, or let it generate one. It listens on every network interface by default; use --host 127.0.0.1 to keep it on this machine. Host, port and out fall back to the receiver section of .synheart/config.yaml. Needs no login. **Usage** ```bash theme={null} synheart receiver [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--gzip` | `bool` | `false` | Accept gzip-compressed payloads | | `--host` | `string` | `0.0.0.0` | Address to bind to; 0.0.0.0 listens on every network interface | | `--out` | `string` | - | Directory to write received payloads to (default: print to stdout) | | `--output-format` | `string` | `json` | Payload output format: json or ndjson | | `--port` | `int` | `8787` | Port to listen on | | `--token` | `string` | - | Bearer token that senders must present (default: a random token is generated) | **Examples** ```bash theme={null} # Print received payloads to stdout synheart receiver # Write NDJSON files to ./exports, with a token you choose synheart receiver --out ./exports --output-format ndjson --token mysecret # Accept gzip payloads on another port synheart receiver --port 9000 --gzip ``` **JSON output:** not supported. This command does not print a JSON body. # Tools Source: https://docs.synheart.ai/cli/reference/troubleshoot Reference for the synheart commands in the Tools group. Every command also accepts the [global flags](/cli/reference/index#global-flags). ## `synheart config` Show how the CLI resolves its settings The CLI resolves each setting in this order, highest first: ```text theme={null} 1. A command-line flag 2. An environment variable 3. The project config, .synheart/config.yaml in this directory or a parent 4. The user config, ~/.synheart/config.yaml (ui.theme, ui.mode, ui.motion, and platform.org/tenant/project as a fallback) 5. The built-in default ``` Use synheart config show to see the values resolved for the current directory and synheart config path to find the project config file in use. **Usage** ```bash theme={null} synheart config ``` **Subcommands** * `synheart config path`: Print the path of the project config file * `synheart config show`: Show the resolved project configuration **Examples** ```bash theme={null} # See the resolved settings synheart config show # Find the config file synheart config path ``` ### `synheart config path` Print the path of the project config file Prints the absolute path of the .synheart/config.yaml in effect. When none is found it prints "(none)" and exits 1, so you can use it in a shell conditional. With --json it prints "loaded" and "config\_path". **Usage** ```bash theme={null} synheart config path ``` **Examples** ```bash theme={null} # Print the path synheart config path # Use it in a script synheart config path --json || echo "no project config" ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ### `synheart config show` Show the resolved project configuration Prints the config files in effect (the project config found by searching up from the current directory, and the user config \~/.synheart/config.yaml), the appearance settings with the layer each came from (flag, env, project, user or default), and the values the project sets for mock, local, receiver and scenarios. Needs no login and no network. With --json it prints the same as an object. **Usage** ```bash theme={null} synheart config show ``` **Examples** ```bash theme={null} # Show the config for this directory synheart config show # As JSON synheart config show --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart doctor` Check your Synheart setup for problems Walks through your environment, scenario data, installed runtime, sign-in and network, and reports each step as ok, warn or error. The runtime check reads synheart.lock: vendored files must still match it, and native libraries must export the functions their variant needs. In a Flutter project it also checks that the runtime satisfies the synheart\_core version your project resolved. Doctor exits 1 only when your app cannot work: the runtime is missing or incompatible, its files are missing or modified, or a library lacks functions its variant must export. Everything else, such as a port in use, an available update or being signed out, is reported without changing the exit code. \--online also asks the registry for a newer runtime and needs you to be logged in. With --json it prints the report as an object. **Usage** ```bash theme={null} synheart doctor [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--examples` | `bool` | `false` | Also print WebSocket connection examples (JavaScript, Python, Go) | | `--host` | `string` | `127.0.0.1` | Host to bind to | | `--online` | `bool` | `false` | Also check the registry for a newer runtime release (requires login) | | `--port` | `int` | `8787` | Port to check | | `--project` | `string` | - | Project directory whose installed runtime to check (default: the project config's directory, else .) | **Examples** ```bash theme={null} # Run all checks synheart doctor # Inspect another project and also check for a newer runtime synheart doctor --project ./my-app --online # Machine-readable report synheart doctor --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart env` Show paths, account and app type Prints what support or an agent needs to know about your setup: Go version, OS and architecture, cache and config paths, the app project's lockfile and vendor directory, the detected app type (ios, android, flutter, multi or none) and app IDs, the signed-in account and plan, and the pinned runtime from synheart.lock. Needs no network; the account section appears only when you are signed in. With --json it prints the same as an object. **Usage** ```bash theme={null} synheart env [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--project-dir` | `string` | `.` | Project directory to inspect | **Examples** ```bash theme={null} # Show the environment for this directory synheart env # Another app project, as JSON synheart env --project-dir ../my-app --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart explain` Read a plain-language primer on a concept Prints a short primer on a Synheart concept, such as HSI or HRV, in your terminal. Run it with no topic to list the available topics. Needs no login and no network. With --json it prints the topic (title, summary, body, examples) as an object, or the topic list as an object with "items". **Usage** ```bash theme={null} synheart explain [topic] ``` **Examples** ```bash theme={null} # List the topics synheart explain # Read about the Human State Interface synheart explain hsi # Read about heart rate variability synheart explain hrv ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart update` Update the CLI to the latest release Checks the release manifest, and if a newer version exists, asks you to confirm and then replaces the running binary. Use --check to only report whether an update exists (exit 0 if you are current, 1 if a newer one is available), --yes to skip the prompt in scripts, and --rollback to restore the binary you had before your last update. Refuses when a package manager (Homebrew, apt, Chocolatey, go install) manages the binary; use --force to override, or update with the package manager. On Windows, re-run the installer instead. Needs network access. After other commands the CLI prints a one-line notice when an update is available. Silence it with SYNHEART\_NO\_UPDATE\_CHECK=1 or by running in CI. With \--json it prints the result as an object. synheart upgrade is an alias. **Usage** ```bash theme={null} synheart update [flags] ``` **Aliases:** `upgrade` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--apply` | `bool` | `false` | Deprecated: applying is the default now | | `--check` | `bool` | `false` | Only report whether an update exists; exit 1 if one is available, 0 if not | | `--force` | `bool` | `false` | Update even when a package manager appears to manage the binary | | `--rollback` | `bool` | `false` | Restore the previously installed binary | | `--yes` | `bool` | `false` | Skip the confirmation prompt (required without a terminal) | **Examples** ```bash theme={null} # Update, with a confirmation prompt synheart update # Update in a script synheart update --yes # Only check, for CI synheart update --check --json # Go back to the previous version synheart update --rollback ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. ## `synheart version` Show the CLI version Prints the CLI version. Add --build for the commit, build date, Go version and OS and architecture; include them when you file a bug. Needs no login and no network. With --json it always prints every field as an object. **Usage** ```bash theme={null} synheart version [flags] ``` **Flags** | Flag | Type | Default | Description | | - | - | - | - | | `--build` | `bool` | `false` | Include build details (commit, build date, Go version, OS and architecture) | **Examples** ```bash theme={null} # Print the version synheart version # Include build details synheart version --build # As JSON synheart version --json ``` **JSON output:** supported. Add `--json` (or `--format json`) to print a machine-readable body. # Install, pin and update Source: https://docs.synheart.ai/cli/workflows Sign in, install the Synheart runtime, pin it with synheart.lock, run the CLI in CI, and keep the CLI up to date. ## Sign in ```bash theme={null} synheart login # OAuth device flow in your browser synheart whoami # the signed-in account, organization and plan synheart auth status # where credentials load from, and when they expire synheart auth refresh # force a token refresh (rarely needed) synheart logout # remove local credentials (add --revoke to revoke them on the server too) ``` `synheart login` prints a URL and a code, opens your browser (unless you pass `--no-browser`) and waits while you approve it. The CLI stores your tokens in the system keychain, or in `~/.synheart/credentials.enc` when no keychain is available. Commands that call the network (`install`, `sync`, `org`, `usage`) need a session. Commands that only touch your machine (`mock`, `local`, `receiver`, `doctor`, `version`) do not. `synheart whoami`, `synheart usage` and the TUI refresh your plan and organization claims automatically when your sign-in is more than 5 minutes old, so an upgrade shows up without signing in again. `synheart auth refresh` forces a refresh if you ever need one. If a command fails with an `SH-AUTH-*` code, run `synheart auth status`. It checks the credentials file, the keyring and the token expiry, and tells you which step failed. See [Errors and environment](/cli/errors) for each code. ## Install the runtime The CLI manages the runtime artifact. You install the SDK packages themselves with your platform's package manager (pub.dev, Maven Central or Swift Package Manager). ```bash theme={null} synheart login synheart install runtime synheart sync synheart env ``` `synheart install` downloads artifacts from the Artifact Registry into your project's `synheart/vendor/` directory and records them in `synheart.lock`. The core runtime goes to `synheart/vendor/runtime/`, and every other package goes to `synheart/vendor//`. Products are `syni` and `core`. Components are `runtime` and `spec`. Give one name to install everything it covers, or two to pin one package: ```bash theme={null} synheart install syni # the Syni packages your plan includes synheart install core # the core runtime synheart install runtime # the runtime, for every product that ships it synheart install runtime syni --version v0.2.0 ``` ### Channel, version and platform ```bash theme={null} synheart install runtime --channel latest # the default synheart install runtime --version v1.2.3 # an exact version; overrides --channel synheart install runtime --platform ios # one platform only: ios or android synheart install runtime --project-dir ../my-app ``` ### Runtime variants The runtime ships in three variants: | Variant | Use | | - | - | | `edge` | The default build for most plans. | | `stable` | Locked-down builds for production. | | `lab` | Research and experimental builds. | Without `--variant`, the server picks the variant your plan includes. Pass `--variant edge|stable|lab` to ask for one. If your account is not entitled to it, the install fails with `SH-INST-FORBIDDEN`. ```bash theme={null} synheart install runtime --variant stable ``` The variant is recorded in `synheart.lock`, so `synheart sync` and `synheart runtime upgrade` stay on it. ### Inspect, upgrade or install from a local build ```bash theme={null} synheart runtime current # what synheart.lock pins; no network call synheart runtime current --json synheart runtime upgrade # latest release of the variant you are on synheart runtime install --from ../synheart-core-runtime/build/dist/core ``` `runtime current` exits 1 with `SH-RT-NOLOCK` when the project has no lockfile. `runtime install --from` copies a runtime you built yourself into `synheart/vendor/runtime/`, with no login or network. ## synheart.lock `synheart install` writes `synheart.lock` in your project. It pins the exact version, variant and artifact hashes that were resolved. Commit it. `synheart sync` reads the lockfile and installs exactly what it pins, with no new resolution: ```bash theme={null} synheart sync # restore the pinned artifacts synheart sync --project-dir ../app # an app project in another directory ``` If an artifact in the lockfile is no longer in the registry manifest, or its SHA-256 does not match, `sync` stops with `SH-INST-004` or `SH-INST-005` instead of installing something different. `synheart doctor` also checks that the vendored files still match the lockfile. A long sync re-signs download links that expire mid-run, the way `install` does, so it no longer fails with `SH-NET-003` on a stale link. ## CI/CD For repeatable builds, commit `synheart.lock` and run `synheart sync` in CI. Sign in with a CI token, because the browser flow needs a person. Create the token in the dashboard and store it as a secret. ```yaml theme={null} # .github/workflows/build.yml - run: curl -fsSL https://synheart.sh/install | bash - run: synheart login env: SYNHEART_CI_TOKEN: ${{ secrets.SYNHEART_CI_TOKEN }} - run: synheart sync # fails if the lockfile no longer matches the registry - run: synheart doctor # exits 1 if the runtime is missing, incompatible or modified - run: flutter build apk ``` Set `SYNHEART_CI_TOKEN` in the environment. Passing `--ci-token` also works, but a flag is visible in process lists and shell history. Add `synheart update --check` if you want CI to flag a new CLI release: it exits 1 when one is available. ## Start a project ```bash theme={null} synheart init # write .synheart/config.yaml and print the next steps ``` `synheart init` writes `.synheart/config.yaml` with every setting the CLI reads from it (mock, local, receiver, ui and platform) commented out at its default, detects the app the way `synheart env` does, and prints what to do next: start mock data, get connection snippets, sign in, install the runtime. It needs no account and no network. Running it again leaves the file alone and exits 0. `--force` rewrites it and keeps the old one as `config.yaml.bak`, then `config.yaml.bak.1`, `.bak.2` and so on, so a backup is never overwritten. It never writes through a symlink: a linked `.synheart`, config or backup path is refused with `SH-CFG-007`. Run it inside your app's folder: in your home directory it refuses with `SH-CFG-006`, because `~/.synheart/config.yaml` holds your personal settings. `--json` prints `{created, path, project_type, next[]}`. ## Diagnose your setup ```bash theme={null} synheart doctor # environment, scenarios, runtime, sign-in and ports synheart doctor --online # also look for a newer runtime (needs login) synheart env # paths, project type, signed-in account, pinned runtime synheart version --build # commit, build date and OS for a bug report synheart explain hsi # a plain-language primer; run it with no topic to list topics ``` `synheart doctor` reports each step as `ok`, `warn` or `error`. It exits 1 only when your app cannot work: the runtime is missing or incompatible, its files are missing or modified, or a library lacks functions its variant needs. Anything else, such as a busy port, an available update or being signed out, is reported without changing the exit code. Outside an app project, a missing `synheart.lock` is not a warning: doctor notes "Not in an app project" and suggests `cd` into your app or `synheart init`. The headline names every problem (`2 warnings not signed in, no runtime`), and the TRY list puts `synheart login` before the installs that need an account. Use `--port` to check a different port and `--project` to inspect another project. `synheart env` reads only local state. It prints the Go version, OS, cache and config paths, the lockfile and vendor directory, the project type (`ios`, `android`, `flutter`, `multi` or `none`), app IDs, the signed-in account and the pinned runtime. ## Update the CLI ```bash theme={null} synheart update # check, ask, then replace the binary synheart update --yes # skip the prompt (required to apply in scripts and agent mode) synheart update --check # report only; exit 1 if a newer version exists synheart update --rollback # restore the binary you had before the last update synheart update --force # update even when a package manager manages the binary synheart update --json # report only, unless you also pass --yes ``` `synheart upgrade` is an alias. The CLI reads the release manifest from `https://dist.synheart.ai/synheart-cli/latest/manifest.json`, downloads the archive for your platform, verifies its SHA-256 against the manifest and swaps the binary in place. It saves the previous binary to `~/.synheart/bin/synheart.prev`, which `--rollback` restores. `synheart update` refuses to run when a package manager (Homebrew, apt, Chocolatey or `go install`) manages the binary. Update with that package manager, or pass `--force`. On Windows, run the installer again. The installer scripts are also the way to recover a broken install: * macOS and Linux: `curl -fsSL https://synheart.sh/install | bash` * Windows (PowerShell): `iwr -useb https://synheart.sh/install.ps1 | iex` After other commands, the CLI prints a one-line notice on stderr when a newer version is available. It checks at most once every 24 hours. The notice does not appear with `SYNHEART_NO_UPDATE_CHECK=1`, in CI, in agent mode or with `--json`. It is also skipped for `update`, `doctor`, `mcp` and `completion`. If an update fails, you get `SH-UPD-APPLY` (the existing binary is left untouched) or `SH-NET-002` (the manifest could not be fetched). Both are safe to retry. # Implementing consent Source: https://docs.synheart.ai/guides/consent Wiring consent into your app — Synheart consent vs OS permissions, the order they must happen in, and the platform entries each type requires. Consent in a Synheart app lives on **two independent layers**. Both must be granted before the runtime ingests data; granting one does not imply the other. This page is the implementation guideline — read [Consent System](/synheart-core/consent-system) for the full reference and API surface. ## The two layers ```mermaid theme={null} flowchart LR U[User] -->|1. In-app UI| SH[Synheart consent
biosignals · phoneContext · behavior
cloudUpload · syni · vendorSync · research] U -->|2. OS prompt| OS[Device permission
HealthKit · Health Connect · BLE
Notification listener · Phone state] SH --> RT[Runtime ingest] OS --> RT RT --> APP[HSI / typed state] ``` | Layer | Issued by | Authorises | Lives in | | - | - | - | - | | **Synheart consent** | Your app, via the SDK | Whether the runtime is allowed to *process, fuse, and upload* the data your app can read | `ConsentSnapshot` in secure storage, plus a cloud-issued JWT when the consent service is configured | | **Device permission** | The operating system | Whether your app can *read* a sensor or data source at all | OS Settings → Privacy | The two layers are independent. `Synheart.hasConsent('biosignals')` returns `true` as soon as the Synheart layer is granted, even if the user denied HealthKit. The data simply never arrives — adapters silently drop on the OS side. This is by design (consent state is portable across reinstalls; OS permission state is not), but it means **you cannot use `hasConsent` to test for OS permission**. Query `SynheartWear.requestPermissions(...)` for that. ## Required order Always request in this order. The reverse works mechanically but produces worse UX and higher decline rates. 1. **Initialise the SDK.** `Synheart.initialize(...)` with a `ConsentConfig` so the runtime knows whether a cloud consent service is configured. 2. **Synheart consent.** Show your in-app consent UI, then either: * `Synheart.grantConsent(...)` — local-only (dev, tests, on-device tier). * `Synheart.consentSubmitForm(...)` — production; returns a JWT, stored automatically. 3. **OS permission(s).** Request only the OS permissions corresponding to the consent types the user just granted (see mapping below). 4. **Start the module** (for example `synheartWear.streamHR()` or a behavior `startSession()`). The runtime gates every sample on the Synheart layer; adapters gate every sample on the OS layer. ## Synheart consent types The runtime defines **seven** consent types. All default to denied. | Type | What it gates | Wire string | | - | - | - | | `biosignals` | HR, HRV, sleep, RR, wearable motion (Wear module) | `biosignals` | | `phoneContext` | Device motion, screen state, system state (Phone module) | `phone_context` | | `behavior` | Tap / scroll / swipe / typing timing (Behavior module) | `behavior` | | `cloudUpload` | HSI snapshot upload to Synheart Platform | `cloud_upload` | | `syni` | On-device LLM input (persona, conversation state) | `syni` | | `vendorSync` | RAMEN subscription to third-party vendor events | `vendor_sync` | | `research` | Lab-session JSON export | `research` | ## Mapping: Synheart consent → device permissions This is the canonical mapping, verified against the iOS, Android, and Flutter SDKs. ### `biosignals` **iOS — HealthKit + BLE.** Add to `Info.plist`: ```xml theme={null} NSHealthShareUsageDescription Synheart reads heart-rate, HRV, and sleep data to compute your HSI. NSBluetoothAlwaysUsageDescription Synheart connects to your BLE heart-rate monitor. ``` Then call `SynheartWear.requestPermissions(...)` for the `PermissionType` values you need (`heartRate`, `hrv`, `sleep`, `steps`, `calories`, `distance`). **Android — Health Connect + BLE.** Add to `AndroidManifest.xml`: ```xml theme={null} ``` You also need the Health Connect rationale intent-filter on your launcher activity and a `ViewPermissionUsageActivity` alias — see `synheart-wear-flutter`'s README for the full activity block. **Vendor cloud sources** (WHOOP, Garmin Cloud, Fitbit): OAuth flow only — no OS permission. ### `phoneContext` The Phone module collects raw accelerometer/gyroscope via `CMMotionManager` (iOS) and `SensorManager` (Android), plus screen-state and system-state via OS callbacks. * **iOS:** no `Info.plist` entry required. Raw `CMMotionManager` is permission-free on iOS — `NSMotionUsageDescription` is only needed for `CMMotionActivityManager` / `CMPedometer`, which Synheart does not use. * **Android:** no runtime permission required. Raw `SensorManager` sensors are permission-free. (Only `ACTIVITY_RECOGNITION` would be needed for the step-counter sensor, which Synheart does not use directly — step counts come from Health Connect under `biosignals`.) This is the one consent type where Synheart consent alone is enough. ### `behavior` Touch/scroll/typing timing is captured via view-tree hooks inside your app — no OS permission needed. **Notification and call-state signals are separate** and do require OS permission on each platform. **iOS:** ```swift theme={null} UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in } ``` No `Info.plist` entry; iOS surfaces the prompt via `UNUserNotificationCenter`. Call/phone signals are no-op on iOS. **Android** — add to `AndroidManifest.xml`: ```xml theme={null} ``` `BIND_NOTIFICATION_LISTENER_SERVICE` is a **special permission** — the user grants it in Settings → Notification access, not via a runtime dialog. `READ_PHONE_STATE` is a runtime permission. Tap / scroll / typing all work without either; the Behavior consent + view-tree hooks are sufficient. Notification and call signals just won't be populated until the user grants those permissions. ### `cloudUpload` Network only — no OS permission. Make sure `INTERNET` and `ACCESS_NETWORK_STATE` are in your Android manifest (most apps have these already). ### `syni` On-device LLM — no OS permission. Microphone, if you wire voice input into Syni, is your app's responsibility (`NSMicrophoneUsageDescription` on iOS, `RECORD_AUDIO` on Android). ### `vendorSync` OAuth credential for the vendor (issued by your backend, not an OS prompt). No device permission. ### `research` No additional OS permission beyond what the underlying data types already require. If your research export covers `biosignals`, you still need the HealthKit / Health Connect grants for `biosignals`. ## Minimal implementation (Flutter) ```dart theme={null} // 1. Initialise. await Synheart.initialize( config: SynheartConfig( appId: 'com.example.app', subjectId: 'anon_user_123', consentConfig: ConsentConfig( appId: 'com.example.app', deviceId: deviceId, platform: Platform.isIOS ? 'ios' : 'android', userId: 'anon_user_123', ), ), ); // 2. Synheart consent — show your in-app UI, then submit. if (!await Synheart.hasConsent('biosignals')) { await Synheart.consentSubmitForm( deviceId: deviceId, platform: Platform.isIOS ? 'ios' : 'android', formJson: consentForm, // Map, not an encoded string ); } // 3. OS permission — only after the user agreed in (2). final os = await synheartWear.requestPermissions( permissions: { PermissionType.heartRate, PermissionType.heartRateVariability, PermissionType.sleep, }, ); // 4. Start streaming. Adapters gate samples on the OS layer; the runtime // gates fusion/upload on the Synheart layer. if (os[PermissionType.heartRate] == ConsentStatus.granted) { await synheartWear.initialize(); synheartWear.streamHR().listen((metrics) { /* ... */ }); } ``` Swift and Kotlin differ: both need `initialize()` before `requestPermissions`, take no `reason`, and return a `Bool` per type. Swift's parameter is unlabeled (`requestPermissions([.heartRate, .hrv])`), and Kotlin's call doesn't show the Health Connect screen. See [Wear · Swift](/synheart-wear/swift), [Wear · Kotlin](/synheart-wear/kotlin), [Wear · Flutter](/synheart-wear/flutter). ## Handling denial and revocation | Scenario | What you see | What to do | | - | - | - | | User denies Synheart consent | `hasConsent(type) == false`; module never starts. | Show a "consent required" state. Don't request OS permission — the prompt has no value yet. | | User denies OS permission | `requestPermissions` returns `denied`; `hasConsent` is still `true`. | Show a rationale and re-request, or deep-link to OS settings. See [Wear · Errors](/synheart-wear/errors). | | User revokes Synheart consent mid-session | Streams keep firing; fields derived from revoked data drop out; HSI confidence on affected axes falls. | Observe `Synheart.consentChanges` and pause UI as needed. See [What happens mid-session](/synheart-core/consent-system#what-happens-mid-session). | | User revokes OS permission mid-session | Adapter stops receiving samples; runtime sees an empty stream. | Re-prompt the next time the feature is used. | | Cloud JWT expires | `getConsentStatus()` returns `expired`. | Call `ensureCloudConsentReady()` — handled automatically on most paths. | Local data is **not** deleted on either revocation. Call `Synheart.wipeLocalData()` if your policy requires a hard wipe. ## Common mistakes * **Treating OS permission as consent.** A user who tapped "Allow" on HealthKit has not consented to `cloudUpload`. Each is separate. * **Using `hasConsent` to test for OS permission.** It only reflects the Synheart layer. Use `requestPermissions` (Wear) or the platform's own permission API. * **Calling `grantConsent` in production.** It only mutates the local snapshot; without a JWT, `hasConsent` returns `false` whenever a consent service is configured. Use `consentSubmitForm`. * **Forgetting the Health Connect manifest plumbing on Android.** The library manifest ships empty — you must declare every `health.READ_*` permission, the rationale intent-filter, and the `ViewPermissionUsageActivity` alias yourself, or Health Connect reads silently return empty. * **Forgetting the notification listener service registration.** Behavior consent + `BIND_NOTIFICATION_LISTENER_SERVICE` are not enough on their own — you also need the `` block in your manifest, and the user must enable it in Settings → Notification access. * **Adding `NSMotionUsageDescription` "to be safe" on iOS.** It's harmless but misleading — Synheart doesn't use the activity classifier, so the string never appears in any prompt. * **Requesting OS permission before Synheart consent.** Mechanically valid; users decline at higher rates because the prompt arrives without context. ## Account deletion `Synheart.requestAccountDeletion()` overrides every consent type to denied for outbound traffic, regardless of stored state. OS permissions are untouched — that's the user's call. `cancelAccountDeletion()` lifts the override. ## Related * [Consent System](/synheart-core/consent-system) — full reference: types, tiers, channels, status, API. * [App policy](/platform/app-policy) — the per-app dashboard layer that backstops what your SDK is allowed to offer. * [Consent profiles](/platform/consent-profiles) — the per-app blueprints your SDK uses to render the consent UI. * [Capability System](/synheart-core/capability-system) — the second authority alongside consent. * [Wear · Adapters](/synheart-wear/adapters) — `PermissionType` → OS-scope mapping. * [Behavior · Threat Model](/synheart-behavior/threat-model) — the three-layer consent model for Behavior specifically. * [Troubleshooting](/guides/troubleshooting) — HealthKit / Info.plist gotchas. # FAQ Source: https://docs.synheart.ai/guides/faq Frequently asked questions about Synheart SDKs ## General ### What is Synheart? Synheart is a privacy-preserving platform for building human-state-aware applications. It includes: * **Synheart Core** — unified SDK with on-device HSI (Human State Interface) computation via the Synheart runtime engine. * **Synheart Wear** — biometric data streaming from Apple Watch, WHOOP, Garmin, BLE HRMs, and more. * **Synheart Behavior** — content-free interaction event capture (taps, scrolls, typing patterns). * **Synheart Session** — explicit time-bounded HR + behavioral sessions on phone or watch. ### What platforms are supported? * **Flutter** (Dart) * **Android** (Kotlin) * **iOS** (Swift) * **CLI**: `synheart-cli` for runtime install, mock streams, and local platform. ### Is Synheart HIPAA / GDPR compliant? Synheart SDKs are designed with privacy in mind: all inference is on-device, derived signals only leave the device with explicit consent, and users can revoke permissions and delete data. Compliance for *your* application depends on how you implement it — consult legal counsel for your specific use case. ### Is Synheart a medical device? **No.** Synheart is for wellness, productivity, and research purposes only. It is not a medical device and must not be used for medical diagnosis or treatment. ## Synheart Wear ### Which wearables are supported? See the [device matrix](/synheart-wear/overview#multi-device-support). Highlights: Apple Watch (HealthKit), Health Connect (Android), WHOOP, Garmin (cloud + native RTS — RTS requires a separate Garmin Health SDK license), BLE HRMs (Polar, Wahoo, Garmin straps). ### Do I need OAuth credentials for all wearables? No. Cloud-based vendors (WHOOP, Garmin, Fitbit, Oura) require OAuth credentials. Local sources (Apple Watch via HealthKit, Health Connect, BLE HRMs) use system permissions only. ### Can I use multiple wearables at once? Yes. The SDK supports multiple device adapters simultaneously and normalizes everything into the same `WearMetrics` shape — see the [wear data shape](/synheart-wear/data-schema) for the canonical fields. ## Integration ### Can I use a single module standalone? Yes. Wear, Behavior, and Session can each be used standalone via their package — no CLI, no platform account, no runtime needed. See [Quickstart Track B](/quickstart#track-b). ### How do I combine signals into HSI output? Use [Synheart Core](/synheart-core/overview). Core loads the Synheart runtime, accepts signals from Wear / Behavior / Phone modules, and emits HSI 1.3 JSON frames on-device. See the [Quickstart Track A](/quickstart#track-a). ### How do I handle permissions? * **iOS**: HealthKit usage descriptions in `Info.plist` and `requestAuthorization()`. * **Android**: Health Connect permissions via system settings. * **Cloud APIs**: OAuth flow per vendor (WHOOP, Garmin, Fitbit). ## Development ### Can I test without a physical wearable? Yes — `synheart mock start` streams mock Whoop/Garmin payloads over WebSocket/SSE/UDP. See [Synheart CLI reference](/cli/overview). ### Where can I find code examples? * [Quickstart](/quickstart) — both standalone and Core tracks. * Per-SDK pages under each module (Wear, Core, Behavior, Session). * [GitHub organization](https://github.com/synheart-ai). ## Privacy & Security ### Does Synheart send data to servers? Only when you explicitly enable cloud upload via Synheart Core's Cloud Connector, and only after consent has been granted. Raw biosignal content never leaves the device. ### How is data stored? * **Local storage**: AES-256 encrypted (when enabled). * **Memory**: Processed and discarded by default. * **Cloud**: HSI snapshots only, gated by user consent and capability tokens. ### Can users delete their data? Yes. Users can revoke consent (stops collection), clear app data (removes local storage), or uninstall the app. ## Performance ### Will Synheart drain my battery? Synheart is designed for low overhead in continuous background operation. Real numbers depend on device, sensor mix, and update cadence — profile your own integration with `Synheart.runtimeDiagnostics()` and platform profilers, and tune by adjusting streaming frequency and HSI window sizes. ## Support ### Where can I get help? 1. Check the relevant guide in this documentation. 2. File issues on the per-repo [GitHub trackers](https://github.com/synheart-ai). 3. Email [support@synheart.ai](mailto:support@synheart.ai). # Glossary Source: https://docs.synheart.ai/guides/glossary One-line definitions of every Synheart concept, product, and acronym you'll encounter in these docs. A quick reference for terms used throughout the docs. Follow the links for full pages. ## Products * **[Synheart Core](/synheart-core/overview)** — The on-device SDK that fuses biosignals, behavior, and phone context into a single human-state stream. Available in Flutter, Kotlin, and Swift. * **[Synheart Wear](/synheart-wear/overview)** — Standalone wearable SDK that normalizes data from Apple Watch, WHOOP, Garmin, Fitbit, Health Connect, Oura, and BLE HRMs into a single API. * **[Synheart Behavior](/synheart-behavior/overview)** — Standalone SDK for behavioral signals (taps, scrolls, typing cadence, app context). Content-free; timing and motion only. * **[Synheart Session](/synheart-session/overview)** — Standalone SDK for watch-driven session capture with pluggable biosignal and behavior providers. * **[Synheart Auth](/synheart-auth/overview)** — Hardware-backed device identity and request signing (RFC-AUTH-MOBILE-0001). * **[Syni](/syni/overview)** — On-device adaptive LLM stack: a native runtime, a versioned persona / safety spec, and language SDKs. * **[Synheart CLI](/cli/overview)** — Command-line tool for installing the runtime + spec, running a local platform mock, mocking wearable streams, and CI/CD pinning. ## Concepts * **[HSI — Human State Interface](/hsi/overview)** — The wire-format JSON contract for exchanging human-state signals. Language-agnostic; versioned (current `1.3`). * **HSV — Human State Vector** — The typed in-memory representation Synheart Core emits before packing into HSI. See [HSV specification](/synheart-core/hsv-specification). * **Flux** — The step inside the Synheart Runtime that packs `HSV[]` outputs into an HSI 1.3 envelope. * **[RAMEN](/ramen/overview)** — Real-time event delivery backplane that pushes vendor webhooks and platform events to connected clients over gRPC. * **Capability tier** — App-level access scope (`core`, `extended`, `research`). See [Capability system](/synheart-core/capability-system). * **Consent type** — User-level grant for a specific data class (`biosignals`, `behavior`, `phoneContext`, `cloudUpload`, `vendorSync`, `research`). See [Consent system](/synheart-core/consent-system). * **Persona** — A versioned behavioral contract Syni resolves at inference time (e.g. `focus.coach.v1`). Pinned via the [Syni Spec](/syni-spec/overview). ## How the pieces relate * **HSI** is the contract; **HSV** is the typed intermediate; **Flux** is the packing step. * **Capabilities** define what an app *can* request; **consents** define what the user *allows*. Data access requires **both**. * **Synheart Core** consumes Wear, Behavior, and Phone module signals and produces HSI. The standalone SDKs (Wear, Behavior, Session) can also be used independently of Core. * **Syni** consumes HSI as a conditioning input but works without it (any `Map` will do). # How it fits together Source: https://docs.synheart.ai/guides/how-it-fits-together A single mental model of Synheart — sensors, SDKs, runtime, cloud, and LLM — and which pieces are mandatory vs optional. If you're trying to figure out which pieces of Synheart your app actually needs, read this page first. Everything else in the docs assumes the shape laid out below. ## The mental model Synheart is a stack with four layers. Most apps use one or two of them; very few use all four. ```mermaid theme={null} flowchart TB subgraph S["1 · Sensors"] S1[Wearable device
Apple Watch, WHOOP, Garmin, Fitbit, BLE HRM] S2[Phone sensors
motion, screen, foreground app] S3[User interactions
tap, scroll, typing rhythm] end subgraph SDK["2 · SDKs (your app)"] SDK1[Synheart Wear] SDK2[Synheart Behavior] SDK3[Synheart Session] SDK4[Synheart Core
fuses Wear + Behavior + Phone] end subgraph RT["3 · Synheart Runtime (on-device, native)"] RT1[Feature pipeline] RT2[HSV inference
6 cognitive/physio heads + MotionState] RT3[Flux → HSI 1.3 JSON] end subgraph OUT["4 · Outputs"] APP[Your app
HSI stream / typed state] SYNI[Syni
on-device LLM
persona-conditioned] CLOUD[Synheart Cloud
ingest / RAMEN events] end S1 --> SDK1 S2 --> SDK4 S3 --> SDK2 S1 -.standalone.-> APP S3 -.standalone.-> APP SDK1 --> SDK4 SDK2 --> SDK4 SDK3 --> APP SDK4 --> RT RT --> APP APP -.optional.-> SYNI APP -.consent-gated.-> CLOUD classDef optional stroke-dasharray: 5 5 ``` The dotted arrows are optional paths. Solid arrows are the default flow for an app using Synheart Core. ## What each layer does **1. Sensors** are the data sources. You bring these — a paired wearable, the phone the app is running on, the user typing or scrolling inside your app. Synheart does not capture any of this without an SDK in your app code. **2. SDKs** are the per-language entry points that capture data. They live in your app process. Four of them ship today: * [**Synheart Wear**](/synheart-wear/overview) — normalises HR, HRV, sleep, motion from any supported wearable into one API. * [**Synheart Behavior**](/synheart-behavior/overview) — content-free interaction events (taps, scrolls, typing cadence, app context). * [**Synheart Session**](/synheart-session/overview) — watch-driven session capture with pluggable biosignal and behavior providers. Use this when the watch is computing session frames locally and streaming them to the phone. * [**Synheart Core**](/synheart-core/overview) — the fusion SDK. Consumes Wear + Behavior + phone signals and produces a single human-state stream. Each standalone SDK can be used **on its own**. You only need Core if you want fused human-state output. **3. The Synheart Runtime** is a native binary (the artifact you install with `synheart install runtime`) that does the heavy lifting: features → inference → packing into HSI. Only Synheart Core links to it. The standalone SDKs don't. See [Architecture](/synheart-core/architecture) for the full pipeline. **4. Outputs** are how data leaves the runtime: * **Your app** is always an output. The SDK exposes HSI envelopes and typed projections via reactive streams (e.g. `Synheart.onHSIUpdate` / `onStateUpdate`). * [**Syni**](/syni/overview) is the optional on-device LLM. It consumes HSI as a conditioning input on inference requests, but works without it. * **The cloud** is optional and consent-gated. With `cloudUpload` consent granted, HSI envelopes are uploaded to `api.synheart.ai` (or your enterprise gateway). [RAMEN](/ramen/overview) is the other direction: cloud → app, for real-time vendor and platform events. ## Mandatory vs optional The smallest useful Synheart app is one SDK and your code. Everything else is opt-in. | Piece | When you need it | | - | - | | One of Wear / Behavior / Session SDKs | Every app — pick the one that matches your data source. | | Synheart Core SDK | When you want fused, multimodal human-state output (HSI, the six axes). Skip if one channel is enough. | | Synheart Runtime (native) | Only when using Synheart Core. Installed via `synheart install runtime`. | | Platform account + CLI | Only when using Core (the runtime is gated). Standalone SDKs don't require either. | | Cloud upload | Only if you want HSI off-device. Pure local-only Core apps don't need it. | | Syni | Only if your app does LLM inference and wants persona contracts + HSI-conditioned prompts. | | RAMEN | Only if your app consumes real-time vendor / platform events (cross-device fan-out, vendor webhooks). | ## How the concepts relate A few terms recur across the docs. Holding these in mind makes the rest of the site easier to skim: * **HSI (Human State Interface)** — the JSON wire contract. Version `1.3` today. See [HSI overview](/hsi/overview). * **HSV (Human State Vector)** — the typed in-runtime representation. The inference engine produces `HSV[]`. * **Flux** — the runtime step that packs `HSV[]` into an HSI envelope on the wire. * **Capability tier** — what your *app* is entitled to (`core`, `extended`, `research`). * **Consent type** — what the *user* allows (`biosignals`, `behavior`, `phoneContext`, `cloudUpload`, `vendorSync`, `research`). * **Data access requires both** the capability tier and the user consent. See [Capability system](/synheart-core/capability-system) and [Consent system](/synheart-core/consent-system). A more compact list lives in the [Glossary](/guides/glossary). ## Two common paths **Path A — "I just want wearable readings."** Add `synheart_wear` (or the Kotlin / Swift equivalent). No CLI, no platform account, no runtime. Stream HR / HRV / sleep into your own code. Stop here. **Path B — "I want a focus / capacity / recovery score."** Add Synheart Core. Install the runtime (`synheart install runtime`), authenticate the CLI, ship the SDK in your app. The runtime fuses whatever modules you've enabled (Wear + Behavior + Phone) into HSI. Subscribe to `onHSIUpdate` or `onStateUpdate`. If you're not sure which path you're on, the [Quickstart](/quickstart) has a one-sentence filter at the top and side-by-side code for both. ## Where to go next > [card] [Quickstart](/quickstart) > > Pick a track and run code in 10 minutes. > [card] [Synheart Core architecture](/synheart-core/architecture) > > The runtime's internal pipeline (features → HSV → HSI) in depth. > [card] [Glossary](/guides/glossary) > > One-line definitions of every product and concept. > [card] [HSI specification](/hsi/overview) > > The wire format your app receives. # Guides Overview Source: https://docs.synheart.ai/guides/overview Comprehensive guides for using Synheart Welcome to the Synheart guides section! Here you'll find detailed walkthroughs and tutorials to help you make the most of Synheart. ## Available Guides ### Getting Started * [Quickstart](/quickstart) - Get up and running quickly * [Setup overview](/setup/overview) - Install CLI, create a platform account, authenticate, install the runtime * [Synheart CLI reference](/cli/overview) - Mock streams, local platform, runtime artifacts, receiver ### Troubleshooting * [Troubleshooting Guide](/guides/troubleshooting) - Common issues and solutions ### Reference * [FAQ](/guides/faq) - Frequently asked questions ## Need Help? If you can't find what you're looking for, feel free to: * Contact [support](mailto:support@synheart.ai) * File issues on the relevant SDK repo at [github.com/synheart-ai](https://github.com/synheart-ai) # Runtime configuration Source: https://docs.synheart.ai/guides/runtime-config Where Synheart Core Runtime reads its identity, API key, and URLs from — and how to map values issued by the Synheart Platform into your app bundle. The Synheart Core Runtime needs a small set of bootstrap values to start: who your app is (`app_id`), who issued it (`org_id`), and an API key to authenticate against the platform (`app_api_key`). All three are issued by the [Synheart Platform](https://platform.synheart.ai). This guide explains where to find them and how to thread them into the runtime. ## Required values The runtime accepts these in `SynheartConfig`. The first three come from the platform; the fourth is set per-user at runtime. | Field | Source | Notes | | - | - | - | | `app_id` | Platform — App detail page, or credentials JSON | Platform-issued identifier, e.g. `app_focus_and_kB8mPx`. Sent in every ingest call. | | `org_id` | Platform — Org switcher, or credentials JSON | Identifier of the organization that owns the app, e.g. `org_focus_kB8mPx`. | | `app_api_key` | Platform — App → **API keys** tab, **one-time creation dialog** | The **secret key**. Shown once when you create the key — not included in the credentials JSON download. Treat it like any other credential. | | `subject_id` | Your app, at runtime | The end-user identifier. **Never** bake this into `synheart.json`. Pass it via `with_subject_id(...)` (or `SynheartConfig(subjectId: ...)` on mobile) per session. | Auto-detected by the SDK (you don't set these): `device_id`, `platform`, `app_version`. Source: `synheart_config.rs:148-176`. The portal exposes **two different credentials JSON downloads**: * The **app detail page** lets you download a four-field identifiers-only file — `org_id`, `tenant_id`, `project_id`, `app_id`. No secrets: ```json theme={null} { "org_id": "org_focus_kB8mPx", "tenant_id": "ten_focus_kB8mPx_dev_a1b2c3", "project_id": "prj_focus_kB8mPx_PJI2AxsO", "app_id": "app_focus_and_kB8mPx" } ``` * The **Generate API Key** one-time success dialog offers a richer download that bundles the new key with the identifiers — adds `secret_key` (your `app_api_key`) and, when issued, `signing_secret`. This file appears once and never again — save it to your secret manager immediately. Either way, the runtime only reads `org_id`, `app_id`, and `app_api_key` (which maps from `secret_key`). `tenant_id` and `project_id` are useful for direct REST calls into the platform (ingestion, data deletion) but are not parsed into `SynheartConfig`. The `signing_secret` is **not for the SDK** — see the next section. ## Where to find them on the platform 1. Sign in at [`platform.synheart.ai`](https://platform.synheart.ai) and switch to the right organization. 2. Open the project that owns your app, then open the app. 3. On the app detail page you can download the **credentials JSON** — `org_id`, `tenant_id`, `project_id`, `app_id`. No secrets are in this file. 4. Open the **API keys** tab → **Generate API Key**. In the side panel: * **Choose App** — pick the app this key authorises (one key, one app). * **Key Type** — `Production`, `Development`, `Staging`, `Testing`, or `Other`. Used for your own bookkeeping; mint a separate key per environment so you can revoke them independently. * **Scopes** — tick at least one of `Read`, `Write`, `Delete`, `Admin`. The form blocks submission until one is selected. 5. The portal returns the **secret key** and a **signing secret** in a one-time dialog. Copy both into your secret manager before closing — they are stored hashed and cannot be recovered. The secret key is your `app_api_key`, sent on every request as the `x-api-key` header. Full walkthrough: [Platform — API keys](/platform/api-keys). Ingestion access for biosignals is gated separately by an app-level allowlist — see the [Ingestion access](/platform/api-keys#ingestion-access) section. ## Packaging into `synheart.json` The runtime reads from a `synheart.json` file baked into your app bundle. This is the recommended path on every platform. ```json theme={null} { "app_id": "app_focus_and_kB8mPx", "org_id": "org_focus_kB8mPx", "app_api_key": "sk_live_abc123..." } ``` Take the four-field credentials JSON from the portal. Server-side runtimes also add `app_api_key` from the one-time secret dialog; mobile builds must not (see the warning below). You can also keep `tenant_id` and `project_id` in the file — the runtime ignores them, but having them in one place is convenient if your backend code reads the same file. Where the runtime looks for it (in order; source: `synheart_config.rs:212-246`): 1. Explicit path passed to `SynheartConfig::from_file(Some("…/synheart.json"))`. 2. `./synheart.json` in the process's current working directory. 3. On desktop builds only: the platform data directory (`~/.synheart/synheart-core/synheart.json` and equivalents). On mobile, ship the file inside your app's resources and pass its path explicitly: ```dart theme={null} // Flutter import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; final cfg = jsonDecode( await rootBundle.loadString('assets/synheart.json'), ) as Map; await Synheart.initialize( config: SynheartConfig( appId: cfg['app_id'] as String, subjectId: currentUserId, cloudConfig: CloudConfig( subjectId: currentUserId, instanceId: stableInstallationId, orgId: cfg['org_id'] as String?, baseUrl: ApiEndpoints.resolvedCloudBaseUrl, ), deviceAuthConfig: const DeviceAuthConfig( authBaseUrl: ApiEndpoints.resolvedAuthBaseUrl, packageName: 'com.example.app', ), ), ); ``` > [!WARNING] > > The Flutter SDK has no `SynheartConfig.fromJson`; map the fields yourself as > above. Do not carry `app_api_key` into the mobile configuration — the native > runtime removed bundle-secret configuration as a security fix, so > `ConsentConfig.appApiKey` and `CloudConfig.apiKey` are deprecated and are not > forwarded to it. Mobile requests are signed with the hardware-backed device > identity configured through `deviceAuthConfig`. See the > [Flutter SDK guide](/synheart-core/flutter). ```swift theme={null} // Swift let url = Bundle.main.url(forResource: "synheart", withExtension: "json")! let json = try String(contentsOf: url) let config = SynheartConfig.fromJson(json).withSubjectId(currentUserId) try await Synheart.initialize(config: config) ``` ```kotlin theme={null} // Kotlin val json = context.assets.open("synheart.json").bufferedReader().use { it.readText() } val config = SynheartConfig.fromJson(json).copy(subjectId = currentUserId) Synheart.initialize(context = context, config = config) ``` ## Resolution order When the same field is set in multiple places, the runtime takes the highest-priority source (source: `synheart_config.rs:121-126`): 1. **Values passed directly to `SynheartConfig`** (highest priority — overrides everything). 2. **`synheart.json`** (recommended for `app_id` / `app_api_key` / `org_id`). 3. **`SYNHEART_API_URL` environment variable** (only for `api_base_url`). 4. **Compiled defaults** (lowest — `api_base_url` defaults to `https://api.synheart.ai`). This means: in development you can override `app_api_key` from a constructor argument or environment variable in your own code, while production builds read everything from `synheart.json`. The runtime itself only reads one OS env (`SYNHEART_API_URL`). ## Enterprise / self-hosted overrides For customers running their own Synheart infrastructure, every service URL can be overridden independently. Add an `enterprise` block to `synheart.json` (source: `synheart_config.rs:92-101`): ```json theme={null} { "app_id": "...", "app_api_key": "...", "org_id": "...", "enterprise": { "auth_url": "https://auth.synheart.example.com", "sync_url": "https://sync.synheart.example.com", "consent_url": "https://consent.synheart.example.com", "cloud_url": "https://cloud.synheart.example.com", "platform_url": "https://platform.synheart.example.com", "lab_url": "https://lab.synheart.example.com", "capabilities_url": "https://capabilities.synheart.example.com" } } ``` Any field left out falls back to the resolved `api_base_url`. If you only need to redirect everything to a single mirror, set `SYNHEART_API_URL=https://api.example.com` and skip the enterprise block. ## What about the signing secret? The Generate API Key dialog issues a `signing_secret` alongside the `secret_key`. **The on-device SDK doesn't use it.** There is no field for it in `SynheartConfig`, and adding one to `synheart.json` is a no-op. The two secrets target different callers (RFC dual-mode auth): | Secret | Used by | How | | - | - | - | | `secret_key` (your `app_api_key`) | Everyone | Sent on every request as the `x-api-key` header. | | `signing_secret` | Server-to-server callers only | HMAC-SHA256 over `timestamp + raw_body`, sent as `X-Synheart-Signature` (Mode B). | On device, the SDK signs ingest requests with an **ECDSA P-256 device key** that `synheart-auth` auto-registers on first launch — not with `signing_secret`. So unless your backend calls the platform REST API directly (a Postman flow, a server-side ingest pipeline, a custom integration), you can ignore the signing secret entirely. If you do need it server-side, keep it out of the mobile bundle and store it next to your other backend credentials. ## Capability tokens Capability tokens are separate from the app API key. The API key authenticates *your app* to the platform; capability tokens authorise *specific modules and channels* (focus estimation, emotion estimation, research export) for a given subject. They flow into the same `synheart.json`: ```json theme={null} { "app_id": "...", "app_api_key": "...", "org_id": "...", "capability_token": "eyJ...", "capability_secret": "..." } ``` For development you can pass `allowUnsignedCapabilities: true` instead, and the runtime will run without a signed token (with a warning). Don't ship that flag to production. See [Capability System](/synheart-core/capability-system) for the full token shape, signing model, and what each capability unlocks. ## Common mistakes * **Committing `synheart.json` to a public repo.** The `app_api_key` is a long-lived secret. Add the file to `.gitignore` and ship it via your build pipeline's secret store. * **Re-using one key across environments.** Mint a separate key per environment tag (`development`, `staging`, `production`) so you can revoke them independently. Revocation is immediate (`401` on the next request). * **Putting `subject_id` in `synheart.json`.** That file is baked into the bundle and shared across every install; the subject is per-user and must be set at runtime. * **Expecting `SYNHEART_API_URL` to override anything else.** It only resolves `api_base_url`. To override individual service URLs, use the `enterprise` block. * **Forgetting the ingestion allowlist.** A valid key still gets `403` if the app hasn't been allowlisted for biosignal ingestion. Email Synheart with the `app_id` to request access — there's no self-service flow today. * **Using `allowUnsignedCapabilities` in production.** It skips capability verification entirely. Use a signed `capability_token` instead. ## Related * [Platform — API keys](/platform/api-keys) — generating, scoping, rotating, and revoking keys. * [Platform — Developer portal](/platform/developer-portal) — org / project / app setup. * [Capability System](/synheart-core/capability-system) — what `capability_token` authorises. * [Implementing consent](/guides/consent) — the other thing your app needs before the runtime ingests data. * [Install the runtime](/setup/install-runtime) — getting the SDK into your project. # Testing without hardware Source: https://docs.synheart.ai/guides/testing Mock wearable streams, a local Synheart cloud, deterministic recordings, and CI patterns. You don't need a real watch, a real platform account, or a real network connection to develop and test Synheart integrations. The CLI ships three building blocks that cover almost every test scenario: * **`synheart mock`** — emits a vendor-shaped biosignal stream to your SDK. * **`synheart local`** — runs a local mirror of the consent + ingest cloud endpoints. * **`synheart sync`** — restores the exact runtime / spec versions pinned in `synheart.lock` across machines and CI. Pick the smallest combination that unblocks your test. You rarely need all three. ## Mock wearable streams `synheart mock` produces deterministic vendor-shaped streams that your SDK consumes as if they came from a real device. Useful for unit tests, UI demos, and reproducing user reports. ```bash theme={null} synheart mock start # default: whoop / baseline scenario synheart mock start --vendor garmin --scenario workout synheart mock start --rate 100hz --duration 5m synheart mock start --seed 42 # deterministic output for tests ``` Default endpoints — listen with whichever transport your SDK uses: * WebSocket: `ws://127.0.0.1:8787` * SSE: `http://127.0.0.1:8788/events` * UDP: `127.0.0.1:8789` All three carry the same payload, so your tests don't have to know which is configured. ### Deterministic record + replay For regression tests, capture a mock stream once and replay it on every run: ```bash theme={null} synheart mock record --vendor whoop --duration 15m --out fixtures/session.ndjson synheart mock replay --in fixtures/session.ndjson --speed 2.0 --loop ``` Commit the `.ndjson` file alongside your tests. Replay accepts the same transport flags as `start`, so the SDK code under test doesn't change. ### Choosing a scenario A scenario is a named time-series profile (`baseline`, `workout`, `recovery_high`, `stress_event`, …). List and inspect them: ```bash theme={null} synheart mock list-scenarios # all vendors synheart mock list-scenarios --vendor whoop synheart mock describe baseline # signal envelope + expected event mix ``` Pick the scenario whose envelope matches the path you're testing — `stress_event` for high-arousal HSI states, `recovery_high` for low-strain outputs, etc. ## Local platform server `synheart local` mirrors the cloud's consent + ingest endpoints on `127.0.0.1`. Use it when you need the full cloud flow — uploads, consent tokens, JWT validation — without burning real platform quota or needing network. ```bash theme={null} synheart local # plain HTTP on :8083 synheart local --port 9000 --api-key my-key # custom credentials synheart local --https # TLS + /etc/hosts entry synheart local --https --domain api.synheart.example synheart local --web --web-port 8090 # status dashboard synheart local cleanup --remove-certs # reverse the OS changes ``` In your app config, point the SDK at the local server's base URL the same way you'd point it at production. The endpoint shapes and auth contract are identical. The `--https` mode generates a local CA, trusts it in the OS keychain, and adds a `127.0.0.1 ` entry to `/etc/hosts` — so your SDK hits `https://api.synheart.example` exactly as it would the production host. Run `synheart local cleanup --remove-certs` when you're done to reverse those OS changes. The `--web` flag runs a small status dashboard on a separate port showing connected SDK clients, queued ingests, and recent consent grants. Useful for debugging "did my upload arrive?" questions. ## Combining the two The common end-to-end shape: ```bash theme={null} synheart mock start & # 1. fake biosignals into your SDK synheart local --web & # 2. fake cloud accepting uploads # 3. run your app or test suite pointed at both ``` Your app sees a vendor-shaped stream coming in and a working cloud accepting HSI uploads, with no real device or network involved. ## CI / CD patterns For deterministic builds, install the runtime once locally, commit the lockfile, then `sync` in CI: ```yaml theme={null} # .github/workflows/build.yml - run: curl -fsSL https://synheart.sh/install | bash - run: synheart login env: SYNHEART_CI_TOKEN: ${{ secrets.SYNHEART_CI_TOKEN }} - run: synheart sync # installs exactly what synheart.lock pins - run: flutter build apk ``` Set `SYNHEART_CI_TOKEN` to sign in non-interactively with a CI service-account token. Tokens are scoped per project and per environment; rotate them via the platform dashboard. `synheart sync` is the most important line: it installs exactly what your committed `synheart.lock` pins, and stops with an error if an artifact no longer matches the registry. That catches silent runtime drift before it ships. See [Install, pin and update](/cli/workflows). ### Running mock + local in CI For integration tests that exercise the full SDK path: ```yaml theme={null} - run: synheart mock start --seed 42 --duration 10m & - run: synheart local --port 8083 & - run: ./run-integration-tests.sh ``` Use `--seed` so test runs are reproducible across machines. ## When you do need real hardware A few things only a real device can validate: * BLE pairing and reconnection edge cases (mocks don't simulate radio). * HealthKit / Health Connect permission prompts as the user sees them. * Watch ↔ phone session handoff timing and battery impact. * Vendor-specific OAuth flows end-to-end (mock simulates the data, not the OAuth dance). Everything else — signal processing, HSI envelope shape, consent gating, capability gating, error paths — is testable without hardware. ## Where to go next > [card] [Synheart CLI reference](/cli/overview) > > Full reference for `mock`, `local`, `sync`, and related commands. > [card] [Quickstart](/quickstart) > > The shortest path from zero to a running integration. # Troubleshooting Source: https://docs.synheart.ai/guides/troubleshooting Common issues and fixes, grouped by where you're hitting them. Jump straight to your section: * [CLI / install](#cli--install) — `synheart` command not found, login fails, install errors. * [Wearable data](#wearable-data) — permissions, missing data, OAuth, schema mismatches. * [Platform-specific build issues](#platform-specific-build-issues) — Flutter / Android / iOS toolchain. * [Performance](#performance) — high CPU, battery drain, thread-safety errors. * [Still stuck?](#still-stuck) — where to ask. ## CLI / install ### `synheart` command not found After installing the CLI, the binary may not be on your `PATH`. ```bash theme={null} synheart version command -v synheart ``` If the second command prints nothing, add the install directory to your shell's `PATH`. See [Install the CLI](/setup/install-cli) for the per-shell snippet. ### `synheart login` device flow doesn't complete * Open the URL the CLI prints in a browser; if it 404s, your CLI is talking to the wrong gateway — check `SYNHEART_API_URL`. * Confirm you have a [platform account](/setup/create-account). * Run `synheart whoami` after authorising to confirm the token is cached. ### Install commands fail with "login required" `install` and `sync` need a valid access token. If you're getting kicked back to login repeatedly: ```bash theme={null} synheart logout synheart login ``` If that doesn't fix it, your token may have expired — the relogin should issue a fresh one. ## Wearable data ### Permission denied accessing health data * **iOS** — verify `Info.plist` has `NSHealthShareUsageDescription` and HealthKit is enabled in your Xcode capabilities. * **Android** — Health Connect permissions must be granted in system settings, and the app must call `requestPermissions()` before requesting data. * Confirm the user actually granted access through your prompt (don't assume a stale permission state). ### SDK initializes but no data arrives * The wearable hasn't synced recently — open its vendor app and force a sync. * For cloud-backed vendors (WHOOP, Garmin, Fitbit, Oura), the OAuth token may have expired — re-auth. * For BLE HRMs, confirm Bluetooth is on and the device is in range and broadcasting. * For Health Connect on Android \< 14, the Health Connect app must be installed via the Play Store. The adapter returns an empty snapshot rather than throwing in this case — on Kotlin, check `HealthConnectAdapter(context).getAvailabilityStatus()`. ### OAuth flow fails * Verify OAuth credentials in `.env.local` or your config file. * The redirect URI must match what's registered in the vendor's dashboard exactly (including trailing slashes). * For local development against a vendor that requires a public redirect URI, run a tunnel (e.g. ngrok) and use its HTTPS URL as the redirect. This is dev-only — never use a tunnel URL in production. * Clear browser cookies for the vendor's auth host and try again. * Check the vendor's API status page for outages. ### Data shape doesn't match what your code expects * Confirm the SDK version matches the adapter version (mismatches can change the normalised schema). * Pin both with `synheart.lock` and run `synheart sync` in CI so drift fails the build. * The wire format is HSI 1.3 — see [HSI overview](/hsi/overview) for the canonical envelope. ## Platform-specific build issues ### Flutter ```bash theme={null} flutter clean flutter pub get cd ios && pod install # iOS only ``` If iOS permissions still don't work after a clean build, double-check: * `Info.plist` entries (`NSHealthShareUsageDescription`, etc.) are present. * HealthKit capability is enabled in your Xcode target. * The app is signed with a provisioning profile that allows HealthKit. Synheart Wear's Flutter bindings also require `MainActivity` to extend `FlutterFragmentActivity` (not `FlutterActivity`) on Android 14+. ### Android / Kotlin * **Health Connect unavailable** — the Health Connect app must be installed (built-in on Android 14+, otherwise via Play Store). Verify Android API ≥ 21. * **Gradle resolution errors** — the SDKs are on Maven Central (`ai.synheart:synheart-wear`, `ai.synheart:synheart-core`, …): make sure `mavenCentral()` is in your repositories, check the version exists on Maven Central, then `./gradlew clean`. ### iOS / Swift * **Swift Package Manager can't resolve** — verify the package URL, confirm the deployment target meets the SDK's minimum (iOS 13+ for Core / Wear / Session / Behavior; the Flutter `synheart_wear` plugin needs iOS 16+), then clear the SPM cache: `rm -rf ~/Library/Developer/Xcode/DerivedData`. * **HealthKit permissions denied** — confirm `Info.plist` usage descriptions, HealthKit capability is enabled, and that you haven't previously denied permission in Settings → Privacy → Health → \[Your App]. ## Performance ### High CPU usage The runtime is designed for low overhead; if you're seeing CPU spikes, the most common causes are: * **Streaming frequency too high** — drop your push rate or use a longer aggregation window. * **Foreground inference on the UI thread** — make sure SDK calls aren't blocking the UI; use background isolates / coroutines / queues. * **Profile first** — `Synheart.runtimeDiagnostics()` exposes live counters so you can see which seam is hot. ### Battery drain * Reduce streaming frequency and use larger aggregation windows. * Handle backgrounding correctly — pause non-essential streams when the app isn't foregrounded. * Batch processing where possible instead of per-sample work. ### Thread-safety crashes * Per-handle thread-safety is guaranteed for the runtime — concurrent calls on the same handle are serialised internally. Concurrent calls on *different* handles run in parallel. * App-side: keep SDK calls on a single context (main isolate / main thread / a dedicated queue). Don't share a single SDK instance across multiple un-synchronised threads. * Make sure you're disposing engines / sessions cleanly on app teardown. ## Still stuck? 1. Re-read the relevant SDK guide — the symptoms above cover the common cases, but specific errors may be documented in the per-SDK page. 2. Search existing issues on [github.com/synheart-ai](https://github.com/synheart-ai). 3. Open a discussion or issue against the relevant per-language SDK repo under [github.com/synheart-ai](https://github.com/synheart-ai). 4. Contact [support@synheart.ai](mailto:support@synheart.ai). When filing an issue, include: SDK version, platform + OS version, device model, the error code (if any — they look like `SH-WEAR-...`), and the minimum reproduction. # Human State Interface (HSI) Source: https://docs.synheart.ai/hsi/overview A contract-only, language-agnostic JSON payload for exchanging human-state signals (HSI 1.3) > [!NOTE] > > HSI is at version **1.3**. This page is a high-level orientation. The canonical schemas, RFCs, and validator live in the [hsi repository](https://github.com/synheart-ai/hsi): > > * **Payload structure.** > * **Canonicalization, content hashing, signatures** (`HSI-VALIDATE-INTEGRITY`). > * **Canonical 5-axis domain set** (`physiological / kinematic / digital / cognitive / affective`). > * **Multimodal attribution** (`modalities_used`, `confidence_breakdown`). > > Producers and consumers dispatch on `hsi_version` and validate against the schema for the declared version. **Human State Interface (HSI)** is a **language-agnostic, contract-only** specification for exchanging **human-state signals** between independent systems (producers and consumers). HSI defines a canonical **JSON payload**, explicit **time windows**, normalized **scores + confidence**, an authoritative **JSON Schema**, and **versioning rules** so teams can interoperate without sharing implementation details. > **HSI is a data contract.** It does not specify models, sensor pipelines, SDKs, or device assumptions. ## What HSI is (and is not) * **HSI is**: a stable, versioned payload contract; a schema you can validate against; and a compatibility policy for evolution. * **HSI is not**: an SDK, an inference model, a sensor pipeline, or a device specification. ## Top-level structure (HSI 1.3) An HSI 1.3 payload is a single JSON object. Required top-level fields: * **`hsi_version`** — `"1.3"`. * **`observed_at_utc`** — RFC 3339 timestamp (event-time; typically aligns with the latest window's `end_utc`). * **`computed_at_utc`** — RFC 3339 timestamp (processing-time; must be `≥ observed_at_utc`). * **`producer`** — identity of the producing system (non-PII). * **`windows`** — map of window IDs to window descriptors (each requires `start_utc` and `end_utc`). * **`privacy`** — privacy assertions; `contains_pii` MUST be `false`, plus required `raw_biosignals_allowed` and `derived_metrics_allowed`. Optional top-level fields: * **`axes`** — human-state axis readings grouped by domain (see canonical 5-axis set below). * **`embeddings`** — window-scoped latent vectors (sensitive; `vector` or `vector_hash`). * **`integrity`** — canonicalization + content hash + signature block. * **`meta`** — non-normative metadata, including `meta.provenance` (sources, providers, engine identifiers, equation IDs, SRM snapshot IDs). ## Canonical 5-axis domain set In HSI 1.3, the `axes` object is closed (`additionalProperties: false`) and permits exactly these five domains: | Domain | What it carries | | - | - | | **`physiological`** | Cardiovascular, autonomic, sleep, recovery, and similar biosignals. | | **`kinematic`** | Motion, posture, activity-state classification. | | **`digital`** | Interaction-derived signals (taps, scrolls, typing rhythm, app context). | | **`cognitive`** | Focus, attention, capacity, fatigue. | | **`affective`** | Valence, arousal, emotional state. | Consumers MUST tolerate **unknown axis names** (`name` values) within a known domain, but MUST reject **unknown domains** under strict validation. ## Axis readings (HSI 1.3) Each axis reading is an object with these required fields: * **`name`** — `lower_snake_case` (e.g. `arousal`, `task_persistence`, `hr_rmssd`). * **`score`** — number in `[0, 1]` (or label, see `direction: categorical`). * **`confidence`** — number in `[0, 1]`. * **`direction`** — one of `higher_is_more`, `lower_is_more`, `bidirectional`, `categorical`. * **`window_ids`** — array of window IDs this reading covers. * **`evidence_source_ids`** — array of source IDs declared under `meta.provenance.sources`. * **`inference_mode`** — describes how the score was produced (e.g. `model`, `heuristic`, `pass_through`). * **`model_id`** — identifier of the model or rulepack used. Optional fields include `unit`, `notes` (no PII), `modalities_used`, `confidence_breakdown` (per-channel attribution), and for `direction: categorical`, `label` and `categories`. ## Example payload A minimal but complete HSI 1.3 envelope with one window and one axis reading: ```json theme={null} { "hsi_version": "1.3", "observed_at_utc": "2026-01-15T10:30:00Z", "computed_at_utc": "2026-01-15T10:30:00.420Z", "producer": { "name": "synheart-runtime", "version": "5.4.0", "instance_id": "device_3f1c8b" }, "windows": { "w_micro_30s": { "start_utc": "2026-01-15T10:29:30Z", "end_utc": "2026-01-15T10:30:00Z", "duration_seconds": 30 } }, "axes": { "cognitive": [ { "name": "focus", "score": 0.72, "confidence": 0.81, "direction": "higher_is_more", "window_ids": ["w_micro_30s"], "evidence_source_ids": ["wear_hrv", "behavior_taps"], "inference_mode": "model", "model_id": "focus.v1", "modalities_used": ["physiological", "digital"] } ] }, "privacy": { "contains_pii": false, "raw_biosignals_allowed": false, "derived_metrics_allowed": true }, "meta": { "provenance": { "sources": [ { "id": "wear_hrv", "kind": "wearable", "vendor": "apple_watch" }, { "id": "behavior_taps", "kind": "behavior", "vendor": "synheart_behavior" } ] } } } ``` The same envelope shape carries any combination of axes across the five canonical domains; consumers MUST validate against the schema for the declared `hsi_version`. ## Privacy block Every payload MUST include `privacy` with at minimum: * `contains_pii: false` * `raw_biosignals_allowed: ` * `derived_metrics_allowed: ` If a producer cannot guarantee `contains_pii=false`, it MUST NOT emit HSI payloads. ## Validation tiers HSI defines three validator levels: * **HSI-VALIDATE-BASIC** — Draft 2020-12 schema validation (structure + ranges). * **HSI-VALIDATE-STRICT** — basic plus cross-field integrity (timestamp ordering, declared-window references, source-id references, embedding dimension equals vector length when present). * **HSI-VALIDATE-INTEGRITY** — strict plus canonicalization + `content_hash` + `signature` verification on the optional `integrity` block. ## Versioning policy HSI uses Semantic Versioning as `MAJOR.MINOR` (patch is unused for payload compatibility). * **Major**: breaking changes. Consumers supporting `1.x` MUST reject `2.0+` unless explicitly updated. * **Minor**: backward-compatible additions/clarifications within the same major. * **Unknown top-level fields** MUST be rejected under strict validation (`additionalProperties: false`). * **Unknown axes** (new `name` values) MUST be tolerated. ## Synheart Core implementation If you're using Synheart's SDK, the HSI contract is implemented by the Synheart runtime and surfaced through Synheart Core: * [HSI in Synheart Core](/synheart-core/hsi-specification) * [HSV Specification](/synheart-core/hsv-specification) — typed intermediate representation that flux packs into HSI payloads. *** **Canonical HSI version:** 1.3. See the [hsi repo](https://github.com/synheart-ai/hsi) for schemas and RFCs HSI-0008 / HSI-0009 / HSI-0010 / HSI-0011. # Introduction Source: https://docs.synheart.ai/introduction Privacy-preserving, human-state-aware AI from biosignals, behavior, and context Meet the next generation of human-state intelligence. AI-native, privacy-first, and built for developers building the future of wellness and mental health. New here? [How it fits together](/guides/how-it-fits-together) is a one-page mental model of the stack — sensors, SDKs, runtime, cloud — and which pieces are mandatory versus optional. Read it before the Quickstart if you're not sure which SDK to pick. > [card] [Quickstart](/quickstart) > > Deploy your first Synheart integration in minutes with our step-by-step guide. > [card] [Synheart Core](/synheart-core/overview) > > Unified SDK for human-state intelligence — single integration point for all Synheart features. > [card] [Synheart Wear](/synheart-wear/overview) > > Stream biometric data from multiple wearables with a unified API across all platforms. > [card] [Synheart Behavior](/synheart-behavior/overview) > > Capture interaction patterns (tap, scroll, type, motion) on-device — no content, no PII. # Lab Mode overview Source: https://docs.synheart.ai/lab/overview Research surface for recording structured experiment data alongside the live HSI loop **Lab Mode** is a Synheart Core surface for recording structured experiment data alongside the live HSI measurement loop. Use it when you're running a study where the protocol — baselines, intervention windows, recovery — needs to be captured as first-class structure on top of the normal sample stream. Lab Mode is **research-tier**. Cloud upload of lab sessions requires the `research` consent type and a capability token whose `hsi` tier is at least `research`. Without those, lab sessions stay on-device. ## What it gives you * A **session** scoped to one protocol (e.g. "morning baseline + 5-min stressor"). * A tree of **windows** inside the session (e.g. baseline → stressor → recovery), each with a type, label, and free-form values. * **Window-level overrides** for state values (used when the experimenter wants to assert a known ground truth for a slice of time). * **Metadata cache** for the device + user info that should accompany every session export. The live engine continues running normally — sample push and HSI emission are not paused by lab calls. ## Public API surface (Synheart Core) ```dart theme={null} // Start a session under a protocol. final ok = await Synheart.labStart( protocolJson: jsonEncode(protocol), startedAtMs: DateTime.now().millisecondsSinceEpoch, ); // Open a window. Returns the window_id; nest by passing parentId. final baselineId = await Synheart.labOpenWindow( windowType: 'baseline', label: 'pre-task', startedAtMs: now(), ); // Close a window. await Synheart.labCloseWindow(windowId: baselineId, endedAtMs: now()); // Annotate the window with values (any JSON object). await Synheart.labSetWindowValues( windowId: baselineId, valuesJson: jsonEncode({'mood': 5, 'caffeinated': true}), ); // Finalize the session — returns the session JSON and (with research // consent + cloud config) enqueues a lab session export upload. final sessionJson = await Synheart.labFinalize(endedAtMs: now()); ``` Kotlin and Swift expose the same surface with idiomatic naming. ## Metadata cache ```dart theme={null} // Compute metadata once at app start, re-upload when it changes. final metaId = await Synheart.labEnsureMetadata( deviceId: deviceId, platform: 'ios', osVersion: osVersion, userInfoJson: jsonEncode(userInfo), deviceExtraJson: null, ); // Force a re-upload (e.g. after the user updates their profile). await Synheart.labMarkMetadataDirty(reason: 'profile-edit'); ``` The runtime stamps the active `meta_id` into every finalized session's `session_metadata.extra_data.metadata_id`, so server-side analysis can group sessions by the device/user state at the time they were recorded. ## Availability Lab is gated by a capability flag in the runtime artifact. Hosts should call `Synheart.isLabAvailable()` before assuming the surface is present: ```dart theme={null} if (await Synheart.isLabAvailable()) { // safe to call labStart, labOpenWindow, etc. } ``` When the runtime is built without the `lab` feature, every `lab*` method returns a "not available" sentinel (false / null) and never throws. ## Cloud upload path When `cloudConfig.lab = true` AND `research` consent is granted, `labFinalize` enqueues an upload to `/ingest/v1/lab/session`. The upload is **separate from** the standard HSI ingest path (`/ingest/v1/hsi`) so research data is routed and retained under research-tier policies. > [!NOTE] > > **Per-record size limit: 1 MB.** A lab record larger than 1 MB is rejected. For batch uploads the limit applies per session — if any single session exceeds it, the whole batch is rejected. Keep window values and metadata compact. See [Cloud Protocol](/synheart-core/cloud-protocol) for the full ingest surface and [Consent System](/synheart-core/consent-system) for the `research` consent flow. ## When to use Lab Mode * You're running an academic study and need protocol structure alongside the live state stream. * You're A/B testing interventions and need windowed ground truth. * You want to attach experimenter-supplied values (mood scores, intervention IDs, custom labels) to slices of time. If you only need to flag interesting moments in a normal recording, prefer regular HSI snapshots with custom metadata. # Account & security Source: https://docs.synheart.ai/platform/account Manage your Synheart Platform profile, password, two-factor authentication, and pending invitations The **Profile** page manages your personal account: your display name, password and two-factor authentication, and any organization invitations addressed to you. It's separate from [organization settings](/platform/organizations-and-tenants#organization-settings), which configure the company account. Open it from the sidebar **Admin** section: **Profile**. The page heading is **Account settings** with the subtitle *"Manage your profile, security preferences, and organization invitations."* Two summary cards show your account **Status** (Active) and **Member since** year. The page has two tabs: **Account** and **Invitations**. *** ## Profile The **Profile** section shows your sign-in identity. Your **Email** is read-only; sign-in email cannot be changed from this page. Your **Display name** controls how your name appears across the dashboard; click **Edit**, make your change, then **Save changes**. If your email is unverified you'll see *"Your email is not verified yet. Check your inbox for the verification link."* *** ## Security The **Security** section manages password sign-in and two-factor authentication (TOTP). ### Set a password If you signed up with Google or GitHub and have no password yet, you can add one to enable email sign-in. Enter a **New password (min. 8 characters)**, **Confirm password**, and click **Save password**. On success: *"Password saved. You can sign in with your email and this password."* > [!NOTE] > > The Profile page lets OAuth-only accounts **set** a password. There is no in-page "change password" form once a password exists. Use the password reset flow if you need to change an existing password. ### Two-factor authentication (TOTP) Two-factor authentication adds an authenticator-app code at sign-in. The card shows an **On**/**Off** badge. **1. Enable** Click **Enable** to open **Set up authenticator**. Scan the QR code with an authenticator app (Google Authenticator, Authy, etc.), or enter the **Secret key (manual entry)** shown. **2. Verify** Enter the 6-digit **Verification code** from your app and click **Confirm**. **3. Save recovery codes** On the **Save your recovery codes** screen, store the codes somewhere safe, as they won't be shown again. Use **Copy all**, **Download .txt**, or **Print / save PDF**, then confirm *"I have saved my recovery codes in a secure place"* and click **Continue**. > [!WARNING] > > Recovery codes are shown **once**. Save them before continuing; they're your fallback if you lose access to your authenticator app. To turn MFA off, click **Disable**, enter your account **Password** and a current **Authenticator code**, and confirm. *"This will sign you out everywhere."* > [!NOTE] > > You must have a password set before you can disable MFA (the **Disable** button is disabled otherwise, with the hint *"Set a password first to disable MFA"*). *** ## Invitations The **Invitations** tab lists organization invitations addressed to your account, with columns for the organization **Title**, who **Invited** you, the **Role**, **Members**, **Invite date**, **Projects**, and an **Action**. * **Accept**: joins the organization. * **Decline**: *"Are you sure you want to decline this invitation? This action cannot be undone."* When you have none: *"You have no pending invitations."* For the full invitation flow across scopes, see [Members & roles → Accept an invitation](/platform/members-and-roles#accept-an-invitation). *** ## Next > [card] [Members & roles](/platform/members-and-roles) > > Understand roles and how invitations work across orgs, tenants, and projects. > [card] [Organizations & tenants](/platform/organizations-and-tenants) > > Manage the workspaces you belong to. > [card] [Developer portal](/platform/developer-portal) > > Sign in, register apps, and request access for your integration. # API keys Source: https://docs.synheart.ai/platform/api-keys Generate, scope, rotate, and revoke API keys for the Synheart Platform API keys authorize calls into the Synheart Platform from the Synheart SDKs and your backend code. Keys are issued per-app, owned by an organization, and managed from the developer portal at [`platform.synheart.ai`](https://platform.synheart.ai). > [!NOTE] > > The CLI uses OAuth Device Flow, not API keys, for `synheart login`. Generate an API key only when you need server-to-server or SDK-to-platform access. See [Authenticate the CLI](/setup/authenticate). ## What a key carries Each key the portal issues is bound to: * An **organization** (selected from the org switcher). * An **app** inside a [project](/platform/projects); keys are minted at the app level, so one key can't speak for multiple apps. * A **label** you supply (free-form, used to identify the key in the list). * One or more **scopes** that name the services the key may call (see [Scopes](#scopes)). * An **environment tag** for your own bookkeeping: `production`, `development`, `staging`, `testing`, or `other`. ## Scopes Scopes use a `resource:action` format. A key can call only the services its scopes name; anything else is rejected. | Scope | Portal label | Grants | | - | - | - | | `synheart:all` | Full access | Every scope below. Prefer narrower scopes unless the key is for an admin backend. | | `ingest:write` | Ingest data | HSI and lab uploads to the ingestion service. Required for SDK data upload. | | `inference:read` | Syni cloud | Syni chat, tools, sessions, devices, channels, scheduler, and models. | | `ramen:read` | Live wearable events | Subscribe to and replay the real-time event stream. | | `hsi:read` | HSI analytics | Tenant, project, and app analytics reads. | | `consent:read` | Consent profile (SDK) | Read the app's consent profile from the SDK. | | `consent:write` | Consent tokens (SDK) | Mint and revoke consent tokens. | | `wear:read` | Wearable data read | Read WHOOP and Garmin data. | | `wear:write` | Wearable connect | Connect and disconnect wearables, and run backfills. | | `sync:write` | Encrypted sync | Push, pull, and attach encrypted sync data. | ## Generate a key 1. Open the developer portal and switch to the organization, tenant, and project that own the app. 2. Open the app's **API keys** tab and choose **Generate API Key**. 3. In the side panel, set: * **Choose App**: the key is bound to one app. * **Key Type**: `Production`, `Development`, `Staging`, `Testing`, or `Other`. * **Scopes**: tick at least one scope from the table below. The form blocks submission until one is selected. 4. The portal returns a **secret key** and a **signing secret** in a one-time dialog. Both are shown only once and stored hashed; copy them immediately into a secret manager. The dialog also offers a **Download credentials JSON** button that bundles the new secrets together with the identifiers: `org_id`, `tenant_id`, `project_id`, `app_id`, `secret_key`, and (when present) `signing_secret`. Save it to your secret manager; it never appears again. The app detail page exposes a separate **credentials JSON** download that contains only the four identifiers (no secrets). Use that one for non-sensitive contexts (CI lookups, support tickets) and the one above for SDK / backend wiring. Use the secret key as `app_api_key` when configuring the runtime; see [Runtime configuration](/guides/runtime-config). The two secrets serve different callers: * **`secret_key`** authenticates every request via the `x-api-key` header. The on-device SDK uses this. * **`signing_secret`** is for server-to-server callers that sign ingest requests directly from your own backend. The on-device SDK does **not** use this; it handles signing automatically. Only configure `signing_secret` if your backend bypasses the SDK and calls the platform REST API directly (e.g. from a server-side ingest pipeline). ## Ingestion access Reading data and pushing biosignals share the same key surface, but **biosignal ingestion is gated by an app-level allowlist** maintained by Synheart. Keys for apps that aren't on the list are rejected at ingestion time with the message *"App `` is not verified for data ingestion."* If you need ingestion access, contact Synheart with the platform `app_id` shown on the App in the dashboard; there's no self-service request flow today. ## Rotate There's no automatic rotation. To rotate: 1. Generate a new key with the same scopes and environment. 2. Roll both the secret key and signing secret out to your callers. 3. Revoke the old key. ## Revoke Revoke unused keys from the API keys list. Revocation is immediate; subsequent requests with the revoked key fail with `401`. Revoked keys stay visible in the list (toggle **Include revoked**) for audit. ## Errors | Status | Meaning | | - | - | | `401` | Missing, malformed, or revoked key. Re-check that the `x-api-key` header is set and the key isn't revoked. | | `403` | Key is valid but not authorized: either the app isn't allowlisted for ingestion, or the request body's `app_id` doesn't match the key's app. | | `429` | Rate limit exceeded. Back off and retry. | ## Next > [card] [Projects](/platform/projects) > > Organize the apps your keys point at into projects. # App attestation Source: https://docs.synheart.ai/platform/app-attestation Verify that traffic comes from your real, unmodified app on a normal device, using Play Integrity (Android) and App Attest (iOS) App attestation lets Synheart confirm that traffic comes from your real, unmodified build on a normal device, not from emulators, repackaged binaries, or scripted clients. The platform supports: * **Android**: [Google Play Integrity API](https://developer.android.com/google/play/integrity/overview) * **iOS**: [Apple App Attest](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity) Both platforms follow the same client flow: the SDK requests a one-time challenge, asks the OS for an attestation over that challenge, and registers the attested device with Synheart. You configure each App in the [platform dashboard](https://platform.synheart.ai/) once; the SDKs handle the runtime path. > [!NOTE] > > The Synheart `app_id` (shown on the App in the [platform dashboard](https://platform.synheart.ai/)) is the platform's identifier for that App record: a short code like `app_focus_and_kB8mPx`. Your Android `packageName` and iOS bundle ID are separate values you also configure on the App. Don't conflate them: Play Console steps below refer to your Play listing's `packageName`, not the platform `app_id`. ## How Android attestation works at Synheart Google Play Integrity's `decodeIntegrityToken` is authorized per Google Cloud project: only callers that can act as your Cloud project may decode tokens minted for your `packageName`. You supply that authorization by creating a dedicated service account in your own Cloud project and uploading its JSON key to your App's settings page. Synheart stores the key encrypted at rest and uses it server-side only to call `decodeIntegrityToken` for your `packageName`. This means: * The credential authorizes one specific operation against one specific package. * Decode calls bill against your Cloud project's quota. * If you rotate or revoke the key in Cloud Console, decode access stops immediately. No Synheart-side action needed. * iOS attestation needs no equivalent credential: App Attest verifies against Apple's global public CA chain. ## Configure attestation in the dashboard For each App in the [platform dashboard](https://platform.synheart.ai/), open **App settings → SDK attestation** and fill in the block. Fields differ by OS: | OS | Required | Optional | | - | - | - | | Android | **Bundle ID** (your Android `packageName`), **Google project ID** (the GCP project linked to Play Console), **Play Integrity decoder credential** (uploaded SA JSON) | **Allow development builds**: accept attestations from `flutter run` / debug-signed / emulator builds | | iOS | **Bundle ID** (your iOS bundle ID), **Apple Developer Team ID** | **Allow development builds**: accept attestations from Xcode-installed builds and TestFlight internal testing | Both platforms expose the same **Allow development builds** toggle on the App settings page. It relaxes attestation verdicts so debug / pre-release builds pass; the server then treats the app as running in dev mode. Turn it off before App Store / Play Store release. ## Android: Play Integrity setup You complete a few one-time steps in Play Console and your own Google Cloud project, then upload one credential to the platform dashboard. ### Before you start You need: * A Google Play Developer account and access to Play Console for the app you want attested. * The app created in Play Console (a draft or any release track is enough). * **Owner or IAM Admin** access on a Google Cloud project you'll dedicate to this app. ### Steps **1. Link Play Console to your Cloud project** Play Integrity decode authorization is granted by the **Cloud project linked to your Play Console app**, not by an IAM role you grant Synheart. 1. Open [Google Play Console](https://play.google.com/console/) and select your app. 2. In the per-app left nav, open **Protected with Play → Play Integrity API settings**. 3. Confirm the **Google Cloud project** row shows your own GCP project. If it doesn't, click **Edit project** and pick your project from the picker. Note the project ID exactly; you'll use it in step 4. **2. Enable the Play Integrity API in that Cloud project** > [tab] Cloud Console UI > > Switch the project picker in [Google Cloud Console](https://console.cloud.google.com/) to the project you linked above, then: > > [Open the Play Integrity API library page →](https://console.cloud.google.com/apis/library/playintegrity.googleapis.com) > > Click **Enable**. If the button already says **Manage**, the API is on; you can continue. > [tab] gcloud CLI > > ```bash theme={null} > export PROJECT_ID=your-cloud-project-id > gcloud services enable playintegrity.googleapis.com --project="$PROJECT_ID" > ``` **3. Create a service account scoped to Play Integrity** > [tab] Cloud Console UI > > Still in Google Cloud Console, in the same project: > > 1. Open **IAM & Admin → Service Accounts**. > 2. Click **+ Create Service Account**. > 3. Name it predictably, e.g. `play-integrity-decoder`. > 4. On **Grant this service account access to project**, give it one role: **Service Usage Consumer** (`roles/serviceusage.serviceUsageConsumer`). > 5. Skip **Grant users access to this service account** and click **Done**. > > Then download a key: > > 1. Click into the service account. > 2. Open the **Keys** tab. > 3. **Add key → Create new key → JSON**. > 4. Save the downloaded `.json` somewhere temporary. > [tab] gcloud CLI > > ```bash theme={null} > export PROJECT_ID=your-cloud-project-id > export SA_NAME=play-integrity-decoder > export SA_EMAIL=${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com > > # 1. Create the service account > gcloud iam service-accounts create "$SA_NAME" \ > --project="$PROJECT_ID" \ > --display-name="Play Integrity Decoder" \ > --description="Per-app decoder credential for Synheart attestation." > > # 2. Grant the only role it needs > gcloud projects add-iam-policy-binding "$PROJECT_ID" \ > --member="serviceAccount:$SA_EMAIL" \ > --role="roles/serviceusage.serviceUsageConsumer" \ > --condition=None > > # 3. Mint a JSON key > gcloud iam service-accounts keys create ./play-integrity-decoder.json \ > --iam-account="$SA_EMAIL" \ > --project="$PROJECT_ID" > ``` > > If the last command fails with `constraints/iam.disableServiceAccountKeyCreation`, see the [org-policy workaround](#if-your-org-disables-service-account-key-creation) below. Treat the downloaded `.json` like a password: anyone with this file can decode integrity tokens for your app. > [!NOTE] > > Play Integrity decode authorization itself comes from the Play Console linkage in step 1, not from a project IAM role; the SA only needs to be able to **call** an enabled API in your Cloud project, which is exactly what Service Usage Consumer grants. Don't add Owner, Editor, or other broad roles. **4. Set the App's attestation fields in the platform dashboard** On the matching App in the [platform dashboard](https://platform.synheart.ai/), under **SDK attestation → Android**: * `bundle_id`: your Android `packageName` (for example `com.example.focus`). * `google_project_id`: the GCP project ID from step 1. **It must match the project\_id inside the SA JSON you'll upload next**; if they disagree the upload is rejected. * **Allow development builds**: keep off for Play Store releases. Turn it on only while testing emulator or debug-signed builds (`flutter run`, `./gradlew installDebug`); the server then accepts `UNRECOGNIZED_VERSION` and emulator verdicts that would otherwise fail. Click **Save changes**. **5. Upload the service account JSON** Click **Edit** again, then under **Play Integrity decoder credential** click **Upload SA JSON…** and pick the file from step 3. The dashboard validates the file (shape, `type == "service_account"`, project\_id match) and stores it encrypted. On success the card flips to: ``` Service account play-integrity-decoder@.iam.gserviceaccount.com Cloud project Uploaded · by fp ``` You can delete the downloaded JSON from your machine now; re-creating it from Cloud Console takes one click if you ever need to. ### Rotating the credential If the JSON key leaks or you rotate on a schedule: 1. Create a fresh JSON key in Cloud Console (same SA, or a new one in the same project). 2. In the dashboard, click **Replace…** on the credential card and upload the new file. 3. Delete the old key in Cloud Console. The card records the rotation time and which user did it. ### Removing the credential Click **Remove**. There is no fallback decoder: every device registration for your app will start failing with `DEV_003` immediately and continue failing until a new credential is uploaded. Only remove it if you mean to. ### What gets enforced Synheart calls `decodeIntegrityToken` using your service account and checks: * **Real device.** Tokens from emulators or virtual devices are rejected unless **Allow development builds** is on. * **Recognized app.** The build must match a Play-distributed version of your `packageName`. Sideloaded or repackaged builds fail. * **Token freshness.** Tokens older than five minutes are rejected to prevent replay. The service account permission above (`roles/serviceusage.serviceUsageConsumer`) lets the SA call enabled APIs in your project. It cannot read your store listing, publish releases, view financials, or access end-user data. ### If your org disables service account key creation Some Google Cloud orgs enforce `constraints/iam.disableServiceAccountKeyCreation`, which blocks step 3's JSON-key download. You'll see this error from `gcloud`: ``` ERROR: (gcloud.iam.service-accounts.keys.create) FAILED_PRECONDITION: Key creation is not allowed on this service account. type: constraints/iam.disableServiceAccountKeyCreation ``` You have two options. #### Option A: Self-service workaround (if you have `orgpolicy.policy.set`) If your role on the Cloud project lets you set org policies, you can temporarily override the constraint at the project level, mint the one key you need, then restore the enforcement. The key keeps working; only *future* key creation is blocked again. ```bash theme={null} export PROJECT_ID=your-cloud-project-id export SA_EMAIL=play-integrity-decoder@${PROJECT_ID}.iam.gserviceaccount.com # Enable the Org Policy API on this project (one-time) gcloud services enable orgpolicy.googleapis.com --project="$PROJECT_ID" # Override the constraint at project level cat > /tmp/allow-key-creation.yaml < [card] [API keys](/platform/api-keys) > > Issue per-app keys and understand ingestion allowlisting. > [card] [Synheart Auth](/synheart-auth/overview) > > How registered devices sign every outbound request once attestation has succeeded. # App policy Source: https://docs.synheart.ai/platform/app-policy Configure what data your app may collect and where it may be processed, the per-app layer of the consent model App policy is the per-app slice of the [three-layer consent model](/synheart-core/consent-system#three-layer-authority). It sits between the Synheart platform (master switches) and your end users (per-channel consent), and lets you express what *this specific app* is allowed to offer. Edit it from the dashboard: **Projects → your project → Apps → your app → App Policy → Edit Policy**. ## What App Policy controls Two kinds of controls, surfaced separately: | Control | Effect | | - | - | | **General Settings**: five high-level allow flags | Coarse on/off gates for the major data pathways. The runtime checks these before every upload class. | | **Restricted Channels**: per-channel deny-list | Channels your app will never collect, even if the end user grants them. Restriction wins over user consent. | There is no "Required Channels" control: the SDK already expresses positive ceilings on the [Consent Profile](/platform/consent-profiles) the user sees during onboarding. The app layer's only job is to *restrict further*, not to mandate. ## General Settings | Toggle | What it lets your app do | | - | - | | **Allow Cloud Processing** | Send session data to Synheart for processing. Required if you want any of the other cloud-bound flags to be useful. | | **Allow HSI Uploads** | Upload Human State Interface snapshots (the fused state your app would otherwise compute on-device). | | **Allow Research** | Let users opt in to sharing their data with research and lab studies. Requires cloud processing. | | **Allow Syni** | Let users chat with Syni, the Synheart AI coach. Subject to your platform plan. | | **Vendor Sync Allowed** | Let your app pull data from connected third-party wearables (e.g. WHOOP, Garmin). | All five default to **off** for a newly registered app. Turn on only what your app actually uses; Synheart's platform-level capability mask refuses to persist a flag that exceeds what your plan grants, so you'll get an error rather than silently being over-permissive. ## Restricted Channels A check next to a channel here means **your app will not collect that data**. The end user's consent doesn't override it. Use this when: * A regulator or your privacy team has told you a specific data type is off-limits for *this app*, even if the SDK supports it. * You ship a focused product (e.g. sleep-only) and want to refuse incidental channels even if the user grants them. * You're piloting a configuration and want to disable a channel temporarily without rolling a new SDK build. Channels are grouped by the same taxonomy the SDK uses; see [Consent System → Granular channels](/synheart-core/consent-system#granular-channels) for the canonical list. Marking a channel restricted causes uploads tagged with that channel to be denied at the consent service before they reach the ingest pipeline. ## How it composes with the other layers ```mermaid theme={null} flowchart LR P[Platform capability
Synheart-controlled] --> AND{ALL must allow} A[App policy
this page] --> AND U[User consent
SDK consent flow] --> AND AND -->|yes| OK[Data flows] AND -->|no| BLOCK[Silently dropped at the seam] ``` * **Platform capability** caps everything. If `syni_integration` is disabled at the platform level, no app can turn on Allow Syni. * **App policy** (this page) further restricts what your app may offer. * **User consent** narrows down to what the end user actually grants. A request only succeeds when all three layers say yes. See [Consent System → Three-layer authority](/synheart-core/consent-system#three-layer-authority) for the SDK-side perspective. ## Default behavior A newly registered app has no policy until you create one. While missing, the consent service treats the app as **deny-all** for the gated upload classes, a safe default. Create a policy as soon as the app is registered. If you change a policy after the app is live: * **Loosening a flag** (turning Allow Research on) takes effect on the next consent token your users mint. Existing tokens carry the older snapshot until they refresh. * **Tightening a flag** (turning Restricted Channels on, or turning Allow Cloud Processing off) is enforced at the next upload; the consent service rechecks the policy on every request, so changes apply within seconds even to already-issued tokens. ## Related * [Consent System](/synheart-core/consent-system): the SDK reference (channel taxonomy, tiers, runtime enforcement). * [Consent Profiles](/platform/consent-profiles): the per-app consent blueprints your SDK ships to end users. * [Implementing consent](/guides/consent): how to wire the consent flow into your app. # Apps register & manage Source: https://docs.synheart.ai/platform/apps Register apps in a project, find the app workspace and credentials, and edit or remove apps on the Synheart Platform An **App** is one mobile or web application connected to the Synheart Platform. Apps live inside a [project](/platform/projects), and each app is the unit where you configure [API keys](/platform/api-keys), [attestation](/platform/app-attestation), [policy](/platform/app-policy), [consent profiles](/platform/consent-profiles), and [Syni](/platform/syni). This page covers registering an app, the app workspace, downloading credentials, and editing or deleting an app. For first-time onboarding context, see the [Developer portal](/platform/developer-portal). ## App identifiers Each app carries two distinct identifiers; don't conflate them: | Identifier | What it is | Where you see it | | - | - | - | | Platform **`app_id`** | A short code or UUID the platform assigns at registration (e.g. `app_focus_and_kB8mPx`) | App card subtitle, workspace header, credentials JSON, API keys | | **Package name / bundle ID** | Your Android `packageName` or iOS bundle ID (e.g. `com.example.focus`) | Set in the registration form as **App ID / Package Name** | > [!NOTE] > > The registration form labels the store identifier field **App ID / Package Name**, but that value is your **`bundle_id`**, not the platform `app_id`. The platform `app_id` is generated for you and appears in credential downloads and support references. *** ## The apps list Open **Apps** from the project sidebar. The page shows all apps linked to this project. Each app appears as a card showing its name, platform badge (OS), and its identifier line. A results line reads **`{filtered} of {total} apps`**. * **Search**: match by name, description, or category. * **Filters**: narrow by **Category** and **Operating system** chips; **Reset filters** clears everything. * Clicking a card opens that app's workspace at **Sessions**. Card hover actions include **Edit app**, **Purge analytics data**, **Delete app** (owner only), and **Remove from project**. *** ## Register an app Apps must be created inside a project. From **Apps**, click **Add App** to open the **Add New App** drawer (*"Add a new app to this project and start tracking ingestion."*) and complete the form: | Form field | Description | | - | - | | **Operating System** | `Android`, `iOS`, `macOS`, `Windows`, `Linux`, or `Web` | | **App ID / Package Name** | Your Android `packageName` or iOS bundle ID (the helper text adapts to the selected OS) | | **App Name** | Display name for the app | | **Category** | Health & Wellness, Communication, Gaming, Entertainment, Productivity, Education, or Other | | **Description** | Optional; shown in the form (max 500 characters) | | **SDK Configuration** | Optional attestation block (see below) | > [!TIP] > > Use **Auto-fill** after entering the OS and package name to pull store metadata (name, icon) automatically. The optional **SDK Configuration** block pre-seeds [attestation](/platform/app-attestation) settings: **Google Project ID** and **Allow development builds** on Android, or **Apple Developer Team ID** and **Allow development builds** on iOS. You can also configure these later in app settings. On success, the platform assigns the app a platform `app_id` and links it to the project. > [!NOTE] > > During **early access**, registering new apps may be disabled and replaced with an early-access notice. *** ## The app workspace Opening an app switches the sidebar to **App** navigation and shows a header card with the app icon, name, the platform `app_id` (monospace), and the category. A breadcrumb reads `Projects / {project} / Apps / {app}`. | App sidebar label | Documentation | | - | - | | **Sessions** | [Connect & view data](/platform/connect-and-view-data#step-3--view-imported-session-data) | | **Wearables** | [Connect & view data](/platform/connect-and-view-data#step-2--connect-a-wearable-integration) | | **API Keys** | [API keys](/platform/api-keys) | | **Consent profiles** | [Consent profiles](/platform/consent-profiles) | | **App policy** | [App policy](/platform/app-policy) | | **Syni** | [Syni](/platform/syni) | | **App settings** | This page | The app landing route redirects to **Sessions**; there is no separate overview tab. ### Download app credentials The workspace header has a **Download App Credentials (.json)** button. It produces an `app-credentials.json` file containing the four non-secret identifiers your SDK and tooling need: ```json theme={null} { "org_id": "…", "tenant_id": "…", "project_id": "…", "app_id": "…" } ``` > [!NOTE] > > This file contains **no secrets**. To download credentials that include the secret key and signing secret, generate them in the one-time dialog under [API keys](/platform/api-keys#generate-a-key). *** ## App settings Open **App settings** from the app sidebar. The page covers app details and SDK attestation; this section documents everything except the attestation block (see [App attestation](/platform/app-attestation) for that). ### App details Click **Edit** to make the **App details** fields editable, then **Save changes**: | Field | Description | | - | - | | **Name** | App display name (required, max 100 characters) | | **Category** | App category (max 200 characters) | | **Operating system** | `ios` or `android` | | **Icon URL** | URL of the app icon image | > [!WARNING] > > The **package name / bundle ID** is set at registration and is **not editable** on this page. Register a new app if you need a different store identifier. During early access, editing app details may be disabled. ### Danger zone | Action | What it does | Who can run it | | - | - | - | | **Purge ingestion data…** | Permanently removes ingested data (HSI v1 ingests and lab metadata/sessions) for this app only. *"App settings, API keys, and policy are not removed."* | Org/tenant admin or project admin (not developers) | | **Delete this app** | Removes the app from the platform and permanently deletes its analytics data. *"This cannot be undone."* | App owner | After a purge, a confirmation shows approximate row counts removed (HSI, lab metadata, lab sessions). Deleting an app returns you to the project apps list. *** ## Remove vs. delete | Action | Surface | Effect | | - | - | - | | **Remove from project** | Apps list card menu | Unlinks the app from this project | | **Delete app** | Apps list / App settings | Permanently deletes the app and its ingested data | | **Purge ingestion data** | Apps list / App settings | Deletes ingested data but keeps the app, keys, and policy | *** ## Next > [card] [API keys](/platform/api-keys) > > Generate and scope per-app keys for the SDKs and your backend. > [card] [App attestation](/platform/app-attestation) > > Configure Play Integrity (Android) and App Attest (iOS) for the app. > [card] [App policy](/platform/app-policy) > > Set what data the app may collect and where it may be processed. > [card] [Connect & view data](/platform/connect-and-view-data) > > Connect a wearable and inspect the session data the app produces. # Billing & usage Source: https://docs.synheart.ai/platform/billing Monitor metered usage, choose a plan, and manage your subscription and invoices on the Synheart Platform The **Billing & Usage** page is where you monitor metered usage for the current billing period and review or change your organization's plan. Subscription changes, invoices, and payment methods are handled through Stripe. Open it from the sidebar **Admin** section: **Billing & Usage**. The page subtitle reads *"Monitor metered usage for this billing period, then review or change your plan."* > [!NOTE] > > Only the **organization owner** can change plans, start checkout, cancel, or open the Stripe billing portal. Admins and members can view usage and plan details (a read-only banner appears for non-owners). > [!TIP] > > **Inference runs on-device, free, forever.** Synheart inference happens on the device, not in the cloud. You only pay for ingestion and storage, never for inference. ## Plans Plan names, prices, limits, and features are driven by the billing service, so the available tiers and pricing always reflect your account. The **Available plans** grid shows each plan with its price and feature bullets, plus a **Current** or **Recommended** badge. For each plan you'll see an action button: **Current Plan**, **Upgrade**, **Downgrade**, or **Contact Sales** for custom or enterprise pricing. Plan feature lines cover ingestion events per month, API requests, storage capacity, data retention period, project and team-member limits, and additional entitlements such as Cloud Extended or Priority Support. ### Change your plan Choosing **Upgrade** or **Downgrade** starts Stripe Checkout (or swaps the plan in place for some changes). The **Free** tier is set directly. **Enterprise** plans are billed off-platform. *"Your Enterprise plan is billed off-platform and managed by your account team."* After a successful change you'll see a **Subscription Successful!** confirmation with the new status, current period, and subscription ID. *** ## Current plan The **Current Plan** card shows the active plan name and price, a status badge (such as **active**, **trialing**, or **Cancels soon**), and the current billing period dates. * **Manage Billing & Subscription** opens the **Stripe Customer Portal** for payment methods, invoices, plan changes, and resuming a scheduled cancellation. * **Cancel subscription** (or **Request cancellation** for Enterprise) starts the cancel flow. ### Cancelling The **Why are you leaving?** dialog asks for a **Reason for cancellation** (Too expensive, Missing features, Switching to a competitor, No longer needed, Other) and optional feedback before handing off to Stripe (or forwarding the request to your account team for Enterprise). > [!WARNING] > > A scheduled cancellation keeps access until the period ends. To reverse it, open the Stripe portal and resume the subscription before the end date. *** ## Usage meters Three meters summarize usage for the current billing period: | Meter | What it measures | Detail shown | | - | - | - | | **Ingestion** | Ingested events | Events used this period, or **Unlimited ingestion** | | **Storage** | Stored data | GB used, or **Unlimited storage** | | **Syni** | Syni messages | Messages used, or **Unlimited Syni usage** | Each meter shows a percentage used, or ∞ for unlimited plans. ### Usage breakdown A **Usage breakdown** section shows billed metrics for the period as KPI cards, covering HSI events ingested, Lab events ingested, storage used (displayed in GB), and Syni token usage (input and output combined). When Syni is in use, a **Syni usage** section breaks it down further: chat messages, sessions, tool executions, input/output tokens, and compute time. ### Plan structure and metered usage When a detailed overview is available, a **Plan structure** panel shows how many projects, tenants, apps, and team members are in use against your plan limits, with a health indicator (healthy, approaching, or exhausted). A metered-usage table lists each metric with units used, units included, and overage cost. A cost summary shows the base plan cost, overage charges, credits applied, and the total amount due. *** ## Extra usage The **Extra usage** panel lets you keep using Synheart after hitting a plan limit: *"Turn on extra usage to keep using Synheart if you hit a plan limit."* Toggle **Extra usage** on to enable metered overage beyond your plan limits. You can also set a **Monthly spend limit** (the maximum overage amount before new requests are blocked), or leave it as **No monthly cap** for unlimited overage. Any available **Credit balance** is applied before charges appear on your invoice. > [!NOTE] > > Overage, balance, and cost details are visible to the **organization owner** only. Metered charges appear on your Stripe invoice. ### Team seats When you're at your team-member limit, **Members** offers an **Add seat** action that adds a seat to your next invoice. See [Members & roles → Invite an organization member](/platform/members-and-roles#invite-an-organization-member). *** ## Invoices The **Recent invoices** card lists your latest invoices with the invoice number, date, payment status, amount, and a link to view the hosted invoice or download a PDF. **Open in Stripe** opens the billing portal for your full invoice history. > [!NOTE] > > Full invoice history, payment methods, and downloadable PDFs live in the **Stripe billing portal**; the dashboard shows only the most recent invoices. *** ## Next > [card] [Members & roles](/platform/members-and-roles) > > Add team-member seats and manage who has access. > [card] [Organizations & tenants](/platform/organizations-and-tenants) > > Manage the organization this subscription belongs to. > [card] [Exports](/platform/exports) > > Export the ingested data your usage meters track. > [card] [Account & security](/platform/account) > > Manage your own profile and security settings. # Connect wearables & view data Source: https://docs.synheart.ai/platform/connect-and-view-data Step-by-step guide to sign in, connect a wearable OAuth integration, and inspect imported session data in the Synheart Platform This guide walks through the primary workflow on [`platform.synheart.ai`](https://platform.synheart.ai): sign in, set your organization and tenant context, connect a third-party wearable to a registered app, and explore the session data that flows in. Each step covers what to do in the UI, what you should see, and what the results mean. Use this page after you have completed [Create a platform account](/setup/create-account) and registered at least one [app](/platform/developer-portal#register-an-app) inside a [project](/platform/projects). ## At a glance ```text theme={null} Sign in → select organization & tenant → open a project → connect a wearable → browse sessions → open session detail ``` | Step | Outcome | | - | - | | **1** | Workspace context set; a project is open | | **2** | Wearable integration created and moving toward **Active** | | **3** | Imported sessions visible in the explorer | | **4** | Snapshot payload inspected | **Prerequisites** * An **organization** with at least one **tenant**, **project**, and registered **app**. * OAuth credentials from your wearable vendor (WHOOP, Garmin, Fitbit, and others in the vendor catalog) when configuring a cloud integration. * An [API key](/platform/api-keys) with **ingestion allowlisting** if your app sends on-device HSI snapshots; this path is separate from vendor OAuth. > [!TIP] > > Keep the **organization** and **tenant** selectors correct before debugging empty lists. Most project-scoped pages require both to be set. *** ## Step 1: Sign in and set workspace context **Goal:** Authenticate, scope the dashboard to the right organization and tenant, and open the project you want to work in. ### 1.1 Sign in 1. Open [`platform.synheart.ai`](https://platform.synheart.ai). 2. Complete sign-in when prompted. Supported methods: * **Email** and **Password** * **Continue with Google** * **Continue with GitHub** 3. If multi-factor authentication (MFA) is enabled on your account, enter your **6-digit TOTP code** on the **Two-factor authentication** screen (or use a recovery code). **What you see:** After a successful login, you land on **Projects** (`/projects`) unless you arrived via an invitation or deep link. ### 1.2 Select organization and tenant In the **left sidebar**, use the two switchers above the navigation links: 1. **Organization switcher**: dropdown header **Organizations**. Pick the company account that owns your projects. 2. **Tenant switcher**: dropdown header **Tenants**. Pick the workspace (tenant) that contains the project. **What you see:** Project lists, wearables, and sessions load for the selected pair. If no tenant exists yet, you may see **No tenant yet** with a **Create your first tenant** action on **Projects**. **What you do if blocked:** Create a tenant at **Tenants** (`/tenants`) or ask an organization administrator to invite you to one. > [!WARNING] > > Wearables and sessions wait for a valid **organization + tenant** pair. Without a tenant, lists stay empty and you may see messages such as *"Create a tenant for this organization to load wearables."* or *"Select a workspace (tenant) to load project API keys."* ### 1.3 Open a project 1. From **Projects** (`/projects`), click a project card. 2. Confirm the **Overview** page loads at `/projects/{projectId}`. **What you see:** The sidebar switches to **Project** navigation with the following items: | Sidebar item | Purpose | | - | - | | **All projects** | Return to the project list | | **Overview** | KPI cards and trend charts | | **Sessions** | Project-wide session explorer | | **Apps** | Registered apps in the project | | **Wearables** | Project-wide wearable OAuth hub | | **API Keys** | Project-scoped key management | | **Studies** | Research studies (when enabled) | | **Project settings** | Rename, archive, data purge | *** ## Step 2: Connect a wearable integration **Goal:** Register an OAuth integration between a platform app and a vendor API so biosignals can flow in once the integration is **Active**. Wearable connections are **OAuth integrations**: one row per **vendor × app**. The platform stores encrypted credentials and scopes; your mobile app or vendor webhooks deliver data after setup completes. ### 2.1 Choose where to manage wearables You can manage wearables from two equivalent surfaces: | Surface | When to use | | - | - | | **Project → Wearables** | See every vendor × app row across all apps in the project. Open from the project sidebar. | | **App → Wearables** | Manage wearables in the context of a single app. Open from the app sidebar. | Both surfaces open the same **Add Wearable** / **Edit Wearable** drawer. ### 2.2 Review hub KPIs On **Wearables**, four summary cards appear at the top: | KPI | Description | | - | - | | **Wearables** | Count of integration rows (vendor × app) in the project | | **Vendor types** | Distinct vendors connected; the link shows how many are available in the catalog | | **Active** | Integrations that are ready for data | | **Needs setup** | Integrations that are pending or have missing credentials | ### 2.3 Start the setup wizard 1. On **Wearables**, click **Setup new wearable**. * The button is **disabled** until the project has at least one app; register an app under **Apps** first. 2. In the **Add Wearable** drawer, complete the form: | Form field | Description | | - | - | | **App** | Registered app that owns this vendor connection | | **Device Type** | Vendor from the active catalog | | **Client ID** | OAuth client ID from the vendor developer portal | | **Client Secret** | OAuth client secret (never shown again after save) | | **App Redirect URI** | OAuth callback URL registered with the vendor | | **Scopes** | Permission keys for this vendor; required scopes are pre-selected | 3. Submit the form. **What you see on success:** The drawer shows **Integration created** with optional **Webhook URLs**, a **Provider Portal** link, and **Setup Notes** with vendor-specific instructions. #### Integration status labels | Status | Action button | | - | - | | **Active** | **Edit Wearable** | | **Pending** | **Continue setup** | | **Not configured** | **Setup Wearable** | > [!TIP] > > Each app supports **one integration per vendor type**. If **Device Type** has no options, every catalog vendor may already be connected for that app; use **Edit Wearable** on an existing row instead. ### 2.4 Finish vendor-side setup 1. Copy any **Webhook URLs** from the success panel into the vendor developer portal. 2. Open the **Provider Portal** link and complete redirect URI registration, webhook endpoints, and user authorization as required. 3. Return to the platform and confirm the row shows **Active**. **Data import timing:** * **Webhook-driven vendors**: biosignals arrive when the vendor POSTs to Synheart webhook URLs. * **On-device SDK path**: sessions appear after your app ingests HSI snapshots with an [allowlisted API key](/platform/api-keys#ingestion-access), independent of OAuth status in the wearables list. #### Filter the wearables list | Filter | Effect | | - | - | | **All Apps** | Show integrations for a specific app | | **All Vendors** | Show integrations for a specific vendor type | *** ## Step 3: View imported session data **Goal:** Confirm data is ingesting and locate individual snapshots in the project **Sessions** explorer. ### 3.1 Open the session explorer 1. In the project sidebar, click **Sessions** (`/projects/{projectId}/sessions`). 2. Confirm the page title **Sessions** and subtitle `{project name} · Session explorer`. **Default date range:** **30D** (last 30 days). KPI comparison labels adapt to the preset (e.g. **vs yesterday**, **vs last week**, **vs last month**). ### 3.2 Read KPI cards | KPI | Description | | - | - | | **Total sessions** | Number of sessions in the selected date range | | **Avg Valence Confidence** | Average valence confidence score across filtered sessions | | **Avg Capacity Confidence** | Average capacity confidence score across filtered sessions | | **Avg Arousal Confidence** | Average arousal confidence score across filtered sessions | Each card shows a period-over-period delta based on the selected date range. ### 3.3 Filter and search | Control | Effect | | - | - | | Search box | Matches snapshot ID, app/producer label, wearable label, emotion, and activity | | **All / Lab / HSI** | **Lab** shows lab warehouse sessions; **HSI** shows on-device SDK ingests | | **1D / 7D / 30D / Custom** | Rolling or custom date window | | **All apps** | Restrict to one registered app | | **All wearables** | Restrict to sessions from a linked wearable device type | | **Export** | Downloads a CSV containing Snapshot ID, Observed, Producer · App, Source, and Windows | > [!TIP] > > If the table is empty, widen the range to **30D** or **Custom**, confirm ingestion allowlisting for HSI data, and verify the correct **organization** and **tenant** are selected. ### 3.4 Session list columns | Column | Meaning | | - | - | | **Snapshot ID** | Unique identifier for the session; click to open session detail | | **Created At** | When the record was stored in the platform | | **Observed** | When the snapshot was observed on device | | **Producer · App** | Which app produced the snapshot and which device instance | | **Source** | **HSI** or **Lab** badge indicating the ingestion source | | **Windows** | Number of time windows in the session | *** ## Step 4: Inspect a single session **Goal:** Open one snapshot, review structured fields and charts, and export the raw JSON if needed. ### 4.1 Open session detail 1. In the sessions table, click a **Snapshot ID**. 2. The detail page opens at `/projects/{projectId}/sessions/{sessionRef}?source=…`. **What you see:** * Page title **Session detail** * Subtitle: *Snapshot payload, axes, and related metrics for this session.* * **Export JSON** button (top right) * **Snapshot detail** section: a view-descriptor-driven layout rendered from the payload ### 4.2 Export the payload 1. Click **Export JSON**. 2. A file named `session-{sessionId}.json` downloads. **What is included:** The full session record in its native JSON format. Internal infrastructure fields are omitted from the download. ### 4.3 Understand the Snapshot detail view The **Snapshot detail** section uses a backend **view descriptor** to render tables, stat cards, and charts dynamically. Depending on HSI schema version and payload shape, you may see: | Section type | Typical content | | - | - | | Stat / key-value panels | Session metadata, app context, timing | | Axis tables or cards | HSI axes by domain (cognitive, affective, …) | | Line / bar / radar charts | Time-series or aggregate metrics | | Enum-labeled fields | Dominant emotion, activity state | > [!NOTE] > > Older snapshots may show fewer sections if axes or biosignals were not captured. Use **Export JSON** to inspect the full payload when a field appears missing in the UI. #### Biosignal fields (when present in payload) | Signal | Description | Update cadence | | - | - | - | | Heart rate | Beats per minute | Per biosignal timestamp | | HRV (SDNN) | Heart rate variability | Per timestamp | | Respiratory rate | Breaths per minute | Per timestamp | | Blood oxygen | SpO₂ percentage | Per timestamp | | Temperature | Skin/body temperature | Per timestamp | *** ## Reference: project overview KPIs The **Overview** page (`/projects/{projectId}`) shows complementary aggregates for the selected **1D / 7D / 30D / Custom** range. Use it for trends; use **Sessions** for row-level inspection. | KPI | Description | | - | - | | **Total Subjects** | Distinct users with snapshots in the selected range | | **Average Valence** | Average valence axis score for the period | | **Average Capacity** | Average cognitive capacity axis score (0–1) | | **Average Arousal** | Average affective arousal axis score | | **Average Sleep** | Average sleep axis value | | Valence–arousal scatter | One point per snapshot in range | *** ## Troubleshooting | Symptom | Likely cause | What to check | | - | - | - | | Wearables list empty | No tenant selected | Create or select a tenant in the sidebar switcher | | **Setup new wearable** disabled | Project has no apps | Register an app under **Apps** first | | Integration stuck **Pending** | Vendor OAuth not finished | Open **Continue setup**; follow **Provider Portal** link | | Sessions list empty | No data in date range, or ingestion not allowlisted | Widen **30D** range; confirm [API key ingestion access](/platform/api-keys#ingestion-access) | | Session detail missing sections | Snapshot predates current HSI schema or lacks axes | Check **Source** badge; **Export JSON** to inspect raw payload | | **Lab** vs **HSI** confusion | Different ingestion pipelines | **HSI** = SDK/runtime snapshots; **Lab** = lab warehouse imports | | Session not found on detail | Wrong org/tenant or invalid ID | Confirm sidebar context; verify the Snapshot ID from the list | See also [Troubleshooting](/guides/troubleshooting) and [Projects](/platform/projects). *** ## Next steps > [card] [Projects](/platform/projects) > > Create projects, add apps, and understand the resource hierarchy. > [card] [API keys](/platform/api-keys) > > Issue keys and request ingestion allowlisting for on-device data. > [card] [Synheart Wear](/synheart-wear/overview) > > Learn how device adapters capture biosignals on mobile and watch. > [card] [Synheart Session](/synheart-session/overview) > > See how sessions are produced before they appear in the platform. # Consent profiles Source: https://docs.synheart.ai/platform/consent-profiles Define what your app may offer end users at consent time, the per-profile blueprint the SDK uses to render the consent flow A consent profile is the blueprint your SDK reaches for when an end user goes through the consent flow. It's the **per-app slice of what's offered to the user**: the channels, tiers, and high-level capabilities your app may request consent for. Edit profiles from the dashboard: **Projects → your project → Apps → your app → Consent Profiles**. ## Profiles vs. App Policy These two layers do related-but-distinct jobs: | Layer | Where you set it | What it expresses | | - | - | - | | [**App policy**](/platform/app-policy) | Dashboard → App → App Policy | Hard deny-list and coarse allow\_\* gates the runtime enforces on every upload | | **Consent profile** (this page) | Dashboard → App → Consent Profiles | The set of options the SDK shows the user during the consent flow | App policy is a *backstop*. Consent profile is the *menu*. The user sees the consent profile; the runtime enforces app policy. A user can only grant something that's both **offered by the consent profile** and **allowed by app policy**; see [the three-layer model](/synheart-core/consent-system#three-layer-authority). ## What a consent profile contains Open or create a profile in the dashboard. You'll see two sections: ### General settings The high-level capabilities your app may offer. End users still pick from these; the profile just says "this app is allowed to ask." | Toggle | Meaning | | - | - | | **Allow cloud processing** | The profile may include cloud upload as an option. Required for research participation. | | **Vendor sync allowed** | The profile may include third-party wearable sync (WHOOP, Garmin, etc.). | | **Allow research** | The profile may include research / lab-export participation. Requires cloud processing. | | **Allow Syni** | The profile may include Syni AI coach access. Subject to your platform plan and your app policy. | | **Set as default profile** | New users see this profile first when your app requests consent. Exactly one default per app. | ### Channels The granular data types the SDK consent UI offers, grouped by source: * **Biosignals**: vitals, cardio advanced, neuromuscular, wearable motion, sleep * **Phone context**: device motion, device context, system state * **Behavior**: digital activity, notification patterns, app context * **Interpretation**: focus estimation, emotion estimation This is the same taxonomy the SDK consumes; see [Consent System → Granular channels](/synheart-core/consent-system#granular-channels) for what each one unlocks. A check next to a channel here means "the consent UI may offer this channel"; an unchecked channel is simply not surfaced. The end user then grants whichever subset they're comfortable with at runtime. ## Multiple profiles, one default You can ship more than one profile per app, for example a Standard and a Research variant, and pick which one is the default. The SDK fetches the default at consent time; your app can request a specific non-default profile by id if your flow needs it. Only one profile may be flagged default. Toggling default on one automatically clears it from the others. ## Versioning: edits publish a new snapshot Profiles are **immutable once published**. Editing the channels or any of the General Settings doesn't overwrite the old data; it creates a new version row and marks it current. Each consent token your SDK mints references the version the user agreed to, so old tokens stay valid against the snapshot they were issued from. When you edit a profile in the dashboard you'll be asked for: * A **version name** (required for any payload-changing edit), e.g. "v2: added sleep channel". * A **description** (optional): release notes for the change. Metadata-only edits (renaming the profile, changing its description, toggling Set as default, deactivating it) don't create a new version. ## How profiles compose with the other layers A channel offered in a profile still needs [App policy](/platform/app-policy) to allow it and the user to grant it; all three layers must agree. See [App policy → How it composes](/platform/app-policy#how-it-composes-with-the-other-layers) for the full diagram. The key distinction between the two layers: * Use a **consent profile** to shape what the user sees and can grant. * Use **App policy → Restricted Channels** to forbid a channel entirely, even if a profile would otherwise offer it. ## Default profile workflow When a developer first wires up a new app, the dashboard auto-creates a default profile with sane defaults (Cloud on, Research off, Syni off, Vendor sync off; biosignals + behavior channels checked, interpretation off). That profile is what users see at first launch. You can then: * **Edit the default** to expand or narrow what your app offers. * **Add additional profiles** if you have a Pro tier, research arm, or other variants, and point your app at them by profile id when needed. ## Related * [App policy](/platform/app-policy): the per-app enforcement layer that backstops what profiles offer. * [Consent System](/synheart-core/consent-system): full SDK reference for the channel taxonomy, tiers, and runtime enforcement. * [Implementing consent](/guides/consent): how to wire the consent flow into your app. # Developer portal Source: https://docs.synheart.ai/platform/developer-portal Sign in, create an organization, and register your apps on platform.synheart.ai The developer portal is where initial setup happens: creating your organization, registering apps, and getting your integration wired up. Finish these steps before pointing the CLI or SDKs at the platform. ## Sign in Go to [`platform.synheart.ai`](https://platform.synheart.ai) and sign in with email and password, Google, or GitHub. The same account authenticates the CLI; see [Authenticate the CLI](/setup/authenticate). ## Create your organization First-time users land in onboarding and create an **organization**, a **tenant** workspace, and optionally invite teammates. For the full details on managing these, see [Organizations & tenants](/platform/organizations-and-tenants). ## Invite teammates Invite collaborators from your organization settings. See [Members & roles](/platform/members-and-roles) for how roles and invitations work across orgs, tenants, and projects. ## Register an app Apps live inside a project and each gets a platform `app_id` at registration. For the full registration steps and app management, see [Apps](/platform/apps). ## Ingestion access API keys work immediately once generated, but biosignal ingestion requires an additional allowlisting step. See [API keys → Ingestion access](/platform/api-keys#ingestion-access). ## Consent configuration Each app has two consent controls that work together: * **[App policy](/platform/app-policy)**: what this app is allowed to collect and process. * **[Consent profiles](/platform/consent-profiles)**: what the SDK offers end users during the consent flow. ## Next > [card] [Organizations & tenants](/platform/organizations-and-tenants) > > Create and manage the workspaces that hold your projects. > [card] [Apps](/platform/apps) > > Register apps, find credentials, and manage them. > [card] [API keys](/platform/api-keys) > > Generate per-app keys and request ingestion access. > [card] [App policy](/platform/app-policy) > > Configure what data your app may collect. # Exports Source: https://docs.synheart.ai/platform/exports Export HSI and Lab data in batch as downloadable archives from the Synheart Platform The **Exports** page lets you export HSI and Lab data in batch as downloadable archives. Large exports run in the background, so you can start one and come back to download it later. Open it from the sidebar: **Exports**. The page subtitle reads *"Export HSI and Lab data in batch as downloadable archives."* > [!NOTE] > > Exports need a selected **organization** and **tenant**. Without both you'll see *"Select an organization and tenant to view and create exports."* > [!WARNING] > > Export archives **expire after a limited time**. Download them promptly. Once an archive expires you'll need to run the export again. ## Permissions Creating exports requires the `data.exports.create` permission. Without it you'll see *"You don't have permission to create exports. Ask an organization or tenant admin."* You can still view existing exports. *** ## Create an export Click **New export** to open the **Export data** dialog (*"Export HSI and Lab data as a downloadable archive. Large exports run in the background. Track progress and download from the Exports page."*). | Form field | Description | | - | - | | **Scope** | What to export: **Current tenant**, **A project**, **An app**, or **Entire organization** | | **Project** | The project to export (when scope is a project or app) | | **Apps** | One or more apps (when scope is an app) | | **From** (optional) | Start of the date range | | **To** (optional) | End of the date range | | **Format** | **NDJSON (recommended, lossless)**, **CSV (flattened, analyst-friendly)**, or **Both** | Click **Start export**. The job appears in the table and updates its progress automatically while running. > [!TIP] > > Choose **NDJSON** for a lossless, machine-readable archive, or **CSV** for a flattened, spreadsheet-friendly version. Pick **Both** when you want each. (NDJSON is newline-delimited JSON, not a single JSON document.) > [!NOTE] > > [Research studies](/platform/studies) reuse this same dialog from a cohort's **Export** action, pre-scoped to the study (and optionally a single participant). *** ## Track and download exports The exports table lists every export job with its scope, the time it was created, current status, row count, archive size, format, and a download link once it's ready. Export status moves through four stages: **Pending** (queued and waiting to start), **Running** (actively processing, with a progress percentage), **Done** (archive ready to download), and **Failed** (shows an error message explaining what went wrong). The **Rows** column shows the total record count across HSI and Lab data once an export finishes. The **Download** link becomes active when the status reaches **Done**. Click it to retrieve the archive before it expires. Use **Refresh** to update the list manually; running jobs also poll automatically. *** ## Next > [card] [Research studies](/platform/studies) > > Export cohort and participant data scoped to a study. > [card] [Connect & view data](/platform/connect-and-view-data) > > Inspect individual sessions before exporting in bulk. > [card] [Billing & usage](/platform/billing) > > See how ingestion and storage usage maps to exportable data. # Members & roles Source: https://docs.synheart.ai/platform/members-and-roles Invite people, assign roles, and manage invitations across organizations, tenants, and projects on the Synheart Platform The Synheart Platform manages access at three scopes: **organization**, **tenant**, and **project**. Each scope has its own members list, its own roles, and its own invitation flow, but they all share the same email-based invite pattern. This page covers who can do what, how to invite and remove people at each level, and how invitations are accepted. For the workspaces themselves, see [Organizations & tenants](/platform/organizations-and-tenants). > [!NOTE] > > Access checks run against your membership at each scope. A person invited to a project does not automatically gain organization-wide access, and removing someone from a tenant or project does **not** remove their organization access. ## Roles at a glance | Scope | Roles | | - | - | | **Organization** | Owner / Admin / Member | | **Tenant** | Tenant admin / Tenant member | | **Project** | Project admin / Project developer / Project viewer | * **Owner**: full control of the organization, including billing and deletion. Only the owner can change the subscription. * **Admin**: manage members, settings, and resources, but not org-level billing changes. * **Member**: work inside the resources they're added to (read-only at org level until granted tenant/project roles). > [!TIP] > > Org-level pages simplify roles to **Owner / Admin / Member** in the switcher and lists. Tenant and project pages use their own, more granular role names shown above. *** ## Organization members Open **Members** from the sidebar. The page lets you invite people to the organization, manage roles, and review pending invitations. Summary cards count members by role, and two tabs, **Members** and **Invitations**, that split active people from pending invites. Use the **Search members** box and the **All roles / Owner / Admin / Member** filter to narrow the list. ### Invite an organization member 1. Click **Invite member**. 2. In the **Invite member** modal, fill in: * **Email**: the invitee's email address. * **Invite to** / **Target**: the scope the invite grants (organization, or a specific tenant/project). * **Role**: the role to assign. 3. Click **Send invitation**. An email with an accept link is sent to the invitee. The invite appears under the **Invitations** tab with a **Pending** badge until accepted. > [!NOTE] > > Your plan caps how many team members an organization can have. When you reach the cap, **Invite member** is disabled, and (depending on plan) you may see an **Add seat** option that bills an extra seat to your next invoice. See [Billing & usage](/platform/billing#extra-usage). ### Manage members and invitations | Action | Where | Effect | | - | - | - | | **Change role** | Member row menu | Updates the member's organization role | | **Remove member** | Member row menu | They will lose access to all tenants and projects in this org | | **Reinvite** | Invitations tab | Resends the invitation email | | **Cancel invite** | Invitations tab | Removes the pending invitation so it can no longer be accepted | *** ## Tenant members Open a tenant's members page from **Tenants → Manage members**, or the **Members** link on a tenant card. Summary cards count **Total members**, **Tenant admins**, **Tenant members**, and **Other roles** (inherited or org-scope). Use **Invite to this tenant** to add people. ### Invite a tenant member Tenant invitations are limited to people who already belong to the organization. Pick an organization member (or, if permitted, an email address), choose a role, and **Send invitation**: | Role | Description | | - | - | | **Tenant admin** | Manage tenant members and settings | | **Tenant member** | Standard access to the tenant's projects | Use **Remove from tenant** on a member row to revoke tenant access. This does not remove their organization access; you need to revoke that separately. *** ## Project members Open a project's members page from the **Members** link in the project sidebar. Summary cards count **Total members**, **Project admins**, **Developers**, and **Viewers**. A tenant must be selected first; otherwise you'll see *"Create a tenant for this organization to view project members."* ### Invite a project member Use **Invite to this project** and choose a role: | Role | Description | | - | - | | **Project admin** | Manage the project, its members, and settings | | **Project developer** | Build and integrate: apps, keys, wearables | | **Project viewer** | Read-only access to project data | > [!WARNING] > > Project invitations require a selected workspace (tenant). If none is selected you'll see *"Select a workspace (tenant) to send project invitations."* Use **Remove from project** to revoke project access (org access is unaffected). *** ## Accept an invitation Invitations are email-based and tied to a one-time token. How you accept depends on where you start: | Entry point | When it's used | | - | - | | Invite email link (signed in) | Primary flow: validates the token and joins on **Accept** | | Invite email link (new user) | Lets a brand-new user create an account, then accept | | In-app org invite | Accept a pending org invite from inside the dashboard | | Profile → Invitations | Review and accept invitations on your account | On the invitation page you'll see the invitation details (**Email**, **Role**, **Organization**, **Invited by**, and **Expires**) with **Accept** and **Decline** actions. After accepting, you're redirected to **Projects**. > [!WARNING] > > Invitations expire. An expired link shows *"This invitation expired on . Please contact for a new invitation."* Ask the inviter to **Reinvite** you. *** ## Next > [card] [Organizations & tenants](/platform/organizations-and-tenants) > > Create and configure the workspaces these members belong to. > [card] [Billing & usage](/platform/billing) > > Team-member seats, plan limits, and adding seats. > [card] [Account & security](/platform/account) > > Manage your own profile, password, and pending invitations. > [card] [Projects](/platform/projects) > > Organize apps, devices, and sessions inside a project. # Organizations & tenants Source: https://docs.synheart.ai/platform/organizations-and-tenants Create and manage the organization and tenant workspaces that hold your projects, members, and billing on the Synheart Platform Organizations and tenants are the two outermost layers of the [resource hierarchy](/platform/overview#the-hierarchy). An **organization** is your company account: it owns billing, members, and every resource below it. A **tenant** is an isolated workspace inside that organization (a department, client, environment, or business unit) where [projects](/platform/projects) actually live. This page covers creating and switching organizations, configuring organization settings, and managing tenants. For people and permissions, see [Members & roles](/platform/members-and-roles). ## At a glance ```text theme={null} Organization (billing, members, settings) └── Tenant (isolated workspace, environment) └── Project (apps, wearables, sessions) ``` | Surface | Purpose | | - | - | | Organization switcher | Switch between organizations you belong to | | **Organizations** | List your orgs and pending invitations | | **Organization settings** | Name, slug, description, SSO, and deletion | | Tenant switcher | Switch the active tenant workspace | | **Tenants** | Create and manage tenant workspaces | > [!TIP] > > Most project-scoped pages (wearables, sessions, API keys) need both a valid **organization** and **tenant** selected. If a list is empty, confirm both switchers first. *** ## Organizations ### Switch organizations Use the **organization switcher** at the top of the left sidebar. Each row shows the organization name and your role in it: **Owner**, **Admin**, or **Member**. Switching organizations changes your active org context, **clears the current tenant selection**, and reloads org-scoped data. Always confirm you are in the right org before generating keys, inviting people, or registering apps. ### Browse organizations and invitations Open **Organizations** from the sidebar to see two tabs: * **My Organizations**: every org you belong to, each card showing your role, a description, and stats (`{n} members · {n} projects · {n} apps`). * **All Organizations**: reserved for a future directory view. Pending invitations appear in a **Pending Invitations** section with **View** and **Accept** actions. Accepting takes you straight into the organization. See [Members & roles → Accept an invitation](/platform/members-and-roles#accept-an-invitation). ### Create an organization First-time users land in onboarding; existing users can create another org from the switcher (**Create Organization**) or from the Organizations page. The setup wizard walks through: 1. **Create**: **Organization Name** and an optional **Description**. 2. **Plan**: pick a tier (Free, Pro, Synheart Plus, Research, or Enterprise). You can change this later in [Billing & usage](/platform/billing). On-device inference is always free. 3. **Team**: optionally invite teammates now, or **Skip for now**. On completion you land on **Projects**. > [!NOTE] > > During **early access**, self-service organization creation may be disabled. If you see an early-access notice, contact Synheart to provision additional organizations. ### Organization settings Open **Organization settings** from the sidebar. The page covers name, slug, and description. Subscription and usage are under **Admin → Billing & Usage**; people are under **Members**. #### General settings Your organization has three core identity fields: * **Organization Name**: the display name shown across the dashboard. Click **Edit Details** to update it. * **Slug**: a URL-safe identifier assigned at creation, shown in monospace. This is read-only after setup. * **Description**: an optional free-form summary. Edit it alongside the name via **Edit Details**, then **Save Changes**. #### Authentication (SSO) Organizations with a claimed domain can enable single sign-on. Only the org owner can enable SSO or claim a domain, and the domain must match the owner's own email domain. Owners and admins can disable SSO. The section shows: * **Claimed domain(s)**: the email domains tied to this org. * **Google Workspace SSO**: click **Enable** to let members sign in with their Google Workspace accounts. Once enabled, the card shows an **Enabled** badge. #### Delete an organization Org owners can permanently remove the organization from the danger zone at the bottom of settings. > [!WARNING] > > Deleting an organization is permanent. All projects, apps, and data associated with this organization will be permanently removed. You must type **DELETE** to confirm before **Delete Permanently** is enabled. *** ## Tenants Tenants are workspaces inside an organization. Each tenant isolates its projects, members, and configuration from other tenants, for example a `production` tenant separated from a `research-lab` tenant. ### Switch tenants Use the **tenant switcher** near the bottom of the sidebar. Each row shows the tenant name and your role in it. The selected organization and tenant together scope all resources in the dashboard. ### Manage tenants Open **Tenants** from the sidebar. The page lets you create and manage workspaces, configure environments, and control who can access each tenant's projects. Four summary cards count tenants by environment: **Total tenants**, **Production**, **Staging**, and **Development**. Each tenant card shows its name, description, member count, project count, an environment badge, and your role. Use the **Search tenants** box or the **All environments** filter to narrow the list. The **Tenant actions** menu offers **Manage members**, **Add people**, **Edit tenant**, and **Delete tenant**. ### Create a tenant Click **Create tenant** and complete the form: | Field | Description | | - | - | | **Tenant name** | Workspace name, e.g. `wellness-pilot`, `research-lab` | | **Description** | Optional summary | | **Environment** | `development`, `staging`, or `production` | The tenant is created under the currently selected organization. Edit these fields later with **Edit tenant**. ### Add people to a tenant Use the **Add people** action to invite someone to this tenant by email. See [Members & roles → Tenant members](/platform/members-and-roles#tenant-members) for roles and the full invitation flow. ### Delete a tenant The **Delete tenant** action permanently removes the tenant. > [!WARNING] > > This will permanently delete the tenant and cannot be undone. Projects and data inside the tenant are removed with it. *** ## Troubleshooting | Symptom | Likely cause | What to check | | - | - | - | | Lists empty after switching org | Tenant selection was cleared | Pick a tenant in the sidebar switcher | | **Could not load tenants** | Your account lacks workspace access | Ask an org admin to invite you to a tenant or project | | **No tenant yet** (org owner/admin) | Org has no tenants | **Create your first tenant**, then retry | | Can't edit or delete the org | Insufficient permissions | Contact the organization owner to adjust your role | *** ## Next > [card] [Members & roles](/platform/members-and-roles) > > Invite people, assign roles, and manage invitations across orgs, tenants, and projects. > [card] [Projects](/platform/projects) > > Create projects inside a tenant and organize your apps and sessions. > [card] [Billing & usage](/platform/billing) > > Choose a plan, monitor metered usage, and manage your subscription. > [card] [Developer portal](/platform/developer-portal) > > Sign in, register apps, and request the access your integration needs. # Synheart Platform overview Source: https://docs.synheart.ai/platform/overview What platform.synheart.ai is, what lives there, and how it fits with the Synheart SDKs `synheart-platform` is the web console at [`platform.synheart.ai`](https://platform.synheart.ai). It's where you create an **organization**, work inside **tenants** and **projects**, register **Apps**, generate API keys, and inspect the sessions and biosignals your integrations produce. If you're using any cloud-backed Synheart feature (installing the runtime, ingesting biosignals, viewing analytics), your CLI and SDKs authenticate against this platform. ## What it owns * **Identity & access**: sign-in, organizations, tenants, members, and invitations. * **Developer portal**: register apps, manage projects and the devices that feed them. * **API keys**: issue, scope, rotate, and revoke keys used by the SDKs and your own backend. * **Session data**: sessions, biosignals, and emotion events your apps produce surface here once ingested. * **Ingestion allowlisting**: Synheart approves which apps may stream biosignals; approved apps can use their key against the ingestion endpoints. ## What it does not own * **On-device intelligence**: the HSI runtime and the Synheart SDKs run in your app, not on the platform. See [Synheart Core](/synheart-core/overview). * **Device adapters**: biometrics are captured by [Synheart Wear](/synheart-wear/overview). * **Crypto and signing**: handled by [Synheart Auth](/synheart-auth/overview). ## The hierarchy Resources nest from the account boundary down to individual apps. From the outside in: ```text theme={null} Organization └── Tenant └── Project ├── Apps ├── Wearables (devices) └── Sessions (usage + biosignals) ``` * **Organization**: The top-level account for your company or business. It manages billing, members, permissions, and every resource underneath it. * **Tenant**: An isolated workspace inside the organization, often a department, client, environment, or business unit. Each tenant keeps its data and configuration separated from others. * **Project**: A logical grouping inside a tenant for applications, services, and configuration tied to one product or initiative. * **App**: A mobile or web application registered on the platform. The dashboard assigns each App a platform `app_id` (a short code such as `app_focus_and_kB8mPx`); integrations, [attestation](/platform/app-attestation), and API keys are configured at the app level. * **Wearable**: A device assigned to a project (Apple Watch, Garmin, Fitbit, etc.). * **Session**: A single usage event with timestamps, biosignals, and emotion events. API keys are minted per app and owned by an organization. Access checks run against your org membership and project ownership. ## How it fits with the rest > [card] [CLI](/cli/overview) > > `synheart login` signs the CLI in to your platform account via OAuth Device Flow. > [card] [Synheart Core](/synheart-core/overview) > > The runtime fetches its native artifacts from the platform registry once you're authenticated. > [card] [Synheart Auth](/synheart-auth/overview) > > Devices register against the platform's auth service and sign every outbound request. > [card] [Synheart Session](/synheart-session/overview) > > Sessions you record on-device surface in the platform once ingestion is approved. ## Reading order ### Set up your workspace > [card] [Developer portal](/platform/developer-portal) > > Sign in, create an org, register apps. > [card] [Organizations & tenants](/platform/organizations-and-tenants) > > Create and manage the org and tenant workspaces that hold your projects. > [card] [Members & roles](/platform/members-and-roles) > > Invite people and assign roles across orgs, tenants, and projects. > [card] [Projects](/platform/projects) > > Organize apps, devices, and sessions inside a project. ### Configure your apps > [card] [Apps register & manage](/platform/apps) > > Register apps, find credentials, and edit or remove them. > [card] [API keys](/platform/api-keys) > > Generate, scope, rotate, and revoke per-app keys for the SDKs and your backend. > [card] [App attestation](/platform/app-attestation) > > Verify real, unmodified apps with Play Integrity (Android) and App Attest (iOS). > [card] [App policy](/platform/app-policy) > > Configure what data your app may collect and where it may be processed. > [card] [Consent profiles](/platform/consent-profiles) > > Define the consent options your SDK offers end users. > [card] [Syni](/platform/syni) > > Enable the Syni AI coach per app and pick its personas. ### Work with your data > [card] [Connect & view data](/platform/connect-and-view-data) > > Step-by-step: sign in, connect a wearable OAuth integration, and inspect imported session data. > [card] [Personas](/platform/personas) > > Create companion personas for Syni-powered experiences. > [card] [Research studies](/platform/studies) > > Run cohorts with access codes, enrolment, and data export. > [card] [Exports](/platform/exports) > > Export HSI and Lab data in batch as downloadable archives. ### Manage the account > [card] [Billing & usage](/platform/billing) > > Choose a plan, monitor metered usage, and manage your subscription. > [card] [Account & security](/platform/account) > > Manage your profile, password, two-factor authentication, and invitations. # Personas Source: https://docs.synheart.ai/platform/personas Create and manage Syni companion personas for a project on the Synheart Platform Personas are the companion identities behind [Syni](/platform/syni)-powered experiences. Each persona defines how the assistant presents itself (its name, description, tone, safety mode, and behavioral rules) for a specific app in a project. Open them from the project sidebar: **Personas**. The page subtitle reads *"Companion personas for syni-powered experiences in this project."* > [!NOTE] > > Personas are configured at the **project** level and bound to an **app**. Which personas an app may actually use is controlled per app under [Syni → Persona allowlist](/platform/syni#persona-allowlist). ## Persona types | Type | Editable? | Source | | - | - | - | | **default** | No (read-only) | Provided by the Synheart Syni service | | **custom** | Yes: create, edit, delete | Created by you in this project | Default personas always exist so an app has something to fall back on; you build **custom** personas to tailor the experience. *** ## The personas list Personas appear as cards with a count header and a **Refresh** action. Each card shows the persona's **name**, a **type badge** (default or custom), a **Safety on** badge when safety mode is enabled, the unique **key** in monospace, its **description**, and its **tone**. **Edit** and **Delete** appear only on custom personas. If the project has no apps yet, the create modal shows *"No apps in this project. Create an app first."* *** ## Create a persona Click **Create persona** and complete the modal: | Form field | Description | | - | - | | **App** | The app this persona belongs to (required) | | **Name** | Display name (required) | | **Persona key** | Unique key, e.g. `my.coach.v1` (required, fixed after creation) | | **Description** | What the persona is and how it behaves | | **Tone** | The conversational tone | | **Safety mode** | Enabled by default; keeps responses within safety guardrails | ### Behavioral rules Optionally add **Rules**; each rule has a **Condition**, an **Action**, and a **Description**. Use **Add rule** to add more and **Remove** to drop one. Empty rules are discarded on save. | Rule field | Description | | - | - | | **Condition** | When the rule applies | | **Action** | What the persona should do | | **Description** | Human-readable note | > [!NOTE] > > Persona behavior is expressed through **description**, **tone**, and **rules**. The dashboard does not expose a raw system prompt, voice, or avatar; those are not part of the persona model today. *** ## Edit and delete * **Edit**: change any field except the **persona key**, which stays read-only. Editing requires the persona's app to be known (it's selected automatically for app-bound personas). * **Delete**: *"Delete "" ()? This cannot be undone."* > [!WARNING] > > Default personas cannot be edited or deleted from the dashboard. Build a custom persona instead if you need different behavior. *** ## How personas relate to Syni Personas are the menu of identities; the per-app [Syni settings](/platform/syni) decide which of them an app may use: ```text theme={null} Project Personas → define companions (name, tone, rules) │ ▼ App → Syni → Persona allowlist → restrict which personas this app may use ``` An empty allowlist on the Syni page means the app may use **all** project personas. To restrict an app to specific personas, select their keys there. *** ## Next > [card] [Syni](/platform/syni) > > Enable Syni per app, set the execution mode, and restrict the persona allowlist. > [card] [App policy](/platform/app-policy) > > The `Allow Syni` flag that gates Syni access for an app. > [card] [Consent profiles](/platform/consent-profiles) > > Offer Syni as a consent option to end users. # Projects Source: https://docs.synheart.ai/platform/projects Organize apps and sessions inside a Synheart Platform project Projects are the unit of work in the platform. They group the apps you've registered and the sessions those apps produce. Every project lives inside a [tenant](/platform/organizations-and-tenants) inside an organization, a logical grouping for one product or initiative. ```text theme={null} Project ├── Apps (one or more registered Apps, each with its own platform `app_id`) └── Sessions (usage events with biosignals + emotions) ``` ## Create a project From the developer portal, open **Projects** and choose **New project**. You'll set: * **Name** and optional **description**. * **Region**: where this project's data is stored. New projects default to **N. Virginia (`us-east-1`)**. Choosing a different region is an **Enterprise** feature; Enterprise plans can pick from the standard region list (e.g. `eu-west-1`, `ap-southeast-2`, `ca-central-1`). Need a region that isn't listed? Contact support. * **Tenant**: which tenant workspace inside your org owns the project. * **Status**: `active`, `archived`, or `setup_incomplete` for a project you're still wiring up. A project starts empty. Add apps next. ## Add apps to a project Each registered App in a project has a platform `app_id` assigned by the dashboard. Register one from inside the project; see [Register an app](/platform/developer-portal#register-an-app). One project can hold multiple apps; a given `app_id` belongs to exactly one project at a time. ## Wearables For connecting wearable integrations and viewing the data they produce, see [Connect wearables & view data](/platform/connect-and-view-data), which covers the full setup flow end to end. ## Sessions A session is one usage event captured on-device and ingested into the platform. Sessions surface under the project's **Sessions** tab once the apps in the project ingest them via an allowlisted API key. See [API keys → Ingestion access](/platform/api-keys#ingestion-access) for how that allowlist works, and [Synheart Session](/synheart-session/overview) for how sessions are produced on-device. ## Project settings Each project exposes a settings page for renaming, archiving, and managing access. Archive projects you're no longer working in rather than deleting them; archived projects stay readable but step out of the active list. ## Patterns that work well * **One project per environment**: keep dev, staging, and prod data isolated. * **Project per study or cohort**: for research, give each cohort its own project so you can scope keys and access cleanly. ## Next > [card] [API keys](/platform/api-keys) > > Generate scoped keys for the apps in your project. > [card] [Connect wearables & view data](/platform/connect-and-view-data) > > Connect a wearable integration and explore the session data it produces. > [card] [Synheart Session](/synheart-session/overview) > > See how sessions are produced on-device before they reach the platform. # Research studies Source: https://docs.synheart.ai/platform/studies Manage research cohorts, access codes, and participant enrolment for a project on the Synheart Platform Research studies let you run structured data collection inside a project: define **cohorts**, issue **access codes** participants redeem to enrol, track **enrolment**, and **export** the resulting data. It's the platform surface for IRB-style research and lab studies. Open it from the project sidebar: **Studies**. The page subtitle reads *"Manage research cohorts, access codes, and enrolment for this project. Available on the research plan."* > [!NOTE] > > Studies are a **research-plan** feature. If your organization isn't entitled, the page shows: *"Cohort management (studies, access codes, enrolment) is a research-plan feature. Upgrade this organization's plan, or ask Synheart to enable research-studies access, to manage cohorts here."* See [Billing & usage](/platform/billing). ## How it fits together ```text theme={null} Cohort (study) ├── Access codes: issued in bulk, redeemed by participants to enrol ├── Participants: enrolment records (consent, status, sessions) └── Export: download HSI + lab data for the cohort or one participant ``` A cohort defines the study parameters and compensation shown to participants on the consent screen. Access codes are how people join. Each enrolment row tracks consent and progress. Data flows out through the shared [export](/platform/exports) pipeline, pre-scoped to the cohort. *** ## Create a cohort Fill in the **Create cohort** form at the top of the page: | Form field | Description | | - | - | | **Cohort code** | Unique short code, e.g. `COHORT1` | | **Name** | Human-readable study name, e.g. `MILA Study` | | **App ID** (optional) | Restrict the cohort to one app | | **Device** | Either device, Polar, or Garmin | | **Duration (days)** | Study length per participant (default 30) | | **Enrolment cap** | Maximum participants (0 = uncapped) | Under **Compensation (shown to participants on the consent screen)** you can set: | Form field | Description | | - | - | | **Currency** | e.g. `CAD` | | **Completion bonus** | Paid at end of study | | **Per valid session** | Per qualifying session | | **Daily completeness** | For meeting daily data targets | Click **Create cohort**. New cohorts are created in the **open** status, ready to accept participants. *** ## Manage cohorts The **Cohorts** table lists every cohort with a count header and a **Filter cohorts by code or name** search box. | Column | Meaning | | - | - | | **Code** | Cohort identifier | | **Name** | Study name | | **Status** | Open or closed (toggled from this row) | | **Device** | Allowed device(s) | | **Days** | Study length | | **Cap** | Max participants (none when uncapped) | | **App** | Linked app, or none | Each row offers **Codes**, **Participants**, **Edit**, **Export**, and a **Close**/**Open** toggle. > [!TIP] > > Use **Close** to stop new enrolments without deleting the cohort. You can reopen it later. **Edit** lets you change the name, device, duration, cap, and compensation; the cohort code and app are fixed after creation. *** ## Access codes Click **Codes** on a cohort to open the access-codes panel. Set a count and click **Issue codes** to mint a batch; the newly issued codes are listed so you can distribute them. Use the search box to filter by code or participant. | Column | Meaning | | - | - | | **Code** | The redeemable access code | | **Status** | Active, claimed, or revoked | | **Claimed by** | Participant who redeemed it, or none | | **Actions** | **Export** (when claimed) | *** ## Participants & enrolment Click **Participants** on a cohort to review enrolment records. | Column | Meaning | | - | - | | **Participant** | Enrolment identifier | | **Status** | invited, consented, active, completed, withdrawn, or disqualified | | **Sessions** | Sessions attributed to the participant | | **Consented** | When consent was given, or not yet | | **Started** | When the study started for them, or not yet | | **Eligible** | Yes or no | | **Consent ver.** | Consent profile version agreed to, or none | Use **Withdraw** on a consented or active participant to stop attributing new sessions to the study. > [!WARNING] > > *"Withdraw this participant? Their new sessions stop being attributed to the study. Already-collected data is not deleted."* *** ## Export cohort data Both the cohort **Export** action and a participant's **Export** action open the shared **Export data** dialog, pre-scoped to the study (and participant where applicable). Choose an optional date range and a format: **NDJSON (recommended, lossless)**, **CSV (flattened, analyst-friendly)**, or **Both**. Then click **Start export**. Track progress and download from the [Exports](/platform/exports) page. *** ## Next > [card] [Exports](/platform/exports) > > Track export jobs and download the archives studies produce. > [card] [Consent profiles](/platform/consent-profiles) > > Define the consent options participants agree to at enrolment. > [card] [Connect & view data](/platform/connect-and-view-data) > > Inspect the sessions participants generate. > [card] [Billing & usage](/platform/billing) > > Check your plan and entitlements for research studies. # Syni Source: https://docs.synheart.ai/platform/syni Configure Syni AI coach settings per app, including execution mode, token limits, and the persona allowlist Syni is the Synheart AI coach. The per-app **Syni** page controls whether an app may use Syni, how Syni runs, and which [personas](/platform/personas) it may use. Open it from the app sidebar: **Syni**. The page subtitle reads *"Syni settings for . Controls which personas this app may use and default execution mode."* > [!NOTE] > > This page is the **operational** toggle for an app. Syni access is also gated by the [App policy](/platform/app-policy) `Allow Syni` flag, the [consent profile](/platform/consent-profiles) Syni option, and your platform plan. All layers must allow Syni for it to work end-to-end. > [!WARNING] > > Select an **organization** and **tenant** before configuring Syni; otherwise the page shows *"Select an organization and tenant to configure Syni for this app."* ## Settings The page is a single settings card. Edit the fields and click **Save** (or **Reset** to reload the saved values): | Setting | Description | | - | - | | **Enable Syni for this app** | Master on/off for Syni in this app | | **Default execution mode** | Where Syni runs by default: **Cloud**, **On device**, or **Auto** | | **Max tokens** (optional) | Optional per-response token ceiling; leave empty for no limit | | **Persona allowlist** | Which personas this app may use | On a successful save you'll see **Settings saved.** ### Execution mode | Mode | Behavior | | - | - | | **Cloud** | Syni runs in the cloud | | **On device** | Syni runs on the device | | **Auto** | The runtime chooses based on context | ### Persona allowlist The allowlist restricts which [project personas](/platform/personas) this app may use. Each available persona is listed with its name and key as a checkbox. > [!TIP] > > Leave the allowlist **empty to allow all project personas**. Select specific keys to restrict the app to those personas only. If you see *"No personas loaded for this project. Create personas under Project → Personas."*, add personas first. *** ## How Syni gating composes Syni works only when every layer permits it: ```text theme={null} Platform plan (syni entitlement) └── App policy → Allow Syni └── Consent profile → Allow Syni (offered to user) └── App Syni settings → Enable Syni (+ persona allowlist) └── End user grants consent ``` * **App policy** caps what the app may offer; see [App policy → Allow Syni](/platform/app-policy#general-settings). * **Consent profile** decides whether Syni is offered to the end user; see [Consent profiles](/platform/consent-profiles). * **This page** is the operational switch plus persona and execution controls. *** ## Next > [card] [Personas](/platform/personas) > > Create the companion personas this app's allowlist points at. > [card] [App policy](/platform/app-policy) > > Enable the `Allow Syni` flag that this page depends on. > [card] [Consent profiles](/platform/consent-profiles) > > Offer Syni to end users during the consent flow. > [card] [Billing & usage](/platform/billing) > > Monitor Syni message and token usage against your plan. # Behavior SDK privacy Source: https://docs.synheart.ai/privacy/behavior What the Synheart Behavior SDK collects, what it never collects, and what your app needs to declare This page describes the privacy properties of the current Behavior SDK releases: Flutter 0.4.1, Kotlin 0.6.0 and Swift 0.5.0. The SDK records **when** and **how** someone interacts with your app, never **what** they see or type. It captures no text, no screen content and no tap coordinates. Everything is processed on the device. ## At a glance | Area | What the SDK does | | - | - | | Text and screen content | Never captured. | | Tap and scroll positions | Never captured. Only durations, counts and velocity magnitudes. | | Personal identifiers | None. Session IDs are generated per session. | | Device identifiers | None. No advertising IDs, IMEI, MAC address or vendor IDs. | | Network | The SDK makes no network requests. | | Storage | Events are held in memory and released when the session ends. | | Third-party SDKs | No analytics or tracking libraries. | ## What is collected ### Interaction timing * **Taps:** tap duration and whether it was a long press. Taps are not counted while the keyboard is open, so typing is not double-counted. * **Scrolls and swipes:** velocity, acceleration, jitter and stop events. * **Typing:** timing only: speed, cadence, gaps, burstiness and a backspace count. The characters typed are never read. * **Clipboard:** counts of copy, paste and cut actions that your app reports. The clipboard's contents are never read. ### Attention signals * **App switches:** foreground and background transitions with their durations. App-switch events do not name other apps. * **Idle gaps:** periods without interaction. * **Notifications:** delivery, opening and ignore counts. On Android, notification events include `source_app`, the package name of the app that posted the notification. Notification titles and text are never read. * **Calls:** call counts and whether they were answered or ignored. No phone numbers or contacts. ### Session context Session summaries can include coarse device state such as screen brightness, orientation, whether the device is charging, Do Not Disturb, and whether it is online. The online check reads Android's connectivity state; it sends nothing. ### Motion (opt-in) * **Kotlin:** with `enableMotionLite`, the SDK reads the accelerometer and gyroscope at 50 Hz and classifies motion on the device. * **Flutter and Swift:** raw 50 Hz accelerometer samples are emitted only when `emitRawMotionSamples` is set. ## What is never collected * Text the user types or reads, and screen content * Tap, touch or scroll coordinates * Notification titles or bodies * Phone numbers, contacts or call audio * Location, camera, microphone or photos * Advertising IDs or other persistent device identifiers * Biometric data ## Permissions Basic interaction capture needs no runtime permission. Notification and call signals use optional permissions. ### Android The libraries declare these permissions in their own manifests, which merge into your app: | SDK | Permissions | | - | - | | Flutter | `BIND_NOTIFICATION_LISTENER_SERVICE`, `READ_PHONE_STATE`, and the notification listener service | | Kotlin | `BIND_NOTIFICATION_LISTENER_SERVICE`, `ACCESS_NETWORK_STATE`, and the notification listener service | If you don't use notification or call signals, remove the entries from your merged manifest: ```xml theme={null} ``` The notification listener only runs after the user enables it in system settings. ### iOS No Info.plist usage descriptions are required. * **Calls** are observed through CallKit (`CXCallObserver`), on by default with `enableAttentionSignals`. * **Notifications** come from `UNUserNotificationCenter` callbacks that your app forwards, or from the SDK's opt-in delegate (`installNotificationDelegate`). ## User control Each signal family has its own switch in `BehaviorConfig`: | Flag | Controls | | - | - | | `enableInputSignals` | Taps, scrolls, swipes and typing timing | | `enableAttentionSignals` | App switches, idle gaps, notifications and calls | | `enableMotionLite` | On-device motion classification (Kotlin) | | `emitRawMotionSamples` | Raw accelerometer samples (Flutter, Swift) | Ask for consent before you call `initialize()` or `startSession()`. The `consentBehavior` field is recorded in event payloads but does not itself stop collection. When behavior events feed into [Synheart Core](/synheart-core/overview), the runtime's `Behavior` consent gate also applies; see [Consent System](/synheart-core/consent-system). ```dart theme={null} final behavior = await SynheartBehavior.initialize( config: BehaviorConfig( enableInputSignals: userAllowsInteraction, enableAttentionSignals: userAllowsAttention, enableMotionLite: false, ), ); ``` ## Regulatory considerations The SDK is built around data minimization: timing metrics only, processed on the device, with no identifiers. Whether your app meets GDPR, CCPA, COPPA or another regulation depends on how the app as a whole collects, uses and shares data, and how it obtains consent. Consult counsel for your deployment. * **App Tracking Transparency (iOS):** the SDK does no cross-app tracking and reads no advertising identifier. * **Privacy Sandbox (Android):** the SDK does not use advertising IDs or share data with third parties. ## Privacy notice template Adapt this to what your app actually enables: ```text theme={null} We measure how you interact with the app to improve your experience, such as how long you tap and how fast you scroll. We do not collect what you type, where you tap, or the content of your screen or notifications. This data is processed on your device. ``` ## Related * [Threat Model](/synheart-behavior/threat-model) * [Behavior Overview](/synheart-behavior/overview) * [Consent System](/synheart-core/consent-system) # Quickstart Source: https://docs.synheart.ai/quickstart Build your first Synheart integration This guide takes you from a fresh machine to a working Synheart integration. Pick the track that matches what you're building. ## Pick a track **Track A** if you want a single, fused human-state signal (focus, emotion, capacity, recovery, strain, sleep) — typically because you're building a wellness, productivity, or coaching app that already pulls data from a wearable and wants higher-level inference on top. **Track B** if you only need one channel of data — wearable readings, behavior events, or session frames — and want to wire it into your own pipeline. No CLI, no runtime, no platform account. > [card] [Track A — Synheart Core (HSI)](#track-a) > > Multimodal human-state inference on-device. Requires CLI, platform account, and the runtime. > [card] [Track B — Standalone module](#track-b) > > Just `synheart_wear`, `synheart_behavior`, or `synheart_session`. No CLI required. ## Track A Synheart Core (HSI). Use this track when you want fused human-state output (focus, emotion, capacity, recovery, strain, sleep) from biosignals + behavior + phone context. ### 1. Install the CLI ```bash theme={null} curl -fsSL https://synheart.sh/install | bash ``` Windows (PowerShell): ```powershell theme={null} iwr -useb https://synheart.sh/install.ps1 | iex ``` Verify: ```bash theme={null} synheart version ``` [Full install guide →](/setup/install-cli) ### 2. Create a platform account Sign up at [platform.synheart.ai](https://platform.synheart.ai) (email + password, or Google, Apple, or GitHub). Signup is self-serve and starts on the free tier. [Account setup →](/setup/create-account) ### 3. Authenticate the CLI ```bash theme={null} synheart login ``` Follow the device-flow prompt to sign in. Confirm: ```bash theme={null} synheart whoami ``` [Authentication details →](/setup/authenticate) ### 4. Install the runtime From your project root: ```bash theme={null} synheart install runtime --version 0.46.0 ``` This downloads the native HSI engine and writes `synheart.lock`. Commit the lockfile so teammates and CI can run `synheart sync`. Run `synheart doctor` to check the installed runtime against your SDK. [Runtime install guide →](/setup/install-runtime) ### 5. Initialize Synheart Core > [accordion] Flutter / Dart > > ```yaml theme={null} > # pubspec.yaml > dependencies: > synheart_core: ^0.23.0 > ``` > > ```dart theme={null} > import 'package:synheart_core/synheart_core.dart'; > > await Synheart.initialize( > config: SynheartConfig( > appId: 'com.example.app', > subjectId: 'anon_user_123', > allowUnsignedCapabilities: true, // development only; use deviceAuthConfig in production > wearConfig: const WearConfig(), > ), > ); > > Synheart.onHSIUpdate.listen((hsiJson) { > print('HSI: $hsiJson'); > }); > ``` > [accordion] Android (Kotlin) > > ```kotlin theme={null} > // build.gradle.kts > dependencies { > implementation("ai.synheart:synheart-core:0.8.0") > } > ``` > > ```kotlin theme={null} > import ai.synheart.core.Synheart > import ai.synheart.core.config.SynheartConfig > import ai.synheart.core.config.WearConfig > > Synheart.initialize( > context = context, > config = SynheartConfig( > appId = "com.example.app", > subjectId = "anon_user_123", > allowUnsignedCapabilities = true, // development only; use deviceAuthConfig in production > wearConfig = WearConfig(), > ), > ) > > Synheart.grantConsent("biosignals") > Synheart.startSession() > > Synheart.onHSIUpdate.collect { hsiJson -> > println("HSI: $hsiJson") > } > ``` > [accordion] iOS (Swift) > > ```swift theme={null} > // Package.swift > .package(url: "https://github.com/synheart-ai/synheart-core-swift.git", from: "0.7.1") > ``` > > ```swift theme={null} > import SynheartCore > import Combine > > var cancellables = Set() > > try await Synheart.initialize( > config: SynheartConfig( > appId: "com.example.app", > subjectId: "anon_user_123", > allowUnsignedCapabilities: true // development only; use deviceAuthConfig in production > ), > userId: "anon_user_123" > ) > > Synheart.onHSIUpdate > .sink { hsiJson in print("HSI: \(hsiJson)") } > .store(in: &cancellables) > ``` > [!NOTE] > > `initialize` throws when the installed runtime doesn't match the SDK (current SDKs need runtime 0.45.0 or later and recommend 0.46.0): `SynheartRuntimeException` on Flutter and Kotlin, `SynheartRuntimeError` on Swift. The error's `installCommand` is the exact command that fixes it. On Flutter and Kotlin a missing runtime doesn't throw: the SDK starts without HSI and `Synheart.runtimeError` says why. On Swift, a runtime that isn't linked throws `SynheartError.runtimeIncompatible`. ### 6. Test locally with mock data (optional) ```bash theme={null} synheart init # optional: write .synheart/config.yaml for this project synheart local # mock platform server (consent + ingest APIs) synheart mock start # mock wearable stream on ws://127.0.0.1:8787/hsi ``` [CLI reference →](/cli/overview) ## Track B Standalone module. If you only need a single signal channel and don't need fused HSI output, install just that SDK. No CLI, account, or runtime needed. > [card] [Synheart Wear](/synheart-wear/overview) > > Biosignals from Apple Watch, WHOOP, Garmin, Fitbit, BLE HRMs. > [card] [Synheart Behavior](/synheart-behavior/overview) > > Tap, scroll, type, and motion patterns — content-free. > [card] [Synheart Session](/synheart-session/overview) > > Time-bounded sessions with HR + behavioral metrics on-device. Quick example — `synheart_wear` in Flutter: ```yaml theme={null} dependencies: synheart_wear: ^0.6.2 ``` ```dart theme={null} import 'package:synheart_wear/synheart_wear.dart'; final synheart = SynheartWear( config: SynheartWearConfig.withAdapters({DeviceAdapter.platformHealth}), ); await synheart.initialize(); synheart.streamHR(interval: const Duration(seconds: 5)).listen((m) { print('HR: ${m.getMetric(MetricType.hr)}'); }); ``` ## How it fits together 1. **CLI** authenticates you, manages the runtime artifact, and runs local mocks for development. 2. **Runtime** is the native on-device engine that computes HSI. The Core SDK loads it at startup. 3. **Core SDK** (Flutter / Kotlin / Swift) coordinates signal collection, drives the runtime, and exposes reactive streams. 4. **Modules** (`synheart_wear`, `synheart_behavior`, `synheart_session`) can be used standalone or composed under Core. ## Privacy posture > [card] On-device > > Inference runs locally — no biosignal content leaves the device. > [card] Consent-gated > > Cloud uploads require explicit user consent and capability tokens. > [card] Content-free > > No text, audio, screen content, or PII is ever captured. ## Next > [card] [Synheart Core](/synheart-core/overview) > > Architecture, HSI/HSV spec, capabilities, consent. > [card] [CLI reference](/cli/overview) > > Mock streams, local platform, install, sync, receiver. > [card] [Modules](/synheart-wear/overview) > > Wear, Behavior, Session details. > [card] [Troubleshooting](/guides/troubleshooting) > > Common issues and fixes. # RAMEN 🍜 overview Source: https://docs.synheart.ai/ramen/overview Real-time event delivery backplane — how clients subscribe to vendor and platform events **RAMEN 🍜** (**R**eal-time **A**synchronous **M**essage **E**vent **N**etwork) is the streaming backplane the Synheart platform uses to push events to connected clients in real time. Clients open a long-lived gRPC stream, subscribe to event types, and receive ordered events with at-least-once delivery and a replay window for catching up after disconnects. This page covers what hosts and apps need to know to **consume** RAMEN events. Broker-side internals are not part of the public surface — only the subscribe / delivery contract is. ## What you can subscribe to The most common subscriptions: * **Vendor webhooks normalized to HSI** — WHOOP, Garmin, Fitbit events arrive as HSI snapshots once normalized. * **HSI snapshots ingested from your own SDK** — useful for cross-device fan-out (e.g. desktop dashboard reading state pushed from a phone). * **Lab session export confirmations** — when running [Lab Mode](/lab/overview). ## Endpoints * **Gateway**: gRPC on `:8083` via the platform endpoint. * **Subscribe**: bidirectional gRPC stream. Clients send a subscription envelope with `app_id`, `subject_id`, and a list of event types and providers; RAMEN streams matching events back. * **Replay**: unary gRPC. Provide the last sequence you saw; RAMEN returns events with `seq > last_seq` from the replay store, then you resume the live stream. ## Connection lifecycle 1. **Authenticate** with a JWT or app API key. 2. **Subscribe** with desired filters; you receive a `connection_id` and a starting sequence. 3. **Heartbeat** every \~30 s to keep the connection registered. Missed heartbeats reap the connection after 5 minutes. 4. On disconnect, **call Replay** with your last `seq` before reopening the subscription to avoid gaps. ## Consent and capabilities RAMEN is gated by both: * **Capability**: `cloud` capability tier on the consent token (subscribing without the token returns `401`). * **Per-type consent**: `vendorSync` for vendor-webhook subscriptions, `cloudUpload` for the rest. See [Consent System](/synheart-core/consent-system) for the wire strings. ## Backpressure and ordering * Events are delivered **per `app_id` + `subject_id`** in `seq` order. * Slow consumers get backpressured by the fan-out worker pool; the platform will drop the connection if the consumer falls more than 5 minutes behind, expecting Replay on reconnect. * At-least-once delivery — clients are expected to dedupe by `seq` (monotonic, gap-free per stream). ## When to use RAMEN * You're building a real-time dashboard or live coaching surface. * You're replicating Synheart-Core HSI streams across multiple devices owned by the same subject. * You're consuming WHOOP / Garmin webhook events server-side without running your own wearable webhook handler. If you only need periodic snapshots, the standard `/ingest/v1/hsi` POST flow + a polling read-API is simpler. # 3. Authenticate the CLI Source: https://docs.synheart.ai/setup/authenticate Sign the CLI in to your Synheart platform account Once you have a platform account, authenticate the CLI so it can install the runtime and other artifacts from the registry. ## Sign in ```bash theme={null} synheart login ``` The CLI uses **OAuth 2.0 Device Flow**: 1. The CLI prints a URL and a one-time code. 2. Open the URL in your browser. 3. Sign in to [`platform.synheart.ai`](https://platform.synheart.ai) and confirm the code. 4. The CLI receives a token and stores it securely. ### Where credentials are stored * **macOS**: Keychain. * **Windows**: Credential Manager. * **Linux**: Secret Service (libsecret-compatible). On headless or container Linux without a Secret Service daemon, the CLI falls back to an encrypted file at `~/.synheart/credentials.enc`. ## Verify ```bash theme={null} synheart whoami synheart auth status # token expiry, refresh state ``` ## Sign out ```bash theme={null} synheart logout # remove local credentials synheart logout --revoke # also revoke the token on the server ``` ## Enterprise gateways The CLI talks to `https://api.synheart.ai` by default, and that's the only endpoint supported on standard builds. Pointing the CLI elsewhere requires either an enterprise plan (which enables `SYNHEART_API_URL` so the same binary can target your dedicated Synheart gateway) or rebuilding the CLI from source against your own endpoint. Once `SYNHEART_API_URL` is enabled for your account, the value is picked up by `login`, `install`, `sync`, `whoami`, and `auth status`. ## Next > [card] [Install the runtime](/setup/install-runtime) > > Download the on-device HSI runtime that powers Synheart Core. # 2. Create a platform account Source: https://docs.synheart.ai/setup/create-account Create your Synheart platform account You need a platform account to authenticate the CLI, install the runtime, and use any cloud-backed features. Signup is self-serve: no invite or approval is needed, and new accounts start on the free tier. ## Create your account Sign up at [`platform.synheart.ai`](https://platform.synheart.ai) using either: * **Email + password**. Verify your email address before you sign in. * **OAuth**: sign in with Google, Apple, or GitHub. To join an existing organization instead of creating your own, ask its owner or an admin to send you an invitation. The same credentials are used by `synheart login` in the next step. ## Next > [card] [Authenticate the CLI](/setup/authenticate) > > Sign the CLI in to your platform account with `synheart login`. # 1. Install the CLI Source: https://docs.synheart.ai/setup/install-cli Install synheart-cli on macOS, Linux, or Windows `synheart-cli` is the entry point for working with the Synheart platform. It installs the on-device runtime, runs a local mock platform, generates wearable data, and authenticates you against `platform.synheart.ai`. ## Install > [tab] macOS / Linux > > ```bash theme={null} > curl -fsSL https://synheart.sh/install | bash > ``` > [tab] Windows (PowerShell) > > ```powershell theme={null} > iwr -useb https://synheart.sh/install.ps1 | iex > ``` ## Add to PATH The installer prints the install directory it chose. Defaults — `~/.local/bin` on macOS / Linux and `%LOCALAPPDATA%\synheart\bin` on Windows. Override either default with the `SYNHEART_INSTALL_DIR` environment variable before running the installer. If `synheart` is not found after install, add the install directory to your shell profile. > [tab] bash > > ```bash theme={null} > echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc > source ~/.bashrc > ``` > [tab] zsh > > ```bash theme={null} > echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc > source ~/.zshrc > ``` > [tab] fish > > ```bash theme={null} > set -U fish_user_paths $HOME/.local/bin $fish_user_paths > ``` > [tab] Windows > > ```powershell theme={null} > setx PATH "$env:PATH;$env:LOCALAPPDATA\synheart\bin" > ``` > > Restart PowerShell after running `setx`. ## Verify ```bash theme={null} synheart version synheart --help ``` If both commands print output, the CLI is installed. ## Next > [card] [Create a platform account](/setup/create-account) > > Sign up at platform.synheart.ai to continue. # 4. Install the runtime Source: https://docs.synheart.ai/setup/install-runtime Install the on-device HSI runtime required by Synheart Core The **Synheart Runtime** is the native engine that performs on-device human-state inference. The Synheart Core SDK loads it across the native bridge at startup, so it must be installed in your project before you initialize Core. > [!NOTE] > > The runtime is **required for Synheart Core**. Standalone use of `synheart_wear`, `synheart_behavior`, or `synheart_session` does not require the runtime — see [Quickstart](/quickstart) for the standalone tracks. ## Install From your project root: ```bash theme={null} synheart install runtime --version 0.46.0 ``` Use the version your SDK release needs; see [Which version](#which-version). This: * Downloads the runtime artifact for your project's platforms (all of them unless you pass `--platform`). * Writes a `synheart.lock` file pinning the exact versions. * Places the native binaries under `synheart/vendor/runtime/`. Flutter and iOS pick them up automatically; an Android-native (Kotlin) app points `jniLibs.srcDirs` at `synheart/vendor/runtime/android/jniLibs` (see [Kotlin setup](/synheart-core/kotlin)). ## Which version Each SDK release is verified against one runtime release, and its install hints and error messages print that version. The runtime's C ABI version decides what loads: | SDK | Recommended runtime | Accepts | | - | - | - | | Flutter `synheart_core` 0.22.1 and later · Kotlin `ai.synheart:synheart-core` 0.7.1 and later · Swift `SynheartCore` 0.7.1 | `0.46.0` | C ABI 4.2 (runtime 0.45.0 and later) | | Flutter 0.22.0 · Kotlin and Swift 0.6.0–0.7.0 | `0.45.0` | C ABI 4.2 (runtime 0.45.0 and later) | | Flutter 0.21 | `0.43.0` | C ABI 4.x (runtime 0.42.0 and later) | | Flutter 0.20 · Kotlin and Swift 0.5 | `0.42.1` | C ABI 4.x (runtime 0.42.0 and later) | | Older SDKs (Flutter 0.19 and earlier, Kotlin and Swift 0.4.x) | `0.41.0` (Flutter) · `0.38.0` (Kotlin, Swift) | C ABI 1.x and 2.x | `Synheart.initialize` throws when the installed runtime falls outside that range, and the error carries the exact `synheart install runtime --version …` command to fix it. Run `synheart doctor` to check the installed runtime against your SDK. > [!WARNING] > > Two boundaries don't mix in either direction. **C ABI 4.2** (runtime 0.45.0): the daily score inputs changed shape, so `synheart_core` 0.22 and Kotlin and Swift 0.6 refuse anything older than 0.45.0, and an older SDK on a newer runtime gets daily scores it cannot parse. **C ABI 4.0** (runtime 0.42): an SDK that accepts ABI 1.x–2.x refuses it, and `synheart_core` 0.20 refuses anything older. Upgrade the SDK and the runtime together. ## Channels and versions ```bash theme={null} # Install from the latest channel (default) synheart install runtime --channel latest # Install a specific version synheart install runtime --version 0.46.0 # Restrict to a single platform (default: all platforms) synheart install runtime --platform ios # ios | android # Choose a runtime variant (default: picked from your plan) synheart install runtime --variant edge # edge | stable | lab ``` > [!NOTE] > > `--channel` accepts `latest` (the default) or `stable`; `stable` may not be published yet. `--version` overrides `--channel`. ## Reproducible installs After the first install, commit `synheart.lock` to your repo. Anyone else on the project (and CI) installs the same versions with: ```bash theme={null} synheart sync ``` ## Inspect environment ```bash theme={null} synheart env synheart env --format json ``` Prints install paths, runtime version, and detected project type. ## Check and upgrade ```bash theme={null} synheart doctor # checks your setup, including runtime compatibility synheart runtime current # shows the runtime pinned in synheart.lock synheart runtime upgrade # fetches the latest runtime for your variant ``` ## Next > [card] [Build your first integration](/quickstart) > > Initialize Synheart Core and start receiving HSI updates. # Setup overview Source: https://docs.synheart.ai/setup/overview The four steps to go from zero to a working Synheart integration To build with Synheart Core, complete these four steps in order. Standalone use of `synheart_wear`, `synheart_behavior`, or `synheart_session` only requires their package — skip ahead to the [Quickstart](/quickstart) for those tracks. **1. Install the CLI** `curl -fsSL https://synheart.sh/install | bash` — see [Install the CLI](/setup/install-cli). **2. Create a platform account** Sign up at [platform.synheart.ai](https://platform.synheart.ai). Signup is self-serve. See [Create a platform account](/setup/create-account). **3. Authenticate the CLI** `synheart login` signs the CLI in via OAuth Device Flow. See [Authenticate the CLI](/setup/authenticate). **4. Install the runtime** `synheart install runtime` downloads the native HSI engine into your project. See [Install the runtime](/setup/install-runtime). Once setup is complete, jump to the [Quickstart](/quickstart) to initialize a Core SDK and start receiving HSI updates. # Set up your team Source: https://docs.synheart.ai/synapse/admin-setup Connect GitHub and your AI tools, write the team's agent rules, and turn on the weekly summary An admin does this once, in [synapse.synheart.ai](https://synapse.synheart.ai), after [Get started](/synapse/get-started). It takes about 15 minutes. Developers then follow [Developer setup](/synapse/developer-setup). **1. Connect GitHub** Open **Connectors** and connect GitHub. This installs the Synapse GitHub App on your GitHub organization. Under **Knowledge sources** on the same page, choose what agents may recall: repositories, a Notion workspace, a Google shared drive, or public Slack channels. Nothing is indexed until you choose it. On Microsoft 365, connect Outlook Calendar, Outlook Mail, Teams and OneDrive under **Microsoft 365 · Organization**, each with its own consent from a tenant administrator. See [Microsoft 365](/synapse/microsoft-365) for what each one reads. **2. Connect your AI tools** In **Connectors**, connect the AI tools your organization pays for. Each one takes an admin key from that vendor (GitHub Copilot can use the GitHub App instead). [AI spend](/synapse/ai-spend#connecting-each-tool) lists which key each tool needs. Then open **AI Effectiveness** and scroll to its **AI spend** section for the overview. A Synapse Admin enters what you pay per Copilot seat there (from your invoice, or as a list-price estimate). **3. Write the team rules** Open **Agents** and scroll to **Team rules**. Paste your rules and save. Each save is a new version, and developers' machines pick it up within 15 minutes. Start from the example in [Writing rules](/synapse/rules#a-team-example) and adjust it to your branches and repositories. **4. Turn on the weekly summary** Connect Slack under **Connectors** if you haven't. Then open **Goals & alerts**, find **Weekly digest**, turn on **Post to Slack weekly**, choose a channel and save. **Send one now** posts this week's summary straight away. See [Weekly digest](/synapse/goals-and-alerts#weekly-digest). The summary includes AI spend and what agents were stopped from doing, alongside team effectiveness when enough members contribute. **5. Check your privacy settings** Open **Admin → Privacy controls**. Team human-state figures are withheld below your organization's cohort floor, 4 people by default. You can raise it to as many as 50. Work and AI figures aren't affected by it. Set the **Time zone for weekly reports** here too. Team human-state views are on by default and can be turned off there. See [Team views and privacy](/synapse/team-views). **6. Invite your developers** Send them [Developer setup](/synapse/developer-setup). Each developer needs a Synapse login and a Synapse seat in your organization. The organization owner or an organization admin grants seats. ## Who can do what | | Admin | Lead | Member | | - | - | - | - | | Connect GitHub, AI tools and knowledge sources | Yes | | | | Edit team rules | Yes | | | | Change the cohort floor, team human-state views and team sharing | Yes | | | | See AI spend, the organization's team views and the team agent report | Yes | Yes | | | See their own department's team view | Yes | Yes | Yes | | See their own agent report (**Agents → Mine**) and decisions (**Agent checks**) | Yes | Yes | Yes | These are Synapse roles, given with each seat. The organization owner with a seat can do everything. The organization owner and organization admins can also change the privacy settings without a seat, and only the owner can erase the organization's Synapse data. See [Who can change what](/synapse/team-views#who-can-change-what). ## Checking it works * **AI spend** lists each connected tool with its usage and cost. For Copilot, once a price is set, it also shows the monthly and yearly cost of unused seats. * **Insights** shows a setup checklist to admins until every step is done. * **Agents → Team** shows totals once enough developers have reported. Until then it says how many have reported so far. When developers use more than one coding agent, the totals are split by agent (Claude Code, Cursor, Droid and so on), each withheld on its own until enough developers use it. * A connection whose stored credentials can no longer be read shows **Reconnect** on the Connectors page. # Agents Source: https://docs.synheart.ai/synapse/agents What your coding agents were stopped from, asked about and let through. The summary, the rules table, team decisions, your own Claude Code usage, and the team rules **Agents**, at [synapse.synheart.ai](https://synapse.synheart.ai), shows what the guard did with your coding agents' actions: what it stopped, what it asked a person about, and what an exception let through. It's built from counts only. **No command, file path or prompt is ever sent or shown.** The guard and its rules are explained in [Writing rules](/synapse/rules). To set it up on a machine, see [Set up as a developer](/synapse/developer-setup). ## The top of the page * **Team** or **Mine.** **Mine** shows your own agents. **Team** shows everyone's, added up, and is for Synapse Leads and Admins. Members see **Mine** only. * **Period.** **7 days** or **30 days**. * **Refresh** reloads the figures. ## Summary | Figure | What it counts | | - | - | | **Blocked actions** | Actions stopped by a guard rule (`verdict: deny`). | | **Approval requests** | Actions the agent had to ask a person about (`verdict: ask`). | | **Exceptions** | Actions let through by an exception someone granted with `synheart guard allow`. | | **Shadow checks** | Times a trial rule (`shadow: true`) would have fired. Nothing was stopped. | ## Rules **Agent actions by rule** lists each rule that did something in the period: | Column | Meaning | | - | - | | **Rule** | The rule's `id`. | | **Outcomes** | A bar split into stopped, asked and approved, and asked and not approved. | | **Stopped** | Times the rule stopped an action. | | **Asked** | Times it asked a person. | | **Approved** | How many of those asks the person approved. | | **Exceptions** | Times an exception let the action through. | | **Shadow** | Times it would have fired as a trial rule. | Search by rule, or use the chips to show only rules that **Blocked**, **Asked** or ran in **Shadow**. When a rule was asked about at least five times and approved every time, a note under the table names it and says it *may no longer need a person*. That's a candidate to relax, so developers are interrupted less. See [When rules are too strict](/synapse/rules#when-rules-are-too-strict). > [!TIP] > > Before turning a new rule on for everyone, add `shadow: true` and watch its **Shadow** count for a week. If it would fire on work you're happy with, adjust it before it starts stopping anyone. ## By coding agent When more than one coding agent reports, such as Claude Code and another agent, **By coding agent** shows the same counts for each. See [Connect your agent](/synapse/connect-agents). ## When nothing shows If no machine has reported yet, the page says *No agent activity reported yet* and offers the setup commands to copy: ```bash theme={null} curl -sSL https://synheart.sh/install | bash synheart login synheart guard team join synheart guard install --write ``` Then restart Claude Code. Activity appears after the next agent session. The steps are explained in [Set up as a developer](/synapse/developer-setup). ## Team decisions On **Team**, **What Synapse advised the team's agents** shows what Synapse told agents when they asked it for context. Team totals only. | Figure | What it counts | | - | - | | **Checked context** | Times an agent checked the team's memory before acting. | | **Asked the developer** | Times Synapse saw a conflict with a recorded decision and the agent asked the developer. | | **Blocked** | Times Synapse advised the agent not to act. | | **First-pass acceptance** | The share of agent edits accepted the first time. | | **Correction cycles** | How often an edit was rejected before one was accepted. | **First-pass acceptance** and **Correction cycles** come only from explicit verdicts: developers running `synheart feedback accept` or `reject`, or choosing accept or reject on [Agent checks](/synapse/ask). Below them: * **Most common reasons** the agents were asked or stopped. * **Decisions cited most**, the team decisions agents leaned on. * **Intent check**, when your organization uses it: how often the agent stopped to ask or flag, and whether the developer **Accepted**, **Edited** or **Overrode** it. ## Your Claude Code usage At the bottom, everyone sees their own Claude Code usage for the last 7 days: **Sessions**, **Input tokens**, **Output tokens** and **Cache tokens** (read and written). **API-equivalent value** estimates what those tokens would cost at API prices. It isn't money spent. Only you see this section. ## Team rules **Team rules** shows the rules every developer's agent follows, and their version, such as **v4**. Open it to read them as YAML. Everyone can read them. Only Synapse Admins can change them. Each save is a new version. Developers' machines pick it up within 15 minutes. For the format and an example to start from, see [A team example](/synapse/rules#a-team-example). ## Who can see what | Section | Who | | - | - | | **Mine**, and your own Claude Code usage | Everyone with a seat | | **Team**, including team decisions | Synapse Leads and Admins | | Read the team rules | Everyone with a seat | | Change the team rules | Synapse Admins | # AI Effectiveness Source: https://docs.synheart.ai/synapse/ai-effectiveness What's on each tab of AI Effectiveness. The AI Effectiveness Index on Overview, Reach and Habit on Adoption, and team human state on Human state **AI Effectiveness**, under **Teams** at [synapse.synheart.ai](https://synapse.synheart.ai), shows how AI is working for a team: who uses it, whether work moves differently, and how people are doing. Everyone with a seat can open it. Members see their own department. Leads and Admins see the whole organization and can open any department. If the terms on this page are new, read [How Synapse works](/synapse/how-synapse-works) first. ## The top of the page These controls stay in place on every tab. * **Scope badge.** Next to the title, it says what you're looking at: **Company** or a department's name. * **Period.** Choose **Today**, **7 days**, **30 days** or **90 days**. Every figure, and every "vs the previous…" comparison, follows it. * **Refresh** reloads the figures. **Updated** shows when they were last loaded. * **Export** downloads the team figures as a CSV, for Leads and Admins. See [Exports](/synapse/exports). * **Set up Synapse** appears until your organization finishes setting up. It shows the next step, such as connecting GitHub or choosing knowledge sources, and links to the [setup guide](/synapse/admin-setup). ## Overview Overview shows the [AI Effectiveness Index](/synapse/how-synapse-works#the-ai-effectiveness-index) as three cards side by side, one for each part. They're separate measures. Don't add them up or compare one with another. Each card opens its own tab. ![The Overview tab of AI Effectiveness, showing the Adoption, Delivery and Human cards and the Synapse use section](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/ai-effectiveness-overview.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=70b55a0bda182e9c2e7ddf080785b0aa) Overview, with the AI Effectiveness Index and Synapse use | Card | The big number | The line under it | | - | - | - | | **Adoption** | **Reach**, the share of measured members who used AI | **Habit**, the share of worked days with AI use | | **Delivery** | The change in median PR lead time after an AI tool's rollout | Which measure and tool, such as *PR lead time · GitHub Copilot* | | **Human** | Team focus, as a work-hour median | How many members opted in | Arrows such as **↓ better** say which way is good for that measure. For PR lead time, a negative change means PRs merged faster after the rollout. The **Delivery** card needs a recorded AI rollout. Until there is one, it says *No AI rollout recorded yet* rather than showing a number. If the newest rollout is still inside its 4-week "after" window, the card says so and shows the last complete one. **Synapse use**, below the index, shows **People using Synapse** and **Synapse calls**: how many people and how many calls went through Synapse MCP in the period, with the change from the previous one. ## Adoption Adoption answers "who uses AI tools, and how often?" It's labelled **Describe**: it counts use, and doesn't say whether AI helped. ![The Adoption tab, showing Reach, Habit and Members measured cards above a table of AI sources with their reach and member coverage](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/ai-effectiveness-adoption.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=b34c051effc70c2bcc907c1a9489405a) Adoption, with Reach, Habit and the by-source table * **Reach.** The share of measured members who used any AI tool in the period. * **Habit.** The share of worked days on which people used AI. * **Members measured.** How many members Synapse has AI data for. Reach and Habit are shares of these people, not of everyone in the team. The **source** table shows the same thing tool by tool: * **Reach** is the share of members covered by that tool who used it. * **Member coverage** is how many of the team's members that tool reports on. A tool that reports use without saying who it covers shows *Reports use only; coverage unknown*. One person counts once in the overall Reach, even if they use several tools. That's why the overall figure can be lower than a single tool's. Further down: * **AI tools in use** shows active people by tool and links to **AI usage** for the full breakdown. * **Synapse** shows calls through Synapse MCP over time (daily, weekly or monthly) and **Top Synapse clients**, the AI clients that made those calls. ## Delivery Delivery shows the work your organization shipped and how AI shows up in merged PRs: lead time, deploys, review times, CI, and Repository AI evidence. It's labelled **Associate**: a change alongside AI use isn't proof that AI caused it. Every metric on this tab is explained in [Metrics explained](/synapse/metrics). ## Human state Human state shows how people are doing during work, from members who connected Life by Synheart and consented. It's in **Beta**, and it's never used in alerts, goals, rankings or recommendations. ![The Human state tab, showing work-hour medians for focus, cognitive load and mental fatigue, consent coverage, and period averages for each human-state axis](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/ai-effectiveness-human-state.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=53b662d1f9650a3b5baf3c45f0554711) Human state, with the human part of AEI and all human-state axes **Human part of AEI** shows the figures behind the Human card on Overview: * **Focus**, **Cognitive load** and **Mental fatigue**, each as the team's median during work hours. Higher focus is better. Lower load and fatigue are better. * **Consent coverage**, the share of the team's members who opted in. A low share means the figures describe only part of the team. **All human-state axes** shows each measure Life provides as an average over worked and focus hours. Because these are averages over different hours, they won't match the work-hour medians above. Axes with no data in the period are listed under **No data**. Scores run from 0 to 1. **Private** means too few people share that axis to show it. Further down: * **Work rhythm** shows **Deep work** and **Meeting load**: how the team's work time is spent. * **Human-state loop** follows agent calls through four steps: Synapse calls, calls that asked for human state, calls where a state was available, and calls that led to a directive (guidance to the agent on how to respond). It counts requests, not people. * **Evidence coverage** shows how much of each input the period has: Synapse MCP, consented human state, and work context. ### When figures are hidden Human-state figures follow the [cohort floor](/synapse/team-views#the-cohort-floor). A footer on every tab says how many people a figure needs. Below that, you'll see a dash or **Private** instead of a number, unless everyone on the team has opted in to [sharing with each other](/synapse/team-views#share-my-numbers-with-my-team). If an admin has turned off [team human-state views](/synapse/team-views#team-human-state-views), this tab and the Human card say the views are off. Adoption and Delivery aren't affected. ## Reading it well * **Read each part on its own.** High adoption with flat delivery is a finding, not a contradiction. * **Check coverage first.** Members measured, member coverage and consent coverage tell you how much of the team a number speaks for. * **Look for patterns over periods.** One week is noisy. Compare 30 or 90 days. * **Don't use it to rate people.** Every figure is a team total, and none of them is a performance score. # AI spend Source: https://docs.synheart.ai/synapse/ai-spend What your organization pays for AI tools, how much is used, and which Copilot seats nobody uses **AI spend** is a section of the **AI Effectiveness** page: one overview of every AI tool you connect, with usage and cost per tool and, for GitHub Copilot, the seats nobody used. Admins connect tools under **Connectors**. Leads and admins can see the report. Old links to `/ai-spend` open this section. ## Connecting each tool | Tool | Connect with | | - | - | | GitHub Copilot | The Synapse GitHub App (recommended), or a GitHub token | | Claude Code | A Claude Console **Admin API key** (`sk-ant-admin01-…`) | | Claude API | A Claude Console **Admin API key** (`sk-ant-admin01-…`) | | OpenAI API | An OpenAI Platform **Admin key** | | Codex | An OpenAI workspace **Admin key** (`sk-admin-…`) with usage analytics access | | ChatGPT | An OpenAI workspace **Admin key** (`sk-admin-…`) with usage analytics access | | Cursor | A Cursor Enterprise **Admin API key** (`crsr_…`) | Each key is checked when you paste it, stored encrypted, and used only to read usage reports. Ordinary API keys and workspace-scoped keys can't read organization usage, so the connection is refused with a message saying which key is needed. ## What it reads Vendor reports list usage per person. Synapse stores those rows under a pseudonym instead of the person's vendor login or email. The pseudonym is a one-way keyed hash of the login or email, specific to your organization. It is computed with a secret key that only Synapse holds, so it can't be matched back to people by hashing a list of emails or logins. For each pseudonym Synapse keeps daily usage counts (such as sessions or requests) and cost, plus activity times where the vendor reports them. For Copilot it also keeps which pseudonyms hold a seat. * **You see totals, not people.** The report shows active users or seats, sessions or requests, and cost. Figures are shown exactly, even for a small group, because they describe tool usage rather than anyone's state. Usage from API keys counts as a workload, not a person. * **Retention.** While a tool is connected, usage older than 90 days is deleted each time its reports refresh. When you disconnect a tool, its usage history is kept unless you choose to delete it. * **Costs are what each vendor reports.** Some vendors report estimated rather than billed cost; your invoice is the final word. The Copilot seat price is labelled as invoice or estimate. * **Tools aren't added together.** Vendor bills can overlap — Claude Code usage can also appear on your Claude API bill, and one OpenAI workspace report can include both ChatGPT and Codex — so each tool is shown on its own instead of in a single misleading total. ## GitHub Copilot seats Copilot is billed per seat, so it gets its own view: how many seats you have, which were active in the last 30 days, which were never used, and which are already being cancelled. | Way to connect | Needs | | - | - | | Synapse GitHub App | The app installed on your organization, with the *GitHub Copilot Business: read* permission accepted by an organization owner. Nothing to paste | | A token | From an organization owner or billing manager, with `manage_billing:copilot` or `read:org`. Stored encrypted | **Price.** GitHub doesn't report what you pay. A Synapse Admin enters the monthly price per seat, from your invoice or as a list-price estimate. An estimate is labelled as one wherever it's used. Without a price you see counts only, never an invented figure. **Per team.** Seats assigned through a GitHub team are also shown per team. ## Not covered * Claude Code and Claude models used through Amazon Bedrock, Google Vertex AI or Microsoft Foundry: those bills come from the cloud provider. * Personal subscriptions people pay for themselves. ## Refreshing and disconnecting Reports refresh on their own, and **Refresh** reads them immediately. Disconnecting a tool under **Connectors** removes its stored key. Its usage history is kept unless you tick **Also delete imported usage history**; for Copilot the seat report is removed either way. A Copilot seat price you entered is kept. ## In the weekly summary When the [weekly digest](/synapse/admin-setup#turn-on-the-weekly-summary) is on, its *AI tools* section reports unused Copilot seats and their cost, usage of your connected tools, and what agents were stopped from doing. # AI usage Source: https://docs.synheart.ai/synapse/ai-usage Which AI tools your organization uses, how much and by how many people. Where each figure comes from, the filters, and why some figures are missing **AI usage**, under **Teams** at [synapse.synheart.ai](https://synapse.synheart.ai), shows which AI tools your organization uses, how much, and by how many people. It counts use. It never names a person, and it doesn't say whether the use helped. For that, see [AI Effectiveness](/synapse/ai-effectiveness). Synapse Leads and Admins can open it on paid plans. Members don't see it. ## Before you start Usage appears once at least one AI tool is connected under **Admin → Connectors** and has reported for the period. Until then the page says *No AI usage yet* and links to Connectors. See [Connectors](/synapse/connectors) for the tools Synapse can read. ## Filters * **Department.** Shown once your organization has departments. Choose **All departments** or one department. * **Period.** **7 days**, **30 days** or **90 days**. Changes are compared with the previous period of the same length, such as *+12% vs prior period*. * **Tools.** When more than one tool reports, pick the tools to include. ## What's on the page ### Summary | Figure | What it counts | | - | - | | **Active people** | People who used at least one AI tool in the period. | | **Tokens** | Tokens used across the tools. | | **Requests** | Requests sent to the tools. | | **Sessions** | Sessions, for tools that report them. | The line under **Tokens**, **Requests** and **Sessions** names where the figure came from: **Connected tools**, **Claude Code sessions** or **Provider reports**. Synapse takes the first source that reported a figure and never adds sources together, so nothing is counted twice. ### Tokens over time Tokens per day, grouped by **Model** or by **Tool**. The table under the chart shows each model's or tool's tokens, requests and sessions, and its share of tokens. ### People * **New people**: first seen using AI in this period. * **Sessions per person** and **Tokens per person**. * **Daily**, **Weekly** and **Monthly active people**, as averages over the period. * **Active people by tool**, with each tool's share of active people. * **Usage by department**: active people, share of tokens and tokens per person for each department. ### Output from AI-assisted coding **Commits**, **Pull requests**, **Lines added** and **Files changed**, as the AI tools report them. These describe output that came with AI use. They don't measure productivity. For delivery figures from your repositories, see [Metrics explained](/synapse/metrics). ## Missing figures A figure is left out, rather than shown as zero, when: * **no tool reported it.** Not every tool reports sessions or requests, for example. A figure nobody has reported yet says *Not reported yet*. ## Export CSV **Export CSV**, at the top, downloads the figures on screen with the same filters. It's available to Synapse Leads and Admins. For scheduled exports, see [Exports](/synapse/exports). ## Related * [AI spend](/synapse/ai-spend): what the tools cost, and which seats go unused. * [AI Effectiveness](/synapse/ai-effectiveness): Reach and Habit, which count the same people from a different angle. # Agent checks Source: https://docs.synheart.ai/synapse/ask What your coding agents checked with you, what was blocked, and why. Your own record, with your verdict on each **Agent checks**, under **You → Your work** at [synapse.synheart.ai](https://synapse.synheart.ai), lists what Synapse told your coding agents to do, newest first. Each time your agent uses Synapse over MCP, or the guard checks an action on your machine, Synapse records a short decision: what it advised and why. Agent checks shows your own decisions only. There's no organization-wide list and no way for a manager to open someone else's. Leads and above see team totals on the Agents page, never individual rows (see [Team totals](#team-totals)). > [!NOTE] > > The search page used to be called Ask. It's now [Ask Synapse](/synapse/search), and old `/ask?q=…` links go there. ## What happened Filter the list by what happened, by period (7, 30 or 90 days) and by task. | Filter | What it means | | - | - | | **Asked you** | The agent was told to check with you before acting. Either the intent check found a current decision that governs the code being changed and a high risk, or one of your team's `ask` rules needed your approval | | **Blocked** | One of your team's `deny` rules stopped the action | | **Checked context** | The agent was told to read the cited decisions or context before acting | | **Proceeded** | Nothing applied, so the agent went ahead | **All checks** shows the first three. **Proceeded** has its own filter. Synapse itself never blocks. Recall and the intent check can at most tell the agent to check with you. Only your organization's own [guard rules](/synapse/rules) block an action or need approval, and the CLI on your machine enforces them. ## Reasons and evidence Each row shows: * **What happened**, and what the agent was told, in one sentence. * **Reasons**, in plain words. For example: a current decision governs this code, a high risk is present, nothing current was found, or a team rule stopped the action. * **Evidence**, as identifiers: the decisions Synapse cited (each links to [Ask Synapse](/synapse/search)), the kind of risk, or the rule id. * **The coding agent** (Claude Code, Cursor, Droid and so on), the time, and the outcome. Open a row to see the full explanation. An agent can get the same explanation with the MCP tool `explain_decision`, for your own decisions only. ### Tasks Decisions are grouped by task so you can follow one piece of work across sessions and agents. Synapse works out the task from, in order: an issue or PR number, an issue number in the branch name (`feat/123-title`, `issue-123`), the branch itself, or the agent's session. Synapse keeps a keyed digest of a branch, not its name. Default branches such as `main` are never a task. ## Accept or reject In the decision's detail panel you can record whether you accepted the agent's edit, with an optional reason. A verdict you give in the dashboard counts as your own, exactly like one from the terminal. A decision with no task can't take a verdict. From the terminal, with [CLI](/setup/install-cli) 0.23.0 or later: ```bash theme={null} synheart feedback accept synheart feedback reject --reason wrong-approach synheart feedback reject --decision 6f4e3c2a-1b0d-4e9f-8a7b-6c5d4e3f2a1b --reason violates-decision ``` The task comes from the current branch unless you pass `--issue`, `--pr` or `--task`. Reasons are `wrong-approach`, `incorrect`, `incomplete`, `out-of-scope`, `style`, `violates-decision`, `breaks-checks`, `security`, `looks-good`, `accepted-with-changes` and `other`. `synheart feedback` runs only for a person at an interactive terminal. It refuses in an agent's shell, so an agent can't accept its own work. ### Relayed feedback If you tell your agent what you think of its edit, the agent can pass that on with the MCP tool `synapse_feedback`. Synapse stores it as **relayed**: the row says *Relayed by the agent*, and relayed verdicts are counted separately from your own. An agent's credentials can't record a verdict as yours. Your own verdict from the dashboard or the CLI takes precedence. ### Summary The cards at the top count, for the period: * **Asked you** and **Blocked**. * **Correction cycles**: on each task, how many times you rejected an edit before you accepted one, averaged over the tasks you accepted. * **First-pass acceptance**: the share of accepted tasks where you accepted without rejecting first. Both measures are rough guides to how well agents land work with you. They aren't for ranking people or judging performance. ## Getting decisions here Decisions appear once either of these is set up: * **Your agent uses Synapse over MCP.** Recall and the intent check (`related_context`) each record a decision. See [Connect your agent](/synapse/connect-agents). * **The guard shares its decisions.** Each guard check can be sent as a decision record. This is off by default. Turn it on, from your own terminal: ```bash theme={null} synheart guard team decisions on ``` It sends the rule id, what the rule did, the coding agent, the time and the agent's session id. It never sends the command, a file path, a prompt, the repository or the branch. `synheart guard team decisions off` stops it. Set up the guard first: see [Developer setup](/synapse/developer-setup). ## What's stored Decision records hold no content. Each record keeps: * the mode and reason codes; * evidence identifiers; * the task id and the coding agent; * the time. Synapse never stores the question or instruction your agent sent, or any prompt, code, diff, excerpt, secret, branch name or session id in clear. The instruction text of an intent check is used for the search and then discarded. Records hold no human state either. Turning off [team human-state views](/synapse/team-views#team-human-state-views) doesn't affect Agent checks or the team decision totals, and neither of them ever shows human state. **Retention.** Decision records and your accept/reject verdicts are kept for 90 days and deleted daily after that. [Erasing your Synapse data](/synapse/team-views#erasing-data) deletes them straight away, as does erasing the organization's data. ## Team totals Leads and above (Synapse Leads, Synapse Admins, and the organization owner with a seat) see totals for the whole team under **Agents → Team**: * decisions by what happened; * the most common reasons; * the decisions cited most; * team correction cycles and first-pass acceptance; * what the intent check found. These are totals only, with no names, tasks or per-person rows. # Audit log Source: https://docs.synheart.ai/synapse/audit-log Who changed what in Synapse, and when. What's recorded, what never is, filtering by action, the detail on each event, and exporting it as a CSV The **Audit log**, under **Admin → Trust** at [synapse.synheart.ai](https://synapse.synheart.ai), records who did what, when, and to what, across your organization's Synapse. Nothing in it can be edited or deleted. Synapse Admins and the organization owner, with a seat, can open it. Anyone else is pointed to their own **Privacy & consent** page. ## What's recorded Governance actions, as they happen, grouped by what they're about: | Group | For example | | - | - | | **Connectors** | Connecting, updating or disconnecting a source, and disconnecting with its data purged | | **Knowledge sources** | Adding, keeping or stopping a source | | **Personal accounts** | Linking, unlinking or verifying an account | | **MCP tokens** | Issuing and revoking a token | | **Exports** | Downloading a CSV or JSON export, and creating, changing, testing or deleting a webhook | | **Goals & alerts**, **Digests** | Creating, changing and deleting goals and alerts, changing the weekly digest, and sending one | | **Departments** | Creating, renaming and deleting a department, and assigning or removing members | | **Agent rules** | Saving a new version of the team rules | | **Privacy**, **Settings** | Changing the cohort floor, team human-state views, team sharing or the reporting time zone | | **Synaptic Mesh** | Restricting and un-restricting a document | | **AI rollouts**, **AI adoption** | Recording a rollout, and matching AI tool users by work email | | **Synapse Life** | Connecting and disconnecting Life | | **Offboarding**, **Memory** | Erasing a member's or the organization's data, and forgetting a memory | | **Audit log** | Exporting the log itself | Goals and alerts that Synapse retired itself, when the AI Effectiveness Index stopped being a single score, are marked **Retired**. ## What's never recorded The log records actions, never content. It never holds: * a credential, token, API key or secret, though it may name one, such as a token's label; * message text, documents, prompts or code; * anyone's human state; * your own consent choices, such as sharing your numbers with your team. Those are kept as proof of consent but never shown here. See [Team views and privacy](/synapse/team-views). ## Reading an event Each row shows when it was recorded, who did it and what they did. Open a row for its details: * **Actor**: the person, or **System** for something Synapse did on its own. A person whose data was erased shows as **Erased user**. * **Target**: what it was done to, such as a department, a connector or a goal. * **Recorded**: the exact time. * **Action**: the action's code, such as `department.created`. * Any detail that applies, such as the metric and threshold of an alert, the channel of a digest, or the number of rows in an export. ## Filtering and paging **Filter by action** shows one kind of event. Choose how many to show **Per page** and move between pages. **Refresh** loads anything new. ## Exporting **Export CSV** downloads every event matching the current filter, not just the page on screen, up to 20,000 rows. A bigger match is refused rather than cut short, so a file you download is always complete for its filter. Narrow the filter and try again. Every export is itself recorded in the log. ## Who can do what | Action | Who | | - | - | | Read and export the audit log | Synapse Admins, and the organization owner with a seat | # Billing & usage Source: https://docs.synheart.ai/synapse/billing-and-usage Your Synapse plan, seats and how much of each allowance has been used this month. Synapse Free, upgrading, trials, invoices, and who can change what **Billing & usage**, under **Admin → Plan** at [synapse.synheart.ai](https://synapse.synheart.ai), shows your Synapse plan, your seats, and how much of each allowance has been used this month. The organization owner and organization admins can open it. Only the owner buys a plan and sees invoices, so for an admin the page is mostly view-only. The same billing covers the rest of the Synheart platform. For platform plans, meters and invoices in general, see [Platform billing](/platform/billing). ## Synapse Free Synapse Free lets a small team try Synapse. By default it includes: * **3 seats**; * **GitHub and Slack** as sources. Other [connectors](/synapse/connectors) are listed under **Included with paid plans**; * **the last 30 days of history** in search, answers and the [mesh](/synapse/mesh). Pages that need a paid plan, such as [My Effectiveness](/synapse/my-effectiveness), [AI usage](/synapse/ai-usage) and [Goals & alerts](/synapse/goals-and-alerts), carry a **Paid** badge. You can still open them to see what they offer and how to upgrade. ## Upgrading Choose **Upgrade**, or pick a plan on this page. Prices are shown when you choose. Then: 1. **Add a payment method.** 2. **Confirm the plan.** You choose the number of seats next. Only the organization owner can buy a plan. Once it's active, each person still needs a seat. See [Members and roles](/synapse/members-and-roles). If an earlier paid plan had ended, picking one again resumes paused seats and connectors, and older history shows again. Nothing was deleted while it was paused. > [!WARNING] > > If the page says it's confirming payment, wait. Don't start a second purchase while one is pending. ### Trials A trial doesn't need a card. The page says when it ends. To keep the plan, add a payment method before then. Otherwise the plan ends with the trial. You can cancel before it starts in payment management. ### Agreements billed off-platform If your organization has a contract with Synheart, the page shows **Platform agreement**. It's billed on that agreement: contact your account team for payment, cancellation or contract changes. ## Plan and seats | Figure | Means | | - | - | | **Current plan** | Your plan and its status, such as **Active**, **Payment due** or **Canceled**, and when it renews or ends. | | **Members with a seat** | How many people hold a Synapse seat. | | **Billed seats** | How many seats you pay for. | | **Contracted seats** | On an agreement, how many seats it covers. | | **Price per seat** | What each seat costs on your plan. | ## Usage this month **Synapse allowances** shows each metered allowance on your plan, how much has been used this month, and the share of it. The mark on each bar is 80% of the allowance. **Synapse calls** shows calls through Synapse this month, added up by day, against an even pace to the allowance, with what's projected by month end. If usage goes over, **Estimated overage** shows the excess and its rate. Figures keep changing until the month closes. Once it does, they're final. The page also shows your own Synapse calls this month, against the shared organization allowance. ## Invoices Invoices, and the full billing history, are in payment management, which the organization owner opens from this page. ## Who can do what | Action | Who | | - | - | | Open Billing & usage | The organization owner and organization admins | | Buy a plan, add a payment method, see invoices | The organization owner | | Change the number of seats on an existing plan | The organization owner and organization admins | | Give and remove seats | The organization owner and organization admins | | Decide what happens when usage goes over the allowance | The organization owner | # Connect your agent Source: https://docs.synheart.ai/synapse/connect-agents Give Claude Code, Cursor, Claude Desktop, Codex or Droid your organization's decisions and context over MCP Synapse is an MCP server. Once connected, your agent can recall what your organization decided and why, find related context for a change, and record new decisions. It only sees sources an admin has designated, and only what you're allowed to see in them. Each time your agent recalls or checks a change, Synapse also records what it advised and why, without the question itself. You can review those records, and accept or reject the agent's edit, under [Agent checks](/synapse/ask). To search the same knowledge yourself, use [Ask Synapse](/synapse/search). The endpoint is `https://api.synheart.ai/synapse/v1/mcp`. You sign in once in the browser; your client keeps its own token after that, so there's nothing to paste. > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http synapse https://api.synheart.ai/synapse/v1/mcp > ``` > [tab] Cursor > > Add to `.cursor/mcp.json` (merge it into `mcpServers` if the file exists): > > ```json theme={null} > { > "mcpServers": { > "synapse": { > "url": "https://api.synheart.ai/synapse/v1/mcp" > } > } > } > ``` > [tab] Claude Desktop > > Add to `claude_desktop_config.json`, then restart Claude Desktop. It runs `mcp-remote` through `npx`, so Node.js must be installed. > > ```json theme={null} > { > "mcpServers": { > "synapse": { > "command": "npx", > "args": ["-y", "mcp-remote", "https://api.synheart.ai/synapse/v1/mcp"] > } > } > } > ``` > [tab] Codex CLI > > Add the server, then sign in. Codex doesn't start the sign-in on its own, so run `codex mcp login` once after adding it. > > ```bash theme={null} > codex mcp add synapse --url https://api.synheart.ai/synapse/v1/mcp > codex mcp login synapse > ``` > > Or add it to `~/.codex/config.toml` (or `.codex/config.toml` in a trusted project) and run `codex mcp login synapse`: > > ```toml theme={null} > [mcp_servers.synapse] > url = "https://api.synheart.ai/synapse/v1/mcp" > ``` > [tab] Droid > > Add the server, then run `/mcp` inside Droid, pick `synapse` and sign in in the browser. > > ```bash theme={null} > droid mcp add synapse https://api.synheart.ai/synapse/v1/mcp --type http > ``` > > `droid mcp add` writes to your user config, `~/.factory/mcp.json`. To share the server with your team, commit it to `.factory/mcp.json` in the project instead: > > ```json theme={null} > { > "mcpServers": { > "synapse": { > "type": "http", > "url": "https://api.synheart.ai/synapse/v1/mcp" > } > } > } > ``` > > Factory admins can provide Synapse to everyone through org-managed settings. If your organization restricts MCP servers with `mcpPolicy`, add Synapse's host to the allowlist: > > ```json theme={null} > { > "mcpPolicy": { > "enabled": true, > "allowlist": ["https://api.synheart.ai"] > } > } > ``` > > See Factory's [MCP configuration docs](https://docs.factory.com/cli/configuration/mcp) for how managed settings are rolled out. > [!NOTE] > > The Codex CLI and Droid setups follow each vendor's current documentation but haven't been tested end to end against Synapse yet. If sign-in or the connection fails, let us know, and use Claude Code or Cursor in the meantime. The same instructions, with your organization's endpoint filled in, are under **Connect your AI** at synapse.synheart.ai (formerly **AI Tools**). That page also lists the clients you've connected. > [!NOTE] > > Connecting an agent over MCP gives it your organization's knowledge. Enforcing team rules is separate and works through the guard hook: see [Developer setup](/synapse/developer-setup). # Connectors Source: https://docs.synheart.ai/synapse/connectors The tools Synapse reads from, what each one gives it and never sees, the connection states, and the accounts you link for yourself Connectors are how Synapse gets its data: your code host, chat, issue tracker, calendar and AI tools. There are two views of them. * **Admin → Connectors** is the organization's sources. Synapse Admins connect them once, for everyone, and only they see this page in the menu. * **You → My connections** is your own linked accounts. Only you see and change them. What Synapse indexes as searchable text is chosen separately, under [Knowledge sources](/synapse/knowledge-sources). Connecting a tool collects activity, never its text. ## Organization sources **Admin → Connectors** lists every source, grouped by where it stands. Search the list, or choose **Refresh statuses** to check them all again. ![The Connectors page, with Slack under Needs attention, GitHub and Notion under Connected, Jira and Linear under Ready to connect, a Microsoft 365 group with four tools, and Zoom under Not set up](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/connectors-organization.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=d53c6bbed91f2109cb1fc959ab5d403a) Organization sources, grouped by status | Group | Means | | - | - | | **Needs attention** | Connected, but something is wrong, such as an expired credential or a failed sync. The row says what happened, and **How to fix** or **Reconnect** shows what to do. | | **Connected** | Working. The row shows when it last synced. | | **Configured without API** | Set up, but with no automatic collection. Its figures come from a report you send in, such as an AI usage import. | | **Ready to connect** | Available. Choose **Connect** to start. | | **Included with paid plans** | On Synapse Free, only GitHub and Slack are included. Other sources keep their settings and data, and sync again when you upgrade. | | **Microsoft 365** | Teams, OneDrive, Outlook Mail and Outlook Calendar, as one organization application. A Global Administrator approves each tool separately. See [Microsoft 365](/synapse/microsoft-365). | | **Not set up** | Not available in your environment yet. Your organization admin can help. | Select a source to open its details: what Synapse reads from it, what it never sees, when it last synced, and when its credential expires. ## What each source gives Synapse **Work and knowledge** | Source | Synapse sees | Never | | - | - | - | | **GitHub** | Repository docs (Markdown, RFCs, ADRs); when PRs, issues and reviews happen; deploys and CI results. | Source code, diffs, PR or issue text, comments. | | **GitLab** | Project docs; when merge requests and reviews happen; pipeline results. | Source code, diffs, comments. | | **Slack** | When messages happen, mentions and after-hours activity. Text only from public channels added as [knowledge sources](/synapse/knowledge-sources). | DMs, private channels, files. | | **Notion** | Titles and plain text of the pages you share with Synapse. | Comments, attachments, pages you don't share. | | **Linear**, **Jira** | Issue titles, who they're assigned to, and when their status changes. Used for cycle time and work in progress. | Descriptions, comments, attachments. | | **Zoom** | When meetings happen and how long they last, for meeting load. | Recordings, transcripts, chat, who attended. | | **Microsoft 365** | Depends on the tool. See [What each tool reads](/synapse/microsoft-365#what-each-tool-reads). | | For GitHub, you can also choose which deployments count as production. See [Production deploys](/synapse/metrics#production-deploys). **AI tools** | Source | Synapse sees | | - | - | | **GitHub Copilot** | Seat counts and daily usage totals. | | **Claude Code** | Usage totals and costs from the Console. | | **Claude Enterprise** | Usage, costs and daily activity. | | **OpenAI API** | How much was used and what it cost. | | **ChatGPT Enterprise** | ChatGPT and Codex usage totals for the workspace. | | **Cursor** | How much was used and what it cost. | | **Google Vertex AI**, **AWS Bedrock**, **Azure OpenAI** | Model token and request counts from the cloud's monitoring, for the project, account or resource you connect. | No AI tool connector sees prompts, responses or code. Cloud monitoring doesn't report who made a request, so those three give totals only. What these figures show is covered in [AI usage](/synapse/ai-usage) and [AI spend](/synapse/ai-spend). ## Disconnecting Disconnecting a source stops new imports. What it already imported is kept, unless you tick **Also delete everything Synapse imported** when you disconnect. Knowledge sources and people's linked accounts aren't changed. ## Your connections **You → My connections** is for you. Linking an account matches it to activity your organization has already connected, so Synapse knows which part is yours. **It doesn't import anything new.** You can link GitHub, Slack, Linear, Jira, Notion, Google Drive, Google Calendar, Outlook Calendar, Outlook Mail, Microsoft Teams and OneDrive. Your linked accounts feed [My Effectiveness](/synapse/my-effectiveness). Unlink any of them at any time. The page also has: * **Life by Synheart.** Connect Life to add your human state to My Effectiveness. Consent is given, and can be withdrawn, in the Life app. * **Local telemetry.** Sent from the CLI on your own machine. It's off until you turn it on with `synheart synapse telemetry on`, which shows what is sent and asks first. It's content-free by design: never prompts, responses or code. **Delete local telemetry** removes every session you've sent. ## Who can do what | Action | Who | | - | - | | Open **Admin → Connectors**; connect, sync and disconnect organization sources | Synapse Admins | | Link and unlink your own accounts | Everyone, for themselves only | # Departments Source: https://docs.synheart.ai/synapse/departments Group members the way you work so each department gets its own team view. Creating, renaming and deleting departments, assigning people, and what members see **Departments**, under **Admin → People** at [synapse.synheart.ai](https://synapse.synheart.ai), group your seated members the way you work, such as Engineering or Design. Each department gets its own team view in [AI Effectiveness](/synapse/ai-effectiveness). Synapse Admins manage departments, on paid plans. ## Why departments matter * **Members see their own department.** A Member's team views are scoped to their department. A seated member who isn't in a department sees no team view until they're in one. * **Leads and Admins can compare.** They see the whole organization and can open any department. * **No departments, one team.** If your organization has no departments at all, the whole organization is everyone's team. Creating the first department ends that. Work and AI activity are shown per department as they are. Human-state figures for a department keep their own protections: consent, and the [cohort floor](/synapse/team-views#the-cohort-floor). ## Creating a department Choose **New department**, type a name and press Enter. ## Assigning people Open a department's **Manage members**. Search the seated members, tick who's in it, and choose **Save assignments**. Nothing changes until you save. A person belongs to one department. Ticking someone already in another department moves them, and the row says *Moves from Engineering* (or wherever they are now) before you save. Only people with a seat can be assigned. To give someone a seat, see [Members and roles](/synapse/members-and-roles). ## Coverage The top of the page says how many seated members aren't in a department yet, and names them, so you can finish assigning. ## Renaming and deleting Use a department's menu to **Rename** or **Delete** it. Deleting asks you to confirm. Its members keep their seats but lose this department's team view until you put them in another one. ## Seeing a department's numbers **View numbers** opens AI Effectiveness scoped to that department. **Compare departments in AI Effectiveness** opens the comparison, for Leads and Admins. ## Who can do what | Action | Who | | - | - | | See your own department's team view | Every seated member in a department | | See and compare every department | Synapse Leads and Admins | | Create, rename and delete departments, and assign people | Synapse Admins | Every change is recorded in the [audit log](/synapse/audit-log). # Developer setup Source: https://docs.synheart.ai/synapse/developer-setup Install the CLI once; your coding agent then follows your team's rules About two minutes, once per machine. You need a Synapse login in your organization. **1. Install the CLI** > [tab] macOS / Linux > > ```bash theme={null} > curl -fsSL https://synheart.sh/install | bash > ``` > [tab] Windows (PowerShell) > > ```powershell theme={null} > iwr -useb https://synheart.sh/install.ps1 | iex > ``` macOS builds are signed and notarized by Apple. If `synheart` isn't found afterwards, see [Add to PATH](/setup/install-cli#add-to-path). **2. Sign in** ```bash theme={null} synheart login ``` A browser window opens. Sign in with your work account. **3. Join your team and add the hook** Run `synheart`, open **Synapse → Set up guard**. Or from the command line: ```bash theme={null} synheart guard team join synheart guard install --write ``` `team join` fetches your organization's rules. `install --write` adds the guard hook to `~/.claude/settings.json`, keeping your other settings and hooks and saving a backup first. Add `--project` to install it for the current repository only (`.claude/settings.local.json`). Using Cursor or Factory Droid? Add `--host cursor` or `--host droid` (CLI 0.22.0 or later). Without `--write`, `install` only shows the change it would make. In Cursor, file edits and reads can be stopped but not asked about. **4. Restart Claude Code** Restart it, or run `/hooks` inside it. From now on, each shell command and file edit is checked before it runs. ## Check it works ```bash theme={null} synheart guard check git push --force origin main ``` ```text theme={null} action git.push map[branch:main force:true remote:origin …] verdict deny Synheart guard [no-force-push-protected]: Never force-push to main, master, dev or production. ``` `check` runs nothing. It shows what the guard would decide for a command in the current directory. In the TUI, **Synapse → Guard status** shows whether the hook is installed, which team policy version you have, and when it last synced. ## What happens when a rule fires * **deny** — the agent is told no, with the rule's own words, and tries another way. * **ask** — Claude Code asks you before the action runs. * Nothing matches — the agent's own permission settings decide, as before. ## Letting something through When a rule is right in general but wrong right now, grant yourself a scoped exception. Only you can, from your own terminal; an agent can't. ```bash theme={null} synheart guard allow no-direct-push-protected --for 30m --repo acme/api --branch hotfix-123 --note "incident 4411" ``` * `--for` defaults to 1h; the maximum is 168h (a week). * `--repo`, `--branch` and `--path` narrow where it applies. * `synheart guard rules` lists the rules in force here and your active exceptions. ## Your own numbers ```bash theme={null} synheart guard report ``` It shows how many actions were checked, stopped, asked about and let through, per rule, for the last 7 days (`--since 720h` for 30). The same totals appear under **Agents → Mine** at synapse.synheart.ai, split by coding agent when you use more than one. Only rule ids and counts leave your machine: never a command, a file path or a prompt. Synapse keeps your daily counts for 90 days, and deletes them when you erase your Synapse data or your organization is deleted. ## Your verdict on an agent's edit Tell Synapse whether you accepted what your agent did. Synapse uses it to count correction cycles: how often you rejected an edit before accepting one. ```bash theme={null} synheart feedback accept synheart feedback reject --reason wrong-approach ``` It needs CLI 0.23.0 or later and runs only at your own terminal, never in an agent's shell. You can also accept or reject from the [Agent checks](/synapse/ask) page. To see each guard check there too, turn on decision sharing (off by default): ```bash theme={null} synheart guard team decisions on ``` It sends the rule id, what the rule did, the coding agent, the time and the agent's session id. It never sends the command, a path, a prompt, the repository or the branch, and only you see these records. ## Commands | Command | Does | | - | - | | `synheart guard team join` | Use your organization's rules here, ahead of your own | | `synheart guard install --write` | Add the hook to Claude Code's settings | | `synheart guard check ` | Show what the guard would do, without running anything | | `synheart guard allow ` | A scoped, time-limited exception | | `synheart guard rules` | Rules in force here and active exceptions | | `synheart guard report` | Your counts per rule | | `synheart guard sync` | Fetch the team rules and send your counts now (otherwise every 15 minutes) | | `synheart guard team status` | Which team, which policy version, last sync | | `synheart guard team leave` | Stop using the team rules on this machine | | `synheart guard team decisions on\|off` | Share each guard check with Synapse as a decision record you can see under **Agent checks** (off by default) | | `synheart feedback accept\|reject` | Record your verdict on an agent's edit | | `synheart guard init` | Create your own rules file from a starter set | ## Troubleshooting | Symptom | Fix | | - | - | | Nothing is ever checked | Guard status says the hook isn't installed: run `synheart guard install --write`, then restart Claude Code | | Team rules are old | `synheart guard sync`. If it fails with *not signed in*, run `synheart login` | | `Only the developer can grant exceptions…` | Expected when an agent tries to run `guard allow`, `team` or `install`. Run it yourself in a terminal | | Your counts don't show on the dashboard | `synheart guard team status` shows the last sync and its error | # Exports Source: https://docs.synheart.ai/synapse/exports Send team-level effectiveness metrics to your BI tools as a CSV or on a schedule to a signed webhook **Admin → Exports** sends your organization's effectiveness metrics to BI tools: as a one-off CSV, or on a schedule to webhooks you add. Leads and admins can use it. Every export carries team aggregates only, the same ones Synapse shows on its own pages. ## What an export contains Each row is one team aggregate over a period: the last 7 days in one summary, or one row per UTC day. | Field | What it is | | - | - | | `period_start`, `period_end` | The period the row covers, in UTC | | `cohort` | How many members had any active work in the period | | `hsi_cohort` | How many of them contributed a confident human-state signal | | `deep_work_availability` | Average flow availability across members with a human-state signal | | `focus_fragmentation` | Average context switches per worked window | | `capacity_coverage` | Share of active time with a known capacity: how much human state informed the row | | `adoption_rate` | Share of members with at least one tracked AI-tool hour | | `ai_habit` | How regularly the team uses AI: the average share of each member's worked days with tracked AI use | | `alignment_rate` | Share of `human_state` calls where the team's state called for an adapted answer. Not part of AEI; a calm team reads low | | `suppressed` | `true` when nobody had active work in the period, so the row has nothing to report | | `human_side_suppression_reason` | Why the human-state columns are blank on a row that isn't suppressed, for example because fewer people than the privacy floor contributed | Every export also states the organization's `cohort_floor` (the privacy floor), the `aei_version` and the `granularity`. A metric with no value is an empty cell, never `0`, so a gap can't be read as a score. > [!NOTE] > > When team human-state views are off under **Trust → Privacy controls**, the human-state columns (`deep_work_availability`, `focus_fragmentation`, `capacity_coverage`, `alignment_rate` and related) are blank in every export, and the export's `human_state_withheld_reason` says so. Work and AI-adoption columns are still filled in. They fill in once the setting is turned on. ## What an export never contains * **Per-person rows.** Not available on any plan: an export can only be built from team aggregates, so there is no individual row to unlock. * **Raw human-state scores or body signals.** Human-state columns are team totals, and only when enough people contributed to meet the privacy floor. Work and AI-adoption columns have no contributor floor, because they never contain human state. * **Prompts, code or content.** AI adoption is measured from tool names and counts only. ## Download a CSV Under **Team export**, choose a **Range** (7, 30 or 90 days) and the **Rows** (one summary for the whole range, or one row per day). The preview below shows the rows exactly as your BI tool will get them, including empty periods and withheld human-state columns. Then select **Download CSV**. Each download is recorded in the organization's audit log. ## Send to a webhook 1. Select **Add destination**. 2. Enter an `https://` URL. Plain `http://` addresses are refused, since exports are only delivered over an encrypted connection. 3. Choose a **cadence** (daily or weekly) and a **granularity** (the last 7 days in one summary, or one row per day). 4. Select **Add destination** and copy the **signing secret**. It's shown once and can't be retrieved later. If you lose it, remove the destination and add it again. Use **Test** on a destination to send an export now. Its **Last delivery** shows whether your endpoint accepted it, or why not. ### Schedule A new destination receives its first export within the hour. After that, daily destinations receive one roughly every 24 hours and weekly ones every 7 days, each covering the 7 days before delivery. A failed delivery isn't retried. The next one follows the destination's usual schedule, so check **Last delivery** if your data stops arriving. **Pause** stops deliveries without deleting the destination; **Remove** deletes it and its signing secret. ### The request Each delivery is a `POST` with a JSON body and these headers: | Header | Value | | - | - | | `Content-Type` | `application/json` | | `X-Synapse-Event` | `synapse.effectiveness.cohort.v1` | | `X-Synapse-Signature` | `sha256=` followed by the hex HMAC-SHA256 of the raw body, keyed with the signing secret | | `User-Agent` | `Synheart-Synapse-Export/1.0` | ```json theme={null} { "event": "synapse.effectiveness.cohort.v1", "delivered_at": "2026-10-29T06:00:00Z", "webhook_id": "…", "export": { "org_id": "…", "cohort_floor": 5, "aei_version": "…", "granularity": "window", "from": "2026-10-22T06:00:00Z", "to": "2026-10-29T06:00:00Z", "series": [ { "period_start": "2026-10-22T06:00:00Z", "period_end": "2026-10-29T06:00:00Z", "suppressed": false, "cohort": 18, "hsi_cohort": 12, "deep_work_availability": 0.41, "focus_fragmentation": 0.32, "capacity_coverage": 0.87, "adoption_rate": 0.72, "ai_habit": 0.55, "alignment_rate": 0.58 } ] } } ``` Your endpoint should answer with a `2xx` status within 30 seconds. Any other answer, or no answer in time, is recorded as a failed delivery. ### Verify the signature Compute the HMAC over the body exactly as received, before parsing it, and compare it in constant time: ```python theme={null} import hashlib import hmac def is_from_synapse(body: bytes, signature: str, secret: str) -> bool: expected = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` Reject any request whose signature doesn't match. # Get started Source: https://docs.synheart.ai/synapse/get-started Set up Synapse for your organization in five steps. Create or choose the organization, pick a plan, pay, invite your team and connect GitHub This is for the person bringing Synapse to their company, usually an engineering lead or CTO. If someone already invited you, see [Join your team](/synapse/join) instead. Go to [synapse.synheart.ai](https://synapse.synheart.ai) and sign up, or sign in with your Synheart account. Setup then walks you through five steps: **Organization**, **Plan**, **Payment**, **Team** and **Connect**. Each one is saved as you go, so you can leave and pick up where you stopped. **1. Choose the organization** Synapse works per organization, and everyone on your team joins the same one. * **An organization you already own** is listed with *It doesn't have Synapse yet*. Pick it to add Synapse to it. * **A new organization** starts fresh. Enter its **Organization name**, usually your company or team name. You can change it later. If you've been invited to someone else's organization, the invitation shows here too, so you can join that one instead of creating your own. **2. Pick a plan** Choose **Synapse Free** to start without paying, or a paid plan. Each person who uses Synapse takes one seat. Enter how many seats you want, and a promo code if you have one: the step shows what the code gives you before you pay. Your total appears once you've picked a plan and a seat count. The button says what happens next: **Start free**, **Start free trial** or **Continue to payment**. A free trial asks for a card at checkout but charges nothing until the free days end. You can change seats later. See [Billing & usage](/synapse/billing-and-usage) for what each plan includes. **3. Pay** Payment happens on a secure checkout page. When you come back, Synapse confirms the payment and turns itself on, which usually takes a few seconds. The page checks by itself, so there's no need to refresh. If it takes longer than usual, you'll get an email when Synapse is ready and can close the page. If the payment doesn't go through, nothing is charged and your organization and plan are kept, so you can try again. If your bank needs an extra check, finish it on the payment page. Synapse Free skips this step. **4. Invite your team** Enter your teammates' work emails and choose each person's role: **Member**, **Lead** or **Admin**. Each person gets an email and uses one seat. The step shows how many seats you're using and how many are free. Choose **Give me a seat too** if you want to see your own AI work as well as run Synapse. It uses one seat. You can **Skip for now** and invite people later from **Admin → Members**. See [Members and roles](/synapse/members-and-roles) for what each role sees. **5. Connect GitHub** Choose **Connect GitHub** to install the Synapse GitHub App. Synapse reads pull requests, reviews and commits, and their activity and timing. It never reads your code. Your first numbers appear within a day. You can **Skip for now** and connect GitLab, Jira, Slack and AI tools later from [Connectors](/synapse/connectors). ## Next Your organization is set up. To finish setting it up for your team, see [Set up your team](/synapse/admin-setup): connect your AI tools, write the team's agent rules and turn on the weekly summary. If you gave yourself a seat, also follow [Developer setup](/synapse/developer-setup) to connect the AI tools on your own computer. ## Starting from a link with a code A link such as `synapse.synheart.ai/start?code=…` saves the code before you sign up. It's applied on the **Plan** step, where you see what it gives you before paying. # Goals & alerts Source: https://docs.synheart.ai/synapse/goals-and-alerts Set targets on team metrics, hear when one crosses a line, and post a weekly digest to Slack. Which metrics you can use, how progress is read, and who can change them **Goals & alerts**, under **Teams** at [synapse.synheart.ai](https://synapse.synheart.ai), is where leaders set targets on team metrics and choose to be told when something moves. It works on team totals only. No goal, alert or digest ever tracks one person. Synapse Leads and Admins can open it, and create and change goals, alerts and the digest, on paid plans. ## What you can track Goals and alerts use the same metrics, in two groups. **Work conditions.** These are the outcomes worth aiming at. | Metric | Unit | Better | | - | - | - | | **Deep-work availability** | % of work time | Higher | | **Focus fragmentation** | Task switches per working hour | Lower | | **Meeting load** | % of work time | Lower | **AI context: usage, not outcomes.** These are kept apart because a target on adoption is a usage target, not a result. | Metric | Unit | Notes | | - | - | - | | **AI adoption** | % of people | Usage, not an outcome. | | **Human-state adaptation requests** | | Shown only for existing goals and alerts. No healthy range exists for it, so new ones can't use it. | > [!NOTE] > > You can't set a goal or alert on the AI Effectiveness Index. It's [three separate measures, not one score](/synapse/how-synapse-works#the-ai-effectiveness-index), so there's nothing single to aim at. Goals and alerts made before this changed are marked **Retired**, and can only be deleted. Every metric is a team total. Work and AI metrics are exact. Anything built from human state follows your organization's [cohort floor](/synapse/team-views#the-cohort-floor). Human-state readings themselves, such as focus or fatigue, are never used in goals or alerts. ## Goals A goal watches one team metric over the last 7 days and shows how close it is to the target. To add one, choose **New goal**, then fill in: 1. **Label** (optional), for example *Protect focus time*. 2. **Metric**, from the lists above. 3. **Target**, as a percentage, or as switches per hour for focus fragmentation. Synapse suggests a starting value. 4. **Review by** (optional), a date to look at it again. Each goal shows its current value and a bar toward the target, in one of three states: * **Met.** The metric has reached the target. * **In progress**, with how far is left, such as *8 pp to go* (percentage points) or *0.40 / hr to go*. * **No reading yet.** There isn't enough data, for example because too few people are behind it. Synapse doesn't guess. Edit or delete a goal from its card. Deleting asks you to confirm first. ## Alerts An alert tells you when a team metric crosses a line. Alerts are checked every hour. To add one, choose **New alert**, then fill in: 1. **Metric.** 2. **Alert when it goes** **Below** or **Above**. 3. **Threshold**, as a percentage or switches per hour. 4. **Notify via**, **In-app** or **Slack**. For Slack, choose a channel and invite `@Synapse` to it. Slack must be connected under **Admin → Connectors** first. Each alert shows whether it's active or paused, and when it last fired. Pause an alert to stop it for a while without losing it, and resume it later. Delete asks you to confirm. ## Weekly digest The weekly digest posts a summary of team totals to a Slack channel once a week. It includes AI tool usage, unused Copilot seats and what agents were stopped from doing. See [In the weekly summary](/synapse/ai-spend#in-the-weekly-summary). 1. Connect Slack under **Admin → Connectors**, if you haven't. 2. Under **Weekly digest**, turn on **Post to Slack weekly** and choose a **Channel**. 3. Choose **Save changes**. 4. To check it, choose **Send one now**. It posts this week's summary straight away, using the saved setting. The digest leaves out human-state totals below the cohort floor, as every team view does. ## Who can do what | Action | Who | | - | - | | Open Goals & alerts | Synapse Leads and Admins | | Create, edit, pause and delete goals and alerts | Synapse Leads and Admins | | Turn the weekly digest on or off, and choose its channel | Synapse Leads and Admins | # How Synapse works Source: https://docs.synheart.ai/synapse/how-synapse-works The ideas behind Synapse, in plain words. Seats and roles, departments, human state and Life, the AI Effectiveness Index, the cohort floor, and how to read evidence labels Synapse sits between your engineering team and the AI tools it uses. Agents ask it about your rules and decisions before they act. Synapse also collects what those tools, your repositories and (with consent) your people's human state say about how AI work is going, and shows it back as team views. This page explains the ideas that come up on almost every screen. Once you know them, the rest of the docs read more easily. ## Seats and roles You need a **Synapse seat** in your organization to use Synapse. The organization owner or an organization admin gives out seats. Each seat comes with one Synapse role, and **the role decides what you can see and do**. Your role on the Synheart platform doesn't. | Role | What it adds | | - | - | | **Member** (the default) | Your own memory, decisions and **My Effectiveness**, your own department's team view, your own AI-tool connections, and your own Life connection and erasure. | | **Lead** | Everything a Member has, plus the whole organization's team views, AI usage, AI spend, goals and alerts, and exports. | | **Admin** | Everything a Lead has, plus connectors, knowledge sources, MCP tokens, departments, rules, the audit log and the privacy settings. | The organization owner can do everything, but only with a seat, like everyone else. A few things never need a seat: the owner and organization admins can change privacy settings, any member can [erase their own data](/synapse/team-views#erasing-data), and only the owner can erase the whole organization's data. > [!TIP] > > If a page you expect is missing from your sidebar, your role probably doesn't include it. Ask a Synapse Admin. See [Find your way around](/synapse/navigate) for what each role sees. ## Departments and scope A **department** is a group of members, such as Platform or Mobile. Admins create departments and add people to them under **Departments**. Every team view has a **scope**, shown as a badge at the top of the page. Members see their own department. Leads and Admins see the whole organization and can pick any department. In an organization with no departments yet, the whole organization is everyone's team. That changes as soon as the first department exists. ## Human state and Life **Human state** is a coarse estimate of how someone is doing at work, such as focus, cognitive load and fatigue. It comes from **Life by Synheart**, which each person connects for themselves under **You → My connections**. * **It's opt-in.** Nobody's human state is used until they connect Life and consent to contribute. Consent is given and withdrawn in the Life app. Leads and admins can't do it for anyone else. * **You see your own.** Your own numbers show in **My Effectiveness**. Your coding agent can also use your current state to change how it answers you, for example shorter, more focused replies when you're tired. Agents only get that coarse guidance, never health data. * **Teams see totals.** Team human-state views are medians over members who consented, and only above the cohort floor. Nobody can drill down to one person. * **It's never used to judge people.** Human state isn't used in alerts, goals, rankings or recommendations. An admin can turn team human-state views off for the whole organization. See [Team human-state views](/synapse/team-views#team-human-state-views). ## The AI Effectiveness Index The **AI Effectiveness Index (AEI)** answers "how is AI working for us?" with **three separate measures, not one score**. Synapse never adds them up, weights them or ranks teams by them, because a single number would hide what's actually going on. | Part | The question | What it shows | | - | - | - | | **Adoption** | Are people using AI? | **Reach**, the share of measured members who used any AI tool, and **Habit**, the share of worked days with AI use. | | **Delivery** | Is work moving differently since AI arrived? | The change in median PR lead time in the 4 weeks after an AI tool's rollout, compared with the 4 weeks before. | | **Human** | How are people doing while they use it? | Team medians of focus, cognitive load and fatigue during work hours, with how many people consented. This part is in Beta. | The current version is **aei-v9**. Figures from aei-v8 or earlier were calculated differently, so don't compare them. For what's on each tab, see [AI Effectiveness](/synapse/ai-effectiveness). ## The cohort floor The **cohort floor** is the smallest number of people a team human-state figure is shown for. Below it, the figure is withheld with a note, rather than estimated. It's **4 by default**, and an admin can raise it to as many as **50**. The floor is why a small team may see "Private" or a dash where a number would be. A team below the floor can still see its own view if every member [opts in to sharing](/synapse/team-views#share-my-numbers-with-my-team). Work and delivery figures, such as merged PRs or AI adoption, describe your repositories and tools rather than people's state, so the floor doesn't hold them back. See [The cohort floor](/synapse/team-views#the-cohort-floor) for every rule. ## Evidence labels Some numbers come with a label that says how strongly you can lean on them. * **Describe.** A plain count or share of what happened, like Reach. It says nothing about why. * **Associate.** A change that happened alongside AI use, like Delivery. It's a pattern worth looking into, not proof that AI caused it. * **Beta.** The measure is new and may change. Read it as a hint. Synapse also never shows a missing value as zero. A dash means there's no data. `0` means Synapse looked and found none. ## Where the data comes from | Source | Gives Synapse | Set up in | | - | - | - | | GitHub and GitLab | PRs, reviews, CI runs and deploys, for delivery metrics and AI attribution | **Connectors** | | AI tools (Copilot, Cursor, Claude, OpenAI) | Usage and spend reports | **Connectors** | | Notion, Google Drive, OneDrive, Slack, repositories | Organization knowledge for agents and search | **Knowledge sources** | | The Synheart CLI and MCP | Rule checks and agent calls, as day totals | [Developer setup](/synapse/developer-setup) | | Life by Synheart | Human state, only for people who consent | **You → My connections** | For exactly what's stored and for how long, see [What Synapse collects](/synapse/overview#what-synapse-collects). # Join your team Source: https://docs.synheart.ai/synapse/join Accept an invitation to your organization's Synapse, then get set up. Install the CLI, link your work accounts and see what your team can see This is for someone invited to an organization that already uses Synapse. If you're setting Synapse up for your company, see [Get started](/synapse/get-started) instead. ## Accept the invitation Open the link in your invitation email. Sign in, or create a Synheart account with the email the invitation was sent to. The page says who invited you, which organization it's for, the **Role** you'll have and when the invitation **Expires**. Choose **Accept invitation**. Joining uses a seat your team has already paid for. It costs you nothing. If the page says *This invitation has expired*, ask the person who invited you to send a new one. If you've already signed in elsewhere, pending invitations are also listed on your [profile](/synapse/profile#invitations). ## Get set up After you accept, **Get set up** walks you through three things: **1. Install the Synheart CLI** The CLI connects the AI tools on your computer, such as Claude Code and Cursor, to Synapse. It asks before sending anything. ```bash theme={null} curl -fsSL https://synheart.sh/install | sh ``` ```bash theme={null} synheart synapse setup ``` On Windows, or to do it by hand, see [Developer setup](/synapse/developer-setup). **2. Link your work accounts** Link GitHub and your other work accounts under **You → My connections**, so your pull requests and AI usage count as yours. See [Connectors](/synapse/connectors). **3. Know what your team sees** Your manager sees team totals, never your own numbers, and only when enough people contribute. You can see and change what you share at any time under **You → Privacy & consent**. See [Privacy & consent](/synapse/privacy-and-consent). You can come back to these steps later from **You → Connect your AI**. Choose **Go to Synapse** when you're done. ## What you'll see What you see depends on the role you were given: * **Member**: your own work in [My Effectiveness](/synapse/my-effectiveness), and your department's team view. * **Lead**: the same, plus team views for the whole organization. * **Admin**: everything a Lead sees, plus running Synapse for the organization. See [Members and roles](/synapse/members-and-roles) for the details, and [Find your way around](/synapse/navigate) for where everything is. # Knowledge sources Source: https://docs.synheart.ai/synapse/knowledge-sources Choose the repositories, pages, drives and channels Synapse indexes for search, who can find each one, and what each status and action means **Knowledge sources**, under **Admin** at [synapse.synheart.ai](https://synapse.synheart.ai), are the repositories, pages, drives and channels whose text Synapse indexes. Their text is what [Ask Synapse](/synapse/search) and your agents' `recall` find. This is separate from [Connectors](/synapse/connectors). Connecting a tool collects activity, never its text. Text is indexed only from the sources chosen here. Synapse Admins choose and change knowledge sources. ![The Knowledge sources page, with an Add source button, filter chips, and a GitHub group listing repositories with their status and document counts](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/knowledge-sources.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=c6feb06ac07fcb3ba4a76c48d2757eb2) Knowledge sources, grouped by provider ## Adding a source Choose **Add source**, then pick the kind: * **GitHub**: a repository's Markdown docs, RFCs and ADRs. The GitHub app must be able to see the repository. * **Notion**: pages shared with Synapse. * **Google Drive**: a shared drive. * **Slack**: a public channel. The provider has to be connected under **Admin → Connectors** first. Each kind says who will be able to search it before you add it. OneDrive folders are chosen by members themselves. See [OneDrive as a knowledge source](/synapse/microsoft-365#onedrive-as-a-knowledge-source). ## Who can find what Each document keeps the audience it has at its source, and every search filters on it. | Source | Who can find it | | - | - | | **GitHub**, **GitLab** | Everyone in your organization | | **Notion** | Members who shared the page | | **Google Drive** | Members who linked Google Drive and can open the file | | **Slack** | Everyone in your organization, from public channels, for the last 90 days | More on this in [Ask Synapse: who sees what](/synapse/search#who-sees-what). ## Statuses Use the chips at the top to show one group at a time. | Filter | Means | | - | - | | **Needs review** | Indexed before admins chose sources. Keep each one or stop indexing it. | | **Needs attention** | Failed, not indexed yet, partly read, or waiting on members to link an account. Each row says what to do. | | **In progress** | Queued, indexing or syncing, or paused and resuming on its own. | | **Indexed** | Has searchable text, and nothing to do. | | **No documents** | Nothing searchable reported yet. | Each row shows how many documents are indexed and when it last finished. ## Row actions * **Index now** or **Retry**: start indexing a source that hasn't been indexed, or try again after a failure. * **Keep**: keep a source from **Needs review**. It stays searchable. * **Sync now**: re-read a source straight away, rather than waiting for the next scheduled sync. * **Stop indexing**: asks you to confirm first. Its indexed text is deleted from Synapse and it stops being searchable. Nothing in the source tool is touched, and adding it again re-indexes it. ## Who can do what | Action | Who | | - | - | | Search indexed knowledge | Everyone with a seat, within each source's audience | | Add, keep, sync and stop indexing sources | Synapse Admins | # Members and roles Source: https://docs.synheart.ai/synapse/members-and-roles Invite people to Synapse, give and remove seats, and choose each person's Synapse role. What Member, Lead and Admin can each do, and who can change what **Members**, under **Admin → People** at [synapse.synheart.ai](https://synapse.synheart.ai), is the roster of everyone who holds a Synapse seat, with their role and department. It's where you invite people, give seats and change roles. The organization owner, organization admins and Synapse Admins can open it. ## Seats and roles Two separate things decide what someone can do in Synapse: * **A seat** lets a person use Synapse at all. Without one, nobody can open Synapse pages, not even the organization owner. Seats are a billing matter, so only the organization owner and organization admins give and remove them. * **A Synapse role** decides what a seated person sees. It only applies inside Synapse and says nothing about the rest of the Synheart platform. Organization roles (owner, admin, member) are covered in [Platform members and roles](/platform/members-and-roles). Apart from the owner, an organization role gives nothing inside Synapse by itself. What a person can do there comes from their seat's Synapse role. ## The three Synapse roles | Role | Can | Can't | | - | - | - | | **Member** (the default) | Use Synapse: their own memory, [My Effectiveness](/synapse/my-effectiveness), their own AI tools and Life link, and their own department's team view. | See the whole organization's team view, or another department's. | | **Lead** | Everything a Member can, plus team views for the whole organization and team exports. | Any administration. | | **Admin** | Everything a Lead can, plus running Synapse: [connectors](/synapse/connectors), [knowledge sources](/synapse/knowledge-sources), MCP tokens, [departments](/synapse/departments), the [audit log](/synapse/audit-log), Life connection status and the [privacy controls](/synapse/team-views#privacy-controls). | Give or remove seats, or erase the organization's data. | The organization owner, while holding a seat, can do everything an Admin can. Erasing all of the organization's Synapse data stays with the owner only. A member who isn't in a department sees no team view until they're in one, unless your organization has no departments at all. See [Departments](/synapse/departments). ## Inviting people Choose **Invite to Synapse**, then enter their **work emails**. Press Enter after each address, or paste a list. Choose a **Synapse role** for them and send. Accepting makes the person an organization member with a Synapse seat. An invitation holds a free paid seat while it waits. Accepting never buys one. If there's no free seat, buy more first under [Billing & usage](/synapse/billing-and-usage). **Pending invitations** lists the ones not accepted yet. **Resend** sends the email again. **Revoke** stops the invite link working. Only the organization owner and organization admins can invite. ## Giving seats to people already in the organization People who are already organization members but have no seat are listed under **Give Synapse seats**. Search for them, pick one or more, choose one Synapse role for all of them (**Member** unless you change it), and choose **Give seats**. Seats are given one person at a time, with a result for each. If a seat can't be given, for example because the seat limit was reached or a payment failed, the panel says which people weren't seated and offers **Retry**. ## Changing a role Open the person's row and choose their **Synapse role**. The change applies straight away. It never changes the number of seats or what you're billed. The organization owner, organization admins and Synapse Admins can change roles. Nobody can change their own role. ## Removing someone From a person's row: * **Remove seat.** They lose Synapse access but stay in the organization. Giving them a seat again restores their role. * **Remove from organization.** They lose access to the organization and its Synapse seat. Both ask you to confirm first. The organization owner can't be removed. Only the owner can remove an organization admin. ## Finding people Search by name or email, or filter the roster by Synapse role. A warning above the roster says when seated members aren't in a department. **Show who** lists them, and **Assign departments** takes you to Departments. ### Life connection status Synapse Admins also see how far the Life rollout has got: how many members have linked Life by Synheart, and a **Life linked** badge on each person who has. This is pairing status only. It never shows anyone's human state. ## Who can do what | Action | Who | | - | - | | Open Members | The organization owner and admins, and Synapse Admins | | Invite people, give and remove seats | The organization owner and organization admins | | Change a seated person's Synapse role | The organization owner, organization admins and Synapse Admins | | Remove someone from the organization | The organization owner and organization admins. Only the owner can remove an admin | # Synaptic Mesh Source: https://docs.synheart.ai/synapse/mesh A map of how your organization's decisions, code, documents and people connect, as a timeline or a network. My Mesh and Org Mesh, restricted items, and where human state appears **Synaptic Mesh**, under **Ask** at [synapse.synheart.ai](https://synapse.synheart.ai), shows the story behind your code: which decisions shaped it, what came from each one, and who did the work. It's built from your organization's indexed [knowledge sources](/synapse/knowledge-sources) and connected work. Everyone with a seat can open it. ## My Mesh and Org Mesh * **My Mesh** shows your own work and what it connects to. Everyone sees it. * **Org Mesh** shows the whole organization. It's for Synapse Leads and Admins, and the organization owner. Members don't see the switch. ## Two views **Timeline** tells the story of one piece of code or one decision through time: what it was built because of, what was added under it, and what replaced it. **Network** is the whole map. Drag nodes, pan and zoom, or use **Fit to view**. Select a node to read its details. A trail of the nodes you've opened runs through both views, so something you read in the timeline can be found on the map and back. Search for code or a decision with **Find code or a decision**. The legend turns categories on and off: decisions, code, documents and notes, issues and tickets, pull requests and commits, and people. ## What the links mean Each link says how two things relate, for example: * **Built because of** and **Added under**: code that follows a decision. * **Replaces** and **Replaced by**: a decision that superseded another. * **Addresses**, **Fixed by**, **Caused by**: work tied to an issue or incident. * **Written by**, **Top contributor**: who did the work. Decisions are drawn bigger when more code follows them. A decision with nothing linked says *No code follows it yet*. Code links to a decision when a commit mentions its id, such as `ADR-0006`, or when the decision is saved in the code's folder. Items linked to nothing are marked as gaps, so you can see what still needs a decision or an owner. ## Ask your agent about a node A node's details include **Ask your AI (MCP)**. **Ask "Why was this created?"** and **Find related context** copy a prompt that names the node. Paste it into Claude Code, Cursor or another agent connected to Synapse, and it answers from the same memory. See [Connect your agent](/synapse/connect-agents). ## Restricted items Some documents are restricted at their source, or by an admin. A restricted item keeps its place on the map so the shape of the story stays true, but its title and content are never shown. It appears as **Restricted item**. You can hide restricted items from the legend. Restricting or un-restricting a document is recorded in the [audit log](/synapse/audit-log). ## Human state on the map If you've connected Life by Synheart, your own nodes can show **Your state across this work**: your readings near the time you did it. Human state appears only on your own nodes, for every role. A teammate's node never carries their human state, whoever is looking, including Leads, Admins and the owner. If your organization has turned off human state, or you haven't connected Life, the map says so and shows no readings. See [Team views and privacy](/synapse/team-views). ## On Synapse Free On Synapse Free, the map covers the last 30 days of history. # Metrics explained Source: https://docs.synheart.ai/synapse/metrics How each delivery and repository metric on Insights is counted, where AI shows up in merged PRs, what counts as a production deploy, and what the numbers can't tell you The **Delivery** section on **Insights** at [synapse.synheart.ai](https://synapse.synheart.ai) shows the work your organization shipped, how it moved from idea to production, and where AI was involved. Each card shows one number and one line under it. The ⓘ next to the title gives the short definition. This page has the full version: what goes into each number, what's left out, and why. ![The Delivery section on Insights, showing delivery and engineering measures as cards](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/metrics-delivery.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=6ed8c54f00cc3f45efe9c81e096ff31a) The Delivery section on Insights ## Before you read the numbers A few rules apply to every metric on this page. * **No data isn't zero.** If a source hasn't reported, or its history is incomplete, the card is left out or shows a dash. It never shows `0`. A zero means Synapse looked and found none. * **"Observed" means partial.** When Synapse can see some of a period but not all of it (for example, an issue tracker's history only goes back part way), a count card is renamed, say from **Issues completed** to **Issue completions observed**. The number is what Synapse saw, and the real figure may be higher. * **Organization-wide, no contributor floor.** Delivery metrics come from your connected repositories and trackers, not from people's human state, so they aren't held back by the [cohort floor](/synapse/team-views#the-cohort-floor). They describe the organization's repositories, not individuals. * **Descriptive, not a score.** These are counts and medians of what happened. They aren't productivity targets, they don't rank people, and on their own they don't show that AI caused a change. * **Medians, not averages.** Times and sizes use the median (the middle value), so one PR that sat open for a month doesn't drag the figure. ## Delivery measures These come straight from GitHub, GitLab and your connected issue trackers, across every connected repository. Bots and people who aren't linked to a Synapse member are included, because they still shipped work. | Metric | What it counts | | - | - | | **Issues completed** | Issues finished in the period. Each issue counts once, even if it's reopened and closed again later. | | **Total merged PRs** | Every pull request (GitHub) or merge request (GitLab) merged in the period, including bots, automation and authors not linked to a member. PRs with impossible timestamps, such as merged before they were opened, are left out. | | **Production deployments** | Successful deploys to production, using what you've told Synapse counts as production. See [Production deploys](#production-deploys). | | **PR lead time** | The typical (median) time from opening a PR to merging it, over the same PRs as **Total merged PRs**. It isn't commit-to-production time. | | **Issues created** | New issues opened in your connected trackers in the period. | | **Production-branch merges** | PRs merged into a branch you've marked as production. A merge isn't a deploy: code can land on `main` and wait for a release. | | **Time to first human review** | The typical wait from opening a PR to its first review by someone other than the author, and not a bot. Only reviews before the merge count. PRs that were merged with no human review are left out, rather than counted as an instant review. | | **CI success rate** | The share of CI runs that passed. Only the latest attempt of each run counts, so a flaky job that passes on retry counts once, as a pass. Timeouts and runs that failed to start count as failures. Canceled, skipped and still-pending runs are left out. | ## Engineering measures These describe the human side of code review and shipping. They count PRs by people with a GitHub or GitLab account linked to their Synapse membership. Bots and draft PRs are left out. | Metric | What it counts | | - | - | | **PR cycle time** | The median time from opening to merging, for human-authored PRs by linked contributors. It's shown only when the repository-wide **PR lead time** has no value. | | **Merged PRs per week** | How many human-authored PRs merged each week. It's a description of pace, not a target or an AI effect. | | **PRs per engineer** | Merged PRs per engineer per week. Every member with a linked GitHub or GitLab account counts for the whole week, including weeks they didn't open a PR. | | **PR size** | The median of lines added plus lines deleted per merged PR. The ⓘ also shows the median number of files changed. | | **Review load** | The average number of reviews on each merged PR, leaving out self-reviews and bots. The ⓘ also shows the average number of distinct reviewers. | | **Production deploys per week** | The weekly median of production deploys. The ⓘ also shows the daily rate. | > [!TIP] > > Engineering measures only include people whose code accounts are linked. If a number looks low, check that your developers have linked their GitHub or GitLab accounts. See [Developer setup](/synapse/developer-setup). ## Production deploys Synapse doesn't guess which of your branches and environments are production. You tell it, one repository at a time, and **Production deployments**, **Production-branch merges** and **Production deploys per week** follow that setting. To set it up, go to **Connectors**, open **GitHub** or **GitLab**, and find **Production delivery**. Only owners and admins can change it. Everyone else sees it read-only. ![The Production delivery settings in the GitHub connector, with production branches, the deploy source and the webhook status](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/metrics-production-delivery.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=db014650a044e8e36758d8684e396123) Production delivery settings for one repository, in Connectors For each repository: 1. **Production branches.** Choose the branches that count as production. Merges into these count as **Production-branch merges**. Synapse suggests the repository's default branch, but nothing counts until you save. 2. **Count deploys from.** Choose one of two sources: * **Deployments to production environments.** Use this if you record deployments in GitHub or GitLab, for example GitHub Environments. Pick the environments that are production. Each successful deploy to one of them counts. CI runs don't. * **Selected CI workflows.** Use this if a CI job does your deploy. Pick the workflows that deploy to production: workflow file paths on GitHub (such as `.github/workflows/deploy.yml`), or exact pipeline names on GitLab. A successful latest run of one of those workflows, on a production branch, counts as a deploy. Saving confirms that these workflows really deploy to production. 3. **Save delivery policy.** Each repository uses one source only, so the same release is never counted twice. Repositories you haven't set up don't add to production metrics. **Webhook.** Below the settings, Synapse shows whether live updates from the provider are arriving. If they stop, scheduled syncs still keep the data up to date, just less often. On GitLab, live updates need the `api` scope and Maintainer access to the project. If you connected GitLab with `read_api` only, reconnect it. ## AI PR attribution **Repository AI evidence**, under Delivery, shows where AI shows up in the PRs your organization merged. It looks for signs that AI wrote or helped with a PR. It can't prove that code was generated, and a PR with no sign of AI wasn't necessarily written without it. ![Repository AI evidence, with merged PRs split by AI attribution and by author account type, and the count of AI coauthored PRs](https://mintcdn.com/synheartai/bIbSKNEqulE95GhK/images/synapse/metrics-ai-attribution.png?fit=max\&auto=format\&n=bIbSKNEqulE95GhK\&q=85\&s=ecf4caf14e4ae1f2e85756d189ada5f1) Repository AI evidence on Insights ### AI attribution Every merged PR falls into exactly one group. When a PR has more than one sign, the strongest one wins. | Group | What puts a PR here | | - | - | | **Agent-authored PRs** | The PR was opened by a coding agent's own bot account on GitHub or GitLab, such as the Copilot coding agent, Claude, Codex, Cursor, Devin or Gemini Code Assist. | | **Declared assistance** | Someone said AI helped: a declaration line at the end of the PR description (for example *Generated with Claude Code*), an `ai-assisted` or `ai-generated` label, or an AI `Co-authored-by`, `Generated-by` or `Assisted-by` trailer on a commit. | | **AI hints only** | Weaker signs with no declaration: a branch named after an agent (such as `claude/…` or `codex/…`), or commits authored from an AI company's email domain. | | **Unknown AI attribution** | No sign either way. That doesn't mean the PR was human-only. Many people use AI without leaving a trace. | Synapse is strict about what counts as a declaration. A line has to be a declaration on its own, at the end of the PR description or in a commit's trailer block. A sentence such as "we didn't use Copilot here", or an example in a code block, doesn't count. The four groups always add up to all merged PRs, so you can read them as shares. ### PR author account type The same merged PRs, split a second way: by who opened them. * **User accounts:** a person's account. * **Automation accounts:** bots and service accounts, including coding agents and dependency bots. * **Unknown account type:** the provider didn't say. This is a separate question from AI attribution. A PR from a user account can still be AI-assisted, and generic bots like Dependabot aren't counted as AI. ### AI coauthored PRs A count of merged PRs with at least one commit carrying an AI `Co-authored-by` trailer, which many coding agents add by default. Each PR counts once. Other kinds of declaration don't count toward this figure, and PRs Synapse could only partly inspect can't be counted as having none. ### What Synapse reads, and what it keeps To classify a PR, Synapse reads the PR's author, labels, description, branch name, commit messages and commit author email domains, as your connector allows. It keeps only the result: the group, the tool name (such as `claude-code`) and how the signal was found. It doesn't store descriptions, commit messages or email addresses. On very large PRs it reads the first 256 commits and marks the result as partial. ## What these numbers can't tell you * **That AI caused a change.** A rise in merged PRs alongside a rise in agent-authored PRs is a pattern, not proof. * **How much code AI wrote.** Attribution is per PR, not per line. * **How productive a person is.** Synapse doesn't rank people by these metrics, and it shouldn't be used to. * **Anything outside connected repositories.** If a repository isn't connected, or the provider's history is incomplete, its work is missing. For how team figures from human state are protected, see [Team views and privacy](/synapse/team-views). For where AI spend comes from, see [AI spend](/synapse/ai-spend). # Microsoft 365 Source: https://docs.synheart.ai/synapse/microsoft-365 What the Outlook Calendar, Outlook Mail, Teams and OneDrive connectors read, what they never keep, and how an admin connects them Synapse connects to Microsoft 365 as four separate tools: **Outlook Calendar**, **Outlook Mail**, **Teams** and **OneDrive**. Each is granted, enabled and disconnected on its own, so an organization can connect one without the others. ## What each tool reads The organization tools read **metadata about work, never its content**: when something happened and which verified member did it. | Tool | Synapse keeps | Synapse never keeps | | - | - | - | | Outlook Calendar | When each meeting on a member's default calendar starts and ends | Subjects, descriptions, attendees, locations, recordings or transcripts | | Outlook Mail | That a member sent a message, and when (Sent Items only) | Subjects, addresses, message bodies or previews, attachments | | Teams | That a member posted or replied in a channel, and when | Message text, attachments, reactions, private chats, calls, meeting recordings or transcripts | | OneDrive | An inventory of files: names, links, sizes and dates | File contents. Organization collection never downloads or indexes a file | A few rules hold across all four: * **Only verified members count.** Activity is attributed only to people Synapse can match to a current member of your organization. Anyone it can't match is counted as unmatched and skipped, never guessed from an email address and never attributed to the admin who connected the tool. * **Teams content is discarded.** Microsoft's channel-message permission returns message text to Synapse; the collector throws it away and keeps only the metadata above. * **None of it is used for recall.** Calendar, mail and Teams metadata never become organization knowledge an agent can quote. * **No Microsoft 365 Copilot data.** These tools don't request access to Microsoft 365 Copilot prompts, conversations or usage. GitHub Copilot is a separate connector. ## OneDrive as a knowledge source The organization OneDrive tool keeps an inventory only. Making OneDrive files available to agents is a separate step: a member chooses a folder as a [knowledge source](/synapse/admin-setup#connect-github), and Synapse indexes that folder's files, answering each person only with files they can open themselves in OneDrive. ## Connecting your organization You need a Synapse admin, and a Microsoft account with the **Global Administrator** or **Privileged Role Administrator** role in your tenant. **1. Open Microsoft 365 under Connectors** In synapse.synheart.ai, open **Connectors** and find **Microsoft 365 · Organization**. **2. Sign in as a tenant administrator** Synapse verifies your Microsoft sign-in, your tenant and your administrator role before asking for consent. **3. Grant consent tool by tool** Each tool asks Microsoft for its own admin consent. Grant only the tools you want. Synapse requests these Microsoft Graph application permissions: | Tool | Permissions | | - | - | | Outlook Calendar | `Calendars.ReadBasic.All`, `User.Read.All` | | Outlook Mail | `Mail.ReadBasic.All`, `User.Read.All` | | Teams | `Team.ReadBasic.All`, `Channel.ReadBasic.All`, `ChannelMessage.Read.All` | | OneDrive | `Files.Read.All`, `User.Read.All` | `User.Read.All` lets Synapse match Microsoft accounts to your organization's members. Two of these permissions allow more than Synapse uses: `ChannelMessage.Read.All` returns message text, which is discarded, and `Files.Read.All` would allow reading files, which organization collection never does. ## Personal connections Members can also connect their own Outlook calendar, mail, Teams or OneDrive from **Your connections**. Those are separate from the organization tools, use the member's own permission, and cover only that member. ## Disconnecting * **Disconnect** on a tool stops that tool; **Disconnect organization suite** stops all four and clears the tenant binding. Members' personal connections stay as they are. * Collected metadata is kept by default. Ticking **Also delete imported Microsoft metadata** deletes it, including the same kind of metadata collected through members' personal connections. This can't be undone. OneDrive files that members chose as knowledge stay. * Disconnecting removes Synapse's access but not the consent you granted in Microsoft Entra. Remove the Synapse applications there too if you no longer want them to have access. * To bind your organization to a different Microsoft tenant, disconnect the whole suite first. # My Effectiveness Source: https://docs.synheart.ai/synapse/my-effectiveness Your own flow, focus and pace. What each measure counts, where the data comes from, the suggestions and Syni's explanations, and who can see it **My Effectiveness**, under **You** at [synapse.synheart.ai](https://synapse.synheart.ai), shows your own work conditions: how much of your time ran in flow, how often you switched tasks, how much went to meetings, and how sustainable your pace was. It's about you only. **Nobody else can see it**, including your manager, admins and the organization owner. Team views are built separately, from totals over many people. See [Team views and privacy](/synapse/team-views). It describes the conditions you worked in, not how well you worked. None of these numbers is a productivity score. Every seat can open it on paid Synapse plans. On Synapse Free it shows a **Paid** badge. ## Where the numbers come from Each source is read on its own, and each one says if it's missing. | Source | Gives | Connect it in | | - | - | - | | **Work activity**: GitHub, Linear, Slack | When you were working and switching between tasks | **You → My connections**, by linking your accounts | | **Calendar**: Google Calendar or Outlook Calendar | Meeting time | **You → My connections** | | **Human state**: Life by Synheart | Focus, load, fatigue and readiness, only if you consent | **You → My connections** | Linking an account doesn't import anything new. It matches your account to activity your organization has already connected, so Synapse knows which part of it is yours. If a source is missing or has a problem, a **Finish setup** panel says what to do, such as **Connect calendar**, **Link Life** or **Verify identity**. ## The page Pick a period at the top: **Today**, **7 days**, **30 days** or **90 days**. **Refresh** reloads the figures. ### Your measures A line at the top sums up the period in plain words, with how many hours were observed. Under it are three measures: | Measure | What it counts | Better | | - | - | - | | **Flow availability** | The share of your observed hours spent in flow: long stretches of focus without switching. | Higher | | **Focus fragmentation** | Task switches per working hour. | Lower | | **Meeting load** | The share of your observed work hours in meetings. | Lower | Each one is compared with the previous period of the same length. If the previous period was measured differently, the two aren't compared. **Where the hours went** shows your hours day by day. On **Today**, it shows the last seven days so today has some context. ### Suggested actions Suggestions written from your own hours, such as which part of the day or which weekdays a pattern shows up on. They aren't stock advice. When too few hours were observed to say anything useful, nothing is suggested, and the card says how many hours it has so far. You can turn on **Explain these with Syni**. Syni then rewrites each suggestion in plain words from your own numbers. Synapse checks every number before it's shown, and only you see it. It's off by default, and turning it off deletes what Syni wrote. ### When you focus A grid of your hours. Each cell is one hour, either in flow, other activity, or worked without a focus reading. Hours with nothing recorded stay blank, never zero. ### Sustainable pace How much of your measured time ran in a hard state. Shorter bars are better. * **Overload share.** Hours past the overload threshold for cognitive load, mental fatigue or capacity. * **Interruption exposure.** Hours past the interruption-pressure threshold. * **Low-readiness work.** Worked hours with a readiness reading below the readiness threshold. These need human state from Life. ### 12-week story Your flow (as a percentage) and fragmentation (switches per hour), week by week, for the last 12 weeks. The period picker doesn't change this chart. ### Mind and environment Model estimates from your consented Life readings, such as focus, cognitive load and mental fatigue, each on a 0–1 scale. They're yours alone, and they aren't a diagnosis. ## Missing numbers A dash or a label replaces a number when there's nothing to show. It never shows zero for missing data. | You see | It means | | - | - | | **Not connected** or **Not set up** | The source isn't connected yet. | | **No activity in range** | The source is connected but recorded nothing in this period. | | **Not shared** | You haven't consented to share it. | | **Limited readings** | There's some data, but too little to rely on. | | **Syncing** | Data is still arriving. | ## Your coding agent If you connect Life and use Synapse in your coding agent, the agent can get coarse guidance from your current state, for example to keep answers short and focused when you're tired. It gets that guidance only, never your readings or any health data. See [Connect your agent](/synapse/connect-agents). ## Your data You can stop sharing human state at any time in the Life app, and erase all your Synapse data from **You → Privacy & consent**. See [Erasing data](/synapse/team-views#erasing-data). # Find your way around Source: https://docs.synheart.ai/synapse/navigate A tour of the Synapse sidebar. What's in each space, who sees each page, and where to go for common tasks The sidebar at [synapse.synheart.ai](https://synapse.synheart.ai) is split into four spaces. Each one answers a different question: > [card] You > > Is this about me? Your own numbers, your agent's decisions, and your own setup. > [card] Teams > > Is this about a group of people? Team views of AI adoption, delivery, spend and goals. > [card] Ask > > What does the organization know? Search and the map of your organization's knowledge. > [card] Admin > > How is Synapse run? Sources, people, privacy and the plan. You only see the pages your [role](/synapse/how-synapse-works#seats-and-roles) allows. If none of a space's pages are open to you, the whole space is hidden, which is why most members don't see **Admin**. On Synapse Free, some pages carry a **Paid** badge. You can still open them to see what they offer and how to upgrade. > [!TIP] > > Press ⌘ K (or Ctrl K) to open the command palette and jump to any page by name. ## You Your own work and setup. Everything here is about you, and nobody else can see it as yours. | Page | What it's for | Who sees it | | - | - | - | | **My Effectiveness** | Your own flow, focus and pace, including your human state if you've connected Life. See [My Effectiveness](/synapse/my-effectiveness). Paid. | Everyone with a seat | | **Agent checks** | What Synapse advised your coding agent and why, so you can accept or reject it. See [Agent checks](/synapse/ask). | Everyone with a seat | | **Connect your AI** | Connect your MCP clients, such as Claude Code or Cursor, and manage their tokens. See [Connect your agent](/synapse/connect-agents). | Everyone with a seat | | **My connections** | Your own links to Life, GitHub and your calendar. This is where you connect Life. See [Your connections](/synapse/connectors#your-connections). | Everyone with a seat | | **Privacy & consent** | What you've consented to, team sharing, and erasing your data. See [Privacy & consent](/synapse/privacy-and-consent). | Everyone | Your account, seats and invitations are under **Account** in the account menu at the bottom of the sidebar. See [Your profile](/synapse/profile). ## Teams Views of groups of people, never of one person. Members see their own department. Leads and Admins see the whole organization and every department, which appear under **Teams** in the sidebar. | Page | What it's for | Who sees it | | - | - | - | | **AI Effectiveness** | Adoption, delivery and human state for a team. See [AI Effectiveness](/synapse/ai-effectiveness) and [Metrics explained](/synapse/metrics). Paid. | Everyone with a seat, scoped to their department | | **AI usage** | Which AI tools each team uses. See [AI usage](/synapse/ai-usage). Paid. | Leads and Admins | | **AI spend** | Seats, cost and coverage for your AI tools. See [AI spend](/synapse/ai-spend). Paid. | Leads and Admins | | **Goals & alerts** | Team targets, alerts when a measure moves, and the weekly Slack digest. See [Goals & alerts](/synapse/goals-and-alerts). Paid. | Leads and Admins | | **Agents** | Your team rules and what agents were stopped or let through. See [Agents](/synapse/agents). | Everyone with a seat | ## Ask What your organization knows. | Page | What it's for | Who sees it | | - | - | - | | **Ask Synapse** | Ask a question and get an answer with citations from your knowledge sources. See [Ask Synapse](/synapse/search). | Everyone with a seat | | **Synaptic Mesh** | A map of your organization's knowledge and work: yours, your team's and the company's. See [Synaptic Mesh](/synapse/mesh). | Everyone with a seat | ## Admin Running Synapse for the organization. The pages are grouped under four labels. | Group | Page | What it's for | Who sees it | | - | - | - | - | | Sources | **Connectors** | GitHub, GitLab, AI tools and other sources for everyone. See [Connectors](/synapse/connectors). | Admins | | | **Knowledge sources** | Which documents and channels Synapse indexes for search and agents. See [Knowledge sources](/synapse/knowledge-sources). | Admins | | | **Exports** | Team CSVs and scheduled webhooks. See [Exports](/synapse/exports). | Leads and Admins | | People | **Members** | Seats and Synapse roles. See [Members and roles](/synapse/members-and-roles). | The organization owner and admins, and Synapse Admins | | | **Departments** | Who rolls up where. Paid. See [Departments](/synapse/departments). | Admins | | Trust | **Privacy controls** | The cohort floor, team human-state views and team sharing. See [The cohort floor](/synapse/team-views#the-cohort-floor). | Admins, and the organization owner and admins | | | **Audit log** | Who changed what, and when. See [Audit log](/synapse/audit-log). | Admins | | Plan | **Billing & usage** | Your plan, seats and invoices. See [Billing & usage](/synapse/billing-and-usage). | The organization owner and admins | | | **Organization settings** | Your organization's details and sign-in. See [Organization settings](/synapse/organization-settings). | The organization owner and admins | In these tables, "Admins" means Synapse Admins, and the organization owner when they have a seat. ## Where do I go to… | I want to… | Go to | | - | - | | See how AI is going for my team | **Teams → AI Effectiveness** | | See what I'm paying for AI tools | **Teams → AI spend** | | Find out why my agent was stopped | **You → Agent checks** | | Connect Claude Code or Cursor | **You → Connect your AI**, then [Developer setup](/synapse/developer-setup) | | Connect Life to share my human state | **You → My connections** | | Stop sharing, or erase my data | **You → Privacy & consent** | | Find a decision or document | **Ask → Ask Synapse** | | Connect GitHub or an AI vendor | **Admin → Connectors** | | Give someone a seat or change their role | **Admin → Members** | | Lower or raise the cohort floor | **Admin → Privacy controls** | | Send team numbers to another system | **Admin → Exports** | | Accept an invitation to another organization | **Account → Invitations** | | Set up Google Workspace sign-in | **Admin → Organization settings** | New to Synapse? Start with [How Synapse works](/synapse/how-synapse-works). Bringing Synapse to your company? Go to [Get started](/synapse/get-started). Invited by your team? See [Join your team](/synapse/join). # Organization settings Source: https://docs.synheart.ai/synapse/organization-settings Your organization's name and description, single sign-on with Google Workspace, its ID, and erasing its Synapse data or deleting it **Organization settings**, under **Admin → Plan** at [synapse.synheart.ai](https://synapse.synheart.ai), shows who your organization is and how its members sign in. It's in the sidebar for the organization owner and organization admins, who can change it. Anyone else who opens it sees it view only. ## Organization | Setting | Means | | - | - | | **Organization name** | Shown across Synapse and in invitations. Select it to change it. | | **Description** | Optional. Choose **Add a description**. | | **Plan** | Your current plan. Change it under [Billing & usage](/synapse/billing-and-usage). | | **Your role** | Your role in the organization. | | **Created** | When the organization was created. | ## Sign-in **Sign-in** controls how members get into the organization. To let members sign in with **Google Workspace**, an organization admin chooses **Enable** and signs in with their work Google account. That account must be on your organization's domain. Once it's on, the domain is listed under **Claimed domains** and the setting shows **Enabled**. ## Organization facts **Organization ID** is your organization's identifier, used by Synheart support and the API. Choose the copy button beside it. **Related settings** links to [Billing & usage](/synapse/billing-and-usage), [Members](/synapse/members-and-roles) and [Privacy controls](/synapse/team-views#privacy-controls). ## Danger zone Only the organization owner sees this. Both actions are permanent. * **Erase Synapse data** removes the organization's connectors, memory and AI tool data. The organization itself stays. To confirm, type the organization's slug, or its name when it has no slug. The same erase is under **Admin → Privacy controls**. See [Erasing data](/synapse/team-views#erasing-data). * **Delete organization** deletes the organization with its projects, apps and Synapse data. To confirm, type `DELETE`, then choose **Delete permanently**. For the platform side of organizations, such as tenants and switching between organizations, see [Organizations and tenants](/platform/organizations-and-tenants). # Synapse Source: https://docs.synheart.ai/synapse/overview What Synapse is, what it does for your team, and where to start, whether you're setting it up, using it, or reading the team views Synapse sits between your engineering team and the AI tools it uses. It gives coding agents your organization's rules and decisions, and it shows leaders how AI is working for their teams, without reporting on any one person. > [card] [Agents follow your rules](/synapse/rules) > > Team rules are checked before an agent pushes, merges, deletes or edits. A rule can stop the action or ask a person first. > [card] [Agents know your decisions](/synapse/connect-agents) > > Any MCP agent can recall what your organization decided and why, from repositories, Notion, Google Drive, OneDrive and Slack. > [card] [Teams see how AI is working](/synapse/ai-effectiveness) > > AI Effectiveness shows adoption, delivery and, with consent, human state, as three separate measures rather than one score. > [card] [Leaders see spend and risk](/synapse/ai-spend) > > What you pay for AI tools (Copilot, Claude, OpenAI, Cursor), which seats go unused, and what agents were stopped from doing. ## Start here | If you're… | Start with | | - | - | | New to Synapse | [How Synapse works](/synapse/how-synapse-works): seats and roles, departments, human state, the AI Effectiveness Index and the cohort floor | | Looking for a page | [Find your way around](/synapse/navigate): what's in each part of the sidebar and who sees it | | Bringing Synapse to your company (CTO, platform lead) | [Get started](/synapse/get-started): create the organization, pick a plan and invite your team. Then [Set up your team](/synapse/admin-setup): connect AI vendors and write the team rules | | Invited by your team | [Join your team](/synapse/join): accept the invitation and get set up | | A developer | [Developer setup](/synapse/developer-setup): install the CLI once, and your coding agent follows the team rules | | Reading the team numbers | [AI Effectiveness](/synapse/ai-effectiveness), then [Metrics explained](/synapse/metrics) for every delivery figure | | Wondering what others can see about you | [Team views and privacy](/synapse/team-views) | ## What Synapse collects Synapse reports on teams, not people. * **Agent rules.** Each developer's machine sends day totals per rule: how many times it stopped an action, asked, or was let through. Never the command, the file, the prompt or the repository. These totals are stored per member. Developers can see their own; leads and admins see the organization's combined totals. * **Team human state has a floor.** Team human-state figures appear only when enough people contribute: your organization's cohort floor, 4 by default and adjustable up to 50. Below it, they're withheld rather than shown, so a total can't describe one person's state. Work and AI figures are shown exactly. Members see their own department; leads and above see the organization. A team smaller than the floor sees its own view only if every member opts in. See [Team views and privacy](/synapse/team-views). * **AI spend.** Vendor reports list usage per person. Synapse keeps each person's usage under a pseudonym: a one-way keyed hash of their vendor login or email, specific to your organization and computed with a secret key only Synapse holds. The login or email from the report isn't kept. Leads and admins see totals only, never one person's usage. While a tool is connected, usage older than 90 days is deleted. * **Organization knowledge.** Only sources an admin designates are indexed, and source permissions still apply when content is recalled or [searched](/synapse/search). * **Agent decisions.** When your agent uses Synapse, or the guard shares its checks, Synapse records what it advised and why: the mode, reason codes and evidence ids, never the prompt or question. Each person sees only their own, under [Agent checks](/synapse/ask). Records are kept for 90 days. ## Requirements * A Synapse organization at [synapse.synheart.ai](https://synapse.synheart.ai). * Coding agents: rules are enforced in **Claude Code**, and in **Cursor** and **Factory Droid** with CLI 0.22.0 or later. Organization knowledge works in any MCP client (Claude Code, Cursor, Claude Desktop, Codex, Droid). * The [Synheart CLI](/setup/install-cli) 0.18.0 or later on each developer's machine (macOS, Linux or Windows). # Privacy & consent Source: https://docs.synheart.ai/synapse/privacy-and-consent Your own privacy choices in Synapse. What you've agreed to, where your human state can go, your AI tool matches, and erasing your data **Privacy & consent**, under **You → Your setup** at [synapse.synheart.ai](https://synapse.synheart.ai), shows what you've agreed to and where your numbers go. Every choice on it is yours alone: nobody else, including a manager, admin or owner, can make it for you. For the settings your organization controls, such as the cohort floor, see [Team views and privacy](/synapse/team-views). ## Your consent Your human state comes from **Life by Synheart**. Consent to share it is managed in the Life app, not in Synapse. * If you haven't connected Life yet, choose **Connect in My connections**. * After changing your consent in Life, choose **Check consent again** so Synapse picks up the change. Without Life, Synapse still works for you. It just has no human state about you. ## Where your human state can go | Where | What's shown | | - | - | | **You** | Only you can open [My Effectiveness](/synapse/my-effectiveness) and [Agent checks](/synapse/agents). Always private. | | **Your department** | Your human state counts in your department's totals, only above the [cohort floor](/synapse/team-views#the-cohort-floor). | | **Your organization** | Protected human-state summaries only. Work and AI activity can still be shown when few people contribute, because it isn't about your state. | Nobody sees your human state on its own, in any view, whatever their role. ### Share my human state If your team is smaller than the cohort floor, it sees no team human state. **Share my human state** lets it see its own view, but only once every member of the team has turned it on. Turning it off takes effect at once and needs no reason. See [Share my numbers with my team](/synapse/team-views#share-my-numbers-with-my-team) for exactly who sees what. > [!WARNING] > > Turning sharing off stops future sharing only. Numbers already sent in an export or digest can't be recalled. ## Your AI tool matches If your organization has turned on work email matching, Synapse may have matched you to your account in an AI tool's usage report, by the work email you verified, so that usage counts as yours. Each match is listed here, and you can **stop the match** at any time. ## Erasing your data **Erase my Synapse personal data** removes your linked accounts and AI tool data in this organization. You don't need a seat to do it, and it works after your organization's subscription has lapsed. It can't be undone. The erase is recorded in the organization's [audit log](/synapse/audit-log), where you show as **Erased user**. ## Who can do what | Action | Who | | - | - | | Open Privacy & consent | Every member of the organization, with or without a seat | | Share or stop sharing your human state with your team | You, for yourself only | | Stop an AI tool match | You, for your own matches | | Erase your own Synapse data | You | # Your profile Source: https://docs.synheart.ai/synapse/profile Your Synapse account at a glance. The organizations where you have a seat, your pending invitations, and where to change your password **Profile** shows your Synapse account, your seats and your invitations. Open it from your account menu at the bottom of the sidebar at [synapse.synheart.ai](https://synapse.synheart.ai): choose **Account**. It has two tabs, **Workplace** and **Invitations**. ## Workplace **Your account** shows your name and email, with: | Figure | Means | | - | - | | **Connectors** | How many data sources you've connected for yourself. See [Connectors](/synapse/connectors). | | **Signal windows** | How many work-only windows are active for you. | | **Synapse seats** | How many organizations you hold an active Synapse seat in. | **Synapse access** lists each organization where you hold an active seat. **Account on Synheart.** Your password, two-factor authentication and Synheart profile are managed on the Synheart platform, not in Synapse. Choose **Open Synheart account**. See [Account](/platform/account). **Log out** signs you out of Synapse. ## Invitations **Synapse invitations** lists the invitations waiting for you. Choose **Accept invitation** to join with the role you were given, then **Continue to workplace**. Accepting never buys seats or changes anyone's plan. If accepting fails, the organization may have no free seat left, or the invitation may have expired. Ask the organization's owner or an admin to check its seats or send it again. **Waiting for a Synapse seat** lists organizations you already belong to but have no Synapse seat in. Ask an organization owner or admin to give you one. If you're an owner or admin there yourself, choose **Assign seats in Members**. See [Members and roles](/synapse/members-and-roles). ## Related * [Privacy & consent](/synapse/privacy-and-consent): what you share, and erasing your data. * [Join your team](/synapse/join): accepting your first invitation. # Writing rules Source: https://docs.synheart.ai/synapse/rules The rule format, the actions the guard recognizes, and how team, personal and repository rules combine A rule names an **action**, optional conditions on it (**where**), what to do (**verdict**), and what to tell the agent (**say**). ```yaml theme={null} rules: - id: no-admin-merge say: Never merge with --admin; branch protection is not to be bypassed. action: gh.pr_merge where: {admin: "true"} verdict: deny ``` | Field | Required | Meaning | | - | - | - | | `id` | Yes | Lowercase letters, digits, `.`, `_` and `-`. Shown in reports and used by `guard allow` | | `say` | Yes | Your words. The agent sees them when the rule stops it | | `action` | Yes | An action kind from the table below. A glob works: `git.*` | | `where` | No | Conditions on the action's fields; all must match | | `verdict` | Yes | `deny` (the agent is told no) or `ask` (a person decides) | | `shadow` | No | `true` to count when the rule would fire without enforcing it. Useful to try a rule on a team first | ## Conditions Each `where` value is matched against one field: * `"main|master"` — any of the alternatives. * `"*/migrations/*"` — `*` matches any run of characters, including `/`; `?` matches one character. * `"!main|dev"` — a leading `!` negates the whole value: anything except main or dev. * A field the action doesn't have never matches, so the rule doesn't fire. ## Actions Commands are parsed, not pattern-matched. `cd`, `git -C`, `bash -c`, `eval`, `env` and `sudo` wrappers are followed. Writes through `>`, `tee`, `cp`, `mv` and `sed -i` count as file writes. | Action | When | Fields | | - | - | - | | `git.push` | `git push` | `remote`, `branch` (the current branch when none is named), `force`, `delete`, `all` | | `git.discard` | `reset --hard`, `clean`, `restore`, `checkout --` | `how` | | `git.branch_delete` | `git branch -D` (or `--delete --force`) | | | `git.stash` | `git stash` | `op` (`push`, `drop`, `clear`…), `tagged` | | `git.commit`, `git.merge`, `git.rebase`, `git.cherry-pick`, `git.revert` | Those subcommands | | | `gh.pr_merge` | `gh pr merge` | `method` (`merge`, `squash`, `rebase`), `admin`, `auto` | | `gh.pr_create` | `gh pr create` | `base` (`@default` when not given) | | `gh.workflow_run` | `gh workflow run` | `workflow`, `ref`, `inputs` | | `file.write` | Edit and write tools, and shell writes | `path`, `via` (`redirect`, `tee`, `cp`, `mv`, `sed`) | | `file.read` | The read tool, and `cat`-style reads | `path` | | `shell.rm_recursive` | `rm -r` / `rm -rf` | `path` | | `mcp.call` | A tool from an MCP server | `server`, `tool` | | `shell.unparsed` | A command that couldn't be parsed | | Inside a git repository, every action also has `repo` (`owner/name`, from the `origin` remote) and `current_branch`. File and directory actions have `dir`. > [!TIP] > > Test a rule before you save it. `synheart guard check ` prints the action and its fields, and which rule would fire. ## Where rules come from Rules load in this order. When two have the same `id`, the first one wins. 1. **Built-in rules.** An agent can't grant exceptions, edit rule files, edit the CLI's config (`.synheart/config.yaml` in a repository or in your home folder) or turn the guard off. These can't be overridden. 2. **Team rules**, set by an admin under **Agents → Team rules** and synced to each machine. 3. **Your own rules**, in `~/.synheart/guard/rules.yaml` (`synheart guard init` writes a starter set). 4. **Exceptions** you granted with `synheart guard allow`. 5. **Repository rules**, in `.synheart/guard.yaml` at the repository root. So a personal or repository file can add rules, but can't redefine a team rule. ## A team example ```yaml theme={null} rules: - id: no-force-push-protected say: Never force-push to main, master, dev or production. action: git.push where: {force: "true", branch: "main|master|dev|production"} verdict: deny - id: no-direct-push-protected say: Changes reach main, dev and production through pull requests, not direct pushes. action: git.push where: {branch: "main|dev|production"} verdict: deny - id: no-admin-merge say: Never use admin privileges to bypass branch protection. action: gh.pr_merge where: {admin: "true"} verdict: deny - id: ask-discard-work say: Ask before discarding uncommitted work. action: git.discard verdict: ask - id: ask-rm-recursive say: Ask before deleting directories outside temp and build folders. action: shell.rm_recursive where: {path: "!/tmp/*|*/node_modules|*/node_modules/*|*/dist|*/build|*/target"} verdict: ask - id: ask-read-secrets say: Ask before reading secret files (.env, keys). action: file.read where: {path: "*/.env|*/.env.*|*.pem|*.key|*/id_rsa*|*/id_ed25519*"} verdict: ask - id: ask-migrations say: Database migrations are reviewed by the platform team; ask before changing one. action: file.write where: {path: "*/migrations/*"} verdict: ask ``` ## When rules are too strict **Agents → Team** lists rules people always let through when asked. Those are candidates to relax, so developers are asked less. Before turning a new rule on for everyone, add `shadow: true` and watch the *would fire* column for a week. # Ask Synapse Source: https://docs.synheart.ai/synapse/search Search your organization's knowledge from the dashboard, with every result cited and only the sources you're allowed to see **Ask Synapse**, under **Ask** at [synapse.synheart.ai](https://synapse.synheart.ai), finds answers in your organization's knowledge. Every result is an excerpt with a link to where it came from. It's the same search your coding agent runs with the MCP tool `recall`, run as you. > [!NOTE] > > The page is headed **Search**. It used to be called Ask, at `/ask`, and old links that carry a search (`/ask?q=…`) open it with the same query. What your agents checked with you is now [Agent checks](/synapse/ask). ## What it searches Only sources an admin has chosen under **Admin → Knowledge sources** (see [Knowledge sources](/synapse/knowledge-sources)): * repository documentation; * a Notion workspace; * a Google shared drive; * OneDrive folders that members chose as knowledge; * public Slack channels. Decisions your organization has recorded are labelled as decisions in the results. Results open in their source: **Open in Notion**, **Open in Google Drive**, **Open in Slack** and so on. ## How results are found Search is hybrid. It combines keyword matching with semantic matching, which finds documents that mean the same thing in different words. Each result shows the excerpt that matched. **Keyword-only results.** If the semantic part is unavailable, Search still returns keyword matches and says *Keyword-only results right now*. A document that uses different words from your query may be missing until semantic search is back. Try the words the document itself would use. ## Who sees what Search only returns what you're allowed to see. Each document keeps the audience it has at the source, and every search filters on it, as do your agent's `recall`, `why` and `related_context`. | Source | Visible to | | - | - | | Repository documentation | Everyone in your organization | | Public Slack channels | Everyone in your organization | | Notion | People who can open the page in Notion | | Google Drive | People who can open the file in Google Drive | | Microsoft OneDrive | People who can open the file in OneDrive | A document whose audience can't be worked out is withheld rather than shown. Permissions are read again when a source syncs, so access removed at the source is removed from Search after the next sync. ## When Search can't run | Message | What to do | | - | - | | Search needs a Synapse seat | Ask an organization owner or admin for a seat | | Too many searches in a short time | Wait a minute, then try again | | Search is temporarily unavailable | Try again in a minute | # Team views and privacy Source: https://docs.synheart.ai/synapse/team-views Who sees which team view, the human-state cohort floor, team human-state views, sharing human state with a small team, the other privacy controls, and erasing data Synapse reports on teams, not people. Nobody (manager, admin or owner) can drill down to one person's human state. This page covers who sees which team view, and the settings under **Admin → Privacy controls** at [synapse.synheart.ai](https://synapse.synheart.ai). For the choices each member makes for themselves, see [Privacy & consent](/synapse/privacy-and-consent). ## Who sees which team view **AI Effectiveness** shows a team view to everyone with a seat, scoped by role. A badge at the top says which scope you're looking at. | Role | Sees | | - | - | | Member | Their own department. In an organization with no departments yet, the whole organization is their team | | Synapse Lead, Synapse Admin, and the organization owner with a seat | The whole organization and every department, plus AI spend, AI tool usage and exports | A member can't pick another department or widen the scope. In an organization that has departments, a member who isn't in one sees a message asking an admin to add them, never organization data. The organization-wide fallback ends as soon as the first department is created. See [Departments](/synapse/departments). ## Human state and work figures Synapse treats two kinds of team figure differently. * **Human-state figures** come from Life by Synheart: focus, cognitive load, fatigue, capacity, and anything built from them. They describe how people are, so they only ever appear as totals over members who consented, and only above the [cohort floor](#the-cohort-floor). * **Work and AI figures** describe your repositories, tools and calendars: AI usage and spend, adoption, agent actions, delivery and engineering metrics, meeting load. Synapse shows these exactly, even for a small group, because they aren't about anyone's state. Who can see them still depends on their role. ## The cohort floor The cohort floor is the fewest contributing people a team human-state figure is shown for. Below it, the figure is withheld with a note saying so ("fewer than *F* people"), rather than estimated. * **Default 4.** Each organization can raise its floor, up to **50**. It can't go below 4. Only a team whose members all opt in to [sharing their human state with each other](#share-my-numbers-with-my-team) can see a human-state view below the floor. * **It covers human state only.** Work and AI figures aren't held back by it. * **Even above the floor,** a human-state figure is withheld when it could be worked out by subtracting one shown total from another, or when the people behind it changed by fewer than the floor since it was last shown. * **Lowering it needs an acknowledgment.** A lower floor lets smaller groups be shown, so you must read and accept the disclosure first. Raising it needs only a confirmation. * **Every change is audited** with the old and new value and whether the disclosure was acknowledged. * **Fails safe.** If the floor can't be read, human-state figures are withheld as if it were 50. The floor applies everywhere a team human-state figure appears: AI Effectiveness, departments, trends and comparisons, exports, the weekly digest, and the team tools your AI assistant can call. ## Team human-state views Human-state views are team and department totals built from Life by Synheart: * the Human state tab of AI Effectiveness, and the Human card on Overview; * team focus, cognitive load and mental fatigue; * human effectiveness and capacity. They include only members who have connected Life under **You → My connections** and consented, in the Life app, to contribute. These views are **on by default**. They can be turned off under **Admin → Privacy controls**. Turning them back on after that means acknowledging the disclosure again. Every change is audited. **Turning them off hides** every team and department human-state value, immediately, in AI Effectiveness, departments, exports, digests and the team tools your AI assistant can call. Cards show that the views are off instead of a value. **What stays:** * work and AI figures; * every member's own **My Effectiveness** view; * the coding-agent guidance each person gets from their own state; * [Agent checks](/synapse/ask) and the Agents team totals, which never contain human state. The setting can only hide data. Turning the views on never shows anything a member hasn't consented to. ## Share my numbers with my team A team smaller than the cohort floor normally sees no team human state. **Share my human state**, under **You → Privacy & consent**, lets a small team see its own human-state view, if everyone on it agrees. * **Everyone must opt in.** The view is shown only while every current member has opted in. Until then no human state about the team is shown below the floor. When someone new joins, it's withheld until they opt in too. * **Your team** is your department, or the whole organization when it has no departments. Moving to another department ends your old choice. * **Each person decides for themselves.** Nobody can opt anyone else in: not a manager, admin or owner. There are no reminders or nudges. * **One click to stop.** Opting out takes effect at once, needs no reason, and works even without a seat. * **Who sees it.** A shared view is shown to exactly the people who would see that team at the floor: the team's own members and those who see the whole organization. Human state still includes only members who consented to it, and the team human-state setting still applies. * **Who knows who opted in.** Members of the team see which teammates have opted in. Everyone outside the team, including leads, admins and owners, sees only *Shared by all N members* or *Not shared: not every member has opted in*. They never see names or a count of who hasn't opted in. In a team of one, the team view is that person's own numbers. Only that person can choose to share them. **The organization switch.** Team sharing is available by default. It can be turned off for the whole organization under **Admin → Privacy controls**. Turning it off withholds every shared view immediately and keeps everyone's choices, so turning it back on (after acknowledging the disclosure) restores the views whose members are all still opted in. The switch opts nobody in and gives nobody extra access. > [!WARNING] > > Opting out stops future sharing only. Numbers already sent in an export, export webhook or digest can't be recalled. Everything produced after you opt out, including the next scheduled export, leaves your team out. When you opt out, your choice is deleted at once. Synapse keeps an audit record of each opt-in and opt-out as proof of consent. That record is never shown in the organization's [audit log](/synapse/audit-log). ## Privacy controls **Admin → Privacy controls** holds the organization's privacy settings. Every change is recorded in the audit log. | Setting | What it does | | - | - | | **Privacy floor** | The [cohort floor](#the-cohort-floor) for team human-state figures. | | **Time zone for weekly reports** | Weeks, months and work days in team views start at midnight in this zone. Until it's set, Synapse uses UTC. | | **Team human-state views** | Turns [team human-state views](#team-human-state-views) on or off. | | **Sharing for small teams** | The organization switch for [sharing human state with a small team](#share-my-numbers-with-my-team). | | **Work email matching** | Matches people in an AI tool's usage report to members by the work email they verified, so their usage counts as theirs. Off by default. Shared emails are skipped. Each person is told and can undo their own match under **You → Privacy & consent**. | The organization owner also finds the organization-wide erase here. ## The Synaptic Mesh Human state appears only on your own nodes in the [Synaptic Mesh](/synapse/mesh#human-state-on-the-map), for every role. A teammate's node never carries their human state, whoever is looking. ## Erasing data Erasure is a data right, not a paid feature. It works without a Synapse seat and after the organization's subscription has lapsed. **Your own data.** Any member of the organization, with or without a seat, can erase their own Synapse data under **You → Privacy & consent → Erase my data**. See [Erasing your data](/synapse/privacy-and-consent#erasing-your-data). **The whole organization.** Only the organization owner can erase all of the organization's Synapse data. It's under **Admin → Privacy controls** and **Organization settings**, which an owner can reach without a seat. To confirm, the owner types the organization's slug (or name, when it has no slug). The request names the organization explicitly and is refused for any other. It can't be undone, and every erase is recorded in the audit log. ## Who can change what | Action | Who | | - | - | | See the cohort floor | Every member | | Change the cohort floor, time zone, team human-state views or the team sharing switch | The organization owner or an organization admin (no seat needed), or a Synapse Admin | | Turn work email matching on or off | Synapse Admins | | Opt in or out of sharing with your own team | Each member, for themselves only | | Erase your own Synapse data | Every member, with or without a seat | | Erase the organization's Synapse data | The organization owner only, with or without a seat | Being able to change a setting doesn't let anyone see the team views. What each person sees comes from their seat's role, as described above, for organization admins too. # Errors Source: https://docs.synheart.ai/synheart-auth/errors SynheartAuthError taxonomy, key invalidation detection, and clock skew correction The SDK exposes a sealed `SynheartAuthError` hierarchy in Dart (mirrored as enum-style errors in Kotlin and Swift). Every error has a stable code that maps 1:1 to RFC-AUTH-MOBILE-0001 §11. ## Taxonomy | Code | Dart class | Trigger | SDK behaviour | | - | - | - | - | | `NETWORK_ERROR` | `NetworkError(message)` | Challenge or register HTTP call failed | Retry with backoff (RFC §12.1). | | `CHALLENGE_EXPIRED` | `ChallengeExpired` | Server rejects stale challenge | Re-fetch a new challenge. | | `ATTESTATION_UNAVAILABLE` | `AttestationUnavailable` | Device/OS doesn't support attestation | Surface to developer; cannot proceed. | | `ATTESTATION_FAILED` | (subset of `ServerError`) | Attestation provider rejects | Retry once; then surface. | | `KEY_INVALIDATED` | `KeyInvalidated` | Hardware key no longer usable | Transition to `keyInvalid`; next `registerDevice` wipes and restarts. | | `KEYSTORE_ERROR` | `StorageError` | Android Keystore op failed | Surface with platform details. | | `SECURE_ENCLAVE_ERROR` | `StorageError` | iOS Secure Enclave op failed | Surface with platform details. | | `SIGNING_FAILED` | `CryptoError` | Signature computation failed | Return immediately; non-recoverable in-request. | | `DEVICE_REVOKED` | `ServerError` | Server marks device inactive | Force re-registration via `resetDeviceIdentity`. | | `CLOCK_SKEW` | `ClockSkew` | Timestamp freshness rejected | Apply offset correction; retry. | | `ROTATION_FAILED` | `ServerError` | Key rotation request rejected | Keep old key active; retry later. | | `NONCE_REPLAY` | `ServerError` | Server rejects duplicate nonce | Generate new nonce and retry once. | | `ALREADY_REGISTERED` | `AlreadyRegistered` | `registerDevice` called when state is `registered` | No-op fast-path; treat as success. | | `NOT_REGISTERED` | `NotRegistered` | `signRequest` called before registration | Call `registerDevice` first. | | `NOT_CONFIGURED` | `NotConfigured` | API used before `configure(baseUrl)` | Call `configure` once at app launch. | | `REGISTRATION_IN_PROGRESS` | `RegistrationInProgress` | Concurrent `registerDevice` | Wait for the in-flight call. | | `CRYPTO_ERROR` | `CryptoError(message)` | Generic crypto failure | Inspect message; usually surfaced to developer. | | `STORAGE_ERROR` | `StorageError(message)` | Keychain / EncryptedSharedPreferences failure | Inspect message; surface. | | `INVALID_STATE_TRANSITION` | `InvalidStateTransition(from, to)` | Programmer error; state machine misuse | Inspect call site. | | (any other server code) | `ServerError(code, serverMessage)` | Catch-all for server-defined codes | Inspect; default surface to developer. | `SynheartAuthError.fromCode(code, msg?)` maps platform-channel error codes back to the typed exception in Dart. ## Key invalidation detection (RFC §11.1) Hardware keys can become unusable due to: * OS updates that rotate Secure Enclave / Keystore root keys. * Biometric enrollment changes. * Device security state changes (PIN reset, factory reset). * Backup/restore between devices. | Platform | Detection | | - | - | | Android | `KeyPermanentlyInvalidatedException` on `Cipher.init`/`Signature.initSign`. `UnrecoverableKeyException` when the alias no longer resolves. | | iOS | `errSecItemNotFound` from `SecKeyCopyExternalRepresentation` or `SecKeyCreateSignature`. `errSecAuthFailed` when the biometric context can't authenticate. `LAError.biometryLockout` for biometry-bound keys after too many failures. | On detection: 1. The SDK emits `KEY_INVALIDATED` (Dart: `KeyInvalidated`). 2. State transitions `registered → keyInvalid`. 3. The next `registerDevice(appId)` call wipes local state and runs the full registration flow. The SDK never silently retries with the invalid key. ## Clock skew correction (RFC §11.2) Mobile clocks drift. The SDK can't force NTP, so it learns the offset from the server. ### Server contract When rejecting a request with `CLOCK_SKEW`, the response includes: ```json theme={null} { "error": "CLOCK_SKEW", "server_timestamp": 1709312345, "message": "Request timestamp too far from server time" } ``` ### SDK behaviour ```dart theme={null} Future correctClockSkew(double serverTimestamp) { final localTimestamp = DateTime.now().millisecondsSinceEpoch / 1000; final offsetMs = ((serverTimestamp - localTimestamp) * 1000).round(); // persist offsetMs as clock_offset_ms // on next sign: adjusted_ts = local_ts + clock_offset_ms / 1000 } ``` The SDK exposes `correctClockSkew(serverTimestamp)` for hosts to call when they receive a `CLOCK_SKEW` error from any Synheart endpoint. Subsequent signatures use the corrected timestamp automatically. The persisted `clock_offset_ms` survives app restarts. Per RFC §11.2, the SDK SHOULD periodically re-validate the offset by comparing with `X-Synheart-Server-Time` from successful responses (server-supplied; not currently emitted by all services). ## Retry policy (RFC §12) ### Challenge + registration ```text theme={null} delay = min(base * 2^attempt + random(0, jitter), max_delay) base = 1 second jitter = 500 ms max = 30 seconds attempts = 5 ``` Always re-fetch a new challenge after any register failure (challenges are single-use). ### Signing Signing failures are non-recoverable in-request — return error immediately. If `KEY_INVALIDATED` is detected, transition to `keyInvalid` and trigger re-registration before the next request. ### Key rotation Rotation failures MUST NOT block normal request signing. Backoff: base 60s, max 1 hour, attempts 3 per cycle. After max attempts, log warning and retry on next app launch. ## Logging policy Per RFC §13: | Allowed (prod) | Never (prod) | | - | - | | `app_id` | Raw signatures | | `device_id` (truncated/hashed) | Raw request bodies | | Error codes | Attestation proof payloads | | Timing metrics | Public key material (debug builds only with opt-in) | | Rotation events | Clock offset values | | State transitions | | `InvalidStateTransition` should be logged at error level — it indicates a programmer bug. ## Related * [State Machine](/synheart-auth/state-machine) — `KeyInvalidated` and `InvalidStateTransition` semantics. * [Registration](/synheart-auth/registration) — failure paths during the handshake. * [Signing](/synheart-auth/signing) — `CLOCK_SKEW`, `NONCE_REPLAY` recovery. # Synheart Auth Overview Source: https://docs.synheart.ai/synheart-auth/overview Hardware-backed device identity and request signing for Synheart mobile SDKs `synheart-auth` is the mobile-side device-identity SDK. It generates an ECDSA P-256 key pair in hardware (Secure Enclave on iOS, Android Keystore on Android), registers the device with the Synheart auth service, and signs every outbound request from the cloud paths in your app. The SDK is normatively defined by RFC-AUTH-MOBILE-0001. Mode A (hardware ECDSA) only — backend HMAC API-key flow is out of scope. > [!NOTE] > > If you're using **Synheart Core**, you get `synheart-auth` automatically — Core wires its crypto callbacks into the runtime during `Synheart.initialize`. You only deal with this SDK directly if you're integrating without Core. ## What it owns * Key pair generation in hardware (non-exportable). * Device registration via challenge + attestation (App Attest on iOS, Play Integrity on Android). * Request signing per RFC-AUTH-MOBILE-0001 §8. * Key invalidation detection and recovery. * Key rotation. * Clock-skew correction. * Per-`app_id` scoped identity (a single device can carry independent identities for multiple apps). ## What it does not own * Crypto primitives — uses Apple `CryptoKit` and Android `KeyStore`. * Attestation providers — uses App Attest / Play Integrity native APIs. * Capability and consent tokens — those live in `synheart-core` / runtime. * Cloud HTTP transport beyond the Synheart Auth endpoints. The SDK returns signed-headers; consumers attach them to their own requests. ## Packages > [card] Flutter / Dart > > `synheart_auth` 0.1.0 — MethodChannel wrapper around the native plugins. No crypto in Dart. > [card] iOS / Swift > > `SynheartAuth` (SwiftPM + CocoaPods). Crypto runs in Secure Enclave. > [card] Android / Kotlin > > `ai.synheart:synheart-auth`. Crypto runs in Android Keystore. The Dart package is **orchestration-only** — all crypto and attestation lives in the native plugins. Calls flow through `MethodChannel`s into Swift/Kotlin code. ## Public API The SDK exposes the same surface across all three platforms: | Method | Purpose | | - | - | | `configure(baseUrl)` | Sets the Synheart Auth base URL. Must be called before any other method. | | `isRegistered(appId)` | Returns whether a device identity exists locally for this app. | | `registerDevice(appId)` | One-time registration. Generates key, attests, calls `/auth/v1/device/register`. | | `signRequest(appId, method, path, bodyBytes?)` | Returns six signed headers (see [Signing](/synheart-auth/signing)). | | `getDeviceId(appId)` | Returns the server-issued `device_id`, or null when unregistered. | | `rotateKey(appId)` | Rotates the signing key while preserving `device_id`. | | `resetDeviceIdentity(appId)` | **Destructive.** Wipes local key + device\_id; forces full re-registration. | | `correctClockSkew(serverTimestamp)` | Stores the offset learned from a server-supplied timestamp on a `CLOCK_SKEW` error. | Dart `SynheartAuth.instance` is a singleton; Kotlin uses `class SynheartAuth` constructed once per app context; Swift uses `class SynheartAuth` with the same shape. All operations that touch the network or hardware return `async`/`Future`/`suspend` per platform. ## Multi-app-id model A device may hold independent key pairs for multiple `app_id`s. Storage, registration, and signing are scoped per `app_id`; key alias is `synheart_auth_{app_id}` (deterministic). This lets a single device run several Synheart-backed apps without identity collision. ## How Synheart Core consumes it `synheart-core` does **not** call `SynheartAuth` HTTP-shaped methods directly. Per the runtime-only networking policy: * The Core SDK constructs a `DeviceAuthProvider` that wraps `SynheartAuth`. * The Core SDK registers the auth provider's crypto callbacks (`generate_key`, `sign_bytes`, `get_attestation`, `key_exists`, `delete_key`) with the Synheart runtime. * The runtime owns the network calls to the auth service (challenge → attestation → register). The Dart-side `registerDevice` / `rotateKey` are flagged in source as "performed by the runtime" — they exist for direct consumers (CLIs, custom integrations) that don't use Core. ## Security invariants (from RFC §6) 1. Private key MUST be hardware-backed and **non-exportable**. 2. Every external request MUST be signed; there is no unsigned path. 3. Signature covers `method + path + timestamp + raw_body_bytes` exactly (not parsed JSON). 4. Server-side timestamp freshness window: **300 seconds**. 5. Nonce replay protection enforced for write endpoints (POST/PUT/PATCH/DELETE); recommended for GET. 6. Key rotation MUST be authenticated by the current key. ## Synheart Auth endpoints used | Endpoint | When | | - | - | | `POST /auth/v1/device/challenge` | Step 1 of registration. | | `POST /auth/v1/device/register` | Step 5 of registration. | | `POST /auth/v1/device/rotate-key` | Key rotation flow. | ## Reading order > [card] [Registration](/synheart-auth/registration) > > Challenge → keygen → attestation → register. > [card] [Request Signing](/synheart-auth/signing) > > Message construction, the six headers, server-side verification. > [card] [State Machine](/synheart-auth/state-machine) > > `unregistered → challengeReceived → keyReady → registering → registered`. > [card] [Errors](/synheart-auth/errors) > > Error taxonomy, key invalidation, clock skew recovery. # Registration Flow Source: https://docs.synheart.ai/synheart-auth/registration Challenge → keygen → attestation → register, per RFC-AUTH-MOBILE-0001 §7 Registration is a one-time-per-(app\_id, device) handshake that establishes a hardware-backed device identity with the auth service. After it completes, the SDK can sign every outgoing request without further server round-trips. ## Steps (normative) ```text theme={null} 1. SDK → POST /auth/v1/device/challenge { app_id } 2. SDK ← { challenge, expires_at, ttl_seconds } 3. SDK gen keypair in hardware (alias: synheart_auth_{app_id}) 4. SDK compute binding_nonce = SHA256(challenge + base64(public_key)) 5. SDK attest with binding_nonce (App Attest / Play Integrity) 6. SDK → POST /auth/v1/device/register { app_id, public_key, challenge, platform, proof, device_local_id? } 7. Server verify challenge (GETDEL), recompute nonce, verify proof, store (app_id, device_id, public_key, platform) 8. SDK ← { device_id, status } ``` When used through Synheart Core, steps 1, 6, and 8 are performed by the Synheart runtime, which calls the SDK's crypto callbacks for steps 3, 4, 5. ## 1. Request a challenge ```http theme={null} POST /auth/v1/device/challenge Content-Type: application/json { "app_id": "com.example.app" } ``` Response: ```json theme={null} { "challenge": "", "expires_at": "", "ttl_seconds": 90 } ``` Challenge TTL is **90 seconds** (RFC §7.3). Single-use, server-enforced. If the SDK fails to complete steps 2–7 within the TTL, it must request a new challenge. ## 2. Generate the keypair | Platform | Algorithm | Storage | Alias | | - | - | - | - | | iOS | ECDSA P-256 | Secure Enclave (`SecKey` with `kSecAttrTokenIDSecureEnclave`) | `synheart_auth_{app_id}` | | Android | ECDSA P-256 | Android Keystore (`KeyGenParameterSpec` with hardware backing) | `synheart_auth_{app_id}` | The key MUST be **non-exportable**. The Dart SDK never sees the private key; only `signRequest` results. ## 3. Compute binding nonce ```text theme={null} binding_nonce = SHA256( challenge_bytes || base64(public_key_bytes) ) ``` This binds the attestation proof to the specific public key the SDK is registering. The server recomputes the nonce in step 7 and rejects mismatches — preventing attestation reuse with a different key. ## 4. Attest with platform provider | Platform | API | Input | | - | - | - | | iOS | `DCAppAttestService.attestKey(...)` | `keyId` from key generation, `clientDataHash = binding_nonce` | | Android | `IntegrityManager.requestIntegrityToken(...)` | nonce = `binding_nonce` | Returns the attestation proof (Apple) or integrity token (Google). The SDK does not validate it — that's the server's job in step 7. The Dart facade returns `AttestationUnavailable` if the platform doesn't support attestation. ## 5. Register with auth service ```http theme={null} POST /auth/v1/device/register Content-Type: application/json { "app_id": "com.example.app", "public_key": "", "challenge": "", "platform": "ios" | "android", "proof": "", "device_local_id": "" } ``` Server verifies (RFC §7.2.6): 1. `GETDEL` the challenge from Redis (single-use, atomic). 2. Recompute `SHA256(challenge + base64(public_key))` and compare with the attestation proof's nonce field. 3. Verify proof against Apple/Google attestation APIs. 4. Persist `(app_id, device_id, public_key, platform, status, registered_at)`. 5. Return `{ device_id, status }`. `status` is one of `"registered" | "pending" | "rejected"`. ## 6. Persist locally The SDK stores per `app_id`: | Field | iOS | Android | | - | - | - | | `device_id` | Keychain | EncryptedSharedPreferences | | Key alias / handle | Secure Enclave | Keystore | | `platform` | Local storage | Local storage | | `registered_at` | Local storage | Local storage | | `key_rotated_at` | Local storage | Local storage | | `clock_offset_ms` | Local storage | Local storage | **Never persisted**: private key bytes (live only in hardware), raw attestation tokens. ## Idempotency `registerDevice(appId)` is idempotent: subsequent calls return `{ status: alreadyRegistered, deviceId: }` without touching the network. Call it at app start regardless — the SDK fast-paths when `isRegistered(appId)` is true. ## Failure paths | Failure | SDK behavior | Recovery | | - | - | - | | Challenge request 5xx / network | `NETWORK_ERROR` with backoff | Retry. | | Challenge expired | `CHALLENGE_EXPIRED` | Re-fetch challenge. | | Attestation unsupported | `ATTESTATION_UNAVAILABLE` | Cannot proceed without dev-mode bypass. | | Attestation API rejects | `ATTESTATION_FAILED` | Retry once, then surface. | | Register 4xx with `INVALID_CHALLENGE` | server says nonce mismatch | Re-fetch challenge and restart. | | Register 4xx with `INVALID_ATTESTATION` | server rejects proof | Surface as `ATTESTATION_FAILED`. | | Register 5xx / network | `NETWORK_ERROR` | Backoff + retry; always with a fresh challenge. | | Already registered | `ALREADY_REGISTERED` | No-op. | | Registration in progress | `REGISTRATION_IN_PROGRESS` | Caller already racing — wait. | ## Rotation flow (RFC §8.3) `rotateKey(appId)` replaces the signing key while preserving the `device_id`: ```text theme={null} 1. Generate new keypair: synheart_auth_{app_id}_next 2. Sign rotation request with the CURRENT key: POST /auth/v1/device/rotate-key Body: { app_id, device_id, new_public_key } 3. Server verifies signature against current public key 4. Server atomically replaces stored public key 5. Server returns { status: "rotated", effective_at: } 6. SDK promotes: - delete old key from hardware - rename _next → primary alias - update key_rotated_at 7. On any failure, keep the old key active and retry later ``` **Rotation policy** (RFC §8.3): SDK SHOULD rotate every 90 days; MUST rotate immediately on platform key-compromise signals; server MAY reject keys older than its configured maximum age. ## Dev / QA bypass (RFC §14) Attestation bypass exists for emulator/CI and is **strictly controlled**: * Server-side allowlist on `app_id` + build channel (dev/staging only). * `"development_integrity_allowed": true` on the platform-side app record. * Mobile SDK MUST set `X-Synheart-Dev-Mode: true` header so the server tracks dev vs. prod traffic. * Bypass MUST be compile-time gated (`#if DEBUG` / `BuildConfig.DEBUG`) — never runtime-toggleable. There are no hidden bypasses. A production build that emits `X-Synheart-Dev-Mode: true` is treated as a security incident. ## Related * [Request Signing](/synheart-auth/signing) — the contract used after registration. * [State Machine](/synheart-auth/state-machine) — the states each step transitions through. * [Errors](/synheart-auth/errors) — full error code taxonomy. # Request Signing Source: https://docs.synheart.ai/synheart-auth/signing Message construction, the six signed headers, and server-side verification per RFC-AUTH-MOBILE-0001 §8 After registration, every outbound request to the Synheart cloud must be signed by the device's hardware key. This is the SDK-side reference for RFC-AUTH-MOBILE-0001 §8. ## Public API ```text theme={null} signRequest( appId: String, method: String, path: String, bodyBytes: ByteArray, ) -> SignedHeaders ``` Dart, Kotlin, and Swift expose the same shape. The SDK generates the timestamp and nonce internally. ## Message construction (normative) The signed message MUST be: ```text theme={null} method = uppercase HTTP method, ASCII (e.g. "POST") path = request path, ASCII (e.g. "/ingest/v1/hsi") no query string timestamp_str = Unix seconds, ASCII decimal (e.g. "1709312345") raw_body_bytes = exact HTTP request body bytes on the wire (empty bytes for GET / no body) ``` The bytes signed: ```text theme={null} message = method || "\n" || path || "\n" || timestamp_str || "\n" || raw_body_bytes signature = ECDSA-P256-SIGN(private_key, SHA256(message)) ``` > [!NOTE] > > For Synheart Core's cloud ingest, the runtime strips the `/ingest/` prefix from POSTs to `/ingest/v1/...` so signatures cover `/v1/...`. If you build clients that talk to those endpoints from outside Core, mirror this prefix-stripping rule. The signature is encoded as **Base64(ASN.1 DER)**. The runtime native bridge accepts compact `r||s` (64 bytes) from its `sign_bytes` callback and the SDK wraps that in DER for the wire header. ## Six required headers | Header | Value | Notes | | - | - | - | | `X-App-ID` | string | The `app_id` provisioned in the dashboard. | | `X-Device-ID` | UUID | Issued at registration. | | `X-Synheart-Signature` | `Base64(ASN.1 DER)` | ECDSA-P256 over `SHA256(message)`. | | `X-Synheart-Timestamp` | Unix seconds | Decimal ASCII, e.g. `"1709312345"`. | | `X-Synheart-Nonce` | UUID v4 | Unique per request, never reused. | | `X-Synheart-Sig-Version` | `"1"` | Signature scheme version. Future evolution may bump. | The Dart `SignedHeaders.toMap()` returns exactly these six keys. ## Nonce policy * UUID v4. Generated fresh per request; never reused across requests for the same `(app_id, device_id)`. * Server enforces replay protection on **write** endpoints (POST, PUT, PATCH, DELETE) within the 300-second freshness window. * Replay protection is RECOMMENDED for read endpoints. * Server stores nonces with a 300-second TTL keyed by `(device_id, nonce)`. ## Timestamp policy * Server-side freshness window: **300 seconds**. * SDK clock may drift; `correctClockSkew(serverTimestamp)` learns an offset from `CLOCK_SKEW` errors and applies it on subsequent signs. * The SDK persists `clock_offset_ms` in local storage. ## Server-side verification (RFC §8.4) Backends that verify these signatures follow: 1. Extract the six headers; reject if any required header is missing. 2. Reject if `abs(server_time - X-Synheart-Timestamp) > 300`. 3. For write endpoints, reject if `(device_id, nonce)` has been seen in the freshness window. 4. Reconstruct the message: `method + "\n" + path + "\n" + timestamp + "\n" + body_bytes`. 5. Look up the public key by `(app_id, device_id)`. 6. Verify ECDSA P-256 signature over `SHA256(message)`. 7. Store the nonce with a 300-second TTL (write endpoints). ## SignedHeaders type ```dart theme={null} class SignedHeaders { final String appId; final String deviceId; final String signature; final String timestamp; final String nonce; final String signatureVersion; // default "1" Map toMap(); } ``` Kotlin and Swift mirror this. ## Sig-Version `X-Synheart-Sig-Version` is `"1"`. The header is versioned so the signing scheme can evolve without breaking deployed clients. ## Wiring through Synheart Core When `synheart-core` consumes `synheart-auth`: 1. Core constructs a `DeviceAuthProvider` over `SynheartAuth`. 2. Core registers the auth provider's crypto callbacks with the Synheart runtime. 3. The runtime's request-signing path builds `X-Synheart-Proof` (a compact JWS bound to the request URL+method) for HSI ingest. This is a different header from `X-Synheart-Signature` — both are hardware-backed by the same ECDSA P-256 key but cover different surfaces. 4. For non-runtime traffic, hosts call `SynheartAuth.signRequest(...)` directly and attach the six headers themselves. | Header | Used by | | - | - | | `X-Synheart-Signature` (this SDK) | Direct API calls from your app to Synheart endpoints. | | `X-Synheart-Proof` (runtime) | HSI ingest from the Synheart runtime. See [Cloud Protocol](/synheart-core/cloud-protocol). | ## What is not signed * Query string components (signing is over `path` only). Servers that include sensitive parameters in query strings are responsible for separate validation. * Headers other than the six listed above. The body and the path/method are the only signed surface. ## Logging policy | Allowed (prod) | Never (prod) | | - | - | | `app_id` | Raw signatures | | `device_id` (truncated/hashed) | Raw request bodies | | Error codes | Attestation proof payloads | | Latency metrics | Public key material (debug builds only with opt-in) | | Rotation events | Clock offset values | | State transitions | | ## Related * [Registration](/synheart-auth/registration) — how the public key reaches the server. * [Errors](/synheart-auth/errors) — `CLOCK_SKEW`, `NONCE_REPLAY`, `KEY_INVALIDATED` recovery. * [Cloud Protocol](/synheart-core/cloud-protocol) — `X-Synheart-Proof` for HSI ingest. # State Machine Source: https://docs.synheart.ai/synheart-auth/state-machine Device authentication state machine per RFC-AUTH-MOBILE-0001 §7.1 The mobile auth SDK runs an explicit state machine per `(app_id, device)`. Transitions are validated; invalid transitions throw `InvalidStateTransition`. The state is persisted alongside `device_id` so the SDK can resume across app restarts. ## States | Dart enum | Wire string | Meaning | | - | - | - | | `unregistered` | `"unregistered"` | No device identity exists for this `app_id`. | | `challengeReceived` | `"challengeReceived"` | Challenge fetched from server, awaiting key generation. | | `keyReady` | `"keyReady"` | Hardware keypair generated, awaiting attestation. | | `registering` | `"registering"` | Attestation proof generated, register call in flight. | | `registered` | `"registered"` | Device identity established, ready to sign. | | `keyInvalid` | `"keyInvalid"` | OS-detected key invalidation; requires re-registration. | ## Allowed transitions ```text theme={null} unregistered → challengeReceived challengeReceived → keyReady keyReady → registering registering → registered registering → unregistered (failure → reset → retry) registered → registering (key rotation) registered → keyInvalid (OS detected key gone) keyInvalid → unregistered (wipe and start fresh) ``` Any other transition throws `InvalidStateTransition`. ```text theme={null} ┌─────────────┐ │ unregistered│ ◄─────────────┐ └─────┬───────┘ │ │ fetch challenge │ wipe ▼ │ ┌──────────────────┐ │ │ challengeReceived│ │ └─────┬────────────┘ │ │ generate key │ ▼ │ ┌──────────┐ │ │ keyReady │ │ └────┬─────┘ │ │ attest + register │ ▼ │ ┌──────────────────┐ │ │ registering │ ────fail──────────►│ └─────┬────────────┘ │ │ success │ ▼ │ ┌────────────┐ rotate ┌─────────────┐ │ │ registered │────────►│ registering │──┘ └─────┬──────┘ └─────────────┘ │ OS invalidation ▼ ┌────────────┐ wipe ┌─────────────┐ │ keyInvalid │────────►│unregistered │ └────────────┘ └─────────────┘ ``` ## Mapping to public API | API call | Triggered transition | | - | - | | `configure(baseUrl)` | (no state change) | | `isRegistered(appId)` | (no state change) | | `registerDevice(appId)` step 1 | `unregistered → challengeReceived` | | key generation | `challengeReceived → keyReady` | | attestation + register call | `keyReady → registering` | | register success | `registering → registered` | | register failure | `registering → unregistered` | | `rotateKey(appId)` | `registered → registering → registered` | | OS detected key invalidation | `registered → keyInvalid` | | `resetDeviceIdentity(appId)` | any state → `unregistered` | ## Persistence The current state is stored alongside `device_id`, key alias, `platform`, `registered_at`, `key_rotated_at`, and `clock_offset_ms`. | Platform | Storage | | - | - | | iOS | Keychain (state + metadata) + Secure Enclave (key reference). | | Android | EncryptedSharedPreferences (state + metadata) + Keystore (key alias). | Private key bytes are **never** persisted in app-managed storage — they live only in hardware. ## Key invalidation detection (RFC §11.1) The SDK transitions `registered → keyInvalid` automatically when the OS reports the key is no longer usable. | Platform | Detection | | - | - | | Android | `KeyPermanentlyInvalidatedException` on any Keystore operation; `UnrecoverableKeyException` when alias no longer resolves. | | iOS | `errSecItemNotFound` (key deleted from Secure Enclave); `errSecAuthFailed` (biometric context changed); `LAError.biometryLockout` for biometry-bound keys. | On detection: 1. SDK emits `KeyInvalidated` error. 2. State transitions to `keyInvalid`. 3. The next `registerDevice(appId)` call wipes local state (`keyInvalid → unregistered`) and starts fresh. The SDK never silently retries with the invalid key. ## State after `resetDeviceIdentity` `resetDeviceIdentity(appId)` is the one-step path from any state back to `unregistered`. RFC §9.3 restricts when it's allowed: * Server explicitly instructs identity reset (e.g. `DEVICE_REVOKED`). * User explicitly requests it ("sign out of all devices"). * Key invalidation is detected and rotation is impossible. It MUST NOT be called as a convenience retry. After it returns: * The hardware key is deleted (best-effort; on hardware failures the alias is abandoned). * `device_id` and metadata are cleared. * Next API call requires a full re-registration. ## Related * [Registration](/synheart-auth/registration) — happy-path transitions. * [Errors](/synheart-auth/errors) — `KeyInvalidated`, `InvalidStateTransition`, recovery paths. * [Signing](/synheart-auth/signing) — only `registered` enables this. # Synheart Behavior - Chrome Extension Source: https://docs.synheart.ai/synheart-behavior/chrome Browser-side behavioral input for the Synheart stack — timing and patterns only, streamed to your local sensor agent ## Overview The Synheart Behavior Chrome Extension extends behavioral input to the desktop browser. It captures how you interact with Chrome — rhythm, attention, movement patterns — not what you read or type, and streams anonymized session events to your local [Synheart Sensor Agent](/synheart-sensor-agent/overview). It produces the same event shape as the mobile SDKs ([Flutter](/synheart-behavior/flutter), [Kotlin](/synheart-behavior/kotlin), [Swift](/synheart-behavior/swift)), so the browser becomes another input source for the same downstream pipeline. As with the mobile SDKs, the extension is an input layer; higher-level metrics (focus, distraction, HSI fields) are derived downstream — see the [Behavior overview](/synheart-behavior/overview). **Distribution:** Source-available. The repository is open for reading, reviewing, and filing issues. Pull requests are not accepted — see the repo's `CONTRIBUTING.md`. Security reports follow `SECURITY.md`. ## Privacy posture The extension records interaction timing and patterns only. It does not record URLs, page titles, passwords, or typed content. Tabs use anonymous labels (`tab-1`, `tab-2`). Sites are classified into generic categories only. | Captured | Never captured | | - | - | | Mouse movement patterns (not precise positions tied to page content) | URLs or page titles | | Keystroke timing (categories: letter / digit / symbol — never which key) | Typed content, passwords, or search queries | | Tab-switch timing with anonymized tab IDs | Clipboard, form values, or link destinations | | Scroll patterns and reversals | Media URLs | | Generic site categories | — | ### Site categories | Category | Examples | | - | - | | `search-engine` | Google, Bing, DuckDuckGo | | `video-platform` | YouTube, Vimeo, Twitch | | `code-repository` | GitHub, GitLab, Bitbucket | | `developer-qa` | Stack Overflow, Stack Exchange | | `social-media` | Facebook, X, LinkedIn | | `forum` | Reddit | | `e-commerce` | Amazon, eBay | | `email` | Gmail, Outlook | | `documentation` | Google Docs, Notion | | `local-development` | localhost, 127.0.0.1 | | `website` | Default for other sites | ## Installation ### From source ```bash theme={null} git clone https://github.com/synheart-ai/synheart-behavior-chrome.git cd synheart-behavior-chrome npm install npm run build ``` Load the extension in Chrome: 1. Open `chrome://extensions` 2. Enable Developer mode 3. Click Load unpacked and select the `dist` folder For iterative development, run `npm run build -- --watch` and use Reload on the extension card after each change. ### Requirements * Chrome (Manifest V3) * A running [Synheart Sensor Agent](/synheart-sensor-agent/overview) reachable on a configured host/port (typically `127.0.0.1`) ## Quick start 1. Start the sensor agent. 2. Open the extension popup, go to Sensor, set the port and auth token, choose Save, then Test Connection. 3. Toggle the main switch to ON to begin capture. Use Stats and HSI in the popup to verify flow. There is no account in this repo — only your local configuration. ### Popup tabs | Tab | Purpose | | - | - | | Stats | Buffered events, session id, sensor-agent status. | | Sensor | Port, auth token, test + save. | | HSI | Latest human-state readouts when your agent returns them. | ## Behavioral metrics captured ### Focus and attention | Metric | Description | | - | - | | Tab switch | Moves between tabs (anonymized IDs). | | Tab hijacking | Rapid tab switches within a short window (e.g. 5 seconds). | | Window focus / blur | Browser focus at the OS level. | | Visibility change | Tab hidden / visible transitions. | | Cursor parking | Where the cursor settles (e.g. by quadrant). | ### Micro-motor patterns | Metric | Description | | - | - | | Cursor path tortuosity | Movement efficiency (1.0 ≈ straight; higher ≈ more hesitant). | | Click dwell | How long the mouse button is held. | | Scroll events | Velocity, direction, ratchet vs linear. | | Scroll reversals | Direction flips (re-reading–style signal). | ### Keystroke dynamics (timing only) | Metric | Description | | - | - | | Key hold time | By category (letter, digit, symbol) — never which key. | | Flight time | Gap between releasing one key and pressing the next. | | Backspace burst | Rapid backspace bursts (e.g. 3+ in 500ms). | | Modifier combos | Ctrl / Alt / Shift / Meta usage patterns. | ### Navigation patterns | Metric | Description | | - | - | | Navigation events | Transition type (typed, link, reload, generated). | | Anchor scanning | Link hover duration, internal vs external. | | Form submit | GET vs POST (method only). | ## Session payload The extension batches browser events into session payloads and POSTs them to the sensor agent. ```json theme={null} { "session": { "session_id": "SESS-1768471200000", "device_id": "chrome-abc12345", "timezone": "America/New_York", "start_time": "2026-01-15T10:00:00.000Z", "end_time": "2026-01-15T10:05:00.000Z", "events": [ { "timestamp": "2026-01-15T10:00:05.000Z", "event_type": "app_switch", "app_switch": { "from_app_id": "tab-1", "to_app_id": "tab-2", "site_category": "code-repository" } }, { "timestamp": "2026-01-15T10:00:10.000Z", "event_type": "scroll", "scroll": { "velocity": 150, "direction": "down", "direction_reversal": false } }, { "timestamp": "2026-01-15T10:00:15.000Z", "event_type": "typing", "typing": { "key_category": "letter", "hold_ms": 85, "flight_ms": 120 } } ], "meta": { "source": "synheart-behavior-chrome", "version": "0.0.1", "event_count": 45 } } } ``` ### Event type mapping | Browser concept | `event_type` | | - | - | | Tab switch | `app_switch` | | Scroll | `scroll` | | Click dwell | `tap` | | Cursor path | `swipe` | | Keystroke timing | `typing` | | Focus / blur | `focus` | | Idle | `idle` | | Navigation | `navigation` | ## Sensor agent endpoint ```http theme={null} POST http://127.0.0.1:{port}/collect Authorization: Bearer {token} Content-Type: application/json ``` Body: `{ "session": { ... } }` as produced by the extension. Response shape varies with agent version. ## Repository layout * Repository root: `LICENSE`, `README.md` * `synheart-behavior/` (extension package) * `manifest.json` — Chrome MV3 manifest * `background.js` — Service worker (batch + send) * `content.js` — Behavioral capture * `popup.html` * `src/popup.js`, `src/popup.css` * `icons/` ## Testing Validate manifest and JavaScript syntax: ```bash theme={null} node -e "JSON.parse(require('fs').readFileSync('synheart-behavior/manifest.json','utf8'))" node --check synheart-behavior/background.js node --check synheart-behavior/content.js node --check synheart-behavior/src/popup.js ``` For manual verification, load unpacked from `dist`, open the Sensor tab, enable recording, and confirm events in your agent logs. ## Resources * Repository: [synheart-behavior-chrome](https://github.com/synheart-ai/synheart-behavior-chrome) * Sensor agent: [Synheart Sensor Agent](/synheart-sensor-agent/overview) * Behavior concepts: [Synheart Behavior overview](/synheart-behavior/overview), [Metric definitions](/synheart-behavior/metric-definitions), [Threat model](/synheart-behavior/threat-model) ## License Licensed under the Apache License, Version 2.0. # Errors Source: https://docs.synheart.ai/synheart-behavior/errors Permission failures, lifecycle errors, and the runtime-gate drop semantics The behavior SDK has a small, mostly-quiet error surface. Missing permissions show up as missing events and zero counts, not exceptions. Misuse of the API throws. ## Surfaces | Surface | When | | - | - | | Thrown error | Calls before `initialize()`, unknown sessions, native failures. | | Missing events / zero counts | A platform permission is not granted. | | Silent drops at the runtime gate | `Behavior` consent is not granted in the Synheart runtime. | ## Thrown errors | SDK | Type | Examples | | - | - | - | | Flutter | `Exception` with a message | `Exception('SDK not initialized. Call SynheartBehavior.initialize() first.')`, or `Exception('Failed to … : ')` wrapping a native failure. | | Kotlin | `IllegalStateException`, `IllegalArgumentException` | Calls before `initialize()`; ending when no session is active; ending with the wrong session id; `updateConfig()` while a session is active. | | Swift | `BehaviorError` | `.notInitialized`, `.invalidConfiguration`, `.sessionNotFound`. | Lifecycle details: * **Starting a session while one is running:** Kotlin ends the previous session first. Flutter and Swift start the new one without ending the old. * **Ending a session twice:** the second call fails; the SDKs don't cache the summary. * **After `dispose()`:** Flutter calls throw the "not initialized" exception, and `sendEvent` silently does nothing. ## `consentBehavior` `BehaviorConfig.consentBehavior` is carried into payloads, but no SDK reads it to stop collection: events flow with `consentBehavior = false`. Gate collection in your app (don't call `initialize()` or `startSession()` without consent), or rely on the runtime's `Behavior` consent gate described below. ## Permission failures The SDK does not throw when a platform permission is missing. Instead: | Permission | Behavior when denied | | - | - | | Notification listener (Android) | `notification` events do not flow; `notificationSummary.notificationCount = 0`. | | Phone state (Android) | `call` events do not flow; `notificationSummary.callCount = 0`. | | Notifications (iOS) | No `notification` events unless the host forwards its delegate callbacks (Swift) or the SDK is installed as the delegate. | Hosts query availability via: * `checkNotificationPermission()` / `requestNotificationPermission()` — all three SDKs (async on Swift). * `checkCallPermission()` / `requestCallPermission()` — all three SDKs. * Kotlin also has `checkNotificationListenerEnabled()` / `checkNotificationListenerConnected()`. ## Native channel errors (Flutter) If the native plugin isn't registered (for example a desktop build without the platform layer), method-channel calls fail with `MissingPluginException`, and SDK calls that wrap them throw `Exception('Failed to …')`. Verify plugin registration and the platform build steps. ## Motion * **Kotlin:** when `enableMotionLite = true` and the bundled ONNX model fails to load, the failure is logged, `motionState` stays `null` for the session, and events continue normally. * **Flutter:** `onMotionSample` emits only when `emitRawMotionSamples: true`. * **Swift:** raw samples arrive only when `emitRawMotionSamples: true` and a handler is set with `setRawMotionSampleHandler`. ## Runtime gate drops When the host wires the SDK into `synheart-core` → the Synheart runtime, behavior events pass through the runtime's consent gate. If `Behavior` consent is not granted, the runtime drops events at the engine seam silently. The SDK sees no error — events fire on `onEvent`, but the runtime never persists or aggregates them. This is intentional: SDK-side telemetry remains coherent (UIs still see live events) while the privacy boundary is enforced past the SDK. ## Validation invariants * `BehaviorSessionSummary` is returned on session end even when no events flowed. * `BehaviorEvent.timestamp` is an ISO-8601 string. ## Related * [Behavior Overview](/synheart-behavior/overview) — config flags that gate each surface. * [Threat Model](/synheart-behavior/threat-model) — what's collected and what's not. * [Metric Definitions](/synheart-behavior/metric-definitions) — what the runtime computes from events. * [Consent System](/synheart-core/consent-system) — runtime-side `Behavior` gate. # Synheart Behavior - Flutter SDK Source: https://docs.synheart.ai/synheart-behavior/flutter On-device behavioral event collection for Flutter applications ## Overview The Synheart Behavior Flutter SDK collects behavioral events from digital interactions (taps, scrolls, swipes, typing timing, app switches, notifications, calls) and streams them to your app. Since 0.4.0 the SDK is an **event producer**: it emits events and raw per-session counts, and no longer computes focus, distraction or typing aggregates, or classifies motion. Those are computed downstream by [Synheart Core](/synheart-core/overview) and the runtime. ## Installation Add to `pubspec.yaml`: ```yaml theme={null} dependencies: synheart_behavior: ^0.4.1 ``` Install: ```bash theme={null} flutter pub get ``` ### Requirements * Flutter >= 3.10.0 * Dart >= 3.0.0 * iOS 12.0+, Android `minSdk` 21 ## Quick Start ### Basic Usage ```dart theme={null} import 'package:synheart_behavior/synheart_behavior.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Initialize SDK final behavior = await SynheartBehavior.initialize( config: const BehaviorConfig( enableInputSignals: true, enableAttentionSignals: true, ), ); runApp(MyApp(behavior: behavior)); } class MyApp extends StatelessWidget { final SynheartBehavior behavior; const MyApp({super.key, required this.behavior}); @override Widget build(BuildContext context) { return behavior.wrapWithGestureDetector( MaterialApp( title: 'My App', home: HomePage(behavior: behavior), ), ); } } ``` ### Real-Time Event Tracking ```dart theme={null} // Listen to real-time events behavior.onEvent.listen((event) { print('Event: ${event.eventType} at ${event.timestamp}'); print('Metrics: ${event.metrics}'); // Handle different event types switch (event.eventType) { case BehaviorEventType.scroll: final velocity = event.metrics['velocity'] as double?; print('Scroll velocity: $velocity px/s'); break; case BehaviorEventType.tap: final duration = event.metrics['tap_duration_ms'] as int?; print('Tap duration: $duration ms'); break; case BehaviorEventType.swipe: final direction = event.metrics['direction'] as String?; print('Swipe direction: $direction'); break; case BehaviorEventType.typing: final speed = event.metrics['typing_speed'] as double?; final tapCount = event.metrics['typing_tap_count'] as int?; print('Typing speed: $speed, tap count: $tapCount'); break; default: break; } }); ``` ### Session Management ```dart theme={null} // Start a session final session = await behavior.startSession(); print('Session started: ${session.sessionId}'); // ... user interacts with app ... // End session and get summary final summary = await session.end(); print('Session duration: ${summary.durationMs}ms'); print('Total events: ${summary.activitySummary.totalEvents}'); print('Notifications: ${summary.notificationSummary.notificationCount}'); ``` > [!NOTE] > > `summary.behavioralMetrics` and `summary.typingSessionSummary` are always > `null`, and `notificationIgnoreRate` / `notificationClusteringIndex` are always > `0`: the SDK no longer computes them. Focus and distraction scores come from > Synheart Core. ### On-Demand Metrics Calculation Get raw counts and context for a custom time range within a session: ```dart theme={null} // Calculate metrics for a specific time range final metrics = await behavior.calculateMetricsForTimeRange( startTimestampSeconds: 1767688063, // Unix timestamp in seconds endTimestampSeconds: 1767688130, // Unix timestamp in seconds sessionId: 'SESS-1767688063415', // Optional: uses current session if not provided ); // Access the calculated metrics print('Total events: ${metrics['activity_summary']['total_events']}'); print('App switches: ${metrics['activity_summary']['app_switch_count']}'); print('Notifications: ${metrics['notification_summary']}'); // Device context print('Screen brightness: ${metrics['device_context']['avg_screen_brightness']}'); print('Orientation: ${metrics['device_context']['start_orientation']}'); // System state print('Internet: ${metrics['system_state']['internet_state']}'); print('Do not disturb: ${metrics['system_state']['do_not_disturb']}'); ``` The map holds `activity_summary`, `notification_summary`, `device_context` and `system_state`. It no longer includes `behavioral_metrics` or `motion_state`. Failures throw an `Exception('Failed to calculate metrics for time range: …')`. ## API Reference ### `SynheartBehavior` **Main Methods:** | Method | Description | Returns | | - | - | - | | `initialize({config, onEventCallback})` | Initialize SDK | `Future` | | `wrapWithGestureDetector(widget)` | Wrap app to enable gesture tracking | `Widget` | | `startSession({sessionId})` | Start a new session | `Future` | | `calculateMetricsForTimeRange(...)` | Raw counts for a custom time range | `Future>` | | `getCurrentStats()` | Get current statistics | `Future` | | `onEvent` | Stream of behavioral events | `Stream` | | `onMotionSample` | Raw 50 Hz accelerometer batches (needs `emitRawMotionSamples`) | `Stream>` | | `sendEvent(event)` | Send an event yourself | `Future` | | `updateConfig(config)` | Replace the configuration | `Future` | | `createBehaviorTextField(...)` | A `TextField` that reports typing timing | `Widget` | | `dispose()` | Clean up resources | `Future` | Permission helpers are listed under [Permissions](#permissions). **Properties:** | Property | Type | Description | | - | - | - | | `isInitialized` | `bool` | Whether SDK is initialized | | `currentSessionId` | `String?` | Current active session ID | ### `BehaviorConfig` **Parameters:** | Parameter | Type | Default | Description | | - | - | - | - | | `enableInputSignals` | `bool` | `true` | Enable scroll, tap, swipe, typing tracking | | `enableAttentionSignals` | `bool` | `true` | Enable app switching, idle gaps | | `enableMotionLite` | `bool` | `false` | Start the native motion collector (no on-device classification) | | `emitRawMotionSamples` | `bool` | `false` | Deliver raw 50 Hz accelerometer batches on `onMotionSample` | | `sessionIdPrefix` | `String?` | `null` | Prefix for session IDs (null = auto-generated) | | `userId` | `String?` | `null` | Optional user identifier | | `deviceId` | `String?` | `null` | Optional device identifier | | `eventBatchSize` | `int` | `10` | Events per batch | | `maxIdleGapSeconds` | `double` | `10.0` | Max idle time before task drop | | `behaviorVersion` | `String` | `'1.0.0'` | Version string for HSI payloads | | `consentBehavior` | `bool` | `true` | Carried into payloads; the SDK does not gate collection on it | ### `BehaviorEvent` **Properties:** | Property | Type | Description | | - | - | - | | `eventId` | `String` | Unique event identifier | | `sessionId` | `String` | Associated session ID | | `timestamp` | `String` | ISO 8601 timestamp | | `eventType` | `BehaviorEventType` | Type of event | | `metrics` | `Map` | Event-specific metrics | **Event Types:** * `BehaviorEventType.scroll` - Scroll interactions * `BehaviorEventType.tap` - Tap interactions * `BehaviorEventType.swipe` - Swipe interactions * `BehaviorEventType.app_switch` - Foreground / background app-switch events * `BehaviorEventType.notification` - Notification events * `BehaviorEventType.call` - Call events * `BehaviorEventType.typing` - Typing session events (timing only — never characters) * `BehaviorEventType.clipboard` - Clipboard activity (copy / paste / cut counts only — never content) ### `BehaviorSession` **Methods:** | Method | Description | Returns | | - | - | - | | `end()` | End session and get summary | `Future` | **Properties:** | Property | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startTimestamp` | `int` | Start time (ms since epoch) | | `currentDuration` | `int` | Milliseconds since the start | ### `BehaviorSessionSummary` **Properties:** | Property | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startAt` | `String` | Session start time (ISO 8601) | | `endAt` | `String` | Session end time (ISO 8601) | | `durationMs` | `int` (getter) | Session duration in milliseconds | | `activitySummary` | `ActivitySummary` | `totalEvents`, `appSwitchCount` | | `notificationSummary` | `NotificationSummary` | Notification and call counts | | `appId` / `appName` | `String?` | Host app identifiers | | `os` | `String` | OS / platform | | `microSession` | `bool` | Whether the session was very short | | `sessionSpacing` | `int` | Time since the previous session | | `deviceContext` | `DeviceContext` | Brightness and orientation | | `systemState` | `SystemState` | Internet, Do Not Disturb, charging | | `performanceInfo` | `Map?` | Per-session performance counters | | `behavioralMetrics` | `BehavioralMetrics?` | Always `null` (computed downstream) | | `typingSessionSummary` | `TypingSessionSummary?` | Always `null` (computed downstream) | > Motion classification runs in the Synheart Runtime. Set > `emitRawMotionSamples: true`, subscribe to `onMotionSample` and forward the > raw 50 Hz accelerometer batches to the runtime's motion classifier. ## Permissions Since 0.4.1 the plugin's Android manifest merges `BIND_NOTIFICATION_LISTENER_SERVICE`, `READ_PHONE_STATE` and the `SynheartNotificationListenerService` declaration into your app. If you don't collect notifications or calls, remove them in your own manifest: ```xml theme={null} ``` ### Notification Permission ```dart theme={null} // Check if permission is granted final hasPermission = await behavior.checkNotificationPermission(); if (!hasPermission) { // Request permission final granted = await behavior.requestNotificationPermission(); if (granted) { print('Notification permission granted'); } } ``` ### Call Permission ```dart theme={null} // Check if permission is granted final hasPermission = await behavior.checkCallPermission(); if (!hasPermission) { // Request permission await behavior.requestCallPermission(); } ``` ## Configuration ### Update Configuration at Runtime ```dart theme={null} await behavior.updateConfig(const BehaviorConfig( enableInputSignals: true, enableAttentionSignals: true, enableMotionLite: true, )); ``` ## Resources * **pub.dev**: [synheart\_behavior](https://pub.dev/packages/synheart_behavior) * **Repository**: [synheart-behavior-flutter](https://github.com/synheart-ai/synheart-behavior-flutter) * **Full README**: [View on GitHub](https://github.com/synheart-ai/synheart-behavior-flutter#readme) For comprehensive documentation, see the [full README on GitHub](https://github.com/synheart-ai/synheart-behavior-flutter#readme). # Synheart Behavior - Kotlin/Android SDK Source: https://docs.synheart.ai/synheart-behavior/kotlin On-device behavioral event collection for Android applications ## Overview The Synheart Behavior Kotlin/Android SDK collects behavioral events from digital interactions (taps, scrolls, swipes, typing timing, app switches, notifications, calls) in native Android apps and streams them to your app. Since 0.5.0 the SDK is an **event producer**: it emits events and raw per-session counts, and no longer computes focus, distraction or typing aggregates itself. Those scores are computed downstream by [Synheart Core](/synheart-core/overview) from the event stream. Kotlin is the one platform that still runs the on-device motion-state model. ## Installation Add to your `build.gradle`: Published to Maven Central as `ai.synheart:synheart-behavior`: ```gradle theme={null} repositories { mavenCentral() } dependencies { implementation 'ai.synheart:synheart-behavior:0.6.0' } ``` The old `ai.synheart:behavior` artifact stopped at 0.3.0. ### Requirements * Android `minSdk` 21, `compileSdk` 34, Java 17 * Bundles `onnxruntime-android` 1.18.0 for the motion-state model ## Quick Start ### Basic Usage ```kotlin theme={null} import ai.synheart.behavior.* import android.app.Application import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MyApplication : Application() { lateinit var behavior: SynheartBehavior private set override fun onCreate() { super.onCreate() val config = BehaviorConfig( enableInputSignals = true, enableAttentionSignals = true, enableMotionLite = true, // On-device motion state (LAYING, MOVING, SITTING, STANDING) ) behavior = SynheartBehavior.create(this, config) behavior.initialize() } } class MainActivity : AppCompatActivity() { private val behavior by lazy { (application as MyApplication).behavior } private var currentSession: BehaviorSession? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Attach to views for gesture tracking behavior.attachToView(findViewById(android.R.id.content)) // Start a session startSession() } private fun startSession() { try { currentSession = behavior.startSession() android.util.Log.d("Behavior", "Session started: ${currentSession?.sessionId}") } catch (e: Exception) { android.util.Log.e("Behavior", "Failed to start session: $e") } } } ``` ### Real-Time Event Tracking ```kotlin theme={null} // Using callback handler behavior.setEventHandler { event -> android.util.Log.d("Behavior", "Event: ${event.eventType} at ${event.timestamp}") android.util.Log.d("Behavior", "Metrics: ${event.metrics}") // Handle different event types when (event.eventType) { BehaviorEventType.SCROLL -> { val velocity = event.metrics["velocity"] as? Double android.util.Log.d("Behavior", "Scroll velocity: $velocity px/s") } BehaviorEventType.TAP -> { val duration = event.metrics["tap_duration_ms"] as? Int android.util.Log.d("Behavior", "Tap duration: $duration ms") } BehaviorEventType.SWIPE -> { val direction = event.metrics["direction"] as? String android.util.Log.d("Behavior", "Swipe direction: $direction") } BehaviorEventType.TYPING -> { val speed = event.metrics["typing_speed"] as? Double val tapCount = event.metrics["typing_tap_count"] as? Int android.util.Log.d("Behavior", "Typing speed: $speed, tap count: $tapCount") } else -> {} } } // Or using Kotlin Flow (reactive approach) import kotlinx.coroutines.flow.collect import androidx.lifecycle.lifecycleScope lifecycleScope.launch { behavior.onEvent.collect { event -> when (event.eventType) { BehaviorEventType.SCROLL -> { // Handle scroll event } BehaviorEventType.TYPING -> { // Handle typing event } // ... handle other event types else -> {} } } } ``` ### Session Management ```kotlin theme={null} // Start a session val session = behavior.startSession() android.util.Log.d("Behavior", "Session started: ${session.sessionId}") // ... user interacts with app ... // End session and get summary val summary = behavior.endSession(session.sessionId) android.util.Log.d("Behavior", "Session duration: ${summary.durationMs}ms") android.util.Log.d("Behavior", "Total events: ${summary.activitySummary.totalEvents}") android.util.Log.d("Behavior", "App switches: ${summary.activitySummary.appSwitchCount}") android.util.Log.d("Behavior", "Notifications: ${summary.notificationSummary.notificationCount}") summary.motionState?.let { android.util.Log.d("Behavior", "Motion: ${it.majorState}") } ``` `startSession()` ends any session that is already running before starting the new one. > [!NOTE] > > `summary.behavioralMetrics` and `summary.typingSessionSummary` are always > `null`, and `notificationIgnoreRate` / `notificationClusteringIndex` are always > `0.0`: the SDK no longer computes them. Use Synheart Core for focus and > distraction scores. ## API Reference ### `SynheartBehavior` **Main Methods:** | Method | Description | Returns | | - | - | - | | `create(context, config)` | Create SDK instance | `SynheartBehavior` | | `initialize()` | Initialize SDK | `void` | | `attachToView(view)` | Attach to view for gesture tracking | `void` | | `startSession(sessionId: String? = null)` | Start a new session (ends a running one) | `BehaviorSession` | | `endSession(sessionId)` | End session and get summary | `BehaviorSessionSummary` | | `getCurrentStats()` | Get current statistics | `BehaviorStats` | | `setEventHandler(callback)` | Set callback for events | `void` | | `sendEvent(event)` | Manually send an event | `void` | | `updateConfig(config)` | Replace the config (no active session) | `void` | | `reportUserActivity()` | Tell the SDK the user is active | `void` | | `reportNotification(action, sourceApp)` | Report a notification event | `void` | | `reportNotificationIgnored(sourceApp)` / `reportNotificationOpened(sourceApp)` | Report what the user did with a notification | `void` | | `dispose()` | Clean up resources | `void` | Permission helpers are listed under [Permissions](#permissions). **Properties:** | Property | Type | Description | | - | - | - | | `isInitialized` | `Boolean` | Whether SDK is initialized | | `currentSessionId` | `String?` | Current active session ID | | `onEvent` | `Flow` | Flow of behavioral events | ### `BehaviorConfig` **Parameters:** | Parameter | Type | Default | Description | | - | - | - | - | | `enableInputSignals` | `Boolean` | `true` | Enable scroll, tap, swipe, typing tracking | | `enableAttentionSignals` | `Boolean` | `true` | Enable app switching, idle gaps | | `enableMotionLite` | `Boolean` | `false` | Collect motion and run the on-device motion-state model | | `sessionIdPrefix` | `String?` | `null` | Prefix for session IDs (null = auto-generated) | | `userId` | `String?` | `null` | Optional user identifier | | `deviceId` | `String?` | `null` | Optional device identifier | | `eventBatchSize` | `Int` | `10` | Events per batch | | `maxIdleGapSeconds` | `Double` | `10.0` | Max idle time before task drop | | `behaviorVersion` | `String` | `"1.0.0"` | Version string for HSI payloads | | `consentBehavior` | `Boolean` | `true` | Carried into payloads; the SDK does not gate collection on it | ### `BehaviorEvent` **Properties:** | Property | Type | Description | | - | - | - | | `eventId` | `String` | Unique event identifier | | `sessionId` | `String` | Associated session ID | | `timestamp` | `String` | ISO 8601 timestamp | | `eventType` | `BehaviorEventType` | Type of event | | `metrics` | `Map` | Event-specific metrics | **Event Types:** * `BehaviorEventType.SCROLL` - Scroll interactions * `BehaviorEventType.TAP` - Tap interactions * `BehaviorEventType.SWIPE` - Swipe interactions * `BehaviorEventType.APP_SWITCH` - Foreground / background app-switch events * `BehaviorEventType.NOTIFICATION` - Notification events * `BehaviorEventType.CALL` - Call events * `BehaviorEventType.TYPING` - Typing session events (timing only — never characters) * `BehaviorEventType.CLIPBOARD` - Clipboard activity (copy / paste / cut counts only — never content) ### `BehaviorSession` **Properties:** | Property / method | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startTimestamp` | `Long` | Start time (ms since epoch) | | `end()` | `BehaviorSessionSummary` | End this session | | `getCurrentDuration()` | `Long` | Milliseconds since the start | ### `BehaviorSessionSummary` **Properties:** | Property | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startAt` | `String` | ISO 8601 session start time | | `endAt` | `String` | ISO 8601 session end time | | `durationMs` | `Int` | Session duration in milliseconds | | `microSession` | `Boolean` | Whether the session was very short | | `os` | `String` | OS version | | `appId` / `appName` | `String?` | Host app identity | | `sessionSpacing` | `Int` | Time since the previous session | | `deviceContext` | `DeviceContext` | Brightness and orientation | | `activitySummary` | `ActivitySummary` | `totalEvents`, `appSwitchCount` | | `notificationSummary` | `NotificationSummary` | Notification and call counts | | `systemState` | `SystemState` | Internet, Do Not Disturb, charging | | `motionState` | `MotionState?` | On-device motion state (if enabled) | | `motionData` | `List?` | Motion feature windows (if enabled) | | `behavioralMetrics` | `BehavioralMetrics?` | Always `null` (computed downstream) | | `typingSessionSummary` | `TypingSessionSummary?` | Always `null` (computed downstream) | ## Permissions The library's manifest merges `BIND_NOTIFICATION_LISTENER_SERVICE`, the `SynheartNotificationListenerService` declaration and `ACCESS_NETWORK_STATE` into your app. If you don't collect notifications, remove the listener: ```xml theme={null} ``` Call events need `READ_PHONE_STATE`, which the library does **not** declare: add it to your own manifest if you want call events. ### Notification Permission ```kotlin theme={null} // Check if notification listener is enabled val isEnabled = behavior.checkNotificationListenerEnabled() if (!isEnabled) { // Open system settings to enable notification access behavior.requestNotificationListenerAccess() } // Check if notification permission is granted (Android 13+) val hasPermission = behavior.checkNotificationPermission() if (!hasPermission) { // Request permission using Activity.requestPermissions() or ActivityResultContracts // After permission is granted, call: behavior.hotRestartCollectors() } // Whether the listener service is bound right now val connected = behavior.checkNotificationListenerConnected() ``` ### Call Permission ```kotlin theme={null} // Check if permission is granted val hasPermission = behavior.checkCallPermission() if (!hasPermission) { // Request permission using Activity.requestPermissions() or ActivityResultContracts // After permission is granted, call: behavior.reinitializePhoneStateListener() } ``` ## Configuration ### Update Configuration at Runtime ```kotlin theme={null} behavior.updateConfig(BehaviorConfig( enableInputSignals = true, enableAttentionSignals = true, enableMotionLite = true, )) ``` **Note**: Configuration can only be updated when no session is active. ## View Attachment To track gestures on specific views, attach the SDK to them: ```kotlin theme={null} // Attach to a ScrollView behavior.attachToView(scrollView) // Attach to a RecyclerView behavior.attachToView(recyclerView) // Attach to an Activity's root view behavior.attachToView(findViewById(android.R.id.content)) ``` ## Automatic Session Ending Sessions are automatically ended after 1 minute if the app stays in the background. This prevents sessions from running indefinitely when users switch away from your app. ## Resources * **Maven Central**: [ai.synheart:synheart-behavior](https://central.sonatype.com/artifact/ai.synheart/synheart-behavior) * **Repository**: [synheart-behavior-kotlin](https://github.com/synheart-ai/synheart-behavior-kotlin) * **Full README**: [View on GitHub](https://github.com/synheart-ai/synheart-behavior-kotlin#readme) For comprehensive documentation, see the [full README on GitHub](https://github.com/synheart-ai/synheart-behavior-kotlin#readme). # Metric Definitions Source: https://docs.synheart.ai/synheart-behavior/metric-definitions Formal definitions of the BehavioralMetrics fields and the formulas used to compute them The behavior SDKs do not compute these metrics. The canonical implementation runs inside the runtime's behavior feature deriver: the SDK ships events, and the runtime computes the metrics when behavior is fed through [Synheart Core](/synheart-core/overview). The SDKs still define a `BehavioralMetrics` type, but they leave `BehaviorSessionSummary.behavioralMetrics` set to `null`. ## Window The runtime computes each metric over a window of behavior events (a session or an HSI window). Flutter's `calculateMetricsForTimeRange(...)` returns only raw counts and context for a time range, not these metrics. When the window contains no events, every metric returns `0.0` and lists return empty. ## The canonical 12 ### `interactionIntensity` ```text theme={null} non_typing_interaction = total_events − interruption_events − typing_events typing_equivalent = total_typing_duration_sec / 10 // 10s typing = 1 "event" total_interaction = non_typing_interaction + typing_equivalent events_per_minute = total_interaction / session_duration_sec * 60 interaction_intensity = clamp01(events_per_minute / 10) ``` `interruption_events = notification_events + call_events + app_switch_events`. Range `[0, 1]`. Anchored so \~10 events/min reads as full intensity. ### `taskSwitchRate` Exponential saturation: ```text theme={null} task_switch_rate = clamp01( 1 − exp(−app_switches_per_min / 2.0) ) ``` 2 switches/min ≈ 0.63; high rate approaches 1. ### `taskSwitchCost` ```text theme={null} task_switch_cost_ms = clamp(0, 10_000, duration_ms / app_switch_count) // 0 if no switches task_switch_cost = task_switch_cost_ms / 10_000 // normalised 0..1 ``` In the SDK, `BehavioralMetrics.taskSwitchCost` is the **millisecond** form (raw `int`); flux internally also exposes a normalised `[0, 1]` version. ### `idleTimeRatio` ```text theme={null} idle_time_ratio = clamp01( total_idle_time_sec / session_duration_sec ) ``` Idle gaps are counted from the SDK's idle-segment detector (gaps above the configured threshold). ### `activeTimeRatio` ```text theme={null} active_interaction_time_ms = duration_ms − total_idle_time_ms − task_switch_cost_ms active_time_ratio = clamp01( active_interaction_time_ms / duration_ms ) ``` Note: this is **not** simply `1 − idle_time_ratio` — task-switch cost is also subtracted. ### `notificationLoad` Exponential saturation: ```text theme={null} notification_load = clamp01( 1 − exp(−notifications_per_min / 1.0) ) ``` 1 notification/min ≈ 0.63. ### `burstiness` Barabási burstiness over inter-event gaps: ```text theme={null} B = (σ − μ) / (σ + μ) // σ = stddev, μ = mean of inter-event gaps burstiness = clamp01( (B + 1) / 2 ) ``` `0.0` = perfectly regular (Poisson-like), `0.5` = random / no data, `1.0` = very bursty. Flux returns `0.5` when the session has no inter-event gaps yet. ### `behavioralDistractionScore` Weighted composite, fixed weights: ```text theme={null} distraction_score = clamp01( 0.35 * task_switch_rate + 0.30 * notification_load + 0.20 * fragmented_idle_ratio + 0.15 * scroll_jitter_rate ) ``` The four weights are constants in flux; they are not configurable per session. ### `focusHint` ```text theme={null} focus_hint = 1.0 − distraction_score ``` By construction, `focusHint + distractionScore = 1.0`. (Flux's test `test_focus_hint_is_inverse_of_distraction` enforces this.) ### `fragmentedIdleRatio` ```text theme={null} fragmented_idle_ratio = max(0, idle_segment_count / session_duration_sec) ``` Note: the raw ratio can exceed `1.0` on very short sessions; flux clamps at the encoding step before HSI export. ### `scrollJitterRate` ```text theme={null} scroll_jitter_rate = clamp01( direction_reversals / (scroll_events − 1) ) if scroll_events > 1, else 0 ``` A direction reversal counts when scrolling flips between up and down. ### `deepFocusBlocks` Engagement segments lasting at least **`DEEP_FOCUS_MIN_DURATION_SEC = 120` seconds (2 minutes)**, fixed in flux. Each block in the SDK shape: ```dart theme={null} class DeepFocusBlock { final String startAt; // ISO 8601 timestamp final String endAt; // ISO 8601 timestamp final int durationMs; // duration in milliseconds } ``` Flux internally returns just the count. ## Typing metrics (extension) Typing metrics are derived from typing events (formulas live in flux's typing module). Each SDK's typing event carries per-burst timing in its `metrics` map (for example `typing_speed`, `typing_tap_count`); the session-level aggregates below are computed by the runtime. The SDKs' `TypingSessionSummary` is `null`. | Field | JSON key | Range / units | | - | - | - | | `typingSpeed` | `typing_speed` | taps/sec | | `typingCadenceStability` | `typing_cadence_stability` | 0–1 | | `typingCadenceVariability` | `typing_cadence_variability` | unitless (CV) | | `typingActivityRatio` | `typing_activity_ratio` | 0–1 | | `typingGapRatio` | `typing_gap_ratio` | 0–1 | | `typingBurstiness` | `typing_burstiness` | 0–1 | | `typingInteractionIntensity` | `typing_interaction_intensity` | 0–1 | | `clipboardActivityRate` | `clipboard_activity_rate` | 0–1 | | `correctionRate` | `correction_rate` | 0–1 | A few are defined as composite ratios: * `typing_interaction_intensity = w₁ · typing_speed_norm + w₂ · (1 − typing_gap_ratio) + w₃ · typing_cadence_stability` (weights set in the runtime feature deriver). * `clipboard_activity_rate = (copy + paste + cut) / (typing_taps + clipboard_actions)`. * `correction_rate = (backspace + delete) / (typing_taps + backspace + delete)`. ## NotificationSummary | Field | Definition | | - | - | | `notificationCount` | Total notifications received during session. | | `notificationIgnored` | Notifications with `InterruptionAction.ignored`. | | `notificationIgnoreRate` | Defined as `notificationIgnored / notificationCount`. The SDKs currently report `0.0`; compute it from the counts. | | `notificationClusteringIndex` | Variance-based clustering measure over inter-arrival times. The SDKs currently report `0.0`. | | `callCount`, `callIgnored` | Same shape for incoming calls. | ## Numerical stability Flux clamps: * All bounded outputs are wrapped in `.clamp(0.0, 1.0)` (or per-field bounds for raw mileage values like `task_switch_cost_ms` capped at 10000). * Empty input (no events, zero duration, no scrolls, etc.) returns the safe fallback (`0.0` for ratios, `0.5` for burstiness). If a metric ever surfaces outside its declared range, it's a bug in flux — not a value to interpret. ## Related * [Behavior Overview](/synheart-behavior/overview) — full SDK surface. * [Model Card](/synheart-behavior/model-card) — motion state, separate from these metrics. * [Threat Model](/synheart-behavior/threat-model) — what's collected and what's not. # Motion State Model Card Source: https://docs.synheart.ai/synheart-behavior/model-card The bundled Linear SVC motion-state classifier — inputs, classes, runtime, and known limits When `BehaviorConfig.enableMotionLite = true`, the **Kotlin** SDK runs a small classifier on motion features to predict the user's gross motion state. The Flutter and Swift SDKs ship no model: they emit raw accelerometer samples (`emitRawMotionSamples`) for the Synheart runtime to classify. This page is the model card for the Kotlin classifier. ## Identity | Attribute | Value | | - | - | | Family | Linear Support Vector Classifier (One-vs-Rest) | | Format | ONNX | | Asset path | `assets/models/linear_svc_model.onnx` (Kotlin / Android only) | | Runtime | ONNX Runtime for Android (`onnxruntime-android` 1.18.0) | | Class count | 4 | | Latency target | \< 5 ms per inference on a modern mid-range device | | Distribution | Bundled in the SDK; no network calls; no over-the-air updates | ## Classes ```json theme={null} ["LAYING", "MOVING", "SITTING", "STANDING"] ``` These are the only labels the SDK emits today. The class list is loaded from the model's label asset on init; mismatches against the model's output dimension cause init to fail loudly. ## Inputs The classifier consumes a fixed-order feature vector derived from windowed sensor buffers: * 3-axis acceleration in m/s² (gravity included) and 3-axis gyroscope. * Sampling rate: 50 Hz. * Window: 5-second windows the SDK aggregates into derived features. The exact set of derived features (statistical moments, jerk magnitudes, axis correlations, gravity-removed components, etc.) is owned by the SDK's `MotionFeatureExtractor` — refer to source for the authoritative list. ## Outputs ```kotlin theme={null} data class MotionState( val state: List, // per-window labels val majorState: String, // one of the four labels val majorStatePct: Double, // share of windows with the major state val mlModel: String, val confidence: Double, ) ``` `majorStatePct` is the share of windows classified as the major state. `confidence` is the model's score for that state; the underlying SVC produces decision scores rather than probabilities, so treat it as a heuristic, not a calibrated posterior. ## Training context * The model file is shipped as ONNX, exported from `scikit-learn` (Linear SVC with one-vs-rest). * Training data, train/test splits, fairness metrics, and demographic coverage are not documented in the SDK source. Treat the classifier as a fast best-effort component, not a clinical sensor. When you need stronger guarantees, use the runtime's motion classifier: on Flutter or Swift, set `emitRawMotionSamples = true` and forward the samples to the Synheart runtime. ## Runtime considerations | Concern | Behavior | | - | - | | Thread | Inference runs when the session ends, blocking the thread that calls `endSession()` until it finishes. | | Battery | Continuous 50 Hz collection is the primary cost — much higher than the inference itself. Disable when not needed. | | Memory | Model loaded once at `initialize()`; the ORT session is kept for the SDK's lifetime. | | Cold start | First inference includes ORT environment + session init; subsequent inferences are pure compute. | | Failure modes | If the model fails to load (asset missing, ORT init error), the SDK logs and `motionState` is permanently `null` for the session. | ## When the model is and is not loaded | Condition | Loaded? | | - | - | | `BehaviorConfig.enableMotionLite = false` (default) | No — collectors don't run, no inference. | | `enableMotionLite = true` (Kotlin) | Loaded on `initialize()`. | | Flutter or Swift | Never: there is no model. Raw samples come from `emitRawMotionSamples`. | ## Known limits * **No gait variants.** "MOVING" is a single class; the SDK does not distinguish walking, running, cycling, or vehicle motion. * **Posture vs activity.** "SITTING" vs "STANDING" relies on gravity decomposition, which is sensitive to phone orientation. A phone flat on a desk reads differently from one in a pocket. * **No biometric calibration.** The classifier does not adapt per user. * **No location or transport context.** Inputs are motion sensors only; "MOVING" inside a vehicle is detected the same as walking. * **Charging stationary cases.** A phone left charging on a flat surface typically classifies as "LAYING". * **No confidence threshold.** The SDK returns whichever class has the highest score; downstream consumers should apply their own threshold using `majorStatePct` if they want to drop low-confidence predictions. ## Migration path The runtime's `MotionStateHead` is the long-term replacement. Flutter and Swift already rely on it: set `BehaviorConfig.emitRawMotionSamples = true` and read motion state from the runtime's HSI emit. The Kotlin SDK's Linear SVC remains for direct consumers. ## Related * [Behavior Overview](/synheart-behavior/overview) — `enableMotionLite` and `emitRawMotionSamples` config. * [Metric Definitions](/synheart-behavior/metric-definitions) — the other 12 metrics, separate from motion state. # Synheart Behavior Overview Source: https://docs.synheart.ai/synheart-behavior/overview On-device behavioral event collection from digital interactions with privacy-first design ## What is Synheart Behavior? Synheart Behavior is a multi-platform SDK that collects behavioral events from digital interactions (scroll, tap, swipe, typing timing, app switches, notifications, calls) directly on device and streams them to your app. Events are content-free: timing and physical metadata only. The SDKs are **event producers**. They report events and raw per-session counts; focus, distraction and typing scores are computed downstream by the Synheart runtime when behavior is fed through [Synheart Core](/synheart-core/overview). ## Key Features ### On-Device Collection * Events are captured and summarized locally * No network calls * No raw interaction data leaves the device unless your app sends it ### Privacy-First Design * **No PII**: No names, contacts, or user-identifying data * **No content capture**: No text, images, or semantic data * **No keystroke logging**: Typing is captured as timing only, never characters * **Event-level metadata only**: Timing and physical metrics only ### Multi-Platform | Platform | SDK | Installation | Min OS | Version | Status | | - | - | - | - | - | - | | **Flutter** | `synheart_behavior` | `flutter pub add synheart_behavior` | iOS 12+ / Android API 21+ | 0.4.1 | ✅ Ready | | **Kotlin/Android** | `ai.synheart:synheart-behavior` | Gradle: `implementation 'ai.synheart:synheart-behavior:0.6.0'` | Android API 21+ | 0.6.0 | ✅ Ready | | **Swift/iOS** | SynheartBehavior | Swift Package: `.package(url: "https://github.com/synheart-ai/synheart-behavior-swift.git", from: "0.5.0")` | iOS 13.0+ / macOS 10.15+ | 0.5.0 | ✅ Ready | ## Architecture ```text theme={null} User Interactions └─(scroll, tap, swipe, typing, notifications, calls)──► Synheart Behavior SDK [Event Collectors] → BehaviorEvents + raw session counts │ ▼ Your App (or Synheart Core for scoring and HSI fusion) ``` **Components:** * **Event Collectors**: Capture scroll, tap, swipe, app\_switch, notification, call, typing, and clipboard events. * **Session summary**: Raw counts per session (events, app switches, notifications, calls) plus device and system context. * **Motion**: Kotlin runs an on-device motion-state model (LAYING, MOVING, SITTING, STANDING) when `enableMotionLite` is on. Flutter and Swift instead emit raw 50 Hz accelerometer samples (`emitRawMotionSamples`) for the runtime to classify. Use the SDK standalone for raw events, or feed it into [Synheart Core](/synheart-core/overview) to fuse with biosignals into HSI. ## Quick Start ```dart theme={null} import 'package:synheart_behavior/synheart_behavior.dart'; final behavior = await SynheartBehavior.initialize( config: const BehaviorConfig( enableInputSignals: true, enableAttentionSignals: true, ), ); // Wrap app to enable gesture tracking return behavior.wrapWithGestureDetector( MaterialApp(...), ); // Listen to real-time events behavior.onEvent.listen((event) { print('Event: ${event.eventType} at ${event.timestamp}'); }); // Start and end a session final session = await behavior.startSession(); // ... user interacts with app ... final summary = await session.end(); print('Events: ${summary.activitySummary.totalEvents}, ' 'app switches: ${summary.activitySummary.appSwitchCount}'); ``` [Full Flutter SDK Guide →](/synheart-behavior/flutter) ## Use Cases ### Focus and distraction Feed behavior into Synheart Core and read the digital axes of each HSI window. The behavior SDK itself no longer returns focus or distraction scores: `BehaviorSessionSummary.behavioralMetrics` is always `null`. ### Digital wellness analytics Track raw interaction patterns per session: event counts, app switches, notification and call counts, and device context (brightness, orientation, Do Not Disturb, charging). ### Interaction research Subscribe to the event stream and keep the per-event timing metrics (tap duration, scroll velocity, typing cadence) for your own analysis. ## Behavioral metrics Focus, distraction, task-switching and typing metrics are computed by the Synheart runtime from the event stream. See [Metric definitions](/synheart-behavior/metric-definitions) for what each one means. The `BehavioralMetrics` and `TypingSessionSummary` types still exist in the SDKs, but the SDKs leave them `null`. ## Motion state | Platform | What `enableMotionLite` does | Raw samples | | - | - | - | | Kotlin | Collects accelerometer and gyroscope at 50 Hz and runs the on-device model; the result is `summary.motionState` | — | | Flutter | Starts the native motion collector; no on-device classification | `emitRawMotionSamples: true` → `onMotionSample` | | Swift | Nothing yet | `emitRawMotionSamples: true` → `setRawMotionSampleHandler` | ```kotlin theme={null} // Kotlin val summary = session.end() summary.motionState?.let { println("Motion: ${it.majorState} (confidence ${it.confidence})") } ``` ## API Features | Feature | Flutter | Kotlin | Swift | | - | - | - | - | | Real-time event stream | ✅ | ✅ | ✅ | | Session summaries (raw counts) | ✅ | ✅ | ✅ | | Time-range counts (`calculateMetricsForTimeRange`) | ✅ | — | — | | On-device motion state | — | ✅ | — | | Raw motion samples | ✅ | — | ✅ | | Notification events | ✅ | ✅ | ✅ | | Call events | Android only | ✅ | ✅ | | Auto-end after 1 min in background | — | ✅ | — | ## Available SDKs > [card] [Flutter SDK](/synheart-behavior/flutter) > > Cross-platform mobile apps (iOS + Android) > [card] [Kotlin/Android SDK](/synheart-behavior/kotlin) > > Native Android applications > [card] [Swift/iOS SDK](/synheart-behavior/swift) > > Native iOS applications Each repo ships a runnable example in its `example/` directory: [Flutter](https://github.com/synheart-ai/synheart-behavior-flutter/tree/main/example) · [Kotlin](https://github.com/synheart-ai/synheart-behavior-kotlin/tree/main/example) · [Swift](https://github.com/synheart-ai/synheart-behavior-swift/tree/main/Example). ## Stability Synheart Behavior is **pre-1.0**. Minor version bumps may include breaking API changes — pin exact versions in production, and read the CHANGELOG before upgrading. The three language SDKs are versioned independently (Flutter 0.4.x, Kotlin 0.6.x, Swift 0.5.x at time of writing); check each before bumping. ## Privacy & Security * **On-Device Processing**: Events are captured and summarized locally * **No Data Retention**: The SDK keeps no events after a session ends * **No Network Calls**: No data is sent to external servers * **Privacy-First Design**: No built-in storage - you control what gets persisted * **No Content Capture**: No text, images, or semantic data collected * **Event-Level Metadata Only**: Only timing and physical metrics ## Resources * **Dart**: [synheart-behavior-flutter](https://github.com/synheart-ai/synheart-behavior-flutter) · [pub.dev](https://pub.dev/packages/synheart_behavior) * **Kotlin**: [synheart-behavior-kotlin](https://github.com/synheart-ai/synheart-behavior-kotlin) · [Maven Central](https://central.sonatype.com/artifact/ai.synheart/synheart-behavior) * **Swift**: [synheart-behavior-swift](https://github.com/synheart-ai/synheart-behavior-swift) ## Citation If you use this SDK in your research: ```bibtex theme={null} @software{synheart_behavior, title = {Synheart Behavior: Multi-platform SDK for on-device behavioral event collection from digital interactions}, author = {Synheart AI Team}, year = {2025}, version = {0.4.1}, url = {https://github.com/synheart-ai/synheart-behavior-flutter} } ``` # Synheart Behavior — Swift / iOS SDK Source: https://docs.synheart.ai/synheart-behavior/swift On-device behavioral signal capture for iOS applications ## Overview The Synheart Behavior Swift/iOS SDK captures digital interaction events on-device — the eight `BehaviorEventType` cases are `scroll`, `tap`, `swipe`, `appSwitch`, `notification`, `call`, `typing`, and `clipboard` — and streams them to your app. Behavior is content-free — no text, no screen content, no PII. The SDK is an **input layer**: it produces events and raw per-session counts. It does not compute focus, distraction or typing aggregates; that is done downstream by [Synheart Core](/synheart-core/overview) when behavior is fed into it. ## Installation ### Swift Package Manager Add to your `Package.swift` or in Xcode (File → Add Packages...): ```swift theme={null} dependencies: [ .package(url: "https://github.com/synheart-ai/synheart-behavior-swift.git", from: "0.5.0") ] ``` ### Requirements * iOS 13.0+ or macOS 10.15+ * Swift 5.9+ (Xcode 15+) ## Quick Start ```swift theme={null} import SynheartBehavior let config = BehaviorConfig( enableInputSignals: true, enableAttentionSignals: true ) let behavior = SynheartBehavior(config: config) try behavior.initialize() // Real-time events: a callback... behavior.setEventHandler { event in print("Event: \(event.eventType) at \(event.timestamp): \(event.metrics)") } // ...or an AsyncStream Task { for await event in behavior.events { print(event.eventType) } } // Start a session let session = try behavior.startSession() // ... user interacts with app ... let summary = try session.end() // or behavior.endSession(sessionId: session.sessionId) print("Duration: \(summary.duration) ms") print("Total events: \(summary.activitySummary.totalEvents)") print("App switches: \(summary.activitySummary.appSwitchCount)") ``` > [!NOTE] > > `summary.behavioralMetricsStruct`, `summary.typingSessionSummary` and > `summary.motionState` are always `nil`: the SDK reports raw counts and leaves > scoring to Synheart Core. ## Clipboard events The SDK does not observe the system clipboard. Report copy, paste and cut yourself (for example from a `UITextField` subclass that overrides `copy(_:)`, `paste(_:)` and `cut(_:)`): ```swift theme={null} behavior.sendEvent(.clipboard(sessionId: session.sessionId, action: "copy", context: "text_field")) ``` ## Notifications and calls * **Notifications:** forward your `UNUserNotificationCenterDelegate` callbacks to `behavior.notificationDelivered(id:)` and `behavior.notificationOpened(id:)`. Or set `BehaviorConfig(installNotificationDelegate: true)` and the SDK installs itself as the delegate, forwarding every callback to the delegate it replaced. * **Calls:** collected through CallKit when `enableAttentionSignals` is on. * **Permissions:** `checkNotificationPermission()`, `requestNotificationPermission()`, `checkCallPermission()` and `requestCallPermission()` are `async` and return `Bool`. ## Raw motion `enableMotionLite` is accepted but collects nothing on iOS yet. For raw accelerometer data, set `emitRawMotionSamples: true` and register a handler; samples arrive at 50 Hz in 1-second batches: ```swift theme={null} let behavior = SynheartBehavior(config: BehaviorConfig(emitRawMotionSamples: true)) behavior.setRawMotionSampleHandler { batch in // [[String: Any]], one dictionary per sample } ``` ## Event behavior * **Taps and long press**: Not counted when a text field or text view is first responder (keyboard open), so typing is not double-counted as taps. * **Typing events**: carry timing metrics (speed, cadence, gaps, burstiness) and `backspace_count`. No characters are ever captured. ## Errors Calls throw `BehaviorError`: `notInitialized`, `invalidConfiguration` or `sessionNotFound`. ## API summary | Method / property | Description | | - | - | | `initialize()` | Initialize the SDK | | `startSession(sessionId:)` | Start a session; returns a `BehaviorSession` | | `endSession(sessionId:)` | End session and return `BehaviorSessionSummary` | | `setEventHandler(_:)` / `setBatchEventHandler(_:)` | Callbacks for single events or batches | | `events` | `AsyncStream` | | `sendEvent(_:)` | Send an event yourself (for example `.clipboard(...)`) | | `getCurrentSessionId()` | The running session's id | | `getSessionEvents()` | Events for the current session | | `getAppSwitchCount()` | App switches in the current session | | `getCurrentStats()` | Current rolling statistics | | `updateConfig(_:)` | Replace the configuration | | `setRawMotionSampleHandler(_:)` | Raw 50 Hz accelerometer batches | | `notificationDelivered(id:)` / `notificationOpened(id:)` | Report notification events | | `dispose()` | Stop collection and release resources | ## Resources * **Repository**: [synheart-behavior-swift](https://github.com/synheart-ai/synheart-behavior-swift) # Threat Model Source: https://docs.synheart.ai/synheart-behavior/threat-model What the SDK collects, what it deliberately does not, and the platform-permission surface The behavior SDK's privacy posture is the difference between "this thing is invasive" and "this thing is acceptable to ship". This page lists what is collected, what is not, and the permissions involved. ## What is collected | Surface | Captured | Not captured | | - | - | - | | Scroll | direction, velocity, acceleration, jitter | what was scrolled | | Tap | timing, count, pressure (when available) | what was tapped (no view ids, no labels) | | Swipe | direction, timing | content swiped | | Typing | inter-key intervals, burst length, cadence | keystrokes, IME state, text content, language | | App switch | timing of foreground change | app names, package ids (collected internally for session bookkeeping but not emitted in events) | | Notification | timing, `InterruptionAction` (ignored / opened / answered / dismissed); on Android, the posting app's package name (`source_app`) | notification title, body, user response content | | Call | timing, `InterruptionAction` | caller id, contact name, audio | | Clipboard | `ClipboardAction` (copy / paste / cut), `ClipboardContext` (text-field / system) | clipboard contents | | Motion | 50 Hz triaxial accelerometer (m/s²) when `emitRawMotionSamples` (Flutter, Swift) or `enableMotionLite` (Kotlin, which also reads the gyroscope) is enabled | magnetometer / GPS / barometer / camera / mic | ## What is never captured The following classes are not collected by any code path: * Text content (typed, displayed, or in clipboard). * Audio (mic). * Images (camera, screenshots). * Location (GPS, network location, geofencing). * Contacts. * Calendar entries. * Browser history. * Network requests originating from the app (the SDK does not call out to the network at all — see "Outbound traffic" below). ## Outbound traffic The SDK itself makes **no outbound network calls**. There is no HTTP client in the synheart-behavior source. Cloud delivery, when desired, happens through `synheart-core` → the Synheart runtime's ingest connector, which: * Gates on `Behavior` and `cloudUpload` consent. * Hashes `subject_id`; the raw value never leaves the device. * Signs requests with the device's hardware key (see [Synheart Auth](/synheart-auth/overview)). The SDK alone does not transmit any data anywhere. ## Platform permissions | Permission | Required for | Scope | | - | - | - | | Notification listener (Android) | `notification` events with `InterruptionAction` | The SDK uses `NotificationListenerService` which observes notification posts. It records timing + action only; the listener never reads notification text. | | Phone state (Android) | `call` events | Timing and ignored/answered enum only; no caller id stored or emitted. | | Calls (iOS) | `call` events | Observed through CallKit (`CXCallObserver`); timing and outcome only. | | Accelerometer (sensor) | Motion-lite + raw motion samples | Standard sensor access; no special platform prompt on iOS/Android. | | Accessibility service (NOT used) | — | The SDK does **not** request Accessibility on Android. Some apps use Accessibility for keystroke logging; this SDK does not. | | HealthKit (iOS) | (none) | Behavior SDK does not touch HealthKit; that's `synheart-wear`'s domain. | Since Flutter 0.4.1 and Kotlin 0.6.0 the libraries declare these permissions in their own Android manifests, so your app inherits them: * Flutter: `BIND_NOTIFICATION_LISTENER_SERVICE`, `READ_PHONE_STATE` and the notification listener service. * Kotlin: `BIND_NOTIFICATION_LISTENER_SERVICE`, `ACCESS_NETWORK_STATE` and the notification listener service (add `READ_PHONE_STATE` yourself for call events). Remove any you don't use with `tools:node="remove"` in your manifest. `checkNotificationPermission()` / `requestNotificationPermission()` and the call-permission equivalents exist on all three SDKs. On iOS, notification events come from the host forwarding its `UNUserNotificationCenter` delegate callbacks (or the SDK installed as the delegate). ## Adversary model | Adversary | Concern | Mitigation | | - | - | - | | Malicious app on same device | Reading SDK-collected data via shared storage | The SDK does not write events to disk. Aggregates flow only through in-memory streams to the host app. | | Compromised host process | Host can read everything in its address space | Out of scope: the SDK runs *inside* the host. Trust boundary is at the OS, not within the process. | | Network adversary | Intercept telemetry | The SDK makes no network calls. When the host forwards events through the Synheart runtime, transport is TLS + device-signed proof. | | Server-side observer | Reconstruct user identity from behavioral patterns | `subject_id` is hashed; no app names or content reach the cloud. Mitigations are at the cloud-policy layer. | | Curious developer | Use the SDK in ways the user didn't expect | Consent gates at the runtime (`Behavior` consent) and platform OS permission grants. `consentBehavior` in the SDK config is not enforced by the SDK, so the host must not start collection without consent. | ## Implementation invariants The SDK holds to these invariants: 1. **No string captured from input fields.** `BehaviorEventType.typing` events carry only timing fields in their `metrics` map. 2. **No clipboard contents.** `ClipboardAction` and `ClipboardContext` enums encode the action/location, not the payload. 3. **No notification body or title.** `InterruptionAction` enum is the only notification-derived field on events. 4. **No outbound HTTP from the SDK.** No HTTP clients imported in any of the four SDK packages. 5. **No background data persistence by the SDK.** Events flow through streams; aggregates are computed in-memory and surface as `BehaviorSessionSummary`. Hosts decide whether to persist. If any of these change, this page is a release blocker until the threat model is updated. ## Consent gating layers ```text theme={null} Host app: starts the SDK only after consent (BehaviorConfig.consentBehavior is recorded, not enforced) ↓ Core SDK gate: ConsentModule.has_consent(behavior) ↓ Runtime gate: ConsentType::Behavior (Synheart runtime) ↓ Cloud gate: ConsentType::CloudUpload (separate) ``` All four gates must allow for behavioral data to leave the device. Any one closes the loop. ## Logging policy The SDK logs at `info` / `warn` levels in production. Logs include: * Session lifecycle (`session_start`, `session_end`, durations). * Permission state changes. * Inference latency (motion-lite). The SDK does **not** log: * Event-level payloads (no event-by-event logs). * User identifiers (raw `userId` / `deviceId` are never written to logs unless the host injects them). * Motion sample bytes. * Inference inputs. ## Related * [Behavior Overview](/synheart-behavior/overview) — config flags including the `consentBehavior` flag. * [Consent System](/synheart-core/consent-system) — runtime gate enforcement. * [Synheart Auth](/synheart-auth/overview) — request signing for cloud-bound traffic. # Synheart Core Architecture Source: https://docs.synheart.ai/synheart-core/architecture Deep dive into the Core SDK module system and HSI Runtime ## System Overview Synheart Core SDK is a modular, on-device human state intelligence system that collects multi-modal signals and fuses them into a unified state representation via the Synheart runtime (native). ```mermaid theme={null} flowchart TB subgraph SDK["Synheart Core SDK (your app process)"] W["Wear module
HR / HRV / sleep / motion"] P["Phone module
motion / screen / app context"] B["Behavior module
tap / scroll / typing / app switch"] end subgraph RT["Synheart Runtime (native, on-device)"] FP[Feature pipeline
60s window, 5s step] IE[Inference engine
6 heads + MotionState] FX[Flux
HSV[] → HSI 1.3 JSON] FP --> IE --> FX end APP[Your app
onHSIUpdate / onStateUpdate] CC[Cloud connector
consent + capability gated] CLOUD[(Synheart Cloud
api.synheart.ai)] W --> FP P --> FP B --> FP FX --> APP FX --> CC CC -.consent-gated.-> CLOUD ``` The same pipeline runs whether you've enabled one module or all three. Modules feed raw samples across the native bridge into the runtime's feature pipeline; the SDK side only sees the HSI envelope (and a typed projection of it) coming back. ## Module System ### Signal Collection Modules > [!NOTE] > > The module outputs below are illustrative shapes, not a wire format. Each module only emits what a real platform source provides: since Flutter 0.17 and Kotlin 0.4, a module with no platform source emits nothing rather than placeholder values. #### 1. Wear Module Collects biosignals from wearable devices. **Data Sources:** * Heart rate (HR) * Heart rate variability (HRV) * Sleep stages * Motion/activity * Skin temperature (if available) **Output:** * Derived signals only (no raw biosignals) * 30s, 5m, 1h, 24h aggregations * Quality metrics and confidence scores **Platform Support:** * iOS: HealthKit * Android: Health Connect * Multi-device: Apple Watch, Fitbit, WHOOP, Garmin, Samsung ```jsonc theme={null} // Example: Wear module output (illustrative) { "hr_mean": 72, "hr_std": 8, "hrv_rmssd": 45, "hrv_sdnn": 62, "quality_score": 0.95, "window": "30s" } ``` #### 2. Phone Module Collects device-level signals. **Data Sources:** * Motion (accelerometer, gyroscope) * Screen state (on/off, brightness) * App context (coarse categories) * Location context (stay/move, no coordinates) **Privacy:** * No fine-grained location * No app names (only categories: social, productivity, etc.) * No notification content ```jsonc theme={null} // Example: Phone module output (illustrative) { "motion_state": "stationary", "screen_on": true, "screen_brightness": 0.8, "app_category": "productivity", "context": "work" } ``` #### 3. Behavior Module Captures interaction patterns. **Data Sources:** * Tap frequency and pressure * Scroll speed and direction * Typing cadence * App switching frequency * Screen unlock patterns **Privacy:** * No content (what you type/read) * Only patterns (how you interact) ```jsonc theme={null} // Example: Behavior module output (illustrative) { "tap_frequency": 12.5, "scroll_velocity_mean": 0.4, "typing_cadence": 3.2, "app_switches_per_min": 2.1, "interaction_stability": 0.82 } ``` ### HSI Runtime (Synheart Runtime) The Synheart Runtime is the native binary you install with `synheart install runtime` and the only thing the SDKs link against. It owns: * Storage, crypto, sync, consent, capability gating, cloud connector, lab mode, sensor adapters, native binding surface. * The sample-ingest seam (`push_rr`, `push_hr`, `push_accel`, `push_behavior`). The full pipeline: ```text theme={null} feature pipeline ──► FeatureSet (60s window, 5s step) inference engine ──► HSV[] + 64D embedding (six cognitive/physio heads + MotionState) flux ──► HSI 1.3 JSON (canonical wire format) ``` The SDK pushes raw signals across the native bridge and receives HSI JSON on `tick()`. HSV is the typed in-runtime intermediate — see [HSV Specification](/synheart-core/hsv-specification) for the canonical structure. Flux is what packs HSV into HSI for the wire. **Core Functions:** 1. **Signal Ingestion**: `push_rr()`, `push_hr()`, `push_accel()`, `push_behavior()` accept raw samples and feed the Synheart Runtime's FeatureSet builder. 2. **HSV Inference**: the inference engine runs six canonical heads (Emotion, Focus, Capacity, Sleep, Recovery, Strain) plus MotionState. Each emits an `Hsv` with quality-adjusted, tier-capped confidence based on physiological signal fidelity. 3. **Time Windows**: 60s sliding window, 5s emit step (configurable). 4. **64D Embedding**: the Synheart Runtime computes a deterministic, L2-normalized, non-invertible Johnson-Lindenstrauss projection over the HSV bundle (`synheart-jl-64`, 64 dims, `float32`). Privacy-preserving: the original HSVs cannot be reconstructed from the embedding. 5. **HSI Packing**: `flux` builds the HSI 1.3 envelope from `InferenceOutput`, propagating axis readings, source provenance, tier bundles, and the embedding (when capability level + HSI version permit). **Output:** ```dart theme={null} { "affect": { "arousal_index": 0.72, // 0.0-1.0 "valence_index": 0.15, // -1.0 to 1.0 "intensity": 0.68 // 0.0-1.0 }, "engagement": { "engagement_stability": 0.81, "cognitive_load": 0.65, "attention_level": 0.73 }, // Optional embedding fields (presence and dimension depend on capability level + HSI version) "window": { "duration": "30s", "start": "2026-01-15T10:30:00Z", "end": "2026-01-15T10:30:30Z" }, "timestamp": "2026-01-15T10:30:30Z" } ``` **Update Frequency:** * 30s window: Updated every 30 seconds * 5m window: Updated every minute * 1h window: Updated every 5 minutes * 24h window: Updated every 15 minutes **Performance:** The runtime is designed for low overhead — sub-100ms HSI emission and a single-digit-percent CPU budget on a typical mid-range device. These are design targets, not measurements. Profile your app and read `Synheart.runtimeDiagnostics()` for live counters. ### Inference heads The engine emits typed HSV (Human State Vector) heads — there are no separate "Focus Module" or "Emotion Module" SDK products. Each head is one entry inside the HSI envelope's axis readings. The canonical head set lives in `synheart-engine`. See [HSV Specification](/synheart-core/hsv-specification) for the head taxonomy and value ranges. The SDK exposes the engine output two ways: * `Synheart.onHSIUpdate` — raw HSI 1.3 JSON envelope (authoritative). * `Synheart.onStateUpdate` — typed `HSIState` projection of the same JSON. See the per-platform pages for the typed shape. ### Cloud Connector Securely uploads HSI snapshots to Synheart Platform with user consent. The connector lives inside the runtime — the SDK feeds the runtime, which owns the queue and signing. **Features:** * Consent-gated uploads (via `cloudUpload` consent + per-request JWT). * Persistent SQLite queue (offline-resilient). * Automatic retry with backoff. * Hardware-backed request signing (`X-Synheart-Proof`). * Tenant-isolated routing by `org_id`. **Wire payload:** the engine's HSI 1.3 JSON envelope, with the runtime adding `X-Consent-Token` and `X-Synheart-Proof` headers. See [Cloud Protocol](/synheart-core/cloud-protocol) for the full spec. **Privacy:** * No raw signals (only HSI snapshots). * No personally identifiable information (`subject_id` is hashed before upload). * User can revoke at any time; the connector pauses on the next flush. ### Consent Module Manages permissions and data masking. **Responsibilities:** 1. Permission requests 2. Consent tracking 3. Data masking based on consent 4. Runtime enforcement **Consent Levels:** | Module | Permission | Data Access | | - | - | - | | Wear | Health data | Derived biosignals | | Phone | Motion & sensors | Coarse context only | | Behavior | Accessibility (optional) | Interaction patterns only | | Cloud | Network upload | HSI snapshots only | **Example:** ```dart theme={null} // Request consent — opens the cloud consent flow if a service is configured. final token = await Synheart.requestConsent(); // Runtime consent status map (e.g. {"status": "granted" | "pending" | "expired" | ...}) final status = Synheart.consentStatus(); // Fine-grained per-type check final canUpload = await Synheart.hasConsent('cloudUpload'); // Revoke a specific consent type or everything await Synheart.revokeConsentType('cloudUpload'); await Synheart.revokeConsent(); ``` See [Consent System](/synheart-core/consent-system) for the seven consent types, granular channels, and JWT flow. ## Capability System Different apps get different levels of access based on app signature and tenant ID. ### Capability Levels | Level | Access | Who Gets It | | - | - | - | | **None** | No access | Default before a token loads | | **Core** | Basic HSI fields, derived signals | Third-party apps | | **Extended** | Full HSI fields, higher frequency | Enterprise customers and approved partners | | **Research** | Raw streams, full fusion vectors | Authorized research apps | ### Capability Matrix | Module | Core | Extended | Research | | - | - | - | - | | **Wear** | Derived biosignals | Higher-frequency windows | Raw HR/HRV streams | | **Phone** | Motion, screen state | Advanced app context | Full context | | **Behavior** | Basic metrics (aggregated) | Extended metrics | Event-level timing streams | | **HSI Runtime** | Basic state | Full embedding fields in HSI envelope | Full fusion vectors + intermediate states | | **Cloud** | Ingest endpoint (HSI 1.3) | Extended endpoint payloads | Research endpoints | ### Enforcement Capability checks happen at: 1. **SDK Initialization**: Validates app signature and tenant ID 2. **Module Enable**: Checks capability for requested module 3. **Data Access**: Masks/filters data based on capability 4. **Cloud Upload**: Routes to appropriate endpoint ```dart theme={null} // Production: the server determines this app's capability tier from // its registered, hardware-backed device identity. await Synheart.initialize( config: SynheartConfig( appId: 'com.example.app', subjectId: userId, deviceAuthConfig: const DeviceAuthConfig( authBaseUrl: 'https://api.synheart.ai', packageName: 'com.example.app', ), ), ); Synheart.activate(SynheartFeature.wear); final operational = Synheart.isFeatureOperational(SynheartFeature.wear); ``` ## Data Flow ### 1. Signal Collection ```text theme={null} Wearable Device → Wear Module → Derived Signals Phone Sensors → Phone Module → Coarse Context User Interactions → Behavior Module → Patterns ``` ### 2. HSV inference and HSI packing (Synheart Runtime) ```text theme={null} Derived Signals + Coarse Context + Patterns │ ▼ feature pipeline → FeatureSet (60s window, 5s step, signal tiers) │ ▼ inference engine → HSV[] (6 heads + MotionState) + 64D embedding │ ▼ flux → HSI 1.3 JSON envelope ``` ### 3. Output ```text theme={null} HSI 1.3 JSON → onHSIUpdate HSI 1.3 JSON → HSIState typed projection → onStateUpdate HSI Snapshots → Cloud Connector (signed + consent-gated) → Synheart Platform ``` ## Thread Model The SDK uses a multi-threaded architecture for performance: ```text theme={null} Main Thread │ ├─ UI Updates (callbacks) │ Worker Threads │ ├─ Signal Collection Thread │ └─ Wear, Phone, Behavior modules │ ├─ HSI Processing Thread │ └─ Fusion, state calculation │ ├─ Interpretation Thread │ └─ Focus, Emotion modules │ └─ Cloud Upload Thread └─ Batching, encryption, upload ``` **Thread Safety:** * All callbacks delivered on main thread * Internal state protected by locks * Async operations use platform-native concurrency (Coroutines, Combine, async/await) ## Storage ### Local Storage The runtime owns local persistence (SQLite via `synheart-storage`): * **Sessions and HSI windows**: bounded by retention (default platform-specific). * **Vendor events**: backlog from `synheart-wear` adapters. * **Consent snapshot + token**: per `subject_id`. * **Upload queue**: persistent SQLite at `/ingest_upload_queue_.sqlite`. * **SRM snapshot**: longitudinal state restored from `srm_.json` and platform secure storage. Encryption-at-rest is on by default. Hosts on mobile typically wire native secure storage (Keychain / EncryptedSharedPreferences) into the runtime via `synheart_core_set_storage_callbacks`. ### Cloud Storage * Requires explicit `cloudUpload` consent + valid JWT. * Only HSI snapshots leave the device (lab session JSON when explicitly enabled). * Transit: TLS (modern cipher suites only, no fallback to legacy versions). * Hardware-backed `X-Synheart-Proof` per request — see [Synheart Auth — Signing](/synheart-auth/signing). ## Performance The runtime is designed for low-overhead background operation. The exact CPU / memory / battery footprint depends on: * Sample rate (BLE HRM at 1 Hz is much cheaper than 50 Hz raw motion). * Active modules (motion-state inference is the heaviest single load when enabled). * Cloud upload cadence (offline operation costs almost nothing). For live counters in your build, read `Synheart.runtimeDiagnostics()`. Profile your app on the device classes you ship to — overall footprint will vary with the choices above. ## Security ### Data Protection 1. **Encryption** * Local storage: AES-256 * Network: TLS 1.3 * Key storage: Platform keychain 2. **Access Control** * Capability-based access * App signature validation * Tenant ID verification 3. **Privacy** * No raw content * No personal identifiers * Consent-gated access ### Threat Model **Protected Against:** * Unauthorized data access * Man-in-the-middle attacks * Local storage compromise * Malicious apps accessing data **Not Protected Against:** * Device compromise (jailbreak/root) * Physical device access * Platform-level vulnerabilities ## Platform-Specific Notes ### iOS * Uses HealthKit for biosignals * CoreMotion for motion sensors * Combine for reactive streams * Background delivery supported ### Android * Uses Health Connect for biosignals * SensorManager for motion sensors * Kotlin Coroutines and Flow * WorkManager for background tasks ### Flutter/Dart * Platform channels for native access * Streams for reactive updates * Async/await for operations * Cross-platform consistency ## Related Documentation * [HSV Specification](/synheart-core/hsv-specification) - the canonical inference output (`Hsv` struct, six heads, 64D embedding) * [Capability System](/synheart-core/capability-system) - Access level details * [Consent System](/synheart-core/consent-system) - Permission model * [Cloud Protocol](/synheart-core/cloud-protocol) - Upload protocol specification # Baselines facade Source: https://docs.synheart.ai/synheart-core/baselines Typed observable snapshot of the user's wearable-baseline state — latest scores + reference view + recent-scores ring. ## Overview `Baselines` is the **host-facing read facade** for wearable baselines. Apps subscribe to a reactive snapshot stream and get a fully-typed view of the user's most recent sleep / recovery / readiness scores plus the current [`WearableReferenceView`](/synheart-core/srm#wearablereferenceview); no JSON parsing, no FFI. It does NOT compute scores or own ingest pipelines — it caches whatever the host SDK feeds in. The full Flutter `Baselines.ingestVendorSleep` orchestration (Whoop / Garmin / Apple Health / Health Connect → score → snapshot) lives only on the Flutter SDK at this time. On Kotlin / Swift, hosts wire vendor ingest themselves and call the `cache*` setters. ## Surface Process-wide singleton (`Baselines.shared`) with: | Surface | Description | | - | - | | `updates` | Observable stream of `BaselinesSnapshot` — emits after every `cache*` call. Replays the current snapshot to late subscribers. | | `latestSleepScore` / `latestRecoveryScore` / `latestReadinessScore` | Sync getters for the most recent score in each pipeline. | | `reference` | The most recent `WearableReferenceView` from the SRM (see [Self-Reference Model](/synheart-core/srm)). | | `lastSource` | Provider id of whoever produced the latest sleep score (`whoop`, `garmin`, `apple_health`, `health_connect`, `self_report`, ...). | | `cacheSleepScore(result, source)` | Push a new sleep score, roll into the recent-scores ring (cap 7), emit. | | `cacheRecoveryScore(result)` | Push a new recovery score, emit. | | `cacheReadinessScore(result)` | Push a new readiness score, emit. | | `cacheReference(view)` | Push a new wearable reference, emit. | | `reset()` | Forget everything (logout / user switch). | | `current()` | Synchronous snapshot read. | ## BaselinesSnapshot ```text theme={null} reference: WearableReferenceView? latestSleepScore: SleepScoreResult? latestRecoveryScore: RecoveryScoreResult? latestReadinessScore: ReadinessScoreResult? recentSleepScores: [Int] // recent-scores ring; oldest → newest; cap 7 capturedAtMs: Int64 ``` Derived properties (computed without storage): * `isEmpty` — nothing has been ingested and the engine hasn't produced a reference yet * `isReady` — true when the reference reports `READY` status, i.e. all five primary SRM dimensions are mature enough for personalized scoring (see [SRM maturity states](/synheart-core/srm#maturity-states)). * `priorNightCount` — what the scorer saw (nil if no score) * `nightsLoggedCount` — items in the recent-scores ring (capped at 7) * `recentMedian` — median of the ring when populated; falls back to `reference.recentSleepScoreMedian` ## Kotlin ```kotlin theme={null} import ai.synheart.core.modules.baselines.Baselines import ai.synheart.core.modules.baselines.BaselinesSnapshot // Subscribe (Flow) viewModelScope.launch { Baselines.shared.updates.collect { snap -> snap.latestSleepScore?.let { render(it.score) } snap.latestRecoveryScore?.let { render(it.score) } snap.latestReadinessScore?.let { render(it.score) } } } // Push (from your vendor-ingest code) Baselines.shared.cacheSleepScore(result = sleepScore, source = "whoop") Baselines.shared.cacheReference(reference = wearableRefView) ``` ## Swift ```swift theme={null} import SynheartCore var cancellables = Set() // Subscribe (Combine — CurrentValueSubject, late subs get current snapshot) Baselines.shared.updates .sink { snap in if let s = snap.latestSleepScore { render(s.score) } if let r = snap.latestRecoveryScore { render(r.score) } if let rd = snap.latestReadinessScore { render(rd.score) } } .store(in: &cancellables) // Push Baselines.shared.cacheSleepScore(sleepScore, source: "whoop") Baselines.shared.cacheReference(wearableRefView) ``` ## Recent-scores ring semantics `cacheSleepScore` pushes the score (if non-nil) onto a FIFO ring capped at 7. This is the "nights logged" surface for the user — it reflects cumulative ingests in the current session, not what the scorer saw (`priorNightCount` gives you that). The median of the ring is available after the 3rd attach, regardless of HSI window state. ## Cross-language parity The shape is identical across Flutter / Kotlin / Swift. The stream type differs by platform idiom (Dart `Stream`, Kotlin `Flow`, Swift `AnyPublisher`) but the snapshot content is byte-equivalent. * Flutter: `lib/src/modules/baselines/baselines_snapshot.dart` + (full ingest) `baselines.dart` * Kotlin: `synheart-core/src/main/kotlin/ai/synheart/core/modules/baselines/{Baselines,BaselinesSnapshot}.kt` * Swift: `SynheartCore/Modules/Baselines/{Baselines,BaselinesSnapshot}.swift` ## Related * [Self-Reference Model (SRM)](/synheart-core/srm) — the personal baselines behind `reference`: daily metrics, maturity states, and how they are kept * [Scoring models](/synheart-core/scoring) — produces the inputs to `cacheSleepScore` / `cacheRecoveryScore` / `cacheReadinessScore` * [Health Connect / HealthKit backfill](/synheart-core/health-backfill) — populates the SRM that backs `reference` # Breathing module Source: https://docs.synheart.ai/synheart-core/breathing 4-pillar breathing-compliance detector — configure target rate, evaluate over the current RR window, render coaching. ## Overview The Breathing module wraps the runtime's breathing-compliance detector. Every R-R interval pushed via `CoreRuntimeBridge.pushRr` (raw beat data from BLE chest straps and equivalent sources) automatically feeds the detector — this module only configures the target rate / population / window and reads back the verdict. A "compliance" verdict has four pillars (peak frequency match, coherence, RSA amplitude, relative power) and a confidence score in \[0, 1]. The detector returns one of three verdicts: * **Compliant** — user is meeting the target; metrics included * **NotCompliant** — user is breathing but off-target; reason explains why (frequency, depth, regularity, no breathing signature) — feed into coaching copy * **Insufficient** — not enough raw R-R data yet; reason explains what's missing ## Configuration ```kotlin theme={null} // Kotlin val breathing = BreathingModule(bridge = coreRuntime) breathing.setTargetBpm(6.0) // resonance breathing breathing.setWindowSecs(60) // 30–120s clamp breathing.setPopulation(BreathingPopulation.BEGINNER) // / EXPERIENCED / CLINICAL breathing.reset() // call before a new exercise ``` ```swift theme={null} // Swift let breathing = BreathingModule(bridge: coreRuntime) breathing.setTargetBpm(6.0) breathing.setWindowSecs(60) breathing.setPopulation(.beginner) // / .experienced / .clinical breathing.reset() ``` ## Evaluate Call once per UI frame (or at whatever cadence you render coaching): ```kotlin theme={null} // Kotlin when (val v = breathing.evaluate()) { is BreathingComplianceResult.Compliant -> showCompliant(v.metrics) is BreathingComplianceResult.NotCompliant -> showCoaching(BreathingGuidanceCopy.copyFor(v.reason)) is BreathingComplianceResult.Insufficient -> showWarming(v.reason) } ``` ```swift theme={null} // Swift switch breathing.evaluate() { case let .compliant(metrics): showCompliant(metrics) case let .notCompliant(_, reason): showCoaching(BreathingGuidanceCopy.copyFor(reason)) case let .insufficient(reason): showWarming(reason) } ``` ## Metrics `BreathingMetrics` (present on Compliant / NotCompliant, nil on Insufficient): | Field | Range | Meaning | | - | - | - | | `peakHz` / `peakBpm` | Hz / BPM | Detected breathing peak frequency (`peakBpm = peakHz * 60`) | | `coherence` | 0..1 | Peak power / total power in the 0.04–0.26 Hz band | | `rsaBpm` | BPM | Mean per-cycle `HR_max − HR_min` — depth of breath | | `relativePower` | 0..1 | Peak power as a fraction of total breathing-band power | | `criteriaMet` | 0..4 | Number of pillars passed | | `confidence` | 0..1 | Mean of normalized pillar scores | ## NonComplianceReason Structured reason types — render coaching copy from these instead of free-text from the engine: | Reason | When fired | | - | - | | `WrongFrequency(detectedBpm, targetBpm)` | Cycle frequency missed the target band | | `ShallowBreathing(rsaBpm)` | Rhythm is right, RSA too low — breaths aren't deep enough | | `IrregularPattern(coherence)` | Coherence below threshold — uneven cadence | | `NoBreathingSignature` | Detector can't find a respiratory rhythm in the RR signal | `BreathingGuidanceCopy.localize` is a swappable function for the default English coaching strings — override globally to ship in a different language or tone. ## InsufficientReason | Reason | When fired | | - | - | | `NotEnoughBeats(have, need)` | Fewer than `need` (default 50) R-R samples buffered | | `WindowTooShort(haveSecs, needSecs)` | Window hasn't reached the configured length yet | | `VendorOnlyTier(device)` | Source provides only summary metrics (no raw R-R intervals) — the detector needs raw beat data | | `ExcessiveArtifacts(rejectedPct)` | Too many RR samples failed artifact filtering (motion, missed beats) | ## Population profile Adjusts the per-pillar thresholds: | Profile | Use | | - | - | | `Beginner` (default) | First-time users; permissive thresholds, gives wins early | | `Experienced` | Returning users with technique; tighter coherence + RSA cutoffs | | `Clinical` | Research / clinical settings; strictest thresholds | ## Cross-language parity Identical wire format across Flutter / Kotlin / Swift: * Flutter: `lib/src/modules/breathing/{breathing_module,breathing_compliance_result,breathing_guidance_copy}.dart` * Kotlin: `synheart-core/src/main/kotlin/ai/synheart/core/modules/breathing/{BreathingModule,BreathingComplianceResult,BreathingGuidanceCopy}.kt` * Swift: `SynheartCore/Modules/Breathing/{BreathingModule,BreathingComplianceResult,BreathingGuidanceCopy}.swift` ## Related * [Synheart Core overview](/synheart-core/overview) * [Baselines](/synheart-core/baselines) — the same RR stream feeds longitudinal baselines # Capability System Source: https://docs.synheart.ai/synheart-core/capability-system Access control enforcement for Synheart Core features based on app identity and authorization level The **Capability System** enforces access control for Synheart Core features based on app identity and authorization level. ## Core Principle > **Capabilities define what apps CAN access.** > > **Consent defines what users ALLOW.** > > **Data access requires BOTH.** ```text theme={null} Data Access = Capability (app-level) AND Consent (user-level) ``` *** ## Capability Tiers Synheart Core defines three capability tiers: ### 1. Core (External Apps) **Available To:** * Third-party applications * External developers * Public SDK users **What It Provides:** * Basic HSI axes and indices * Standard time windows (30s, 5m, 1h, 24h) * Limited embedding access (normalized only) * Standard cloud ingestion * Basic interpretation modules (if enabled) **Scope:** * Derived biosignals only (no raw signals) * Standard frequency windows (no high-frequency streams) * Derived metrics only (no fusion internals) * Standard endpoints (no research-specific APIs) *** ### 2. Extended **Available To:** * Enterprise customers and approved partners on a signed agreement (case-by-case) **What It Provides:** * Full HSI axes and indices * Full 64D state embeddings * Higher-frequency updates * Advanced app context * Extended behavior metrics * Extended cloud endpoints * Advanced interpretation modules **Scope:** * Derived biosignals only (no raw signal streams) * Derived metrics (no internal fusion vectors) * Extended endpoints (no research-specific APIs) *** ### 3. Research **Available To:** * Research partners with a signed agreement (case-by-case) **What It Provides:** * Full HSI access * Raw signal streams (with consent) * Internal fusion vectors * Event-level behavior data * Full app context (unhashed) * Research cloud endpoints * Unrestricted time windows **Privacy & Consent:** * All access requires explicit user consent * All access respects privacy boundaries and data protection policies *** ## Module-Level Capabilities Each module has tier-specific access levels: ### Wear Module | **Tier** | **Signals** | **Frequency** | **Format** | | - | - | - | - | | Core | HR, HRV, sleep stages | 1-minute windows | Aggregates only | | Extended | HR, HRV, sleep, motion | 30-second windows | Full derived signals | | Research | Full biosignals | Real-time streams | Raw + derived | **Example:** ```dart theme={null} // Core tier WearData { heartRate: 72, // 1-min average hrv: 45, // 1-min RMSSD sleepStage: 'light' } // Extended tier WearData { heartRate: 72, // 30s average heartRateVariability: 45, // 30s RMSSD heartRateTimeSeries: [...], // 30s series motion: {...} // Full motion data } // Research tier WearData { heartRate: 72, rrIntervals: [...], // Full RR series ppgWaveform: [...], // Raw PPG (if available) motion: {...} } ``` *** ### Phone Module | **Tier** | **Context** | **Granularity** | **Privacy** | | - | - | - | - | | Core | Screen state, basic motion | Coarse | Hashed app IDs | | Extended | Screen, motion, app categories | Medium | App categories | | Research | Full context, app names | Fine | Full context | **Example:** ```dart theme={null} // Core tier PhoneContext { screenActive: true, motionState: 'stationary', appCategory: 'hash_abc123' // Hashed } // Extended tier PhoneContext { screenActive: true, motionState: 'stationary', appCategory: 'productivity', // Category notificationCount: 3 // Metadata only } // Research tier PhoneContext { screenActive: true, motionState: 'stationary', appIdentifier: 'com.example.app', // Full identifier notificationMetadata: [...] } ``` *** ### Behavior Module | **Tier** | **Metrics** | **Resolution** | **Data** | | - | - | - | - | | Core | Basic patterns | Aggregates | Counts only | | Extended | Extended patterns | Windowed | Timing patterns | | Research | Full event stream | Event-level | All interactions | **Example:** ```dart theme={null} // Core tier BehaviorMetrics { tapCount: 42, scrollCount: 15, typingCadence: 'medium' } // Extended tier BehaviorMetrics { tapCount: 42, tapTimings: [...], // Timing patterns scrollVelocity: [...], // Velocity series typingRhythm: {...} // Detailed rhythm } // Research tier BehaviorEvents { events: [ {type: 'tap', timestamp: 1704067200, position: {x: 100, y: 200}}, {type: 'scroll', timestamp: 1704067201, delta: 50}, ... ] } ``` *** ### HSI Runtime Tier gating controls **exposure** of HSI fields, not internal pipeline structure. The on-device pipeline runs the same modules at every tier; capability tier is a server-and-SDK contract about which fields the upload payload (and the SDK's typed projections) may include. | **Tier** | **Axes** | **Embedding** | **Per-modality tier bundle** | | - | - | - | - | | Core | Subset of axes (`arousal_index`, `engagement_stability`, etc.) | Suppressed | `core` per modality | | Extended | Full axis set | 64D Johnson-Lindenstrauss vector exposed | `extended` per modality | | Research | Full axis set + research-only fields | 64D vector + signed provenance | `research` per modality | Internally the Synheart Runtime emits one unified state vector and one 64D embedding regardless of tier — tiers do not introduce new vector kinds, they only control which fields the SDK and upload payload expose. See [HSI specification](/synheart-core/hsi-specification). *** ### Cloud Connector | **Tier** | **Endpoint** | **Notes** | | - | - | - | | Core | `/ingest/v1/hsi` | Standard rate / batch size | | Extended | `/ingest/v1/hsi` | Higher rate / batch size | | Research | `/ingest/v1/hsi` + `/ingest/v1/lab/session` | Lab session export gated by `research` consent. See [Cloud Protocol](/synheart-core/cloud-protocol). | All tiers POST to the same `/ingest/v1/hsi` endpoint; tier differentiation happens server-side based on the capability token, not by URL. > [!NOTE] > > The runtime owns this routing and is the only source of truth for it. Paths are > built by `ingest_http_path()`, which prefixes `/ingest` onto the signing path — > a path written anywhere else is a copy that can drift. See > [Cloud Protocol](/synheart-core/cloud-protocol#endpoint). *** ## Capability Enforcement ### 1. Capability Tokens Apps receive a **capability token** from the Synheart Platform during registration. **Token Structure (CapabilityToken):** ```json theme={null} { "org_id": "org_xyz", "project_id": "proj_abc", "environment": "production", "capabilities": { "wear": "core", "phone": "core", "behavior": "core", "hsi": "core", "cloud": "core" }, "issued_at_ms": 1704067200000, "expires_at_ms": 1704153600000, "signature": "..." } ``` The runtime exposes this struct as `CapabilityToken`; `capabilities` is a `HashMap` keyed by `ModuleId` (`Wear`, `Phone`, `Behavior`, `Hsi`, `Cloud`) with values `"none"`, `"core"`, `"extended"`, or `"research"`. **Token Verification:** * SDK validates token signature on initialization * SDK caches capabilities locally * SDK checks capabilities before each module operation * Expired tokens require re-authentication *** ### 2. Runtime Enforcement Each module checks the capability tier before returning data. The sketch below is **illustrative pseudo-code** for the gating shape — the actual API is `Synheart.activate(...)` plus the runtime's internal capability checks; there is no public `WearModule.getBiosignals(tier)` surface to call from app code. ```dart theme={null} // pseudo — illustrative only; not a real public API. class WearModule { Future getBiosignals() async { final capabilities = await CapabilityManager.getCapabilities(); switch (capabilities.wear) { case 'core': return getCoreWearData(); // aggregated only case 'extended': return getExtendedWearData(); // higher cadence case 'research': return getResearchWearData(); // research-only fields default: throw UnauthorizedError('Invalid wear capability'); } } } ``` **Enforcement Points:** * Module initialization * Data collection * HSI computation * Cloud upload * API responses *** ### 3. Server-Side Validation Synheart Platform validates capabilities for cloud operations: Server-side validation flow: 1. Read `X-Consent-Token` and `X-Synheart-Proof` from the request. 2. Verify the `X-Synheart-Proof` signature using the device's registered ECDSA public key (hardware-backed via Secure Enclave / Android Keystore — see [Cloud Protocol](/synheart-core/cloud-protocol)). 3. Decode the consent token; verify capability tier and module-level grants. 4. Reject with `403` if the requested operation exceeds the tier or if a required consent type is missing for the payload. Synheart does **not** use HMAC for SDK→cloud signing; all uploads are device-signed. *** ## Capability Upgrades ### Developer Applications External developers start with **Core** capabilities. To request **Extended** capabilities: 1. Apply via Synheart Platform console 2. Provide use case justification 3. Undergo security review 4. Sign extended data usage agreement **Criteria for Extended Access:** * Established developer account * Clear product use case * Privacy & security review * User benefit justification **Not Available:** * Research tier not available to external developers * Raw biosignals not available outside Synheart *** ## Capability-Consent Interaction Capabilities and consent work together: ### Example Scenarios **Scenario 1: External App, Full Consent** * App capability: Core * User consent: All modules granted * Result: App gets Core-level HSI (basic axes) **Scenario 2: Internal App, Full Consent** * App capability: Extended * User consent: All modules granted * Result: App gets Extended-level HSI (full embeddings) **Scenario 3: External App, Partial Consent** * App capability: Core * User consent: Biosignals denied, behavior granted * Result: App gets Core HSI with `affect` axes = `null` **Scenario 4: Research App, No Consent** * App capability: Research * User consent: All modules denied * Result: No data (consent required regardless of capability) *** ## Capability Auditing ### SDK Logging SDK logs capability checks: ```dart theme={null} logger.info('Capability check', { 'module': 'wear', 'requested': 'extended', 'granted': 'core', 'result': 'downgraded' }); ``` ### Platform Analytics Synheart Platform tracks capability usage: * Endpoint access patterns * Capability tier distribution * Upgrade requests * Violations and errors *** ## Security Considerations ### Tampering Prevention **SDK Protection:** * Capability tokens signed by Synheart Platform * Code obfuscation (release builds) * Runtime integrity checks * Certificate pinning **Attack Mitigation:** * Token replay: Prevented by expiry * Token forgery: Prevented by signature verification * Module bypass: Prevented by enforcement at multiple layers * Man-in-the-middle: Prevented by TLS + cert pinning ### Violation Handling If capability violation detected: 1. SDK logs error 2. Operation denied 3. Error reported to Synheart Platform 4. Repeated violations → token revoked *** ## API surface The capability tier is set server-side in the consent token and is not exposed to host code as a programmatic field. The SDK enforces tier caps internally — when you call a metric or stream that exceeds your tier, the SDK either downgrades the response (e.g. coarser embeddings) or returns `null` / a permission error, rather than emitting elevated data. To inspect what the SDK is currently doing, use the existing diagnostic hooks: ```dart theme={null} // Live counters, queue depths, and last-error strings for the runtime. final diag = Synheart.runtimeDiagnostics(); // Coarse consent status — capability tier is bundled in the token. final status = Synheart.consentStatus(); ``` If your integration needs to *react* to a tier change at runtime, listen to consent updates through the host's existing consent flow — the consent service is the source of truth for the tier. *** ## Testing ### Mock Capabilities For local development and tests, set `allowUnsignedCapabilities: true` in `SynheartConfig`. This loads the SDK's default capabilities without requiring a signed token: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.test', subjectId: 'test_user', allowUnsignedCapabilities: true, ), ); ``` This setting does not let host code select an arbitrary capability tier. Test tier-specific behavior with server-issued test credentials or at the module boundary. Never enable `allowUnsignedCapabilities` in production builds. ### Capability Test Matrix | **Test Case** | **Capability** | **Consent** | **Expected Result** | | - | - | - | - | | Basic access | Core | Granted | Basic HSI axes | | No consent | Core | Denied | All axes = null | | Extended access | Extended | Granted | Full HSI + embeddings | | Downgrade | Core | Granted | Core HSI (not Extended) | | Research access | Research | Granted | Full HSI + fusion | *** ## Migration Guide ### From Core to Extended When upgrading from Core to Extended: 1. **Request upgrade** via Synheart Platform console 2. **Update SDK** to handle Extended data: ```dart theme={null} Synheart.onStateUpdate.listen((state) { // Stable typed accessors remain the same across tiers. print(state.hsi.arousal?.value); print(state.hsi.stress?.value); // Fields not represented by HSIState, including embeddings, are // available only through the authoritative JSON when the tier permits. inspectExtendedFields(state.rawJson); }); ``` 3. **Test thoroughly** with Extended data 4. **Update privacy policy** to reflect Extended data access 5. **Deploy with new capability token** *** ## Related Documentation * [Architecture](/synheart-core/architecture) - Module system and HSI Runtime * [HSV Specification](/synheart-core/hsv-specification) - State representation * [Consent System](/synheart-core/consent-system) - User permission model * [Cloud Protocol](/synheart-core/cloud-protocol) - Cloud upload specification *** **Last Updated:** 2026-05-05 **Version:** 1.1.0 # Cloud Protocol Source: https://docs.synheart.ai/synheart-core/cloud-protocol How HSI snapshots travel from the SDK to Synheart Platform — endpoints, headers, and authentication When you turn cloud upload on, Synheart Core hands HSI snapshots to the runtime's **unified ingest connector**. The connector batches, signs, and uploads them to Synheart Platform. This page is the developer-facing reference for what crosses the wire and how to authenticate. > [!NOTE] > > The runtime owns the upload queue and signing. You enable cloud upload in your config — most apps never touch the lower-level paths described here. ## Architecture ```mermaid theme={null} flowchart LR subgraph SDK["SDK (On-Device)"] ENG["HSI Runtime\n(emits HSI windows)"] --> BRIDGE["Auto-enqueue bridge\n(consent-gated)"] BRIDGE --> Q["Persistent queue\n(SQLite)"] Q --> CONN["Cloud Connector\n- batch\n- retry\n- sign"] end subgraph CLOUD["Synheart Platform"] GATE["Ingest gateway"] --> AUTH["Verify\nX-Synheart-Proof\n+ X-Consent-Token"] AUTH --> SCHEMA["Schema validate"] SCHEMA --> STORE["Tenant-isolated storage"] end CONN -->|"HTTPS POST"| GATE ``` The connector is part of the Synheart runtime (native). The Dart/Swift/Kotlin SDKs do not maintain their own queues. ## Core principles 1. **Consent-gated** — every upload checks the runtime's consent state before sending. 2. **Derived data only** — only HSI snapshots leave the device. No raw biosignals, no clipboard contents, no notification bodies. 3. **Hardware-backed authentication** — every request is signed by an ECDSA P-256 key in the device's Secure Enclave (iOS) or Android Keystore. 4. **Per-request consent token** — every upload carries a JWT issued by the consent service. 5. **Tenant-isolated** — payloads route to per-`org_id` storage; no cross-tenant access. 6. **Offline-resilient** — the runtime persists its queue in SQLite; uploads resume after restart and reconnect. 7. **Rate-limited** — the runtime caps outbound flow at 10 uploads/sec, burst 20. ## Endpoint The runtime POSTs to: ```http theme={null} POST /ingest/v1/hsi Content-Type: application/json ``` When the lab feature is enabled and `Research` consent is granted, the runtime also POSTs to: ```http theme={null} POST /ingest/v1/lab/session ``` `` is `https://api.synheart.ai` by default. Flutter builds can override the origin with `SYNHEART_BASE_URL`, or use `SYNHEART_INGEST_BASE_URL` for an ingest-specific override. > [!NOTE] > > The runtime owns this routing, and it is the only source of truth for it. The > SDKs pass an origin and nothing more — they never build a request path — so a > path written anywhere else is a copy that can drift. Paths are constructed in > `ingest_http_path()`, which prefixes `/ingest` onto the signing path. ## Authentication Every request carries two pieces of authentication: ### `X-Synheart-Proof` A compact JWS (JSON Web Signature) bound to this specific request. Built by the runtime via `synheart_core_sdk_build_proof_header(method, url)`. The proof binds: * The HTTP method. * The signing path (the runtime strips the `/ingest/` prefix; signing is over `/v1/hsi`). * The device's registered `device_id`. * A subject hash. * A fresh nonce. The signature is produced by the device's hardware key — your app does not handle private key bytes. > [!NOTE] > > The runtime signs `/v1/hsi` even though the request is POSTed to > `/ingest/v1/hsi`. If you build clients that talk to `/ingest/...` endpoints > from outside the runtime, mirror this prefix-stripping rule. ### `X-Consent-Token` A JWT issued by the consent service when the user grants `cloudUpload` consent. Carries: * `profile_id` — which consent profile the user accepted. * `expires_at` — token validity (refreshed at the 5-minute threshold). * `scopes` — granted channels (e.g. `bio:vitals`, `cloud:upload`). The runtime keeps this token in memory and refreshes it before each flush. ### Request signing Requests are signed with **hardware-backed ECDSA P-256 plus attestation** per `RFC-AUTH-MOBILE-0001`. HMAC is not used for cloud ingest. See [Synheart Auth](/synheart-auth/overview) for the full device-identity flow. ## Pre-conditions for upload Before any HSI window leaves the device, the runtime checks: 1. `IngestConfig.enabled = true` and `IngestConfig.hsi = true` (or `lab = true` for lab uploads). 2. The capability level permits cloud upload. 3. `cloudUpload` consent is granted with a valid token. 4. The account-deletion override is not active. 5. Device-bound crypto callbacks are registered (the host's `synheart-auth` integration). 6. Network reachability (best-effort). Any failure short-circuits the upload; the window stays in the queue (or buffer) and retries on the next cycle. ## Cold-start consent buffer The runtime opens an HSI session immediately, but the consent token may take a few seconds to fetch on cold start. To avoid losing the first window: * The auto-enqueue bridge holds up to **8 pending HSI windows** in a FIFO buffer when consent is `pending`. * On grant, the buffer drains and replays into the queue. * If consent never arrives within the buffer window, the oldest windows drop FIFO. This is automatic — your app does not configure or observe it directly. ## Payload shape Every upload is an HSI 1.3 JSON envelope produced by the engine. The exact field set follows the canonical [HSI specification](/hsi/overview); the SDK does not reshape it before sending. ```jsonc theme={null} { "hsi_version": "1.3", "observed_at_utc": "2026-01-15T10:30:00Z", "computed_at_utc": "2026-01-15T10:30:00Z", "producer": { "name": "synheart-core", "version": "", "instance_id": "" }, "window_ids": [...], // see hsi/overview for the full shape "windows": { ... }, "axes": { ... }, "privacy": { "contains_pii": false } } ``` The `subject_id` you supply in `SynheartConfig` is **never sent in the clear** — the runtime hashes it into a per-tenant `subject_hash` for identity routing, and that's what reaches the cloud. ## What capability level changes Every level uploads to the same HSI endpoint. The level does not select a path — it controls which fields the engine includes in the envelope (e.g. embedding presence), and differentiation happens server-side via the capability token. | Capability level | HSI upload | Lab upload | | - | - | - | | `core` | Base envelope fields | Not available | | `extended` | Richer payload fields | Available | | `research` | Full fields | Available | ## Lab session uploads When `enable lab ingest` is set in the SDK config and the user grants `research` consent, the runtime auto-enqueues the JSON returned by `Synheart.labFinalize(...)`. The runtime stamps the active lab metadata id into `session_metadata.extra_data.metadata_id` before sending. ## Backlog and offline behavior * **Persistent queue:** the runtime's queue is SQLite at `/ingest_upload_queue_.sqlite`. Survives app restarts. * **Network recovery:** transient network failures remain queued and are retried by the runtime connector. * **Backoff:** failed uploads use exponential backoff with jitter. Persistent 4xx failures (malformed payload, rejected token) are quarantined and surfaced through the connector's metadata. ## Inspecting upload state ```dart theme={null} // Force a flush via the ingestion façade. Checks consent before draining. final result = await Synheart.ingestion.flushIfEligible(); print('uploaded=${result.uploaded} failed=${result.failed} requeued=${result.requeued}'); // Current queue depth (synchronous getter). final depth = Synheart.uploadQueueLength; // Last successful upload (epoch ms; null/0 means "never"). final lastMs = Synheart.lastIngestSuccessAtMs; // Runtime diagnostics: availability, version, frame count, last quality. final diag = Synheart.runtimeDiagnostics(); ``` `Synheart.ingestion.flushIfEligible()` is the canonical entry point for manually draining the queue. `Synheart.ingestion.enqueueHsiWindows(...)` enqueues HSI JSON windows directly. The Kotlin and Swift SDKs expose the same surface with platform-idiomatic names. ## Errors Common failures and how to handle them: | Failure | Cause | Recovery | | - | - | - | | Queue grows but never drains | Consent token expired or never issued | Call `Synheart.ensureCloudConsentReady()` and confirm `Synheart.consentStatus()?['status']` is `granted`. | | Upload rejected with auth error | Device not registered or proof invalid | Call `Synheart.ensureDeviceAuthRegistered()`. | | Upload returns 4xx with malformed payload | Engine emitted a payload the gateway rejects | File a bug — the runtime should not produce invalid HSI. | | Construction errors mentioning `org_id` | `cloudConfig.orgId` empty when HSI ingest enabled | Set `CloudConfig.orgId` in your config. | ## Privacy guarantees enforced in code * Raw `subject_id` never leaves the device — only `subject_hash`. * Raw biosignals never leave the device — only HSI snapshots (and lab session JSON when explicitly enabled). * Cloud-bound traffic gates on consent at every flush; revocation immediately pauses the connector via the runtime's consent-check hook. * TLS 1.2+ for HTTPS; gRPC streams (RAMEN) use `tonic` with `tls-webpki-roots`. * Account-deletion mode (set via `Synheart.requestAccountDeletion()`) fully suspends outbound traffic. ## Wipe vs. account deletion * `Synheart.wipeLocalData()` clears the runtime's local stores (queue, history, sessions, HSI windows). Does **not** delete cloud data. * `Synheart.requestAccountDeletion()` puts the runtime in wind-down mode and signals the platform to delete cloud data. Call `cancelAccountDeletion()` to undo before the platform confirms. ## Related * [Synheart Auth — Request Signing](/synheart-auth/signing) — the `X-Synheart-Proof` contract. * [Consent System](/synheart-core/consent-system) — `cloudUpload` consent, token lifecycle. * [Capability System](/synheart-core/capability-system) — what each level unlocks. * [HSI Specification](/hsi/overview) — payload schema (HSI 1.3). # Consent System Source: https://docs.synheart.ai/synheart-core/consent-system User permission management — types, tiers, granular channels, and how the runtime enforces them The Consent Module manages user permissions and enforces privacy boundaries across all Synheart Core modules. The runtime is the authoritative enforcer; this page describes what you control and how. ## Core principles 1. **Explicit consent** — every data-collection or upload operation requires an explicit grant. 2. **Granular control** — module-level booleans plus per-channel flags. 3. **Revocable** — consent can be withdrawn at any time; the runtime stops within the next cycle. 4. **Cloud-verified** — when the consent service is configured, a valid JWT is required, not just a local boolean. 5. **Enforced** — missing consent silently drops samples and uploads at the runtime seam; nothing fakes the data. *** ## Three-layer authority Before a sensitive feature fires — Syni chat, lab export, vendor sync, HSI cloud upload — **three independent gates must all be open**: | Layer | Controlled by | Stored as | Granularity | | - | - | - | - | | **Platform capability** | Synheart (master switch) | `platform_capabilities.feature_key` | Product-wide (`syni_integration`, `research_export`, `vendor_sync`, `cloud_processing`, `hsi_uploads`, `wear_integration`, `lab_ingest`) | | **App policy** | App owner via the dev portal | `app_policies.allow_*` columns | Per app (`allow_syni`, `allow_research`, `allow_cloud_processing`, `allow_hsi_uploads`, `vendor_sync_allowed`) | | **User consent** | End user via the consent UI | `ConsentSnapshot` (this page) | Per channel (the seven types below) | The layers compose by AND: an app cannot enable what the platform has disabled, and a user cannot exercise what the app's policy forbids. The consent service enforces the platform ↔ app layer at write time (`PUT /v1/apps/{app_id}/policy` rejects bits the platform mask doesn't grant — e.g. `allow_syni=true` is refused unless `syni_integration` is enabled); the runtime enforces the app ↔ user layer when issuing the JWT and at the per-action gates listed below. This page covers the **user-consent layer**. The other two are out of band for the SDK consumer: platform capability is opaque to the app, and app policy is read-only from the device — it shapes which consent types the user is *allowed* to grant in the first place. *** ## Consent types Synheart Core defines **seven** consent types, mirrored across Dart, Kotlin, and Swift: | Consent type | Wire string | Module / scope | What it enables | | - | - | - | - | | `biosignals` | `"biosignals"` | Wear | HR, HRV, sleep, motion from wearables, RR intervals. | | `phoneContext` | `"phoneContext"` / `"phone_context"` | Phone | Device motion, screen state, app context (no app names). | | `behavior` | `"behavior"` | Behavior | Tap/scroll/swipe/typing timing — **no content**. | | `cloudUpload` | `"cloudUpload"` / `"cloud_upload"` | Cloud Connector | HSI snapshot upload to the platform. | | `syni` | `"syni"` | Syni | On-device LLM input (persona, conversation state). | | `vendorSync` | `"vendorSync"` / `"vendor_sync"` | RAMEN stream | Subscription to third-party vendor events (WHOOP, Garmin webhooks). | | `research` | `"research"` | Lab session export | Lab-session JSON upload. Required for research-tier uploads. | All seven default to **denied**. The user grants each one explicitly through a consent flow. ### Granular channels Each module can be consented at a finer grain via `ConsentChannels`: | Group | Channels | | - | - | | `biosignals` | `vitals`, `sleep`, `cardio_advanced`, `neuromuscular`, `wearable_motion` | | `phone_context` | `device_motion`, `device_context`, `system_state` | | `behavior` | `digital_activity`, `notification_patterns`, `app_context` | | `interpretation` | `focus_estimation`, `emotion_estimation` | When a consent submission carries explicit channel flags, those win over the module-level boolean. When the channel map is absent or all-false but the module-level flag is `true`, the module-level boolean wins (sensible default for callers that don't yet pass per-channel flags). ### Consent tiers `ConsentTier` describes the maximum processing destination: | Tier | Wire value | Allowed | | - | - | - | | `local` | `"local"` | On-device only — nothing leaves the device. **Default.** | | `cloud` | `"cloud"` | Derived/aggregated data may upload to Synheart Platform. | | `research` | `"research"` | Raw data may be exported to a research lab. Implies `cloud`. | *** ## Consent status The runtime computes a status from the local snapshot plus the cached cloud token: | Status | Condition | | - | - | | `granted` | Cached JWT is present and not expired. | | `expired` | Cached JWT is present and past expiry. | | `pending` | Local grant exists but no token yet, **or** consent service is configured and the cycle is in flight. | | `denied` | No token and consent service is not configured. | Token refresh threshold is **5 minutes** — `Synheart.consentNeedsTokenRefresh()` returns `true` when the JWT expires within that window. *** ## Consent flow ### 1. Initial consent request When the SDK initializes, the consent module loads any persisted snapshot. If nothing is stored, every type is `denied`. ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.app', subjectId: 'anon_user_123', consentConfig: ConsentConfig( appId: 'com.example.app', deviceId: deviceId, platform: 'ios', userId: 'anon_user_123', ), ), ); bool ready = await Synheart.hasConsent('biosignals'); if (!ready) { // Show your consent UI, then submit: final result = await Synheart.consentSubmitForm( deviceId: deviceId, platform: 'ios', formJson: consentForm, ); // On success, result contains synced / accepted / token fields. // The consent module stores the token automatically. } ``` ### 2. Granting Two paths grant consent: * **Local grant** — `Synheart.grantConsent(...)` mutates the local snapshot. Useful for unit tests and dev. **In production with a configured consent service**, the runtime will still report `pending` until a JWT is issued. * **Cloud submit** — `Synheart.consentSubmitForm(...)` sends a signed form to the consent service and stores the returned JWT. This is the production path. ### 3. Storage The consent module persists state via the platform's secure storage (Keychain on iOS, EncryptedSharedPreferences on Android, `keyring` on desktop). The runtime registers its own secure-storage callbacks during init; you don't manage this directly. What is stored: * The local `ConsentSnapshot` (per-type booleans, channels, tier, timestamps). * The cached `ConsentToken` (JWT, profile id, expiry, scopes). * Per-platform storage keys are scoped per `subject_id`. What is **not** stored: * Private keys (those live in the Secure Enclave / Keystore via `synheart-auth`). * Raw form input fields beyond the consent submission. ### 4. Revocation ```dart theme={null} await Synheart.revokeConsentType('biosignals'); // single type await Synheart.revokeConsent(); // all types ``` Effects: * Each module checks consent before pushing samples; revoked modules' samples are silently dropped at the runtime engine seam. * Cloud uploads stop on the next flush — the runtime's connector hook reads the consent state before draining the queue. * Local data is **not** deleted automatically. Use `Synheart.wipeLocalData()` if you need a hard wipe. ### What happens mid-session Revocation is non-destructive to your app: nothing throws, no streams close. * **Sample ingest stops at the seam.** Samples for revoked types are dropped before inference. Depending on which inputs remain consented, HSI output can lose affected axes or stop until enough permitted input is available. * **In-flight cloud uploads continue; queued ones don't.** Whatever is already on the wire when the user revokes will complete. Anything still in the local queue is held until consent is re-granted, or discarded on `wipeLocalData()`. * **Already-emitted HSI events are not retroactively recalled.** If your app has buffered HSI envelopes from before the revocation, that data is yours to delete or retain per your own policy. * **A consent stream is available.** Observe `Synheart.consentChanges` if the app needs to pause UI or surface a consent-required message. Re-granting consent resumes ingest on the next cycle without restarting the SDK; buffered cloud uploads from before the revocation are not replayed unless explicitly re-queued. *** ## Enforcement ### `hasConsent` semantics ```text theme={null} hasConsent(type) = if cloudConsentConfigured AND consentStatus != granted: return false return localSnapshot.allows(type) ``` When the consent service is configured (typical in production), the local snapshot is **not authoritative on its own** — a valid cloud-issued JWT must be present. ### Per-action gates | Action | Required consent type(s) | | - | - | | Push HR / RR / vendor HRV / sleep stages | `biosignals` | | Push behavior events | `behavior` | | Push phone context | `phoneContext` | | HSI cloud upload | `cloudUpload` | | RAMEN stream subscription | `cloudUpload` AND `vendorSync` | | Syni chat / cloud relay | `syni` (plus app policy `allow_syni` and platform capability `syni_integration`) | | Lab session export | `research` | The runtime applies these gates at the engine seam. Sample pushes that fail a gate are silently dropped. ### Account-deletion override `Synheart.requestAccountDeletion()` puts the runtime in a wind-down state that overrides every consent type to denied for outbound traffic, regardless of stored state. `cancelAccountDeletion()` lifts the override. *** ## Cold-start consent buffer The runtime opens an HSI session immediately, but the consent token may take seconds to fetch on a fresh app launch. To avoid losing the first window: * The auto-enqueue bridge buffers up to **8 pending HSI windows** when consent is `pending`. * On `granted`, the buffer drains and replays into the upload queue. * If consent never lands, the oldest buffered windows drop FIFO. This is automatic and not configurable from the SDK. *** ## API reference ### Querying state ```dart theme={null} // Snapshot summary (booleans + timestamp). final snapshot = Synheart.shared.currentConsent; // Coarse status enum. final status = Synheart.getConsentStatus(); // Returns: ConsentStatus.granted | .pending | .denied | .expired // Raw status map (status string + last-updated timestamp). final raw = Synheart.consentStatus(); // True when the JWT expires within 5 minutes. final needsRefresh = Synheart.consentNeedsTokenRefresh(); // Single-type query. final ok = await Synheart.hasConsent('biosignals'); ``` ### Mutating state ```dart theme={null} // Grant per channel (named-bool form is the canonical signature). await Synheart.grantConsent( biosignals: true, behavior: true, phoneContext: false, cloudUpload: false, ); await Synheart.revokeConsentType('biosignals'); await Synheart.revokeConsent(); // revoke every channel ``` ### Cloud submission ```dart theme={null} // Get the editable form (built from cached profile + current snapshot). final form = Synheart.consentGetEditableFormTyped(); if (form == null) { throw StateError('Consent runtime is unavailable'); } // Submit and receive a JWT. Signed by the device key automatically. final result = await Synheart.consentSubmitFormTyped( form: form, deviceId: deviceId, platform: 'ios', userId: userId, // optional ); // Force a token refresh if needed. await Synheart.ensureCloudConsentReady(); ``` The consent service origin is read from `ConsentConfig.consentServiceUrl`. It resolves to `SYNHEART_CONSENT_BASE_URL` when provided and otherwise to `SYNHEART_BASE_URL`. Neither has a Dart-side default — when both are unset the value is empty and the native runtime applies its own built-in origin, which keeps one source of truth rather than two that can drift. The runtime appends service paths. *** ## Privacy invariants These hold regardless of consent state: * The SDK never collects content (no text, no clipboard payloads, no notification bodies, no audio). * Raw `subject_id` never leaves the device — only `subject_hash`. * Token material is in-memory only; never persisted in plaintext. * Revocation pauses outbound traffic on the next flush, not on a timer. *** ## Related * [Cloud Protocol](/synheart-core/cloud-protocol) — what `cloudUpload` actually authorises. * [Capability System](/synheart-core/capability-system) — the second authority alongside consent. * [Synheart Auth — Signing](/synheart-auth/signing) — how consent submissions are device-signed. * [Synheart Behavior — Threat Model](/synheart-behavior/threat-model) — what `behavior` consent unlocks at the SDK layer. # Synheart Core - Edge SDK (watch + wearable) Source: https://docs.synheart.ai/synheart-core/edge Slim watch-class SDK for streaming biosignals + running on-device HSI on Apple Watch and Wear OS ## Overview The **Synheart Core Edge** SDK is a watch-class build of Synheart Core targeted at Apple Watch, Wear OS, and other low-power wearables. It runs the session lifecycle (start / pause / resume / stop), captures HR + motion samples, and either streams the raw samples to a paired phone for HSI computation, or — when the native runtime binary is bundled — runs the edge HSI pipeline locally. Two language flavours, same API shape: * **`SynheartCoreEdge`** (Swift) — for watchOS / iOS / macOS targets * **`ai.synheart:synheart-core-edge`** (Kotlin) — for Wear OS / Android targets Both consume the same native runtime (built with the `edge` feature) via FFI when present. When absent, both fall back to a `STREAM` mode that surfaces raw samples for the host to relay. ## When to use Edge vs Core | | Synheart Core (kotlin / swift) | Synheart Core **Edge** | | - | - | - | | Target | Phone / desktop | Watch / wearable | | Runtime variant | `stable` (with ONNX) or `lab` | `edge` (no ONNX, deterministic models only) | | Binary size | full | \~13 MB (Android ships `arm64-v8a` only) | | Default biosignal source | platform-specific health adapter | platform-specific health adapter (overridable) | | Compute mode | always compute locally | **STREAM** (default) or **COMPUTE\_LOCAL** | Watches almost always run **STREAM** in production — the phone has more thermal headroom and a longer-running runtime. **COMPUTE\_LOCAL** is for standalone-watch use cases (no phone reachable) and offline sessions. ## Installation ### Swift (SwiftPM) `Package.swift`: ```swift theme={null} .package(url: "https://github.com/synheart-ai/synheart-core-swift-edge.git", from: "0.0.6"), ``` Target dependency: ```swift theme={null} .product(name: "SynheartCoreEdge", package: "synheart-core-swift-edge"), ``` Platforms: watchOS 9.0+, iOS 15.0+, macOS 13.0+. ### Kotlin (Gradle) Until the SDK publishes to Maven Central, consume via composite build: ```kotlin theme={null} // settings.gradle.kts val coreEdge = providers.environmentVariable("SYNHEART_CORE_EDGE_LOCAL").orNull if (!coreEdge.isNullOrBlank()) { includeBuild(coreEdge) } ``` Then in the wear module: ```kotlin theme={null} dependencies { implementation("ai.synheart:synheart-core-edge") implementation("ai.synheart:synheart-session:0.4.0") } ``` Targets: Wear OS 3.0+ / API 30+ (`minSdk 30`, `compileSdk 34`). ## Quickstart ### Swift (watchOS) ```swift theme={null} import SwiftUI import SynheartCoreEdge import SynheartSessionHealthKit // HealthKitBiosignalProvider (synheart-session-swift) import SynheartWear @main struct MyWatchApp: App { @StateObject private var engine = WatchSessionEngine( provider: HealthKitBiosignalProvider(wear: SynheartWear()), outbox: EdgeOutbox(), sessionManager: EdgeSessionManager() ) var body: some Scene { WindowGroup { VStack { Text("HR: \(Int(engine.currentHr))") Button("Start") { engine.startEdgeSession(preset: SessionPreset.defaults[0]) } } } } } ``` The heart-rate source is always injected: `HealthKitBiosignalProvider` comes from the `SynheartSessionHealthKit` product of [synheart-session-swift](https://github.com/synheart-ai/synheart-session-swift). Pass your own provider to use another source: ```swift theme={null} let bleProvider = MyPolarChestStrapProvider() let engine = WatchSessionEngine(provider: bleProvider, ...) ``` ### Kotlin (Wear OS) ```kotlin theme={null} class WatchApp : Application() { private val provider by lazy { HealthServicesBiosignalProvider(this) } private val motionSensor = MotionSensor() val engine: WatchSessionEngine by lazy { WatchSessionEngine( provider = provider, motionSensor = motionSensor, outbox = EdgeOutbox(this), sessionManager = EdgeSessionManager(this), ) } override fun onCreate() { super.onCreate() motionSensor.init(this) } } ``` The Wear OS adapter (`HealthServicesBiosignalProvider`) wraps Wear OS Health Services `MeasureClient`. It lives in the host app rather than the SDK because Wear platform binding is the host's choice. ## Engine API (both platforms) ```text theme={null} startSession(config, mode? = nil) // mode resolves: COMPUTE_LOCAL if runtime present else STREAM pauseSession() resumeSession() stopSession() startEdgeSession(preset) // standalone watch session (no phone) acknowledgeArtifacts(ids) // after phone confirms it received them ``` Observable state: On Swift these are `@Published` properties of the engine. On Kotlin they are fields of `engine.state` (a `StateFlow`); the session state is `UiState.watchState`. * `currentHr: Double` — latest HR sample (BPM) * `state: WatchSessionState` — `.idle | .starting | .running | .paused | .stopping | .syncing | .error` * `elapsedSec: Int`, `remainingSec: Int`, `pendingArtifacts: Int` * `lastMetrics: [String: Any]?` — frame metrics (`hr_mean_bpm`, `hr_sdnn_ms`, `rmssd_ms`, `motion_rms_g`) Event/sample streams: * Kotlin: `engine.hrEvents` (Flow), `engine.events` (Flow), `engine.bioSamples` (Flow, STREAM only) * Swift: `engine.onHrSample`, `engine.onEvent`, `engine.onBiosignalSample` (callback assignments) ## Mode resolution When `startSession(...)` is called with `mode = nil` (the default), the engine probes for the native runtime via the platform's standard dynamic-symbol lookup: * **Runtime resolves** → mode = `COMPUTE_LOCAL`, HSI computed on-watch, artifacts go to `EdgeOutbox` * **Runtime missing** → mode = `STREAM`, raw samples surfaced via `bioSamples` / `onBiosignalSample` for the host to relay to the phone Pass an explicit `mode` to force one path (e.g. `.stream` for low-battery preference, `.computeLocal` for standalone use). ## Runtime native binary ### Android (Wear OS) The edge runtime ships as `arm64-v8a` only: ```bash theme={null} synheart install runtime --platform android --variant edge ``` The CLI writes it to `synheart/vendor/runtime/android/jniLibs/arm64-v8a/`. Point your `:wear` module's `jniLibs.srcDirs` at `synheart/vendor/runtime/android/jniLibs` (see [Kotlin setup](/synheart-core/kotlin)), or copy the `.so` into `wear/src/main/jniLibs/arm64-v8a/`. Or, building from source against a local runtime checkout: ```bash theme={null} SYNHEART_CORE_RUNTIME_LOCAL=/path/to/synheart-core \ ./gradlew :wear:assembleDebug ``` (The reference wear app includes a `:wear:vendorEdgeRuntime` Gradle task that builds the edge runtime and drops the `.so` into `jniLibs/`. Build with `cargo ndk … --features edge`; `--no-default-features` alone strips the `synheart_core_edge_*` exports.) ### Apple (iOS + watchOS) ```bash theme={null} synheart install runtime --platform ios --variant edge ``` Lands two xcframeworks side-by-side under `synheart/vendor/runtime/ios/`: | | | | - | - | | `SynheartCoreRuntime.xcframework` | iOS device + simulator (dynamic Mach-O frameworks, dSYMs embedded for App Store Connect symbolication) | | `SynheartCoreRuntime-watchos.xcframework` | watchos-arm64 + watchos-arm64-simulator (static `.a` archives) | Xcode picks the right slice per target automatically — the iOS app links the dynamic framework, the watchOS app links the static archive. The SDK's `RuntimeBridge` uses `dlsym(RTLD_DEFAULT, …)`, so the watch's statically-linked symbols resolve the same way as the iOS dylib's dynamically-loaded ones. **Why two:** Apple's xcframework format prohibits mixing `-framework` and `-library` inputs in a single bundle, and the native runtime's tier-3 watchOS target only emits a static library (not a dynamic one). **Building from source** (runtime contributors): `make ios-edge` produces both. See the runtime repo for toolchain prerequisites. ## Session lifecycle (RFC §8.1) ```text theme={null} IDLE │ start ▼ STARTING ──error──┐ │ │ │ ▶ ▼ RUNNING ◀──pause──┐ ERROR │ ▲ │ resume │ │ ▼ ▼ │ PAUSED ──stop──► STOPPING ──► IDLE │ └──► SYNCING ──► IDLE ``` `pause` is host-driven (UI interruption, call, breath). Resume shifts `startedAtMs` forward by the paused interval so elapsed-time accounting skips the pause. ## Compute provenance Every HSI artifact the engine produces (in `COMPUTE_LOCAL` mode) is stamped with a `meta.synheart.compute` block per the edge-tiering RFC: ```jsonc theme={null} "meta": { "synheart": { "compute": { "tier": "edge_deterministic", "runtime": "synheart_core_edge", "runtime_version": "", "model_id": "rulepack://hsi-edge/v1.4", "computed_on": "wearable", "session_role": "canonical" } } } ``` Cloud-side tier-aware queries (overview KPI breakdowns, shadow reconciliation) join on this block. ## See also * [Synheart Core (Kotlin SDK)](/synheart-core/kotlin) — phone-class SDK * [Synheart Core (Swift SDK)](/synheart-core/swift) — phone-class SDK * [Synheart Wear adapters](/synheart-wear/adapters) — BLE HRM, HealthKit, Health Connect details * [HSI Specification](/synheart-core/hsi-specification) — schema reference # Synheart Core - Flutter SDK Source: https://docs.synheart.ai/synheart-core/flutter Install and integrate Synheart Core 0.20 in a Flutter application ## What this SDK does Synheart Core connects a Flutter app to the native Synheart Runtime. It: * collects user-consented wearable, phone, and behavior signals; * sends those signals to the on-device runtime; * exposes Human State Interface (HSI) 1.3 output as Dart streams; * optionally stores, synchronizes, and uploads derived state. The Flutter package coordinates platform integrations. Human-state computation, storage, device authentication, and sync run in the separately installed native runtime. > [!NOTE] > > HSI is the public output. Most applications should use > `Synheart.onStateUpdate` for typed values or `Synheart.onHSIUpdate` for the > canonical JSON. Internal HSV data does not cross the public SDK boundary. ## Requirements * Dart `>=3.8.0 <4.0.0` * Flutter `>=3.32.0` * iOS 15 or later * Android API 24 or later * A Synheart Runtime binary installed in the host application The example Flutter app targets Android API 28 or later. Individual wearable providers can impose additional OS, hardware, or licensing requirements. ## Installation ### 1. Add the Flutter package ```bash theme={null} flutter pub add synheart_core ``` Or add the current release to `pubspec.yaml`: ```yaml theme={null} dependencies: synheart_core: ^0.23.0 ``` ### 2. Install the native runtimes The package alone loads no runtime and produces no HSI. Native artifacts are provisioned by the Synheart CLI, not by pub. Install and authenticate the CLI once: ```bash theme={null} curl -fsSL https://synheart.sh/install | bash synheart login ``` From your Flutter application root: ```bash theme={null} synheart install runtime --version 0.46.0 synheart install syni ``` `synheart_core` 0.23 is verified against runtime `0.46.0` and requires C ABI 4.2 (runtime 0.45.0 or later); older runtimes are refused at initialization. ABI 4.2 changed the daily score inputs, and neither shape parses on the other runtime. `synheart doctor` checks the installed runtime against the package. > [!WARNING] > > `synheart install syni` is not optional on iOS. `synheart_core` depends on the > `syni` package, whose iOS pod links its own vendored framework and fails > `pod install` when it is absent — even if your application never uses Syni. Commit the generated `synheart.lock`, which pins each artifact by SHA-256. Other developers and CI can restore the pinned artifacts with: ```bash theme={null} synheart sync ``` The CLI installs runtime artifacts under: * iOS: `synheart/vendor/runtime/ios/SynheartCoreRuntime.xcframework/` * iOS: `synheart/vendor/syni-runtime/SyniRuntime.xcframework/` * Android: `synheart/vendor/runtime/android/jniLibs//` ### 3. Configure the platforms #### iOS Set `SYNHEART_APP_ROOT` near the top of your application's `ios/Podfile`: ```ruby theme={null} ENV['SYNHEART_APP_ROOT'] = File.expand_path('..', __dir__) ``` Treat this as required rather than as a monorepo workaround. The Synheart podspecs symlink their vendored framework from `/synheart/vendor/` during `pod install`. Without it they walk up from the pod's own source directory, which either fails to find an application root (pods resolved from pub-cache) or reaches a different project that happens to have a `synheart/vendor/` directory — linking a runtime your `synheart.lock` does not pin. Enable the HealthKit capability when using health data. Add a usage description to `ios/Runner/Info.plist`: ```xml theme={null} NSHealthShareUsageDescription This app reads health data to calculate consented wellbeing insights. ``` Use permission copy that accurately describes your application. `synheart_core` 0.23 asks Apple Health and Health Connect for read access only (through `synheart_wear` 0.6.1 and later), so `NSHealthUpdateUsageDescription` and the Health Connect `WRITE_*` permissions are needed only if your app writes health data itself. #### Android Declare only the permissions required by the sources you enable: ```xml theme={null} ``` `synheart_behavior` 0.4.1 (required by `synheart_core`) merges its notification listener service and the `BIND_NOTIFICATION_LISTENER_SERVICE` and `READ_PHONE_STATE` permissions into your manifest automatically, so you no longer declare them. If your app does not collect notification or call interruptions, remove them: ```xml theme={null} ``` Keep app data out of Android backups: the runtime's secure store is sealed with a device-bound key that a restored copy cannot use. Set `android:allowBackup="false"` and `android:dataExtractionRules` on the ``. On iOS the SDK excludes its data directories from backup itself. Health Connect requires package queries, a permission-rationale intent, and a privacy-policy activity alias. Copy the applicable declarations from the [Flutter example manifest](https://github.com/synheart-ai/synheart-core-flutter/blob/main/example/android/app/src/main/AndroidManifest.xml). On Android 14 and later, use `FlutterFragmentActivity`: ```kotlin theme={null} import io.flutter.embedding.android.FlutterFragmentActivity class MainActivity : FlutterFragmentActivity() ``` Build your application module against a current `compileSdk`. The package compiles against 36, matching Flutter's default and the sibling AndroidX dependencies. The minimum supported Android version is unchanged at API 24. ## Start here The minimum integration has five steps: 1. Initialize the SDK. 2. Ask the user for consent. 3. Subscribe to HSI output. 4. Start a collection session. 5. Stop the session and release resources. The following example uses unsigned capabilities for local development: ```dart theme={null} import 'dart:async'; import 'package:synheart_core/synheart_core.dart'; late final StreamSubscription hsiSubscription; Future startSynheart() async { await Synheart.initialize( config: SynheartConfig( appId: 'com.example.my_app', subjectId: 'user-123', appVersion: '1.0.0', allowUnsignedCapabilities: true, // Development only. wearConfig: const WearConfig(), behaviorConfig: const BehaviorConfig(), ), ); await Synheart.grantConsent( biosignals: true, behavior: true, phoneContext: false, cloudUpload: false, ); hsiSubscription = Synheart.onStateUpdate.listen((state) { print('Focus: ${state.hsi.focus?.value}'); print('Arousal: ${state.hsi.arousal?.value}'); }); await Synheart.startSession(); } Future stopSynheart() async { await Synheart.stopSession(); await hsiSubscription.cancel(); await Synheart.dispose(); } ``` > [!WARNING] > > `allowUnsignedCapabilities: true` bypasses production capability verification. > Never enable it in a release build. ## Initialization `SynheartConfig.validate()` requires: * a non-empty `appId`; * a non-empty `subjectId`; * a `subjectId` that does not contain `|`; * `PrivacyConfig(allowResearch: true)` when using research mode. ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.my_app', subjectId: 'pseudonymous-user-id', mode: SynheartMode.personal, appName: 'My App', appVersion: '2.1.0', category: 'Wellness', developer: 'Example Inc.', allowUnsignedCapabilities: true, // Development only. ), autoStart: false, ); ``` Passing `userId:` to `initialize()` does not populate `config.subjectId`. Set `subjectId` on the config itself. `initialize()` throws `SynheartRuntimeException` (`kind: incompatible`) when the installed runtime cannot be used with this SDK: a C ABI other than 4.2 or a later 4.x, a runtime older than 0.45.0, or a library that does not report its build info. Its `installCommand` is the exact command that fixes it. A missing, wrong-architecture, or unloadable runtime does not throw: the SDK starts without HSI and `Synheart.runtimeError` says why. ```dart theme={null} try { await Synheart.initialize(config: config); } on SynheartRuntimeException catch (e) { print('${e.message}\nFix: ${e.installCommand}'); } if (Synheart.runtimeError != null) { print('Runtime unavailable: ${Synheart.runtimeError!.message}'); } ``` Initialization is idempotent. Concurrent callers share the in-progress initialization, and calls made after initialization are no-ops. By default, initialization does not collect data. Call `startSession()` after consent is ready. Use `autoStart: true` only when consent has already been completed. ### Modes | Mode | Persistence | | - | - | | `SynheartMode.personal` | HSI, session summaries, and baselines | | `SynheartMode.insight` | Personal-mode data plus application metrics | | `SynheartMode.research` | Can include raw research data; requires explicit privacy configuration and consent. Forwards raw phone motion to the runtime by default (`BehaviorConfig.emitRawMotionSamples`). | When the signed-in identity changes, keep the runtime identity aligned without reinitializing: ```dart theme={null} final changed = await Synheart.rebindSubjectId('new-subject-id'); ``` ### Running without cloud credentials The SDK is usable with no platform account. Omit `CloudConfig` and `DeviceAuthConfig`, and everything on-device works: collection, HSI computation, consent, local storage, and baselines. Nothing leaves the device and no attestation is attempted. The runtime consent-form flow needs a `ConsentConfig` to stamp submissions: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.my_app', subjectId: 'usr_stable_identifier', allowUnsignedCapabilities: true, // Development only. wearConfig: const WearConfig(), consentConfig: ConsentConfig( deviceId: 'dev_stable_identifier', platform: 'flutter', userId: 'usr_stable_identifier', ), ), ); ``` HSI upload, cross-device sync, research-study enrolment, and server-issued capability tokens are unavailable in this configuration. Consent still persists locally; the runtime is offline-first and reconciles with the cloud profile only when cloud upload is enabled. ## Consent Consent and capability are different: * **Capability** says what the application is authorized to use. * **Consent** says what the user allows. Standard collection features are operational only when activation, consent, capability, and an active session all permit them. Syni also has its own model installation and execution lifecycle; see [Syni for Flutter](/syni/flutter). The seven consent channels are: * `biosignals` * `phoneContext` * `behavior` * `cloudUpload` * `vendorSync` * `research` * `syni` Each category is made of finer channels, such as `phone_context.device_motion` and `behavior.app_context`. By default a granted category turns on all of its channels. Set `SynheartConfig(strictChannelConsent: true)` to enforce consent per channel instead: the runtime then accepts a sample only when its own channel is granted (and, when cloud consent is configured, present in the verified consent token), and the SDK checks the same channel before starting a sensor. Available since `synheart_core` 0.18.0. When a newer version of your app's published HSM Schema declares an input the person was never asked about, the runtime keeps it off until they consent. `Synheart.schemaNeedsConsent()` is true while that is the case, and `hsmSchemaConsent()` returns the schema version and the new channels. Show the consent form again when it is true. A channel the person declined is not asked about again. Available since `synheart_core` 0.21.0 (runtime 0.43.0 or later). HSI windows reach `onHSIUpdate`, `onStateUpdate` and `getSessionHsiWindows()` when any collection category (`biosignals`, `behavior`, `phoneContext`) or `research` is granted, so an app that collects only behavior still receives its digital axes. With none of them granted, windows are dropped. Before 0.23.0 a window needed `biosignals` or `research`. ### Local development consent ```dart theme={null} await Synheart.grantConsent( biosignals: true, phoneContext: true, behavior: true, cloudUpload: false, vendorSync: false, research: false, syni: false, ); final channels = Synheart.getConsentStatusMap(); print(channels['biosignals']); ``` Observe consent changes: ```dart theme={null} final consentSubscription = Synheart.consentChanges.listen((snapshot) { print('Cloud upload allowed: ${snapshot.cloudUpload}'); }); ``` Revoke one channel or all consent: ```dart theme={null} await Synheart.revokeConsentType('behavior'); await Synheart.revokeConsent(); ``` `hasConsent()` reports whether a channel is currently enforceable, not what the user chose. Once cloud is configured, the runtime denies every channel until a consent token is issued. For hosted consent profiles and JWT lifecycle, see [Consent System](/synheart-core/consent-system). ## Feature activation and sessions Module config enables the corresponding module. Features may also be activated explicitly: ```dart theme={null} Synheart.activate(SynheartFeature.wear); Synheart.activate(SynheartFeature.behavior); print(Synheart.isActivated(SynheartFeature.wear)); print(Synheart.isFeatureOperational(SynheartFeature.wear)); ``` Available features are: | Feature | Purpose | Consent | | - | - | - | | `wear` | Wearable biosignals | `biosignals` | | `behavior` | Interaction timing and patterns | `behavior` | | `phoneContext` | Motion, screen, and app context | `phoneContext` | | `cloud` | HSI cloud upload | `cloudUpload` | | `synsync` | [Cross-device sync](/synheart-core/sync) | `cloudUpload` | | `syni` | Adaptive AI integration | `syni` | Start and stop the full collection lifecycle: ```dart theme={null} final session = await Synheart.startSession(durationSec: 30 * 60); print(session?.sessionId); // Later: await Synheart.stopSession(); ``` > [!NOTE] > > `startSession()` requires both halves of a pair: a collection feature enabled > in `SynheartConfig` (`wearConfig` / `behaviorConfig` / `phoneConfig`) **and** > its matching consent granted (`biosignals` / `behavior` / `phoneContext`). > Neither alone is enough, and `cloudUpload`, `vendorSync`, `research`, and > `syni` never qualify — they govern what happens to data once gathered. A > session that could collect nothing throws a `StateError` instead of starting. Or control individual collectors: ```dart theme={null} await Synheart.startWearCollection( interval: const Duration(seconds: 1), ); await Synheart.startBehaviorCollection(); await Synheart.startPhoneCollection(); await Synheart.stopPhoneCollection(); await Synheart.stopBehaviorCollection(); await Synheart.stopWearCollection(); ``` Module-level methods still enforce consent and capability gates. ## Reading HSI ### Typed state Most Flutter applications should use: ```dart theme={null} final subscription = Synheart.onStateUpdate.listen((state) { final focus = state.hsi.focus; final stress = state.hsi.stress; if (focus != null) { print('Focus ${focus.value}, confidence ${focus.confidence}'); } if (stress != null) { print('Stress ${stress.value}, confidence ${stress.confidence}'); } }); ``` The typed state contains: ```dart theme={null} class HSIState { final String subjectId; final int timestampMs; final HSIAxes hsi; final Modalities modalities; final Tiers tiers; final String rawJson; final String? parseError; } class HSIAxes { // Physiological and fused axes. final HSIAxisValue? focus; final HSIAxisValue? arousal; final HSIAxisValue? capacity; final HSIAxisValue? sleep; final HSIAxisValue? stress; // Digital axes, derived from interaction rather than physiology. final HSIAxisValue? focusQuality; final HSIAxisValue? interruptionPressure; final HSIAxisValue? interactionMode; } ``` Axis values can be null when there is not enough input or when an older payload does not contain that reading. Missing means unknown; it does not mean zero. The digital axes come from interaction, so they resolve on hardware with no biosignal source. Use `HSIAxes.hasDigital` to check whether the window carried any of them. `onStateUpdate` parses each HSI window once and shares the result across subscribers. `Synheart.currentHSIState` reuses the same parse, so it is cheap to read repeatedly. ### Canonical JSON Use the raw stream when forwarding or validating the exact HSI 1.3 envelope: ```dart theme={null} final subscription = Synheart.onHSIUpdate.listen((hsiJson) { sendToYourConsumer(hsiJson); }); ``` `HSIState.rawJson` preserves the same JSON. See [HSI in Synheart Core](/synheart-core/hsi-specification) for mapping details. ### Raw source streams ```dart theme={null} final wearSubscription = Synheart.wearSampleStream.listen((sample) { print('HR: ${sample.hr}'); print('RR intervals: ${sample.rrIntervals}'); }); final behaviorSubscription = Synheart.behaviorEventStream.listen((event) { print('${event.type} at ${event.timestamp}'); }); ``` Raw streams are consent-gated. Always cancel subscriptions with their owning widget, provider, or service. Per-session buffers are also available through `Synheart.getSessionHsiWindows()` and `Synheart.getSessionWearSamples()`. Both are capped ring buffers — see `maxSessionHsiWindows` and `maxSessionWearSamples`. ## Personal baselines and daily scores The runtime keeps the personal baselines on the device and **saves and restores them itself**. Most apps need no code for this. **Push a daily value** (for example from a wearable's nightly summary), then refresh the reference once. Both calls build the engine pipeline when no session is running (since 0.23.0), so a background health pull or vendor sync is stored: ```dart theme={null} Synheart.srmPushWearableDaily( provider: 'garmin_connect', metric: DailyMetric.restingHrBpm, // the unit is in the name date: wakeDate, // the local date the person woke on value: 54, ); // 0 = stored Synheart.srmRefreshWearableReference(); ``` **Attach Strain** with `attachStrainScore()` before local midnight, or `attachClosedDayStrain()` after it. **Score a night** against the runtime's baselines. After `srmRefreshWearableReference()`, read `Synheart.dailySleepBaselines()` for the Sleep Score and `Synheart.dailyBaselineRefs()` for Recovery and Readiness: * `SleepScoreInput` takes `tonightMidpointH` (the night's local sleep midpoint, or null without a start and end time) and `baselines`. Without the baselines the score stays in its cold-start mode. * `RecoveryScoreInput.baselines` comes from `dailyBaselineRefs()`. * `ReadinessScoreInput.baselineMaturity` (`0..1`) is `BaselineRefs.maturity`, or `0` when `dailyBaselineRefs()` returns null. Push heart rate under two names. `cardiac.overnight_hr_bpm` (`DailyMetric.overnightHrBpm`) is the mean HR asleep, which the Sleep Score reads. `cardiac.resting_hr_bpm` is the resting-HR record, which Recovery and Readiness read. A source with one overnight figure fills both. A daytime resting HR on its own fills resting only. Push steps and `motion.active_min` only for days that are over. Never push `cardiac.rest_rmssd_ms`; the engine writes it. > [!NOTE] > > Upgrading from 0.19 or earlier? `rollDay()` and the SRM/longitudinal snapshot > calls are gone, and daily values use the new `DailyMetric` names. The first > launch after the upgrade starts the baselines fresh once. From 0.21 or earlier, > the score inputs changed with runtime 0.45 (see [Upgrading](#upgrading)). See the > [changelog](https://pub.dev/packages/synheart_core/changelog) for each change. ## Production device authentication Production applications should configure hardware-backed device identity: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.my_app', subjectId: 'user-123', deviceAuthConfig: const DeviceAuthConfig( authBaseUrl: 'https://api.synheart.ai', packageName: 'com.example.my_app', ), cloudConfig: CloudConfig( subjectId: 'user-123', instanceId: 'stable-installation-uuid', orgId: 'organization-id', baseUrl: ApiEndpoints.resolvedCloudBaseUrl, ), ), ); ``` The runtime registers a hardware-backed identity and signs supported requests. No shared HMAC secret is required for normal production upload. > [!WARNING] > > `DeviceAuthConfig.packageName` is the installed bundle id, which Play Integrity > and App Attest verify against. It is not `SynheartConfig.appId`, the > platform-issued application identifier. Passing the latter fails attestation. Registration is triggered by cloud-upload consent, not by `initialize()`. Configuring `DeviceAuthConfig` only makes it possible. Device registration is deferred until a cloud-bound action needs it: ```dart theme={null} final registered = await Synheart.ensureDeviceAuthRegistered(); final status = Synheart.coreDeviceAuthStatus(); ``` Use `Synheart.reattestDeviceAuth()` as an explicit repair action if the server has lost or revoked an otherwise valid local device identity. It refreshes the attestation without rotating the device identity. (`reregisterDeviceAuth()` is deprecated and calls it.) ## Endpoints The platform origin is `https://api.synheart.ai`, but the SDK does **not** bake it in. `SYNHEART_BASE_URL` is empty unless you set it, and with nothing configured the native runtime applies its own default. Set it explicitly on any build that talks to the cloud: ```bash theme={null} flutter run \ --dart-define=SYNHEART_BASE_URL=https://api.example.com ``` Optional service-specific overrides: * `SYNHEART_AUTH_BASE_URL` * `SYNHEART_CONSENT_BASE_URL` * `SYNHEART_INGEST_BASE_URL` > [!WARNING] > > Set `SYNHEART_BASE_URL` rather than relying on a per-service override alone. An > override moves one service; the rest keep resolving through > `SYNHEART_BASE_URL`. Overriding auth by itself points device registration at > one environment while consent and ingest stay on another, which surfaces as > authentication failures with no obvious cause. The values must be origins. The runtime appends service paths. ## Cloud upload Cloud upload requires: 1. `CloudConfig`; 2. `DeviceAuthConfig` in production; 3. `cloudUpload` consent; 4. an issued consent token and a registered device. The runtime uploads on its own. It subscribes to the engine's HSI broadcast, enqueues each closed window, and POSTs on `CloudConfig.uploadInterval`. No host code is required to move data. Inspect the queue and user-facing status: ```dart theme={null} print(Synheart.cloudSyncStatus); print(Synheart.uploadQueueLength); print(Synheart.lastIngestSuccessAtMs); print(Synheart.lastUploadError); final ready = await Synheart.ensureCloudConsentReady(); final result = await Synheart.ingestion.flushIfEligible(); ``` Use `cloudSyncStatus` for user interface copy. Queue depth is more useful for diagnostics than for end users. If HSI is produced but nothing uploads, the cause is almost always a closed consent gate — `lastUploadError` names it. See [Cloud Protocol](/synheart-core/cloud-protocol) for wire-level details. ## Syni chat and sessions Runtime 0.21.0 and later expose device-signed, non-streaming Syni service calls. Configure `SYNHEART_BASE_URL` and register the device before calling them. The SDK keeps the active session id after each successful turn, so subsequent calls continue the same conversation until `startNewSession()`. ```dart theme={null} final syni = Synheart.syni?.service; if (syni != null && syni.isAvailable) { final response = await syni.chat( 'Help me reflect on today', personaId: 'focus.coach.v1', includeState: true, ); final sessions = await syni.listSessions(limit: 20); final messages = await syni.getSessionMessages(response.sessionId); await syni.closeSession(response.sessionId); } ``` Chat calls are serialized because sending is non-idempotent and order matters. If a timeout produces a `SyniServiceException` with `deliveryUnknown == true`, inspect the session messages before offering a retry; resending immediately could duplicate a turn. On an older native runtime `isAvailable` is false and the rest of the SDK continues to work. On-device model installation and streaming chat are covered in [Syni for Flutter](/syni/flutter). ## Errors and diagnostics Configuration validation throws `SynheartError` with a stable `code`. An incompatible runtime throws `SynheartRuntimeException` from `initialize()` (see [Initialization](#initialization)). Lifecycle preconditions commonly throw `StateError`; invalid arguments throw `ArgumentError`; structured runtime failures throw `SynheartNativeException` (sync calls throw its subclass `SyncNativeException`). ```dart theme={null} try { await Synheart.startSession(); } on SynheartError catch (error) { print('${error.code}: ${error.message}'); } on SynheartNativeException catch (error) { if (error.isUnsupported) { // The loaded runtime cannot do this. } else if (error.isMisconfigured) { // Fix configuration before retrying. } else if (error.retryable) { // Offer a retry. } } on StateError catch (error) { print(error.message); } ``` After any native call that failed (returned `null`, `false`, or an error code), `Synheart.lastNativeError` explains it: a `SynheartNativeError` with `code`, `message`, `retryable`, `ownerKind`, `recoveryKind`, `recoveryCall`, `reason`, `argument`, `hint`, `op`, and `errorId`. A call that succeeds clears it. `CoreRuntimeBridge.lastCreateError` says why the runtime handle could not be created. ```dart theme={null} await Synheart.grantConsent(cloudUpload: true); final error = Synheart.lastNativeError; if (error != null) print('${error.code} (${error.errorId}): ${error.message}'); ``` Check runtime health: ```dart theme={null} final diagnostics = Synheart.runtimeDiagnostics(); print(diagnostics['isAvailable']); // bool — native bridge loaded print(diagnostics['version']); // String? — native runtime version print(diagnostics['frameCount']); // int — HSI frames this session print(diagnostics['missingSymbols']); // List print(diagnostics['runtimeError']); // Map? — {kind, message, cause} when unavailable ``` `missingSymbols` lists optional native symbols the loaded runtime does not export. Empty is the healthy state. Anything in it means the vendored runtime predates this SDK release, so the features behind those symbols are disabled and return `null`, `-1`, or an empty list rather than throwing. The list fills lazily, so check it after exercising the features you depend on, or pass `probeAll: true` for a full audit. If `isAvailable` is false, `runtimeError` and its install command say why. If symbols are missing, install the runtime the SDK recommends and check it: ```bash theme={null} synheart install runtime --version 0.46.0 synheart doctor flutter run ``` Then inspect the native linker output and verify the runtime exists under `synheart/vendor/runtime/`. ### Threading Network-touching calls — `syncNow()`, `flushUploads()`, `fetchCloudHsiWindows()`, `requestDataDeletion()`, device registration, and the consent mutations — run on a background isolate and return a `Future`. The per-sample push calls (`pushWearHr`, `pushRr`, `pushAccel`, `tick`, `ingestBatch`) are synchronous and safe on the UI isolate at sensor rates. Diagnostic getters are cheap synchronous FFI reads, but they are still FFI calls: do not poll them per frame. ## Testing ```bash theme={null} flutter test flutter analyze --no-fatal-infos ``` The SDK repository includes a complete example application. It runs without cloud credentials, so it needs no platform account — only the installed native artifacts: > [card] [Flutter example application](https://github.com/synheart-ai/synheart-core-flutter/tree/main/example) > > Initialization, consent, sessions, HSI, watch integration, and runtime diagnostics ## Upgrading Notable changes since 0.10: | Version | Change | | - | - | | 0.23.0 | Requires `synheart_wear` 0.6.2, which asks for health **read** access only; apps that don't write health data can drop `NSHealthUpdateUsageDescription` and the Health Connect `WRITE_*` permissions. HSI is delivered when any collection consent (or research) is granted, not only biosignals. `srmPushWearableDaily` and `srmRefreshWearableReference` build the pipeline first, so values pushed with no session running are no longer refused. Resting HR and mean HR asleep are pushed apart. Steps are pushed only for finished days. Garmin `hrv.updated` carries last night's average. | | 0.22.1 | Install hints recommend runtime 0.46.0, which reports each output no finer than your HSM Schema declares and enforces its `retention`. Runtimes from 0.45.0 still load. | | 0.22.0 | **Breaking:** requires runtime 0.45.0 or later (C ABI 4.2). `ReadinessScoreInput.baselineDays` is now `baselineMaturity` (`0..1`); `SleepScoreInput` gains `tonightMidpointH` and `baselines`; `RecoveryScoreInput.baselines` comes from `dailyBaselineRefs()`. Added `dailyBaselineRefs()`, `dailySleepBaselines()`, `DailyMetric.overnightHrBpm`, `activeMin` and `restRmssdMs`, and `SynheartConfig.modelBackend`. | | 0.21.0 | Install hints recommend runtime 0.43.0 (C ABI 4.1). Added `schemaNeedsConsent()` and `hsmSchemaConsent()`. Runtime 0.42.x still loads. | | 0.20.0 | **Breaking:** requires runtime 0.42.0 or later (C ABI 4.0); install hints recommend 0.42.1. `rollDay()` removed (the engine closes each day; `attachClosedDayStrain()` added). SRM and longitudinal snapshot calls replaced by `exportBaselineSnapshot()` / `loadBaselineSnapshot()`; the runtime persists the baselines itself. `srmPushWearableDaily` takes a provider, a `DailyMetric` name and a local date; `srmTriggerWearableRecompute` is `srmRefreshWearableReference`. Added input-capture reporting, `setCallActive`, `pushInputsJson` and the baseline read-outs. `device_class` defaults to `"auto"`. See [Personal baselines and daily scores](#personal-baselines-and-daily-scores). | | 0.19.0 | **Breaking:** `getSyncStatus()` removed (use `syncStatus()`); `ReadinessScoreInput` takes `recoveryScore` and `sleepScore`. Added `attachRecoveryScore()`, `attachReadinessScore()` and `syncPairingStatus(token)`. | | 0.18.1 | Install hints recommend runtime 0.41.0. | | 0.18.0 | `SynheartConfig.strictChannelConsent`: the runtime accepts a sample only when its own consent channel is granted. Collectors follow the runtime's per-channel decision live. `CoreRuntimeBridge.wellnessJson()` deprecated. | | 0.17.2 | iOS: the runtime's data directories are excluded from iCloud and device backup. | | 0.17.1 | Requires `synheart_auth` ^0.1.12, which recovers an Android secure store restored from a backup. | | 0.17.0 | **Breaking (behavior):** `initialize()` throws `SynheartRuntimeException` for an incompatible runtime. Added `Synheart.runtimeError`, `Synheart.lastNativeError`, `SynheartNativeException`, `CoreRuntimeBridge.lastCreateError`. Runtime C ABI 2.x accepted; install hints recommend runtime 0.38.0. Research mode forwards raw phone motion by default. Requires `synheart_behavior` 0.4.1 (50 Hz Android accelerometer; merges a notification listener service and `READ_PHONE_STATE`). | | 0.16.1 | `SynheartInstance.createAsync`. Requires `synheart_wear` 0.5.1. | | 0.16.0 | `Synheart.ingestStatus()`, `labEnsureMetadataAsync`, `WearConfig.autoStartPlatformHealth`. | | 0.15.0 | `SynheartInstance` can receive every HSI window it completes; `Synheart.runtimeBehaviorEventStream`; `HostDeclarations.notificationsObservable`. Requires `synheart_session` ^0.3.0. | | 0.14.0 | Runtime version check at startup; buffered HSI delivery. **Breaking:** `Synheart.pushContextEvent` takes a `ContextEventInput`. Accelerometer samples are converted to g. Foreground app reporting (`BehaviorConfig.reportForegroundApp`). | | 0.13.0 | **Breaking:** Device Sync calls that touch the network are now async (`await` them). Added `reattestDeviceAuth()`, `logoutDeviceAuth()`, `ensureDeviceAuthRegisteredOrThrow()`; `reregisterDeviceAuth()` deprecated. | | 0.12.0 | Added device-signed Syni chat and session APIs under `Synheart.syni?.service`, requiring a native runtime of 0.21.0 or later. | | 0.11.1 | Android `compileSdk` raised to 36. `minSdk` is unchanged at 24. | | 0.11.0 | **Breaking:** the SDK no longer bakes in an API host — set `SYNHEART_BASE_URL`. Added the digital HSI axes and richer `SyncNativeError` reasons. `runtimeDiagnostics()` dropped `lastQuality` and gained `missingSymbols`. `Synheart.deleteCloudData()` now throws `UnsupportedError`; use `requestDataDeletion()` with `wipeLocalData()`. | The bundle-secret configuration fields — `SynheartConfig.capabilityToken` and `.capabilitySecret`, `CloudConfig.apiKey`, and `ConsentConfig.appApiKey` — are deprecated and pending removal. The native runtime dropped bundle-secret configuration as a security fix, so these values are no longer forwarded to it. Use `deviceAuthConfig` instead, and never ship an API key or signing secret inside an application bundle. See the [changelog](https://github.com/synheart-ai/synheart-core-flutter/blob/main/CHANGELOG.md) for the full list. ## Advanced APIs The package also provides: * local session storage and retention; * cross-device sync and baseline transfer; * sleep, recovery, readiness, resilience, and breathing models; * Apple Health and Health Connect backfill; * watch-to-phone `EdgeIngest`; * lab protocols and research-study enrolment; * secondary `SynheartInstance` runtime handles; * Syni adaptive AI integration. Start with the lifecycle above. Integrate advanced APIs only when your product needs them: > [card] [Architecture](/synheart-core/architecture) > > Runtime, modules, and data flow > [card] [Consent System](/synheart-core/consent-system) > > Consent channels and JWT lifecycle > [card] [Scoring Models](/synheart-core/scoring) > > Sleep, recovery, and readiness > [card] [Health Backfill](/synheart-core/health-backfill) > > Historical HealthKit and Health Connect import ## Resources * [Flutter SDK repository](https://github.com/synheart-ai/synheart-core-flutter) * [pub.dev package](https://pub.dev/packages/synheart_core) * [Generated Dart API](https://pub.dev/documentation/synheart_core/latest/) * [Issue tracker](https://github.com/synheart-ai/synheart-core-flutter/issues) # Health backfill Source: https://docs.synheart.ai/synheart-core/health-backfill Seed the personal baselines from the history already in Health Connect or HealthKit. ## Overview Most people install your app with months of sleep and heart data already in their phone's health store. A one-time backfill reads that history and pushes it into the [personal baselines](/synheart-core/srm), so "your normal" is ready on day one instead of warming up over the first week. | Platform | Source | Class | | - | - | - | | **Android** | Health Connect | `HealthConnectRuntimeSink` | | **iOS** | HealthKit | `HealthKitRuntimeSink` | | **iOS** | Apple Health `export.zip` | `AppleHealthRuntimeSink` (Flutter, Swift) | How far back it reaches depends on what the store kept: on Android typically about 30 days of heart rate and 1–2 years of sleep; on iOS often years. ## What gets pushed Each night's values are filed under the local date the person woke on: | Value | Daily metric | | - | - | | Total sleep, in seconds | `sleep.duration_s` | | Deep sleep, in minutes | `sleep.deep_min` | | REM sleep, in minutes | `sleep.rem_min` | | Sleep midpoint, hours after local midnight (Flutter; needs start and end times) | `sleep.midpoint_h` | | Overnight RMSSD, in ms (from samples taken asleep) | `cardiac.overnight_rmssd_ms` | | Mean heart rate asleep, in bpm | `cardiac.overnight_hr_bpm` | | Resting heart rate, in bpm | `cardiac.resting_hr_bpm` | The Flutter Health Connect sink also pushes `motion.steps_count` and `motion.active_min` for each day that is over, including days with no night. A missing value is skipped, never sent as zero. **Resting HR.** Flutter `synheart_core` 0.23 pushes the store's resting-HR record as `cardiac.resting_hr_bpm` and the mean HR asleep as `cardiac.overnight_hr_bpm`, using the asleep mean for resting only when there is no record. The Kotlin and Swift sinks (0.6 and later) push the asleep mean as both. > [!NOTE] > > These names are used from Flutter `synheart_core` 0.20 and Kotlin and Swift > 0.5 (runtime 0.42); `cardiac.overnight_hr_bpm` and `motion.active_min` from > Flutter 0.22 and Kotlin and Swift 0.6 (runtime 0.45). Earlier SDKs pushed > `sleep_need`, `deep_sleep_min`, `rem_sleep_min`, `hrv_rmssd` and `resting_hr`, > which runtime 0.42 and later refuse. Before Flutter 0.23 a backfill run with no > session open was refused value by value; `daysIngested` and `dimensionsPushed` > count only accepted values (since Flutter 0.22). ## Run it Call it once, after the user grants the health permission **and** biosignals consent. A year of history can take 10 seconds or more on the first run. ```dart Flutter theme={null} // Android: Health Connect final result = await HealthConnectRuntimeSink().backfill(daysBack: 365); print('seeded ${result.daysIngested} days'); ``` ```kotlin Kotlin theme={null} // reader comes from synheart-wear-kotlin val reader = HealthConnectAdapter(context) val sink = HealthConnectRuntimeSink(reader = reader, bridge = Synheart.runtimeBridge) val result = sink.backfill(daysBack = 365) println("seeded ${result.daysIngested} days") ``` ```swift Swift theme={null} // reader comes from synheart-wear-swift let sink = HealthKitRuntimeSink( reader: HealthKitHistoryReader(), pushDaily: { provider, metric, year, month, day, value, vendorSummary in let date = Calendar.current.date(from: DateComponents(year: year, month: month, day: day))! return Synheart.srmPushWearableDaily( provider: provider, metric: metric, date: date, value: value, vendorSummary: vendorSummary) }, triggerRecompute: { Synheart.srmRefreshWearableReference() } ) let result = try await sink.backfill(daysBack: 365) print("seeded \(result.daysIngested) days") ``` The result tells you how many days were stored (`daysIngested`), how many values (`dimensionsPushed`), and, when nothing ran, why (`skipped`, `skipReason`, for example "Health Connect not available on this device"). ## When not to call it * **Before permission or consent.** Without the health permission the sink returns `skipped: true`; without biosignals consent the person hasn't agreed to their history being used. * **On every launch.** Pushing the same day twice only replaces it, but reading the health store each launch is wasteful. Run it on first launch, and again after a long gap. ## Related * [Baselines](/synheart-core/baselines): what these values feed * [Scoring models](/synheart-core/scoring): what is computed once baselines are warm * [synheart-wear](/synheart-wear/overview): the health-store readers # HSI in Synheart Core Source: https://docs.synheart.ai/synheart-core/hsi-specification How Synheart Core consumes HSI 1.3 payloads emitted by flux (after the inference engine produces HSV) The **Human State Interface (HSI)** is the canonical interchange format for human-state outputs. It is a separate, language-agnostic specification ([github.com/synheart-ai/hsi](https://github.com/synheart-ai/hsi), currently version **1.3**) that is not owned by this SDK. In the Synheart engine pipeline, HSI is the wire format that **flux** produces from **HSV** (the typed inference output of the Synheart Runtime). The SDK is a *consumer* of HSI: it receives HSI JSON from the Synheart runtime (which embeds the engine pipeline) and exposes it as typed events. For the canonical contract, see the [HSI overview](/hsi/overview) on this site or the [hsi repository](https://github.com/synheart-ai/hsi). ## Pipeline, recap ```text theme={null} feature pipeline ──► FeatureSet inference engine ──► HSV[] + 64D embedding (see HSV Specification) flux ──► HSI 1.3 JSON payload Synheart runtime broadcasts the HSI JSON SDK exposes: Synheart.onHSIUpdate (raw JSON), Synheart.onStateUpdate (typed) ``` The SDK does not produce HSI itself — flux does. The SDK does not validate HSI either; it parses leniently and exposes a typed view. For the upstream typed shape, see [HSV Specification](/synheart-core/hsv-specification). ## Where HSI enters Synheart Core ```text theme={null} flux emits HSI window │ ▼ Synheart runtime broadcasts the window (raw JSON + timestamp) │ ▼ SDK listener (registered by Synheart.initialize) │ ├── Synheart.onHSIUpdate → Stream (raw JSON) └── Synheart.onStateUpdate → Stream (typed) ``` ## Typed view: `HSIState` ```dart theme={null} class HSIState { final String subjectId; final int timestampMs; final HSIAxes hsi; final Modalities modalities; final Tiers tiers; final String rawJson; // preserved for diagnostic use } ``` `HSIState.fromJson(json)` extracts: * `timestampMs` from `timestamp_ms` or `observed_at_ms`. * `subjectId` from `subject_id`. * `hsi` from the canonical HSI 1.3 domain arrays when `hsi_version == "1.3"`. Older payloads fall back to the legacy flat `hsi.` representation. * `modalities` derived from `meta.provenance.sources[*].signals` per the Synheart signal-modality mapping contract. * `tiers` derived from per-source `source_tier` (physiological) and `meta.synheart.tiers.{kinematic, digital}`. `rawJson` is preserved on every state so apps that need full payload access can read it directly. ## Axes (`HSIAxes`) The current Flutter SDK exposes eight axis-shaped accessors: ```dart theme={null} class HSIAxes { final HSIAxisValue? focus; final HSIAxisValue? arousal; final HSIAxisValue? capacity; final HSIAxisValue? sleep; final HSIAxisValue? stress; // Digital axes (`axes.digital[]`, HSI 1.3 only) - derived from interaction // events, so these are the axes that resolve with no wearable attached. final HSIAxisValue? focusQuality; final HSIAxisValue? interruptionPressure; final HSIAxisValue? interactionMode; } class HSIAxisValue { final double value; // 0.0..1.0 final double confidence; // 0.0..1.0 } ``` These map onto the HSV heads emitted upstream: | HSI axis (`HSIAxes` field) | HSV head (`HsvType`) | | - | - | | `focus` | `Focus` | | `arousal` | `Emotion.arousal` (one component of the `Multiscalar` value) | | `capacity` | `Capacity` | | `sleep` | `Sleep` | | `stress` | Multimodal stress reading in `axes.affective[]` (HSI 1.3) | | `focusQuality` | `axes.digital[focus_quality]` (HSI 1.3) | | `interruptionPressure` | `axes.digital[interruption_pressure]` (HSI 1.3) - `direction: lower_is_more` | | `interactionMode` | `axes.digital[interaction_mode]` (HSI 1.3) - `direction: bidirectional` | The HSI 1.3 canonical *domain* set is `physiological / kinematic / digital / cognitive / affective` — those describe the **modalities** that produced a reading, not the head identity. Head names (focus, capacity, etc.) appear as `axis_reading.axis` strings under those domains. Missing axes are `null` (not zero). ## Modalities ```dart theme={null} class Modalities { final bool physiological; final bool kinematic; final bool digital; } ``` Use these to gate UX — for example, drop physiology copy when `physiological == false`. ## Tiers ```dart theme={null} class Tiers { final int? physiological; // 1..=4 from source.source_tier (HSV's source_tier) final int? kinematic; // 1..=3 from meta.synheart.tiers.kinematic final int? digital; // 1..=3 from meta.synheart.tiers.digital } ``` Lower number = higher fidelity. The tier values originate on the upstream `Hsv.tiers` (`TierBundle`); flux carries them into the HSI envelope. ## Modality / tier derivation in the SDK Signal-name → modality mapping (used by `HSIState.fromJson` when reading flux output): | Signal name | Modality | | - | - | | `hr`, `hrv`, `rr`, `ecg`, `spo2`, `respiration`, `temperature`, `eda` | `physiological` | | `accel`, `gyro`, `motion`, `posture`, `step` | `kinematic` | | `tap`, `scroll`, `swipe`, `key`, `notification`, `app`, `screen` | `digital` | Source tier walk: physiology takes the worst-numbered tier across sources emitting any physiological signal (lowest-fidelity source wins for the modality). ## Validation The SDK does not enforce HSI schema validation — that lives with the producer (flux) and any cloud consumer. Apps that need strict validation can cross-check `rawJson` against `hsi-1.3.schema.json` before consuming. The HSI repo defines two validation levels: * **HSI-VALIDATE-BASIC** — structural + range checks against the JSON Schema for the claimed `hsi_version`. * **HSI-VALIDATE-STRICT** — cross-field integrity (references, time ordering, dimension checks). ## Embedding presence The 64D Johnson-Lindenstrauss embedding from the inference engine is forwarded into `embeddings[]` on the HSI envelope when capability level and HSI version permit. The SDK's typed `HSIState` does not surface the embedding directly — apps that need it parse `rawJson`. ## Subscribing ```dart theme={null} StreamSubscription? sub; @override void initState() { super.initState(); sub = Synheart.onStateUpdate.listen((state) { setState(() { _arousal = state.hsi.arousal?.value; _hasPhysio = state.modalities.physiological; }); }); } @override void dispose() { sub?.cancel(); super.dispose(); } ``` The stream is `BehaviorSubject`-backed: late subscribers receive the latest value. `Synheart.currentHSIState` is also exposed for synchronous access. ## Privacy posture HSI by design carries no PII (`privacy.contains_pii = false`). The runtime hashes `subject_id` before emit; cloud-bound HSI carries `subject_hash`, not the SDK-supplied `subjectId`. The 64D JL embedding is privacy-preserving by construction — the random projection is non-invertible, so the original HSVs cannot be reconstructed from the embedding alone. ## Related * [HSV Specification](/synheart-core/hsv-specification) — the typed upstream shape produced by the inference engine. * [HSI overview](/hsi/overview) — canonical contract, schemas, RFCs HSI-0008/0010/0011. * [Architecture](/synheart-core/architecture) — full data flow. * [Cloud Protocol](/synheart-core/cloud-protocol) — what HSI actually carries upstream. # HSV — Human State Vector Source: https://docs.synheart.ai/synheart-core/hsv-specification The canonical typed output of the Synheart Runtime, before flux packs it into HSI **HSV (Human State Vector)** is the typed intermediate representation in the Synheart engine pipeline. It is what the Synheart Runtime emits from each inference head. **Flux** is the engine component that packs HSVs into HSI 1.3 payloads for the wire. This page documents the canonical `Hsv` struct emitted by the Synheart Runtime's inference engine. ## Pipeline placement ```text theme={null} raw signals │ ▼ feature pipeline ──► FeatureSet (60s window, 5s step, signal tiers) │ ▼ inference engine ──► InferenceOutput (HSV[] + 64D embedding) │ - 6 cognitive/physio heads │ - 1 motion/posture head ▼ flux ──► HSI 1.3 payload (canonical wire format) ``` `Hsv` is what the Synheart Runtime emits per inference head. Flux consumes `InferenceOutput` (or `&[Hsv]`) and produces an HSI payload via `HsiBuilder::build_from_output(...)`. ## The seven canonical heads `HsvType` enum (all caps on the wire, snake\_case in JSON): | Head | Group | Output shape | | - | - | - | | `Emotion` (`EMOTION`) | Primary cognitive | `Multiscalar` — typically `[("valence", v), ("arousal", a)]`. | | `Focus` (`FOCUS`) | Primary cognitive | `Scalar` in `[0, 1]`. | | `Capacity` (`CAPACITY`) | Primary cognitive | `Scalar` in `[0, 1]`. | | `Sleep` (`SLEEP`) | Physiological context | `Scalar` plus optional `breakdown` (`SleepScore.components`). | | `Recovery` (`RECOVERY`) | Physiological context | `Scalar`. | | `Strain` (`STRAIN`) | Physiological context | `Scalar`. | | `MotionState` (`MOTION_STATE`) | Behavioral context | `Multiscalar` indicator + `notes` carrying `LAYING / SITTING / STANDING / MOVING / UNKNOWN`. | The inference engine can be configured to enable a subset; default is all six core heads + MotionState. ## `Hsv` struct ```text theme={null} pub struct Hsv { pub hsv_id: Option, // optional deterministic id pub hsv_type: HsvType, // which head emitted this pub value: HsvValue, // Scalar | Multiscalar pub confidence: f64, // [0, 1] — quality-adjusted, tier-capped pub window: WindowRef, // { start_ms, end_ms, aggregation } pub inference: InferenceMetadata, // mode, engine, engine_version, model_id, model_version, components pub providers: Vec, // e.g. ["garmin", "whoop"] pub source_tier: u8, // physiological fidelity tier pub tiers: TierBundle, // per-modality tier bundle (HSI 1.3) pub breakdown: Option>, // sub-components (e.g. SleepScore parts) pub notes: Option, // human-readable notes (forwarded to HSI axis_reading.notes) } pub enum HsvValue { Scalar(ScalarValue), // single value clamped to [0, 1] Multiscalar(Vec<(String, f64)>), // named scalars, each [0, 1] } ``` ## HSV invariants `Hsv::validate()` enforces: * `confidence ∈ [0, 1]`. * Every scalar value in `value` (whether `Scalar` or each entry of `Multiscalar`) is in `[0, 1]`. * `window.end_ms > window.start_ms`. Higher values mean *more of the named property*. **Axis inversion is forbidden across versions** — once a head emits `focus` where higher means more focus, it cannot flip semantics. ## Tier-capped confidence The inference engine caps `confidence` by signal fidelity tier so proxy signals never over-report certainty: | Tier | Source | Max confidence | | - | - | - | | Tier 1 | Native RR ground truth | ≤ 1.0 | | Tier 2 | Vendor HRV (RMSSD/SDNN/stress/recovery) | ≤ 0.9 | | Tier 3 | HR series | ≤ 0.7 | | Tier 4 | HR snapshot | ≤ 0.5 | | Tier 0 | No physiological signal | (head-dependent; typically rulepack only) | The Tier-4 ONNX guard short-circuits Emotion/Focus/Capacity to rulepack inference when the window carries fewer than 5 HR samples — no probabilistic inference on single-snapshot signals. The per-modality `TierBundle` is the canonical 1.3 carrier; the `source_tier` field on `Hsv` mirrors its `physiological` entry for convenience. ## 64D Johnson-Lindenstrauss embedding `InferenceOutput.embedding` carries a **64-dimensional**, **L2-normalized**, **deterministic**, **non-invertible** projection of the HSVs: ```text theme={null} pub struct EmbeddingOutput { pub vector: Vec, // 64 dims, ‖v‖₂ = 1 pub space: &'static str, // "synheart-jl-64" pub dims: u32, // 64 pub encoding: &'static str, // "float32" pub vector_hash: Option, // sha256: integrity tag } ``` Properties: * Always 64 dims. * Always L2-normalized to unit norm. * Deterministic — identical HSVs produce byte-identical vectors. * Privacy-preserving — Johnson-Lindenstrauss random projection is non-invertible: you cannot reconstruct the underlying HSVs from the embedding. Flux consumes the embedding pre-computed via `HsiBuilder::build_from_output(InferenceOutput)`. The fallback path `HsiBuilder::build(&[Hsv])` recomputes the embedding from HSVs — same result, just an extra projection step. When the embedding reaches the HSI payload, capability level + HSI version control whether it appears in the output. ## InferenceOutput ```text theme={null} pub struct InferenceOutput { pub hsvs: Vec, pub embedding: EmbeddingOutput, } ``` Inference engine entry points: | Method | Purpose | | - | - | | `StateRuntime::infer(features, baseline_present)` | HSV-only inference; returns `Vec`. | | `StateRuntime::infer_with_embedding(features, baseline_present)` | Returns `InferenceOutput` (HSV + 64D embedding). | | `StateRuntime::infer_with_personalization(features, ctx)` | HSV inference with personalization context. | | `StateRuntime::infer_with_embedding_personalization(...)` | Both, with personalization. | | `StateRuntime::infer_head(head, features, baseline_present)` | Single-head inference. | ## HSV → HSI mapping (Flux) `HsiBuilder` (in the flux engine component): 1. Takes `&[Hsv]` plus the embedding vector + optional integrity tag. 2. Maps each HSV onto an HSI axis reading via `flux::export::map_axes(hsvs, window_ids, default_source_ids)`. 3. Writes `evidence_source_ids` from `hsv.providers` (or the builder's defaults when providers is empty). 4. Forwards `breakdown` entries as one HSI `axis_reading` per component. 5. Forwards `notes` to `axis_reading.notes`. 6. Carries the 64D embedding into `embeddings[]` if capability/policy permits. 7. Stamps `source_tier` and `tiers` into the HSI envelope. 8. Returns a validated `HsiPayload`. | Method | Purpose | | - | - | | `build(&[Hsv])` | Compute embedding + build HSI. | | `build_from_output(&InferenceOutput)` | **Preferred.** Use the pre-computed embedding from the inference engine. | | `build_json(&[Hsv])` / `build_json_from_output(...)` | Same, plus pretty-printed JSON. | ## Why HSV exists alongside HSI | Layer | Type | Optimised for | | - | - | - | | HSV (`Hsv`) | in-process, typed, head-shaped | Fast, deterministic, type-safe inference inside the Synheart Runtime; downstream in-runtime consumers (personalization, scoring) consume `Hsv` directly without going through JSON. | | HSI 1.3 | JSON wire format, multi-language, version-stable | Cross-process, cross-platform, cross-vendor interchange; canonical contract per [hsi repo](https://github.com/synheart-ai/hsi). | Flux is the boundary that converts the in-process typed shape into the wire shape. Producers that don't run the Synheart Runtime can still emit HSI directly; SDK consumers never see HSV — they only ever see HSI 1.3 JSON. ## What the Synheart Core SDK exposes The SDK does not expose `Hsv` directly to host code (Dart/Kotlin/Swift). It exposes: * The HSI JSON via `Synheart.onHSIUpdate` — what flux emitted. * Typed `HSIState` (axes, modalities, tiers) via `Synheart.onStateUpdate` — parsed from the HSI JSON; see [HSI in Synheart Core](/synheart-core/hsi-specification). Apps that need direct `Hsv` access integrate at the runtime / engine level — typically only research-tier integrations. ## Related * [HSI in Synheart Core](/synheart-core/hsi-specification) — the wire contract HSV is packed into. * [Architecture](/synheart-core/architecture) — full pipeline diagram. * [HSI overview](/hsi/overview) — canonical HSI spec. # Synheart Core - Android/Kotlin SDK Source: https://docs.synheart.ai/synheart-core/kotlin Install and integrate Synheart Core 0.4 in an Android application ## What this SDK does Synheart Core connects an Android app to the native Synheart Runtime. It: * collects user-consented wearable, phone, and behavior signals; * sends those signals to the on-device runtime; * exposes Human State Interface (HSI) 1.3 output as Kotlin Flows; * optionally stores, synchronizes, and uploads derived state. The Kotlin library handles platform concerns only: Health Connect and BLE collection, Android Keystore, `EncryptedSharedPreferences`, Flow streams, and Jetpack integration. Human-state computation, storage, device authentication, and sync run in the separately installed native runtime. > [!NOTE] > > HSI is the public output. Most applications should use > `Synheart.onStateUpdate` for typed values or `Synheart.onHSIUpdate` for the > canonical JSON. Internal HSV types do not cross the public SDK boundary. ## Requirements | | | | - | - | | `minSdk` | **26** | | `compileSdk` | 35 | | Java / Kotlin JVM target | 17 | | Core library desugaring | Required | | Native runtime | Provisioned by the Synheart CLI, not bundled in the AAR | The library module declares `minSdk 24`, but it depends on `ai.synheart:syni`, whose manifest declares 26. A library never runs the full manifest merge, so the conflict appears only when an **application** builds against it. Set your app to 26. ## Installation ### 1. Add the dependency ```gradle theme={null} dependencies { implementation 'ai.synheart:synheart-core:0.8.0' coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4' } android { defaultConfig { minSdk 26 } compileOptions { coreLibraryDesugaringEnabled true sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } } ``` ### 2. Install the native runtime The library alone loads no runtime and produces no HSI. Install and authenticate the CLI once, then provision the runtime from your application root: ```bash theme={null} curl -fsSL https://synheart.sh/install | bash synheart login synheart install runtime --version 0.46.0 ``` SDK 0.8.0 is verified against runtime `0.46.0` and needs `0.45.0` or later (C ABI 4.2). An older runtime is refused at initialization. SDK 0.5 needs `0.42.0` or later; SDK 0.4.x and earlier need `0.38.0`. Commit the generated `synheart.lock`, which pins each artifact by SHA-256. Other developers and CI restore the pinned artifacts with `synheart sync`. The CLI writes the binaries to `/synheart/vendor/runtime/android/jniLibs//`. AGP reads only `src/main/jniLibs`, so point your module at the vendored path: ```gradle theme={null} android { sourceSets { main { jniLibs.srcDirs = [ project.findProperty('synheart.runtime.android.jniLibs') ?: new File(projectDir, 'synheart/vendor/runtime/android/jniLibs') .absolutePath ] } } } ``` > [!WARNING] > > Without the `jniLibs.srcDirs` entry the APK builds cleanly and ships no > runtime. Every FFI call then degrades to "native library not loaded" with no > build-time error. ### 3. Declare permissions Declare only the permissions required by the sources you enable: ```xml theme={null} ``` Keep app data out of Android backups: the runtime's secure store is sealed with a device-bound key that a restored copy cannot use. Set `android:allowBackup="false"` and `android:dataExtractionRules` on the ``. (Since 0.4.1, if a restored store cannot be decrypted, the SDK recreates it empty instead of failing on every secure read.) Health Connect also requires package queries, a permission-rationale intent filter, and a permission-usage activity alias. Copy the applicable declarations from the [example manifest](https://github.com/synheart-ai/synheart-core-kotlin/blob/main/example/src/main/AndroidManifest.xml). ### 4. Verify before writing integration code ```kotlin theme={null} println(Synheart.isRuntimeAvailable) // true once the bridge loaded println(Synheart.runtimeDiagnostics()?.opt("missingSymbols")) // empty on a matching runtime ``` `isRuntimeAvailable == false` means the runtime is not loaded, and `Synheart.runtimeError` says why (`NOT_INSTALLED`, `WRONG_ARCHITECTURE` or `LOAD_FAILED`, with the `installCommand` that fixes it). A non-empty `missingSymbols` means the runtime loaded but predates this SDK release, so the features behind those symbols return null or false rather than throwing. ## Start here The minimum integration has five steps: 1. Initialize the SDK. 2. Ask the user for consent. 3. Subscribe to HSI output. 4. Start a collection session. 5. Stop the session and release resources. ```kotlin theme={null} import ai.synheart.core.Synheart import ai.synheart.core.config.SynheartConfig import ai.synheart.core.config.WearConfig import ai.synheart.core.config.BehaviorConfig lifecycleScope.launch { Synheart.initialize( context = applicationContext, config = SynheartConfig( appId = "com.example.app", subjectId = "user-123", appVersion = "1.0.0", allowUnsignedCapabilities = true, // Development only. wearConfig = WearConfig(), behaviorConfig = BehaviorConfig(), ), ) Synheart.grantConsent("biosignals") Synheart.grantConsent("behavior") launch { Synheart.onStateUpdate.collect { state -> println("Focus: ${state.hsi.focus?.value}") println("Arousal: ${state.hsi.arousal?.value}") } } Synheart.startSession() } // When finished: lifecycleScope.launch { Synheart.stopSession() Synheart.dispose() } ``` > [!WARNING] > > `allowUnsignedCapabilities = true` bypasses production capability > verification. Never enable it in a release build. ## Initialization `SynheartConfig.validate()` requires a non-empty `appId`, a non-empty `subjectId`, a `subjectId` without `|`, and `PrivacyConfig(allowResearch = true)` when using research mode. It throws `SynheartCoreError` before the runtime is touched. `subjectId` is the identity everything attaches to — HSI uploads, baselines, consent tokens, device identity. A value that changes per launch looks like a new person every time and baselines never mature. Passing `userId` to `initialize()` does **not** populate it; set it on the config. `initialize()` throws `SynheartRuntimeException` (`kind = INCOMPATIBLE`) when the installed runtime cannot be used with this SDK: a C ABI other than 4.2 or a later 4.x, a runtime older than 0.45.0, or a library that does not report its build info. Its `installCommand` is the exact command that fixes it. A missing runtime does not throw; see `Synheart.runtimeError` above. `initialize()` is idempotent: a second call returns without throwing. Guard with `Synheart.isInitialized` if you need to know. It does not start collection — call `startSession()` once consent is ready, or pass `autoStart = true` when consent is already complete. ### Modes | Mode | Persistence | | - | - | | `SynheartMode.PERSONAL` | HSI, session summaries, and baselines | | `SynheartMode.INSIGHT` | Personal-mode data plus application metrics | | `SynheartMode.RESEARCH` | Can include raw bio streams; requires explicit privacy configuration and consent. Forwards 50 Hz raw accelerometer samples to the runtime by default. | When the signed-in identity changes, keep the runtime identity aligned without reinitializing: ```kotlin theme={null} val changed = Synheart.rebindSubjectId("new-subject-id") ``` ### Running without cloud credentials The SDK is usable with no platform account. Omit `CloudConfig` and `DeviceAuthConfig`, and everything on-device works: collection, HSI computation, consent, local storage, and baselines. Nothing leaves the device and no attestation is attempted. HSI upload, cross-device sync, research-study enrolment, and server-issued capability tokens are unavailable in this configuration. ## Consent Consent and capability are different: * **Capability** says what the application is authorized to use. * **Consent** says what the user allows. Channels are named with camelCase wire strings: `biosignals`, `behavior`, `phoneContext` (`motion` is a long-standing alias), `cloudUpload`, `vendorSync`, `research`, `syni`, `focusEstimation`, and `emotionEstimation`. The runtime keys the same channels in snake\_case; the SDK translates. ```kotlin theme={null} Synheart.grantConsent("biosignals") Synheart.grantConsent("cloudUpload") // mints a consent token as a side effect Synheart.revokeConsent("behavior") Synheart.consentChanges.collect { snapshot -> println("Cloud upload allowed: ${snapshot.cloudUpload}") } ``` Or install your own consent screen and let the SDK apply the profile the user picks — it ships none of its own: ```kotlin theme={null} Synheart.setConsentUIProvider { profiles -> showYourConsentSheet(profiles) } Synheart.requestConsent() ``` > [!WARNING] > > `hasConsent()` reports whether a channel is **enforceable right now**, not what > the user chose. Once a cloud consent client is configured, the runtime denies > every channel until the consent service issues a token. Gate uploads with > `hasConsent()`; render UI from `consentEffectiveStateTyped()`. A missing default consent profile on the platform app is the most common cause of "consent is on but nothing uploads". See [Consent System](/synheart-core/consent-system) for profiles and JWT lifecycle. ## Feature activation and sessions A feature collects data only when **all four** of these hold: ``` operational = activated && consented && capability-allowed && session-running ``` | Authority | Set by | Read with | | - | - | - | | Activated | a module config, or `activate(feature)` | `isActivated(feature)` | | Consented | `grantConsent(type)` | `hasConsent(type)` | | Capability allowed | the capability token, or `allowUnsignedCapabilities` | — | | Session running | `startSession()` | `isSessionRunning` | Miss one and the feature stays silent — there is no error, because none of these is a failure. `Synheart.isFeatureOperational(feature)` collapses all four into one answer; check it first when data is not arriving. Declaring `wearConfig`, `phoneConfig`, or `behaviorConfig` activates that feature. Features may also be activated explicitly: ```kotlin theme={null} Synheart.activate(SynheartFeature.WEAR) Synheart.deactivate(SynheartFeature.CLOUD) ``` | Feature | Purpose | Consent | | - | - | - | | `WEAR` | Wearable biosignals | `biosignals` | | `BEHAVIOR` | Interaction timing and patterns | `behavior` | | `PHONE_CONTEXT` | Motion, screen, and app context | `motion` | | `CLOUD` | HSI cloud upload | `cloudUpload` | | `SYNI` | Adaptive AI integration | `syni` | > [!NOTE] > > Activation is intersected with `deviceRole.supportedFeatures`, so a > `DeviceRole.WATCH` build cannot activate behavior or phone context even if the > config declares them. A host that declares none of the three module configs > collects nothing. Start and stop the full lifecycle with `startSession()` / `stopSession()`, or control individual collectors: ```kotlin theme={null} Synheart.startWearCollection() Synheart.startBehaviorCollection() Synheart.startPhoneCollection() ``` Module-level methods still enforce consent and capability gates. ## Reading HSI ### Typed state ```kotlin theme={null} Synheart.onStateUpdate.collect { state -> val focus = state.hsi.focus val stress = state.hsi.stress if (focus != null) println("Focus ${focus.value}, confidence ${focus.confidence}") if (stress != null) println("Stress ${stress.value}, confidence ${stress.confidence}") } ``` `HSIState` carries `subjectId`, `timestampMs`, `hsi`, `modalities`, `tiers`, `rawJson`, and `parseError`. The axes are the five physiological and fused ones (`focus`, `arousal`, `capacity`, `sleep`, `stress`) plus three digital ones (`focusQuality`, `interruptionPressure`, `interactionMode`). Axis values are null when there is not enough input. Missing means unknown; it does not mean zero. On a phone with no biosignal source the canonical axes arrive at `confidence: 0` — expected, not a fault. Use `state.modalities` to tell "nothing was collected" from "signal arrived, just not physiological", and `HSIAxes.hasDigital` to check whether the window carried a digital axis. `Synheart.currentHSIState` reuses the same parse, so it is cheap to read repeatedly. ### Canonical JSON ```kotlin theme={null} Synheart.onHSIUpdate.collect { hsiJson -> sendToYourConsumer(hsiJson) } ``` `Synheart.currentState` and `HSIState.rawJson` hold the same JSON. See [HSI in Synheart Core](/synheart-core/hsi-specification) for mapping details. ### Raw source streams ```kotlin theme={null} Synheart.wearSampleStream.collect { sample -> println("HR: ${sample.hr}") } Synheart.behaviorEventStream.collect { event -> println("${event.type} at ${event.timestamp}") } ``` Raw streams are consent-gated. Collect them in a lifecycle-aware scope. ## Behavior capture Android has no view-tree hook, so the SDK ships no gesture detector: nothing is observed unless the host forwards its touches. ```kotlin theme={null} override fun dispatchTouchEvent(ev: MotionEvent): Boolean { Synheart.recordTouchEvent(ev) return super.dispatchTouchEvent(ev) } ``` `recordTouchEvent` derives taps and scrolls, including the part that is easy to get wrong: recording per `ACTION_MOVE` floods the aggregator. Interaction alone produces the HSI digital axes, so behavior works on hardware with no wearable. ## Wearable permissions Health Connect gates reads behind a runtime prompt, so a manifest declaration alone leaves the source polling an empty store — every sample arrives carrying nothing, which is indistinguishable from a paired-but-silent wearable. ```kotlin theme={null} if (!Synheart.hasWearPermissions) { val granted = Synheart.requestWearPermissions() // Map if (granted.values.none { it }) { Synheart.openHealthPermissionSettings(context) } } println(Synheart.hasWearSource) // false when no wearConfig was declared ``` ## Watch sessions Added in 0.2.0. The phone drives a session on a paired Wear OS watch over the Wearable Data Layer; the watch owns the session and computes the metrics. Watch heart rate is forwarded into the runtime, so HSI has physiology on a phone with no sensor of its own. ```kotlin theme={null} val status = Synheart.getWatchStatus() // null before initialize() if (status?.canStartSession == true) { Synheart.startWatchSession( SessionConfig( sessionId = "watch_${System.currentTimeMillis()}", mode = SessionMode.FOCUS, durationSec = 10 * 60, ), ) } Synheart.watchSessionEvents.collect { event -> render(event) } println(Synheart.isWatchSessionActive) println(Synheart.watchHrSampleCount) // engine-bound samples, counted separately Synheart.stopWatchSession() ``` Session types come from `ai.synheart:synheart-session`, which this SDK re-exports. Subscribe to `watchSessionEvents` before sending the start command so the watch's first event cannot arrive before anything is listening. > [!NOTE] > > A `WatchStatus(supported = false)` means the device has no watch transport at > all; a null status means the SDK was never initialized. The companion app must > share the phone app's `applicationId` and signature — the Data Layer delivers > only between apps that match on both. For the watch-to-phone artifact contract, see [Edge](/synheart-core/edge). ## Production device authentication ```kotlin theme={null} SynheartConfig( appId = "com.example.app", subjectId = "user-123", deviceAuthConfig = DeviceAuthConfig( authBaseUrl = "https://api.synheart.ai", packageName = "com.example.app", ), cloudConfig = CloudConfig( subjectId = "user-123", orgId = "organization-id", instanceId = "stable-installation-uuid", ), ) ``` The runtime registers a hardware-backed ECDSA identity in the Android Keystore and signs supported requests. No shared secret is required. > [!WARNING] > > `DeviceAuthConfig.packageName` is the installed bundle id, which Play Integrity > verifies against. It is not `SynheartConfig.appId`, the platform-issued > application identifier. Passing the latter fails attestation. Registration is triggered by cloud-upload consent, not by `initialize()`: ```kotlin theme={null} val registered = Synheart.ensureDeviceAuthRegistered() val status = Synheart.coreDeviceAuthStatus() ``` `ensureDeviceAuthRegistered()` returns `false` on a refusal; `ensureDeviceAuthRegisteredOrThrow()` throws `SynheartNativeException` with the server's code instead. Use `Synheart.reattestDeviceAuth()` as an explicit repair action when the server has lost or revoked an otherwise valid local identity. It refreshes the attestation and keeps the same device id, key and sync membership; a refusal throws `SynheartNativeException`. (`reregisterDeviceAuth()` is deprecated and calls it.) See [Synheart Auth](/synheart-auth/overview) for the device-identity flow. ## Endpoints The SDK ships **no built-in API host** — a host baked into the library becomes the destination for any build that forgot to name one, including forks and self-hosted deployments. Resolution order, first non-empty wins: 1. `ApiEndpoints.baseUrlOverride` and the per-service overrides 2. the `synheart.baseUrl` system property 3. the `SYNHEART_BASE_URL` environment variable ```kotlin theme={null} ApiEndpoints.baseUrlOverride = BuildConfig.SYNHEART_BASE_URL ``` With none set, no origin is passed to the runtime and the runtime applies its own default — correct for a local-only build, which makes no network calls at all. Check `apiBaseUrlConfigured(config)` before enabling anything cloud-bound. > [!WARNING] > > Prefer setting the one base URL over a per-service override. Overriding auth > alone points device registration at one environment while consent and ingest > stay on another, which surfaces as authentication failures with no obvious > cause. The values must be origins. The runtime appends service paths. ## Cloud upload Cloud upload requires `CloudConfig` with an `orgId`, `DeviceAuthConfig` in production, `cloudUpload` consent, an issued consent token, and a registered device. The runtime then uploads on its own cadence; no host code moves data. ```kotlin theme={null} when (Synheart.cloudSyncStatus) { CloudSyncStatus.LOCAL_ONLY -> "Nothing leaves the device" CloudSyncStatus.SYNCING -> "Uploading…" CloudSyncStatus.SYNCED -> "Up to date" CloudSyncStatus.PENDING -> "Will sync when ready" } val result = Synheart.ingestion.flushIfEligible() if (!result.success) println(result.errorMessage) // names a closed gate ``` Drive user-facing copy from `cloudSyncStatus` or `lastIngestSuccessAtMs`. `uploadQueueLength` fluctuates on every flush tick and is a diagnostic, not UI. See [Cloud Protocol](/synheart-core/cloud-protocol) for wire-level details. ## Errors and diagnostics `SynheartCoreError` carries a stable machine-readable `code`. Branch on the code rather than the message. ```kotlin theme={null} try { Synheart.initialize(context = this, config = config) Synheart.startSession() } catch (e: SynheartRuntimeException) { // ai.synheart.core.bridge: the installed runtime is incompatible. println("${e.message}\nFix: ${e.installCommand}") } catch (e: SynheartCoreError) { when (e.code) { "ERR_NOT_CONFIGURED" -> println("Missing appId / subjectId") "ERR_SESSION_ACTIVE" -> println("A session is already running") else -> println("${e.code}: ${e.message}") } } catch (e: IllegalStateException) { println("Not startable: ${e.message}") } ``` Common codes: `ERR_NOT_CONFIGURED`, `ERR_INVALID_MODE`, `ERR_RESEARCH_NOT_ALLOWED`, `ERR_SESSION_ACTIVE`, `ERR_NO_ACTIVE_SESSION`, `ERR_STORAGE_DISABLED`, `ERR_SYNC_DISABLED`. Cloud operations throw a `CloudConnectorException` subtype (`ConsentRequiredError`, `TokenExpiredError`, `RateLimitExceededError`, `SchemaValidationError`, `NetworkError`, …). Sync calls throw `SyncNativeException` so the runtime's reason survives (see [Cross-device sync](/synheart-core/sync#errors)): Since 0.7.0 the sync calls that reach the server (`syncNow`, `syncNowRaw`, `syncCreateSpace`, `syncGeneratePairing`, `syncJoinSpace`, `syncRecoverSpace`, `syncLeaveSpace`, `syncListDevices`, `syncRevokeDevice`, `syncDeleteSpace`) are `suspend` and run on `Dispatchers.IO`. Call them from a coroutine: ```kotlin theme={null} try { Synheart.syncNow() } catch (e: SyncNativeException) { when { e.isUnsupported -> disableCloudPermanently() // never possible on this hardware e.isMisconfigured -> reportToDeveloper(e) // a human has to fix setup e.retryable -> scheduleRetry(e.retryAfterMs) else -> showError(e.message) } } ``` Branch on the `is*` helpers rather than `retryable` alone — `retryable` says whether to try again, not whether it can ever work. `SyncNativeException` extends `SynheartNativeException`, so one `catch` handles every structured runtime failure. After any native call that failed, `Synheart.lastNativeError` explains it: a `SynheartNativeError` with `code`, `message`, `retryable`, `ownerKind`, `recoveryKind`, `recoveryCall`, `reason`, `argument`, `hint`, `op`, and `errorId`. A call that succeeds clears it. `CoreRuntimeBridge.lastCreateError` says why the runtime handle could not be created. Check runtime health with `Synheart.runtimeDiagnostics()`, the native runtime's version with `Synheart.runtimeVersion`, and this SDK's own version with `SYNHEART_CORE_VERSION`. To see why an integration stalled, route the runtime's own logs somewhere: ```kotlin theme={null} SynheartConfig( appId = "com.example.app", subjectId = "user-123", runtimeLogEnvFilter = "info", ) ``` Without a filter the runtime logs nowhere, and the silence reads as "nothing happened" rather than "you never asked to be told". ## Upgrading | Version | Change | | - | - | | 0.8.0 | Added `reattestDeviceAuth()` and `ensureDeviceAuthRegisteredOrThrow()`; `reregisterDeviceAuth()` deprecated (it calls `reattestDeviceAuth()`). HSI is delivered when any collection consent (or research) is granted, not only biosignals. A successful registration is no longer reported as a failure, and an already registered device isn't registered again. `srmPushWearableDaily` and `srmRefreshWearableReference` build the pipeline first, so values pushed with no session running are no longer refused. Still needs runtime 0.45.0 or later; recommends 0.46.0. | | 0.7.1 | Install hints recommend runtime 0.46.0 (0.45.0 still loads). `initialize()` no longer throws when `deviceAuthConfig` is set without a capability token. `SynheartAuth.shared` gets the app context first, so it uses Keystore keys and on-disk registration state. | | 0.7.0 | **Breaking:** the sync calls that reach the server are `suspend`. Added `syncPairingStatus(token)`, typed `syncStatus()` and `SynheartFeature.SYNSYNC` (a `when` over `SynheartFeature` needs the new case). | | 0.6.0 | **Breaking:** requires runtime 0.45.0 or later (C ABI 4.2). `ReadinessScoreInput` takes `recoveryScore`, `sleepScore`, an optional `OvernightAlignment` and `baselineMaturity`; `AcuteWorkloadContext`, `FatigueContext`, `HistoryContext` and `fromRecovery` are removed. `SleepScoreInput` gains `tonightMidpointH` and `baselines`. Added `dailyBaselineRefs()`, `dailySleepBaselines()` and `DailyMetric.OVERNIGHT_HR_BPM`, `ACTIVE_MIN`, `REST_RMSSD_MS`. | | 0.5.0 | **Breaking:** requires runtime 0.42.0 or later (C ABI 4.0); install runtime 0.42.1. `rollDay()` removed (`attachClosedDayStrain()` added); SRM and longitudinal snapshot calls replaced by `exportBaselineSnapshot()` / `loadBaselineSnapshot()`, and the runtime now saves the baselines itself. `srmPushWearableDaily` takes a provider, a `DailyMetric` name and a `LocalDate`. Health Connect backfill and vendor events now reach the baselines. Device registration works on devices without StrongBox (`synheart-auth` 0.1.5). See [SRM](/synheart-core/srm). | | 0.4.1 | Recovers an Android secure store restored from a backup. Set `allowBackup="false"` and `dataExtractionRules` anyway. | | 0.4.0 | **Breaking (behavior):** `initialize()` throws `SynheartRuntimeException` for an incompatible runtime (catch it explicitly: it is not an `IllegalStateException`). Added `Synheart.runtimeError`, `Synheart.lastNativeError`, `SynheartNativeException`, `CoreRuntimeBridge.lastCreateError`. Runtime C ABI 2.x accepted; install hints recommend runtime 0.38.0. Research mode forwards 50 Hz raw accelerometer samples by default. `PhoneModule` collectors no longer emit fabricated data; their summary getters were removed. | | 0.3.1 | `initialize()` creates the runtime off the main thread; `SynheartInstance.createAsync`. | | 0.3.0 | `SynheartInstance` can receive every HSI window it completes; `Synheart.runtimeBehaviorEvents`; `HostDeclarations.notificationsObservable`; `pushWristAccel` / `pushWornAccel`; `WearConfig.autoStartPlatformHealth`; runtime version check at startup; buffered HSI delivery. | ### Upgrading to 0.2.0 | Change | What to do | | - | - | | **Breaking:** module activation now follows the config. | Declare `wearConfig`, `phoneConfig`, or `behaviorConfig` for the collectors you want. A host that declares none collects nothing. | | **Breaking:** no built-in API host. | Set `ApiEndpoints.baseUrlOverride`, `synheart.baseUrl`, or `SYNHEART_BASE_URL` on any cloud build. | | Synthetic biosignals are off by default. | Opt in with `allowSyntheticBiosignals = true` for development only — the samples enter the runtime's baselines exactly as real readings would. | | Behavior events reached no collector before 0.2.0. | Forward touches with `recordTouchEvent`; the digital axes now resolve without a wearable. | 0.2.0 also adds watch sessions, a real Health Connect and BLE wear source, `requestWearPermissions()`, `HSIState.modalities` / `tiers`, and `runtimeLogEnvFilter`. See the [changelog](https://github.com/synheart-ai/synheart-core-kotlin/blob/main/CHANGELOG.md) for the full list, including the four device-verified bug fixes. ## Advanced APIs The library also provides local session storage and retention, cross-device sync and baseline transfer, sleep/recovery/readiness scoring, Health Connect backfill, watch-to-phone `EdgeIngest`, lab protocols and research enrolment, secondary `SynheartInstance` runtime handles, and Syni integration. Start with the lifecycle above. Integrate advanced APIs only when your product needs them: > [card] [Architecture](/synheart-core/architecture) > > Runtime, modules, and data flow > [card] [Consent System](/synheart-core/consent-system) > > Consent channels and JWT lifecycle > [card] [Scoring Models](/synheart-core/scoring) > > Sleep, recovery, and readiness > [card] [Edge](/synheart-core/edge) > > Watch-to-phone artifacts and ingest ## Testing ```bash theme={null} ./gradlew :synheart-core:test ``` The SDK repository includes a runnable example app and a Wear OS companion. It runs without cloud credentials, so it needs no platform account — only the installed native runtime: > [card] [Android example application](https://github.com/synheart-ai/synheart-core-kotlin/tree/main/example) > > Initialization, consent, sessions, HSI, watch integration, and runtime diagnostics ## Resources * [Kotlin SDK repository](https://github.com/synheart-ai/synheart-core-kotlin) * [Integration guide](https://github.com/synheart-ai/synheart-core-kotlin/blob/main/doc/INTEGRATION.md) * [Maven Central artifact](https://central.sonatype.com/artifact/ai.synheart/synheart-core) * [Issue tracker](https://github.com/synheart-ai/synheart-core-kotlin/issues) # Synheart Core SDK Overview Source: https://docs.synheart.ai/synheart-core/overview Unified SDK for human-state intelligence — single integration point for all Synheart features ## What is Synheart Core SDK? Synheart Core SDK is the unified integration point for developers who want to collect multimodal signals, process human state on-device via the Synheart runtime (native), and upload derived state snapshots ([HSI 1.3 format](/hsi/overview)) to the cloud with explicit user consent. > [!NOTE] > > Not sure whether you need Core or just one of the standalone SDKs (`synheart_wear`, `synheart_behavior`, `synheart_session`)? Start with [How it fits together](/guides/how-it-fits-together) — a one-page mental model of the stack with a mandatory-vs-optional table. ## Key Features ### Unified API * **Single SDK**: One integration point for all Synheart features * **Modular Design**: Enable only the modules you need * **Consistent Interface**: Same API patterns across all platforms * **Multi-Module Support**: Wear, Phone, Behavior, HSI Runtime, Consent, Cloud ### On-Device Processing * **HSI Runtime**: Powered by the Synheart runtime (native) — on-device human state fusion * **Privacy-First**: All processing happens on-device * **Designed for low overhead**: targets sub-100ms HSI emission and a single-digit-percent CPU budget on a typical mid-range device > [!NOTE] > > The numbers above are design targets, not measurements — actual footprint varies by device class and workload. Profile your app and read `Synheart.runtimeDiagnostics()` for live counters. ### Multi-Platform Support | Platform | Language | Min OS | Status | Repository | | - | - | - | - | - | | **Flutter/Dart** | Dart | iOS 15+ / Android API 24+ | Ready | [synheart-core-flutter](https://github.com/synheart-ai/synheart-core-flutter) | | **Android** | Kotlin | Android API 26 (Android 8.0) | Ready | [synheart-core-kotlin](https://github.com/synheart-ai/synheart-core-kotlin) | | **iOS** | Swift | iOS 16+ | Ready | [synheart-core-swift](https://github.com/synheart-ai/synheart-core-swift) | ### Capability System Access levels tied to app signature and tenant ID: | Module | Core | Extended | Research | | - | - | - | - | | **Wear** | Derived biosignals | Higher frequency | Raw streams | | **Phone** | Motion, screen | Advanced app context | Full context | | **Behavior** | Basic metrics | Extended metrics | Event-level streams | | **HSI Runtime** | Basic state | Full embedding | Full fusion vectors | | **Cloud** | Ingest (HSI 1.3) | Extended ingest | Lab session export | By default, third-party apps run under **Core** capabilities. **Extended** and **Research** capabilities are enabled only for first‑party Synheart apps and approved partners, since they may unlock higher-sensitivity data access and require additional privacy/security review and contractual controls. ## Module System The Core SDK consolidates all Synheart signal channels: ```text theme={null} Synheart Core SDK │ ├── Wear Module │ (HR, HRV, sleep, motion — derived signals only) │ ├── Phone Module │ (motion, screen state, coarse app context) │ ├── Synheart Behavior (Module) │ (interaction patterns: taps, scrolls, typing cadence) │ ├── HSI Runtime (On-device, Synheart Runtime) │ - feature pipeline: raw signals → FeatureSet │ - inference engine: HSV[] (6 cognitive/physio heads + MotionState) + 64D JL embedding │ - flux: HSV[] → HSI 1.3 JSON envelope │ - sliding-window state with configurable cadence │ ├── Consent Module │ (permissions, masking, enforcement) │ └── Cloud Connector (secure, consent-gated uploads) ``` ## Quick Start ### Flutter/Dart > [card] [Flutter SDK Guide](/synheart-core/flutter) > > Complete Flutter integration guide **Installation:** ```yaml theme={null} dependencies: synheart_core: ^0.23.0 ``` The Flutter package also requires the native runtime. From the application root, run `synheart install runtime --version 0.46.0`, commit `synheart.lock`, and use `synheart sync` in CI. See the [Flutter SDK guide](/synheart-core/flutter) for platform setup. **Basic Usage:** ```dart theme={null} import 'package:synheart_core/synheart_core.dart'; // Initialize Core SDK await Synheart.initialize( config: SynheartConfig( appId: 'com.example.app', subjectId: 'anon_user_123', allowUnsignedCapabilities: true, // Development only; use deviceAuthConfig in production wearConfig: const WearConfig(), ), ); // Subscribe to HSI updates (raw JSON from the Synheart Runtime) Synheart.onHSIUpdate.listen((hsiJson) { print('HSI JSON: $hsiJson'); }); // Activate the features your app needs. // SynheartFeature.wear / .behavior / .phoneContext / .cloud Synheart.activate(SynheartFeature.wear); await Synheart.grantConsent( biosignals: true, behavior: false, phoneContext: false, cloudUpload: false, ); await Synheart.startSession(); ``` ### Android (Kotlin) > [card] [Kotlin SDK Guide](/synheart-core/kotlin) > > Complete Android integration guide **Installation:** ```kotlin theme={null} dependencies { implementation("ai.synheart:synheart-core:0.8.0") } ``` **Basic Usage:** ```kotlin theme={null} import ai.synheart.core.Synheart import ai.synheart.core.config.SynheartConfig import ai.synheart.core.config.WearConfig import ai.synheart.core.config.BehaviorConfig Synheart.initialize( context = context, config = SynheartConfig( appId = "com.example.app", subjectId = "anon_user_123", allowUnsignedCapabilities = true, // development only wearConfig = WearConfig(), // declaring a config activates the module behaviorConfig = BehaviorConfig(), ) ) Synheart.grantConsent("biosignals") Synheart.grantConsent("behavior") Synheart.startSession() Synheart.onHSIUpdate.collect { hsiJson -> println("HSI JSON: $hsiJson") } ``` ### iOS (Swift) > [card] [Swift SDK Guide](/synheart-core/swift) > > Complete iOS integration guide **Installation:** ```swift theme={null} dependencies: [ .package(url: "https://github.com/synheart-ai/synheart-core-swift.git", from: "0.7.1") ] ``` **Basic Usage:** ```swift theme={null} import SynheartCore import Combine var cancellables = Set() try await Synheart.initialize( config: SynheartConfig( appId: "com.example.app", subjectId: "anon_user_123", allowUnsignedCapabilities: true // development only; use deviceAuthConfig in production ), userId: "anon_user_123" ) Synheart.onHSIUpdate .sink { hsiJson in print("HSI JSON: \(hsiJson)") } .store(in: &cancellables) Synheart.activate(.wear) Synheart.activate(.cloud) ``` ## Privacy & security * **Zero raw content**: no text, microphone audio, URLs, or messages. * **On-device processing**: HSI inference runs locally on the host. * **Consent-gated cloud**: uploads require an explicit `cloudUpload` grant from the consent service. * **Capability-enforced**: feature access is bound to the consent token's capability tier; the SDK silently downgrades responses when the tier is insufficient. ## Performance targets These are **internal targets**, not measured runtime numbers. Use `Synheart.runtimeDiagnostics()` (`diagnostics()` on Swift) and the `uploadQueueLength` / `lastUploadAt` getters to inspect what the SDK is doing in your app. ## Available SDKs > [card] [Flutter SDK](/synheart-core/flutter) > > Flutter integration > [card] [Kotlin SDK](/synheart-core/kotlin) > > Android/Kotlin integration > [card] [Swift SDK](/synheart-core/swift) > > iOS/Swift integration Each repo ships a runnable example in its `example/` directory: [Flutter](https://github.com/synheart-ai/synheart-core-flutter/tree/main/example) · [Kotlin](https://github.com/synheart-ai/synheart-core-kotlin/tree/main/example) · [Swift](https://github.com/synheart-ai/synheart-core-swift/tree/main/ExampleApp). ## Stability Synheart Core is **pre-1.0**. Minor version bumps may include breaking API changes. Use the current lines (Flutter `^0.23.0`, Kotlin `0.8.0`, Swift `0.7.1`) or pin exact versions in production, and read the CHANGELOG before upgrading. The HSI wire contract is versioned separately and follows [its own policy](/hsi/overview#versioning-policy). ## Technical Documentation > [card] [Architecture](/synheart-core/architecture) > > Module system and HSI Runtime > [card] [HSV Specification](/synheart-core/hsv-specification) > > The typed inference output of the Synheart Runtime — six heads + 64D JL embedding > [card] [Capability System](/synheart-core/capability-system) > > Access level enforcement > [card] [Consent System](/synheart-core/consent-system) > > Permission model and enforcement ## Use cases ### Mental health platforms Subscribe to the typed `HSIState` stream and read the affect axis to monitor arousal/valence over time: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.wellness', subjectId: userId, allowUnsignedCapabilities: true, wearConfig: const WearConfig(), ), ); Synheart.activate(SynheartFeature.wear); Synheart.onStateUpdate.listen((state) { final arousal = state.hsi.arousal?.value; if (arousal != null && arousal > 0.7) { showHighArousalAlert(); } }); ``` ### Productivity apps The engagement axis tracks interaction stability over the session window: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.productivity', subjectId: userId, allowUnsignedCapabilities: true, behaviorConfig: const BehaviorConfig(), ), ); Synheart.activate(SynheartFeature.behavior); Synheart.onStateUpdate.listen((state) { final focus = state.hsi.focus?.value; if (focus != null && focus < 0.3) { suggestBreak(); } }); ``` ### Research applications Use a research-tier capability token to collect data with broader fidelity bounds, and activate the cloud connector to upload HSI snapshots: ```dart theme={null} await Synheart.initialize( config: SynheartConfig( appId: 'com.example.study', subjectId: participantId, mode: SynheartMode.research, privacy: const PrivacyConfig(allowResearch: true), deviceAuthConfig: const DeviceAuthConfig( authBaseUrl: 'https://api.synheart.ai', packageName: 'com.example.study', ), wearConfig: const WearConfig(), behaviorConfig: const BehaviorConfig(), ), ); Synheart.activate(SynheartFeature.wear); Synheart.activate(SynheartFeature.behavior); Synheart.activate(SynheartFeature.cloud); ``` ## Next Steps > [card] [Quick Start](/quickstart) > > Get started in 5 minutes > [card] [Architecture Guide](/synheart-core/architecture) > > Deep dive into the system > [card] [HSV Specification](/synheart-core/hsv-specification) > > Understand Synheart Core’s internal state model > [card] [Flutter SDK on GitHub](https://github.com/synheart-ai/synheart-core-flutter) > > View source code ## Related Projects * [Synheart Wear](/synheart-wear/overview) - Wearable device integration * [Synheart Behavior](/synheart-behavior/overview) - Digital behavioral signal capture * [Synheart Session](/synheart-session/overview) - Time-bounded HR + behavioral sessions # Runtime FFI Surface Source: https://docs.synheart.ai/synheart-core/runtime-ffi 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. ## 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. 8. **ABI version** — `synheart_core_build_info` reports the C ABI as `MAJOR.MINOR`. A new MINOR only adds symbols; a new MAJOR removes or re-signs some, so an SDK built for one MAJOR refuses the others. Runtime 0.42 is **ABI 4.0**, 0.43 is **4.1** (HSM Schema consent) and 0.45 is **4.2** (the daily score inputs changed shape). Flutter `synheart_core` 0.22 and later and Kotlin and Swift 0.6 and later require ABI 4.2 (runtime 0.45.0 or later). ## 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` / `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 Signatures below were introduced in ABI 4.0 (runtime 0.42) and are unchanged through ABI 4.2. `ts_ms` is Unix epoch milliseconds. `provider` names the source (`"ble_hrm"`, `"sdk_wear"`, …; `NULL` uses the default). `utc_offset_min` is the person's offset from UTC at the sample, in minutes (±840), so samples land on the right local day across a daylight-saving change or a flight. | Symbol | Purpose | | - | - | | `synheart_core_push_hr(handle, ts_ms, bpm, provider, utc_offset_min)` | Heart-rate sample. | | `synheart_core_push_rr(handle, ts_ms, rr_ms, provider, utc_offset_min)` | RR-interval sample (beat to beat). The highest-fidelity input. | | `synheart_core_push_rr_batch(handle, anchor_ts_ms, rr, len, order, provider, utc_offset_min)` | Several RR intervals that arrived together, such as one BLE notification. | | `synheart_core_push_accel(handle, ts_ms, x, y, z, provider, utc_offset_min)` | Phone accelerometer sample, in g. | | `synheart_core_push_behavior(handle, ts_ms, event_type, value)` | Behavior event (tap, scroll, swipe, app switch, …) by numeric type. | | `synheart_core_push_sleep_stages(handle, stages_json)` | Sleep stages from a wearable. | | `synheart_core_ingest_batch(handle, batch_json, now_ms) -> *char` | Several samples in one call; each event may carry `utc_offset_min`. Returns an HSI document when a window completed, else `NULL`. | | `synheart_core_push_inputs_json(handle, inputs_json) -> *char` | A typed batch (samples, presses, scrolls, notifications, day types, daily values). Returns what went in and why the rest did not. | ## 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 `/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_srm_push_wearable_daily(handle, provider, metric, year, month, day, value, vendor_summary) -> int` | One daily value for one local date. `0` stored, `1004` refused, `5002` out of bounds or not permitted, `-1` no pipeline: call `synheart_core_ensure_pipeline(handle)` first when no session is running. See [daily metrics](/synheart-core/srm#daily-metrics). | | `synheart_core_srm_refresh_wearable_reference(handle, year, month, day) -> int` | Rebuild the wearable reference from the dates before the given date. Call with today after a batch of daily values. | | `synheart_core_daily_baseline_refs_json(handle)` | The Recovery and Readiness baselines as JSON, read after a refresh (ABI 4.2). | | `synheart_core_daily_sleep_baselines_json(handle)` | The Sleep Score's baselines as JSON, read after a refresh (ABI 4.2). | | `synheart_core_export_baseline_snapshot(handle) -> *char` | Every personal baseline as opaque base64. Only for a host that persists outside the runtime's data directory. | | `synheart_core_load_baseline_snapshot(handle, snapshot_b64) -> int` | Restore that snapshot. A snapshot from a runtime before 0.42 is refused, and the baselines start fresh. | | `synheart_core_attach_closed_day_strain_json(handle) -> *char` | Score the local day the engine closed last and attach it to the next frame. | | `synheart_core_set_input_capture(handle, running, ts_ms) -> int` | Report whether input capture is running, which decides when a still window counts as rest. | | `synheart_core_baselines_json(handle) -> *char` | Current per-dimension baselines (mean / std / sample count). | | `synheart_core_srm_overall_status(handle) -> *char` | `{"status": "empty" \| "warming" \| "ready"}`. A stale baseline reports `warming`. See [maturity states](/synheart-core/srm#maturity-states). | ## 9. Sync | Symbol | Purpose | | - | - | | `synheart_core_set_sync_enabled(handle, enabled)` | Build (`1`) or dispose (`0`) the sync engine. Disabling keeps the space membership. | | `synheart_core_sync_readiness(handle) -> *char` | Prerequisite booleans plus the first unmet gate as `state`: `CONFIGURATION_MISSING`, `STORAGE_UNAVAILABLE`, `DEVICE_REVOKED`, `DEVICE_REGISTRATION_REQUIRED`, `ENGINE_NOT_INITIALIZED`, `NO_ACTIVE_SPACE`, `SRK_UNAVAILABLE`, or `READY`. | | `synheart_core_sync_create_space(handle, device_name) -> *char` | Create a space. Returns `{sync_space_id, recovery_key}`. `device_name` may be NULL. | | `synheart_core_sync_generate_pairing(handle) -> *char` | Issue a single-use pairing token. Returns `{token, expires_in}`. | | `synheart_core_sync_pairing_status(handle, token) -> *char` | Poll a pairing token. Returns `{status, sync_space_id, joined_device, joined_at, expires_at}`; `status` is `waiting`, `joined`, `expired`, or `unknown`. | | `synheart_core_sync_join_space(handle, pairing_token, device_name) -> *char` | Join with a pairing token. Returns `{sync_space_id, status}`. | | `synheart_core_sync_recover_space(handle, recovery_key, space_id) -> *char` | Rejoin with the recovery key. Returns `{sync_space_id, owner_user_id, status}`. | | `synheart_core_sync_now(handle) -> *char` | Run one push and pull cycle. Returns `{pushed, pulled, conflicts_resolved, errors}`. Blocks on network I/O. | | `synheart_core_sync_list_devices(handle) -> *char` | Returns `{devices: [{device_id, device_name, is_primary, trusted_at, last_seen_at, revoked}]}`. | | `synheart_core_sync_revoke_device(handle, device_id) -> *char` | Remove another device from the space. | | `synheart_core_sync_leave_space(handle) -> *char` | Remove this device from the space, then clear local state. | | `synheart_core_sync_delete_space(handle) -> *char` | Delete the space for every device. Owner only. | | `synheart_core_sync_clear_local_space(handle) -> *char` | Clear local space state without a network call. | | `synheart_core_sync_status(handle) -> *char` | Returns `{enabled}`: whether the sync engine is built. | Every function except `set_sync_enabled` returns a JSON envelope: `{"ok": true, "data": {...}}` on success, or `{"ok": false, "error": {code, message, retryable, owner, recovery, ...}}` on failure. Free the string with `synheart_core_free_string`. See [Cross-device sync](/synheart-core/sync) for the flow and error codes. ## 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. # Scoring models Source: https://docs.synheart.ai/synheart-core/scoring Typed input + result classes for the Sleep / Recovery / Readiness scorers — cross-language byte-equivalent JSON. ## Overview The Synheart runtime computes three daily scores: | Score | What it answers | | - | - | | **Sleep** | "How good was last night's sleep?" | | **Recovery** | "How recovered is the user today?" | | **Readiness** | "How much strain should the user take today?" | Each scorer takes a typed input bundle, returns a typed result, and emits a JSON shape that's **byte-equivalent across Flutter / Kotlin / Swift**. The Synheart Core SDKs expose Dart / Kotlin / Swift data classes that round-trip with the runtime's wire format. ## Sleep score Three input shapes — pick the one matching your data source: * **Segmented**: stage-by-stage timeline (Apple HealthKit, some Wear OS sources, BLE chest straps) * **Aggregated**: totals only (vendor APIs that don't expose stages — Whoop summary, basic Health Connect, self-report) * **Vendor score**: a single 0-100 number from a vendor that has its own pipeline (Whoop Recovery, Garmin Body Battery) ### Kotlin ```kotlin theme={null} val input = SleepScoreInput( tonight = NightRaw( wakeCalendarDate = epochDayForWake, detail = NightInput.Aggregated( sessionStartMs = bedtime.toEpochMilli(), sessionEndMs = wakeTime.toEpochMilli(), totals = AggregatedTotals( totalSleepMinutes = 420.0, awakeMinutes = 30.0, deepSleepMinutes = 90.0, // null when source can't break stages out remSleepMinutes = 110.0, ), ), avgHrBpm = 58.0, ), priorsNewestFirst = recentNights, // only the two newest are read, for sleep debt tonightMidpointH = 3.2, // local sleep midpoint; null without start and end times baselines = Synheart.dailySleepBaselines(), // null → cold-start mode pipelineVersion = "v1", ) // Engine returns wire JSON; parse with SleepScoreResult.fromJsonString ``` ### Swift ```swift theme={null} let input = SleepScoreInput( tonight: NightRaw( wakeCalendarDate: epochDayForWake, detail: .aggregated( sessionStartMs: Int64(bedtime.timeIntervalSince1970 * 1000), sessionEndMs: Int64(wakeTime.timeIntervalSince1970 * 1000), totals: AggregatedTotals( totalSleepMinutes: 420, deepSleepMinutes: 90, // nil when source can't break stages out remSleepMinutes: 110, awakeMinutes: 30 ) ), avgHrBpm: 58 ), priorsNewestFirst: recentNights, // only the two newest are read, for sleep debt tonightMidpointH: 3.2, // local sleep midpoint; nil without start and end times baselines: Synheart.dailySleepBaselines(), // nil → cold-start mode pipelineVersion: "v1" ) ``` `SleepScoreResult` carries `score: Int?`, `confidence: Double`, `path: SleepPath` (`stage` / `aggregated` / `vendor_score` / `proxy`), `mode: SleepScoreMode` (`cold_start` / `short_history` / `stable`), `components`, `adjustments`, `effectiveWeights`, and a `reason: SleepScoreReason?` for absent/degraded scores. ## Recovery score Three-stage scorer — the engine adapts the formula to the available history: * **Stage 1 (FirstDay)** — 1 night of sleep + (HR or HRV) * **Stage 2 (ShortHistory)** — ≥ 3 nights with HR/HRV trends * **Stage 3 (Personalized)** — ≥ 7 nights + stable wearable baselines ```kotlin theme={null} // Kotlin val input = RecoveryScoreInput( tonight = NightSummary(wakeCalendarDate = today, totalSleepMinutes = 420.0), priors = recentNights, overnight = OvernightPhysiology(hrvRmssdMs = 42.5, overnightHrBpm = 58.0), priorsOvernight = recentOvernight, baselines = Synheart.dailyBaselineRefs(), // the runtime's baselines; null while cold ) ``` `RecoveryScoreResult` carries `score: Int`, `stage` (`first_day` / `short_history` / `personalized`), `mode` (`estimate` / `trended` / `personalized`), `components`, `confidence`, and a `List` explaining the score (`hrv_above_baseline`, `resting_hr_elevated`, `strong_sleep_quality`, etc.). ## Readiness score Combines today's Recovery and Sleep scores, adjusted by how last night's heart rate and HRV sat against their personal baselines (`readiness_score/3.0.0`, runtime 0.45.0 and later): ```kotlin theme={null} // Kotlin val refs = Synheart.dailyBaselineRefs() val input = ReadinessScoreInput( recoveryScore = 65, sleepScore = 78, alignment = OvernightAlignment( // optional hrSleepBpm = 56.0, hrBaseBpm = 58.0, rmssdSleepMs = 44.0, rmssdBaseMs = 41.0, ), recoveryColdStart = false, sleepColdStart = false, baselineMaturity = refs?.maturity ?: 0.0, // 0..1 ) val result = Synheart.computeReadinessScore(input) ``` `ReadinessScoreResult` carries `score: Int`, `band: ReadinessBand`, `recoveryAnchor` and `sleepAnchor`, `components` (`recovery`, `sleep`, `baselineAlignment`, `hrAlignment`, `hrvAlignment`), `confidence`, and a `List` (`poor_sleep`, `hrv_below_baseline`, `baseline_immature`, `scores_only`, …). The band cases (`REST` / `LIGHT` / `NORMAL` / `PUSH`) read the engine's wire names `low` / `reduced` / `normal` / `high`. > [!NOTE] > > Kotlin and Swift 0.6 and `synheart_core` 0.22 removed `AcuteWorkloadContext`, > `FatigueContext`, `HistoryContext`, `recoveryConfidence` and `fromRecovery`; the > runtime no longer reads them. ## Sleep questionnaire Phase-2 self-report input lane — converts subjective answers into the same `AggregatedTotals` shape vendor payloads produce, so the engine scores them without special-casing. ```kotlin theme={null} // Kotlin val q = SleepQuestionnaireAnswers( bedtime = Instant.parse("2026-01-15T22:00:00Z"), wakeTime = Instant.parse("2026-01-16T06:00:00Z"), sleepLatencyMinutes = 20, awakenings = 4, subjectiveQuality = 4, feltRested = SleepFeltRested.YES, ) val payload = q.toIngestPayload() // → feed payload to Baselines.ingestVendorSleep equivalent ``` The engine accepts null deep/REM on the aggregated path and falls back to duration + continuity components — that's deliberate. Don't invent stage durations from subjective signals; surface subjective quality / rested-feeling in the UI alongside the score instead. ## Cross-language parity All three scorers emit identical snake\_case JSON on every platform: * Flutter: `lib/src/models/{sleep,recovery,readiness}_score.dart` + `sleep_questionnaire.dart` * Kotlin: `synheart-core/src/main/kotlin/ai/synheart/core/models/{SleepScore,RecoveryScore,ReadinessScore,SleepQuestionnaire}.kt` * Swift: `SynheartCore/Models/{SleepScore,RecoveryScore,ReadinessScore,SleepQuestionnaire}.swift` A Flutter, Android, and iOS app talking to the same backend produce byte-equivalent scorer payloads. ## Related * [Baselines](/synheart-core/baselines) — reactive snapshot of latest scores + 7-night recent-scores ring * [Synheart Core overview](/synheart-core/overview) * [HSI specification](/synheart-core/hsi-specification) # Self-Reference Model (SRM) Source: https://docs.synheart.ai/synheart-core/srm The personal baselines: what feeds them, when they are ready, and how they are kept. ## Overview The **Self-Reference Model (SRM)** is the set of personal baselines the runtime keeps for each person: "your normal" for heart rate, HRV, sleep and behaviour. Person-relative scores (recovery, readiness, deviations in HSI) are measured against it. You don't write baselines directly. The runtime learns them from the samples your app streams and from the **daily values** you push, and it saves and restores them itself. > [!NOTE] > > This page describes runtime 0.45 and later (C ABI 4.2), used by Flutter > `synheart_core` 0.22 and later and Kotlin and Swift 0.6 and later. Runtime 0.42 > introduced these daily-value names; earlier SDKs used different ones. See each > SDK's upgrade notes. ## Daily metrics Push one value per metric per local date with `srmPushWearableDaily`. The unit is part of the name, and a night belongs to the date the person woke on. | Metric | Value | | - | - | | `sleep.duration_s` | Total sleep, seconds | | `sleep.midpoint_h` | Sleep midpoint, hours after local midnight | | `sleep.deep_min` | Deep sleep, minutes | | `sleep.rem_min` | REM sleep, minutes | | `cardiac.resting_hr_bpm` | Resting heart rate, bpm (Recovery, Readiness) | | `cardiac.overnight_hr_bpm` | Mean heart rate asleep, bpm (Sleep Score) | | `cardiac.overnight_rmssd_ms` | Overnight RMSSD, ms | | `cardiac.overnight_sdnn_ms` | Overnight SDNN, ms | | `cardiac.overnight_hr_sd_bpm` | Standard deviation of overnight heart rate, bpm | | `cardiac.hrr_load_au` | Cardiovascular load for the day | | `vendor.recovery_frac` | A vendor's recovery score as `0`–`1` (72 % is `0.72`) | | `vendor.strain_frac` | A vendor's strain, normalised to `0`–`1` | | `motion.steps_count` | Steps in the day | | `motion.active_min` | Active minutes in the day | Any other name is refused. Pushing the same metric for the same date and provider again replaces it. After a batch, call `srmRefreshWearableReference()` once: it rebuilds the reference from the dates **before** today, so a day is never judged against itself. The engine fills in overnight RMSSD and cardiovascular load from your streamed data when you push none for that date. It also writes `cardiac.rest_rmssd_ms` from certified rest windows; never push it. * **Two heart-rate figures.** Push the mean HR asleep as `cardiac.overnight_hr_bpm` and the source's resting-HR record as `cardiac.resting_hr_bpm`. A source with one overnight figure (WHOOP's resting HR, for example) fills both. A daytime resting HR on its own (Garmin's, for example) fills resting only. * **Only finished days.** Push `motion.steps_count` and `motion.active_min` once the day is over, never a partial total for today. * **No session needed.** The daily calls need an engine pipeline. The SDKs' `srmPushWearableDaily` and `srmRefreshWearableReference` build one when none is running (Flutter 0.23.0 and later), so a background health pull is stored. Over the C ABI, call `synheart_core_ensure_pipeline` first; without a pipeline the push returns `-1`. Read the daily scores' baselines with `dailyBaselineRefs()` (Recovery and Readiness) and `dailySleepBaselines()` (Sleep) after the refresh; see [Scoring](/synheart-core/scoring). ## Maturity states `srm_overall_status` answers "is the reference stable enough to rely on yet?", for example to show a warm-up indicator: | Status | Meaning | | - | - | | `empty` | No baseline has data yet, or no session or pipeline is running. | | `warming` | At least one baseline is still learning, or was ready but has gone stale. | | `ready` | Every baseline with data is ready. Personalized scoring is unlocked. | ## WearableReferenceView The typed reference every SDK exposes through [`Baselines`](/synheart-core/baselines): ```text theme={null} status: String // maturity, see above modelVersion: String? recentSleepScoreMedian: Int? dimensions: Map // per-dimension central value confidence: Map // 0.0 – 1.0 per dimension ``` ## How baselines are kept The runtime **saves the baselines itself**: to its own data directory at the end of a session, after every reference refresh, and every 15 minutes while windows close. It restores them at startup. Keep the runtime's data directory and you need no code for this. Only an app that stores state somewhere else needs `exportBaselineSnapshot()` and `loadBaselineSnapshot()`. The snapshot is opaque base64; store it as private health data. > [!NOTE] > > The first launch after upgrading to runtime 0.42 starts the baselines fresh > once, because 0.42 cannot read a snapshot from an earlier runtime. To erase the baselines, use `wipeLocalData()`, or `forgetBaselines(scope)` to forget part of them at the person's request. ## Related * [Baselines](/synheart-core/baselines): the host-facing read API * [Health backfill](/synheart-core/health-backfill): seed the baselines from health-store history * [Scoring models](/synheart-core/scoring): what is computed once baselines are ready * [Runtime FFI](/synheart-core/runtime-ffi#8-srm-and-baselines): the underlying C calls # Synheart Core - Swift SDK Source: https://docs.synheart.ai/synheart-core/swift Add on-device human-state intelligence to Apple-platform applications ## Overview The Synheart Core Swift SDK collects approved signals, processes human state on-device, and delivers HSI 1.3 state windows to native Apple applications. **Key features:** * iOS, macOS, watchOS, and tvOS support * On-device HSI processing * Typed and raw Combine publishers * Modular signal collection * Consent-aware local storage and cloud delivery ## Requirements * iOS 16+, macOS 13+, watchOS 8+, tvOS 15+ * Swift 5.9 (Xcode 15 or later) * The native Synheart runtime linked into the app ## Installation ### Add the Swift package In Xcode, choose **File → Add Package Dependencies** and enter: ```text theme={null} https://github.com/synheart-ai/synheart-core-swift.git ``` Or add the package dependency directly: ```swift theme={null} dependencies: [ .package( url: "https://github.com/synheart-ai/synheart-core-swift.git", from: "0.7.1" ) ] ``` ### Install the native runtime The Swift package provides the Apple integration layer. On-device HSI computation requires the native Synheart runtime. From your app's project directory: ```bash theme={null} synheart install runtime --platform ios --version 0.46.0 ``` SDK 0.7.1 is verified against runtime `0.46.0` and needs `0.45.0` or later (C ABI 4.2). An older runtime is refused at initialization. SDK 0.5 needs `0.42.0` or later; SDK 0.4.x and earlier need `0.38.0`. To link a runtime you built yourself, use `synheart runtime install --from /path/to/runtime-distribution --project /path/to/project-dir`. See [Install the runtime](/setup/install-runtime) for runtime variants and linking instructions. > [!WARNING] > > Stable and lab runtime variants require `onnxruntime-c` to be linked by the host application. Do not embed duplicate copies of the runtime or ONNX library. ## Apple permissions Add only the usage descriptions required by the features your app enables: ```xml theme={null} NSHealthShareUsageDescription This app uses approved health data to provide private human-state insights. NSMotionUsageDescription This app uses motion data to improve state context and signal quality. ``` Enable **HealthKit** in Xcode when using wearable collection. ## Quick start The normal lifecycle is: ```text theme={null} Initialize → Grant consent → Activate features → Start → Observe → Stop ``` ```swift theme={null} import Combine import SynheartCore final class HumanStateModel: ObservableObject { @Published private(set) var state: HSIState? private var cancellables = Set() func start(subjectId: String) async throws { let config = SynheartConfig( appId: "com.example.myapp", subjectId: subjectId, appVersion: "1.0.0", appName: "My App", category: "wellness", developer: "Example, Inc.", allowUnsignedCapabilities: true ) try await Synheart.initialize( config: config, userId: subjectId, autoStart: false ) try await Synheart.grantConsent("biosignals") Synheart.activate(.wear) Synheart.onStateUpdate .receive(on: DispatchQueue.main) .sink { [weak self] in self?.state = $0 } .store(in: &cancellables) try await Synheart.startSession() } func stop() async throws { try await Synheart.stopSession() } func dispose() async throws { try await Synheart.dispose() } } ``` > [!WARNING] > > `allowUnsignedCapabilities: true` is for local development only. Production apps must use a verified capability configuration. ## Production configuration Use pseudonymous subject identifiers and the service origins issued for your environment. Do not embed API secrets or shared signing keys in the application. ```swift theme={null} let serviceOrigin = "https://api.synheart.ai" let appId = "com.example.myapp" let subjectId = "subject_7f8a..." let deviceId = UUID().uuidString let config = SynheartConfig( appId: appId, subjectId: subjectId, appVersion: "1.0.0", appName: "My App", category: "wellness", developer: "Example, Inc.", deviceId: deviceId, storage: StorageConfig(enabled: true, retentionDays: 30), sync: SyncConfig(enabled: true, baseUrl: serviceOrigin), cloudConfig: CloudConfig( subjectId: subjectId, instanceId: deviceId, orgId: "org_example", baseUrl: serviceOrigin ), consentConfig: ConsentConfig( consentServiceUrl: serviceOrigin, appId: appId, deviceId: deviceId, userId: subjectId ), deviceAuthConfig: DeviceAuthConfig( authBaseUrl: serviceOrigin, packageName: appId ) ) ``` Production cloud requests use registered device identity. Ensure registration and cloud consent are ready before enabling cloud delivery: ```swift theme={null} _ = await Synheart.ensureDeviceAuthRegistered() let consentReady = await Synheart.ensureCloudConsentReady() if consentReady { Synheart.activate(.cloud) } ``` ## Features and consent A feature operates only when it is activated, consented, allowed by capability policy, and an eligible session is active. | Feature | Required consent | Purpose | | - | - | - | | `.wear` | `biosignals` | Approved wearable signals | | `.behavior` | `behavior` | Interaction telemetry | | `.phoneContext` | `phoneContext` | Motion and device context | | `.cloud` | `cloudUpload` | HSI cloud delivery | | `.synsync` | `cloudUpload` | [Cross-device sync](/synheart-core/sync) | | `.syni` | `syni` | Entitled Syni services | ```swift theme={null} try await Synheart.grantConsent("biosignals") Synheart.activate(.wear) // Revoke it later when requested by the user. try await Synheart.revokeConsent("biosignals") ``` Consent revocation stops future use of that consent. It is separate from deleting previously retained data. ## HSI state updates Use the typed publisher for application logic: ```swift theme={null} Synheart.onStateUpdate .sink { state in print(state.hsi.isEmpty ? "no evidence yet" : state.rawJson) } .store(in: &cancellables) ``` Use the raw publisher when you need the complete HSI 1.3 payload: ```swift theme={null} Synheart.onHSIUpdate .sink { rawJson in print(rawJson) } .store(in: &cancellables) ``` `currentHSIState` provides the latest typed value and `currentState` provides the latest raw JSON. HSI is emitted in windows, not for every sensor sample, so applications should show a collecting state while waiting for the first valid window. See the [HSI specification](/hsi/overview) for the wire format. ## Cloud delivery and diagnostics Cloud delivery requires cloud configuration, consent, feature activation, device registration, and network availability. ```swift theme={null} let queue = Synheart.uploadQueueStatus let result = await Synheart.flushUploads(requireConsent: true) print(queue) print(result) ``` For runtime and collection troubleshooting: ```swift theme={null} print(CoreRuntimeBridge.symbolDiagnostics) print(CoreRuntimeBridge.dependencyDiagnostics) print(Synheart.runtimeVersion ?? "unavailable") for (module, reason) in Synheart.collectionStartupFailures { print("\(module): \(reason)") } ``` A zero-length queue does not by itself confirm successful ingestion. Inspect the flush result and the latest upload diagnostics. ## Advanced capabilities The Swift SDK also exposes the following runtime-backed features. Availability depends on the linked runtime and the application’s capability policy. | Capability | Main APIs | | - | - | | [Sync spaces](/synheart-core/sync) | Create, pair, join, recover, inspect, leave, and delete a space | | Baselines | Hydrate, inspect, and securely import or export baseline envelopes | | Scores | Compute sleep, recovery, and readiness scores | | Runtime inputs | Push RR batches, vendor HRV, vitals, and wearable events | | History | Read local HSI history or fetch permitted cloud windows | | Personalization | Supply task, focus, and workout context | | Privacy | Request and monitor customer-data deletion | | Syni | Access entitled Syni cloud operations | | Independent instances | Run isolated native instances for advanced tooling and research | Pairing tokens, recovery keys, and exported baseline material are sensitive. Keep them out of logs and analytics and store them using platform-protected storage. ## Error handling ```swift theme={null} do { try await Synheart.initialize( config: config, userId: subjectId, autoStart: false ) } catch let error as SynheartRuntimeError { // The linked runtime's C ABI or version doesn't fit this SDK. print("\(error.message)\nFix: \(error.installCommand)") } catch SynheartError.runtimeIncompatible(let missingSymbols) { // No runtime is linked, or it lacks required symbols. print("Runtime mismatch: \(missingSymbols)") } catch SynheartError.runtimeDependencyMissing(let dependencies) { print("Missing dependency: \(dependencies)") } catch SynheartError.capabilityTokenRequired { print("Verified device authorization is required") } catch { print(error.localizedDescription) } ``` `initialize` throws `SynheartRuntimeError` (`kind: .incompatible`) before the runtime is created when its C ABI is not 4.2 or a later 4.x, it is older than 0.45.0, or it does not report its build info. `SynheartError.runtimeVersionTooOld` is no longer thrown. After any native call that failed, `Synheart.lastNativeError` explains it: a `SynheartNativeError` with `code`, `message`, `retryable`, `ownerKind`, `recoveryKind`, `recoveryCall`, `reason`, `argument`, `hint`, `op`, and `errorId`. A call that succeeds clears it. `CoreRuntimeBridge.lastCreateError` says why the runtime handle could not be created. ## Troubleshooting | Symptom | Check first | | - | - | | Initialization fails | Configuration, embedded runtime, and native dependencies | | Session will not start | Activation, consent, capability, and device role | | No HSI appears | Active session, incoming signals, and window duration | | HSI has no evidence (`state.hsi.isEmpty`) | Signal coverage, provenance, quality, and baseline status | | Upload does not complete | Device registration, subject binding, consent, origin, and network | | Sync is unavailable | Sync readiness and the linked runtime’s supported capabilities | ## Upgrading | Version | Change | | - | - | | 0.7.1 | Install hints recommend runtime 0.46.0 (0.45.0 still loads). | | 0.7.0 | Added `syncPairingStatus(token:)`; `SyncStatus` reports `pendingCount`, `lastSuccessMs`, `srkReady`, `accountOwned` and `hasActiveSpace` (`nil` when not sent). `syncNow()`, `getSyncStatus()`, `setSyncEnabled(_:)` and `syncStatusSnapshot` read the runtime's `{ok, data}` envelope, so they no longer report zeros or always throw. Starting a session no longer calls UIKit off the main thread. `SyncStatus.deviceCount` deprecated (always `0`; use `syncListDevices()`). | | 0.6.0 | **Breaking:** requires runtime 0.45.0 or later (C ABI 4.2). `ReadinessScoreInput` is rebuilt (`recoveryScore`, `sleepScore`, optional `OvernightAlignment`, `baselineMaturity`); `AcuteWorkloadContext`, `FatigueContext`, `HistoryContext` and `fromRecovery(_:)` are removed. `SleepScoreInput` gains `tonightMidpointH` and `baselines`. Added `dailyBaselineRefs()`, `dailySleepBaselines()` and `DailyMetric.overnightHrBpm`, `activeMin`, `restRmssdMs`. | | 0.5.0 | **Breaking:** requires runtime 0.42.0 or later (C ABI 4.0); install runtime 0.42.1. `rollDay(_:)` removed (`attachClosedDayStrain()` added); SRM and longitudinal snapshot calls replaced by `exportBaselineSnapshot()` / `loadBaselineSnapshot(_:)`, and the runtime now saves the baselines itself. Daily values use `srmPushWearableDaily` with a `DailyMetric` name and a date; `HealthKitRuntimeSink(reader:bridge:)` wires the defaults. HealthKit backfill files nights under the local wake date. See [SRM](/synheart-core/srm). | | 0.4.1 | The runtime's data directory is excluded from iCloud and device backup automatically: its keys never leave the device, so a restored copy could not be read. | | 0.4.0 | **Breaking (behavior):** `initialize` throws `SynheartRuntimeError` for an incompatible runtime, before the runtime is created. Added `Synheart.lastNativeError`, `SynheartNativeError`, `CoreRuntimeBridge.lastCreateError`. Runtime C ABI 2.x accepted; install hints recommend runtime 0.38.0. Research capture samples the accelerometer at 50 Hz; `SynheartConfig.emitRawMotionSamples` opts in from any mode. | | 0.3.1 | `SynheartInstance.create(config:dataDirectory:) async throws` creates the runtime off the main thread. | See the [changelog](https://github.com/synheart-ai/synheart-core-swift/blob/main/CHANGELOG.md) for the full list. ## Resources * [Swift SDK repository](https://github.com/synheart-ai/synheart-core-swift) * [Swift example application](https://github.com/synheart-ai/synheart-core-swift/tree/main/ExampleApp) * [GitHub issues](https://github.com/synheart-ai/synheart-core-swift/issues) * [Architecture](/synheart-core/architecture) * [Capability system](/synheart-core/capability-system) * [Consent system](/synheart-core/consent-system) * [Synheart Auth](/synheart-auth/overview) # Errors Source: https://docs.synheart.ai/synheart-session/errors SessionError event codes, exception classes, and recovery paths The session SDK has two error surfaces: in-stream error events that end a running session, and exceptions thrown synchronously for API misuse. The error codes are the same in Dart, Kotlin, and Swift. ## `SessionErrorCode` Every SDK has a `SessionErrorCode` enum whose values serialize to the same snake\_case strings: | Dart | Kotlin | Swift | Wire string | Typical cause | | - | - | - | - | - | | `permissionDenied` | `PERMISSION_DENIED` | `.permissionDenied` | `permission_denied` | OS denied a sensor permission (HealthKit, Health Connect, BLE, etc.). | | `sensorUnavailable` | `SENSOR_UNAVAILABLE` | `.sensorUnavailable` | `sensor_unavailable` | HR source missing or not connected; no reachable watch. | | `lowBattery` | `LOW_BATTERY` | `.lowBattery` | `low_battery` | Device battery too low. | | `osTerminated` | `OS_TERMINATED` | `.osTerminated` | `os_terminated` | The OS ended the session. | | `invalidState` | `INVALID_STATE` | `.invalidState` | `invalid_state` | API misuse, e.g. starting while a session is running. | Parsing a wire string: Dart `SessionErrorCode.fromString(value)` throws `ArgumentError` for an unknown value; Swift uses `SessionErrorCode(rawValue:)`, which returns `nil`; Kotlin's `SessionEvent.fromMap` maps an unknown `error_code` to `INVALID_STATE`. The wire format is JSON-style maps (see [Watch Protocol](/synheart-session/watch-protocol)); there is no protobuf schema. ## In-stream error events | SDK | Type | | - | - | | Dart | `SessionError` (subclass of `SessionEvent`) with `code` and `message` | | Kotlin | `SessionErrorEvent` (subclass of `SessionEvent`) with `code` and `message` | | Swift | `SessionEvent.sessionError(sessionId:code:message:)` | An error event is terminal: no summary follows it. The Swift `AsyncStream` and the Dart stream finish after it; the Kotlin `SharedFlow` does not complete, so collectors stop on it themselves. `message` is human-readable and platform-specific. Log it, but don't parse it for control flow — only `code` is stable. ### Who emits them | Source | When | Code | | - | - | - | | Kotlin / Swift `SynheartSession` | The `BiosignalProvider` throws from `startStreaming` (for example a BLE HRM that is not connected, or Health Connect unavailable). `SessionStarted` has already been emitted; the session ends. | `sensor_unavailable` | | Kotlin `WatchSessionRelay` | Play Services unavailable, no connected node accepted the command, or the watch sent nothing within 10 seconds. | `sensor_unavailable` | | Companion watch app | Whatever the watch reports; relayed as received. | any | | Dart engines | Not emitted in 0.3.0. | — | ### Wire key Kotlin `toMap()` and Swift `toDictionary()` put the code under `error_code`. Dart `SessionError.toJson()` writes it under `code`, and `SessionError.fromJson()` reads `code`, so the Dart decoder does not accept a `session_error` map that only carries `error_code`. ## Recovery paths | Code | Recovery | | - | - | | `permission_denied` | Request the missing permission with the platform API, then start a new session. The SDK does not retry. | | `sensor_unavailable` | Reconnect the HR source or the watch. For a watch, check `getWatchStatus()` (Flutter) or `WatchSessionRelay.status()` (Kotlin) before starting again. On Wear OS, a timeout usually means the companion app is missing or does not share the phone app's package name and signing certificate. | | `low_battery` | User remediation. The SDK does not throttle or downsample. | | `os_terminated` | Start a new session. Partial data from the ended session is not recoverable from the SDK. | | `invalid_state` | Programmer error. Inspect `message` and the call site. | ## Thrown exceptions ### Dart ```dart theme={null} class SynheartSessionError implements Exception { ... } class SessionPermissionDeniedError extends SynheartSessionError { ... } class SessionSensorUnavailableError extends SynheartSessionError { ... } class SessionInvalidStateError extends SynheartSessionError { ... } ``` | Exception | When | | - | - | | `SessionInvalidStateError` | `startSession` with a `sessionId` that is already running. `startSession`, `stopSession`, `getStatus`, or `getWatchStatus` after `dispose()`. | | `SessionPermissionDeniedError`, `SessionSensorUnavailableError` | Defined but not thrown by the SDK in 0.3.0. | These are thrown directly from the call, not delivered on the stream. `stopSession` with an unknown id does not throw. `ingestHsiMetrics` and `dispose` never throw. ### Kotlin `SessionError` is a sealed `Exception` with subclasses `PermissionDenied`, `SensorUnavailable`, `InvalidState`, `LowBattery`, and `OsTerminated`, each with a `code`. | Call | Throws `SessionError.InvalidState` when | | - | - | | `startSession(config)` | Any session is already running (whatever its id), or the instance is disposed. | | `stopSession(sessionId)` | No session is running, or the id does not match. (No-op after `dispose()`.) | | `SessionConfig.fromMap(map)` | `session_id`, `mode`, or `duration_sec` is missing, or the mode is unknown. | Providers throw `SessionError.SensorUnavailable` from `startStreaming`; `SynheartSession` turns that into a `SessionErrorEvent`. ### Swift `SessionError` is an enum (`Error`) with cases `permissionDenied(String)`, `sensorUnavailable(String)`, `invalidState(String)`, `lowBattery(String)`, and `osTerminated(String)`; `code` returns the `SessionErrorCode`. | Call | Throws `SessionError.invalidState` when | | - | - | | `startSession(config:)` | Any session is already running (whatever its id), or the instance is disposed. | | `stopSession(sessionId:)` | No session is running, or the id does not match. (No-op after `dispose()`.) | | `SessionConfig(from:)` | `session_id`, `mode`, or `duration_sec` is missing, or the mode is unknown. | ## Distinguishing the two surfaces | Situation | Surface | | - | - | | Duplicate start | Dart: `SessionInvalidStateError` for the same id. Kotlin / Swift: `SessionError.InvalidState` / `.invalidState` for any second start. | | Call after `dispose()` | Thrown (see the tables above). | | BLE HRM not connected at start (Kotlin / Swift) | Error event with `sensor_unavailable`. | | Wear OS watch not answering (Kotlin relay) | Error event with `sensor_unavailable` after 10 seconds. | | Watch went out of range (Flutter) | No error — channel errors are swallowed and frames continue with whatever samples arrive. | ## Channel error swallowing In Flutter, `WatchBiosignalProvider` treats event-channel errors as non-fatal, so a brief disconnect does not end the session. Apps that need strict reachability must poll `getWatchStatus()` and stop the session themselves. ## Logging The Dart SDK only prints from an `assert`-guarded block (a failed watch stop command), so release builds print nothing. The Kotlin `WatchSessionRelay` and `HealthConnectBiosignalProvider` log warnings with `android.util.Log`. Hosts that need structured logging should log events at the call site. ## Related * [Lifecycle](/synheart-session/lifecycle) — when the stream ends and what state follows. * [Watch Protocol](/synheart-session/watch-protocol) — the event maps on the wire. # Synheart Session - Flutter SDK Source: https://docs.synheart.ai/synheart-session/flutter Flutter SDK with stream-based session API for HR metrics and behavioral signals ## Overview The Synheart Session Dart SDK provides a stream-based API for running timed biometric sessions. Sessions emit session frames with HR metrics at configurable intervals and deliver a final summary when complete. Frames can include behavioral signal data (typing, scrolling, taps, app switches, idle gaps, stability/fragmentation indices) when a `BehaviorProvider` is configured. A built-in mock engine lets you develop and test without hardware. **Key Features:** * Stream-based session lifecycle (`SessionStarted` -> `SessionFrame*` -> `SessionSummary`) * Pluggable `BiosignalProvider` and optional `BehaviorProvider` * Companion-watch sessions on Apple Watch and Wear OS through `WatchBiosignalProvider` * Built-in mock engine with seeded output * Configurable session modes, duration, and compute profile > [!NOTE] > > The SDK computes mean HR. HRV (`hr_sdnn_ms`, `rmssd_ms`, `pnn50`) is supplied by the host through `ingestHsiMetrics()` and is `0.0` until then. See [HRV metrics](#hrv-metrics). ## Installation Add to your `pubspec.yaml`: ```yaml theme={null} dependencies: synheart_session: ^0.3.0 ``` Install dependencies: ```bash theme={null} flutter pub get ``` ### Requirements * Dart SDK `>=3.8.0 <4.0.0` * Flutter `>=3.22.0` ## Quick Start ### Mock Mode (Development) ```dart theme={null} import 'package:synheart_session/synheart_session.dart'; final session = SynheartSession.mock(seed: 42); final config = SessionConfig( mode: SessionMode.focus, durationSec: 30, profile: const ComputeProfile(windowSec: 10, emitIntervalSec: 3), ); session.startSession(config).listen((event) { switch (event) { case SessionStarted(): print('Session started'); case SessionFrame(): print('HR: ${event.metrics['hr_mean_bpm']} bpm'); case BiosignalFrame(): print('Raw samples: ${event.samples.length}'); case SessionSummary(): print('Done: ${event.durationActualSec}s'); case SessionError(): print('Error [${event.code.value}]: ${event.message}'); } }); ``` `SessionEvent` is sealed, so a `switch` without a `default` must cover all five subclasses, including `BiosignalFrame()`. ### Live Mode with a Companion Watch ```dart theme={null} final session = SynheartSession( biosignalProvider: WatchBiosignalProvider(), ); final config = SessionConfig( mode: SessionMode.breathing, durationSec: 60, ); final subscription = session.startSession(config).listen( (event) { // Handle events }, onDone: () { print('Stream closed'); }, ); // Stop early await session.stopSession(config.sessionId); // Clean up session.dispose(); ``` `SynheartSession()` takes two optional named arguments: `biosignalProvider` and `behaviorProvider`. Watch routing happens only when `biosignalProvider` is a `WatchBiosignalProvider`: `startSession` and `stopSession` then also send `start_session` / `stop_session` commands to the companion app (WatchConnectivity on iOS, Wearable Data Layer on Android). The watch's events feed the phone-side engine as HR samples, and the phone-side engine emits the frames you receive. There is no fallback to another source. If no watch is reachable, frames still arrive on schedule with `sample_count` 0 and `hr_mean_bpm` 0.0. With no `biosignalProvider` at all, the same happens. See [Lifecycle](/synheart-session/lifecycle#fallback-semantics). ## Watch Connectivity Query watch connectivity status from your Flutter app: ```dart theme={null} final session = SynheartSession(biosignalProvider: WatchBiosignalProvider()); final status = await session.getWatchStatus(); if (status != null) { print('Supported: ${status.supported}'); print('Paired: ${status.paired}'); print('Installed: ${status.installed}'); print('Reachable: ${status.reachable}'); } ``` `WatchStatus` fields: | Field | Type | Description | | - | - | - | | `supported` | `bool` | iOS: WatchConnectivity is supported. Android: Google Play services is available | | `paired` | `bool` | iOS: an Apple Watch is paired. Android: same as `reachable` | | `installed` | `bool` | iOS: the companion watch app is installed. Android: same as `reachable` | | `reachable` | `bool` | iOS: `WCSession.isReachable`. Android: at least one Wear OS node is connected | > [!NOTE] > > `getWatchStatus()` returns `null` in mock mode and whenever `biosignalProvider` is not a `WatchBiosignalProvider`. On iOS, `reachable` requires the watch to be paired, the companion app installed, and the watch app reachable. The start command is only sent when the watch is reachable at the moment `startSession` is called. ## Session Configuration ```dart theme={null} final config = SessionConfig( mode: SessionMode.focus, // focus, breathing, or typing durationSec: 60, // session duration in seconds profile: const ComputeProfile( windowSec: 10, // sliding window size emitIntervalSec: 3, // session frame interval ), windowLabel: 'morning-check', // optional label ); // Auto-generated UUID accessible via config.sessionId ``` ### SessionConfig | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `mode` | `SessionMode` | Yes | - | `SessionMode.focus`, `SessionMode.breathing`, or `SessionMode.typing` | | `durationSec` | `int` | Yes | - | Session duration in seconds | | `profile` | `ComputeProfile` | No | 60s window, 5s interval | Session frame computation timing | | `windowLabel` | `String?` | No | `null` | Optional label for the session window | | `includeRawSamples` | `bool` | No | `false` | Enable raw biosignal frames (mock engine only) | | `sessionId` | `String?` | No | Auto-generated UUID | Custom session ID | ### ComputeProfile | Parameter | Type | Default | Description | | - | - | - | - | | `windowSec` | `int` | 60 | Sliding window size in seconds | | `emitIntervalSec` | `int` | 5 | How often to emit session frames in seconds | | `rawEmitIntervalSec` | `int?` | `null` | How often to emit raw biosignal frames (defaults to `emitIntervalSec`) | ## Session Events All events extend the sealed `SessionEvent` class and include a `sessionId`. ### SessionStarted Emitted immediately when `startSession` is called. ```dart theme={null} case SessionStarted(): print('Started at ${event.startedAtMs}'); ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startedAtMs` | `int` | Unix timestamp in milliseconds | ### SessionFrame Emitted at each `emitIntervalSec` with computed session metrics. ```dart theme={null} case SessionFrame(): final hr = event.metrics['hr_mean_bpm'] as double?; final rmssd = event.metrics['rmssd_ms'] as double?; print('HR: $hr bpm, RMSSD: $rmssd ms'); // Optional behavioral signals if (event.behavior != null) { print('Stability: ${event.behavior!['stability_index']}'); } ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `seq` | `int` | Frame sequence number (1-based) | | `emittedAtMs` | `int` | Unix timestamp in milliseconds | | `metrics` | `Map` | Flat metrics map (see below) | | `behavior` | `Map?` | Optional behavioral signals (when a `BehaviorProvider` is configured) | **Live engine `metrics` keys:** | Key | Type | Description | | - | - | - | | `hr_mean_bpm` | `double` | Mean HR over the window, one decimal; `0.0` when the window is empty | | `hr_sdnn_ms` | `double` | From `ingestHsiMetrics` (`hrv.sdnn_ms`), else `0.0` | | `rmssd_ms` | `double` | From `ingestHsiMetrics` (`hrv.rmssd_ms`), else `0.0` | | `pnn50` | `double` | From `ingestHsiMetrics` (`hrv.pnn50`), else `0.0` | | `sample_count` | `int` | Samples in the window | | `start_ms` / `end_ms` | `int` | First and last sample timestamps (the current time when the window is empty) | | `session_id` | `String` | Session identifier | | `mode` | `String` | Session mode value | | `seq` | `int` | Frame sequence number | The mock engine emits the same keys except `pnn50`, computes synthetic `hr_sdnn_ms` and `rmssd_ms` from its generated data, and adds `"mock": true`. ### BiosignalFrame Emitted at each `rawEmitIntervalSec` when `includeRawSamples` is `true`. In 0.3.0 only the mock engine emits `BiosignalFrame`; the live engine does not. ```dart theme={null} case BiosignalFrame(): for (final sample in event.samples) { print('BPM: ${sample.bpm}, RR: ${sample.rrIntervalMs} ms'); if (sample.accelerometer case final accel?) { print('Accel: (${accel.x}, ${accel.y}, ${accel.z})'); } } ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `seq` | `int` | Raw frame sequence number (1-based, separate from `SessionFrame.seq`) | | `emittedAtMs` | `int` | Unix timestamp in milliseconds | | `samples` | `List` | Raw biosignal samples | **BiosignalSample fields:** | Field | Type | Description | | - | - | - | | `timestampMs` | `int` | Unix timestamp in milliseconds | | `bpm` | `double` | Heart rate | | `rrIntervalMs` | `double?` | Inter-beat interval in milliseconds | | `accelerometer` | `({double x, double y, double z})?` | 3-axis accelerometer (synthetic in the mock engine) | | `spo2` | `double?` | SpO2 percentage (0-100) | ### SessionSummary Emitted when the session completes (duration elapsed or stopped manually). The stream closes after it. ```dart theme={null} case SessionSummary(): print('Duration: ${event.durationActualSec}s'); print('Avg HR: ${event.metrics['hr_mean_bpm']} bpm'); ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `durationActualSec` | `int` | Actual session duration in seconds | | `metrics` | `Map` | Metrics over the final window (same keys as `SessionFrame`) | | `behavior` | `Map?` | Behavioral snapshot taken at the end | ### SessionError Part of the sealed hierarchy and of the wire format. Neither Dart engine emits it in 0.3.0; misuse is reported by throwing `SessionInvalidStateError` instead. See [Errors](/synheart-session/errors). ```dart theme={null} case SessionError(): print('[${event.code.value}]: ${event.message}'); ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `code` | `SessionErrorCode` | Error code | | `message` | `String` | Human-readable error message | **Error codes:** | Code | Description | | - | - | | `permission_denied` | Health data permissions not granted | | `sensor_unavailable` | Heart rate sensor not available | | `low_battery` | Device battery too low | | `os_terminated` | Operating system terminated the session | | `invalid_state` | Invalid session state | ## HRV Metrics The live engine does not compute HRV. Pass values from your HRV source (typically the Synheart runtime) with `ingestHsiMetrics`; the latest map is used for every following frame and the summary: ```dart theme={null} session.ingestHsiMetrics(config.sessionId, { 'hrv.sdnn_ms': 48.2, 'hrv.rmssd_ms': 36.5, 'hrv.pnn50': 14.0, }); ``` It is a no-op in mock mode, after `dispose()`, or when no session with that id is running. ## Behavioral Signals Pass a `BehaviorProvider` to `SynheartSession()` or `SynheartSession.mock()`. The engine pulls a snapshot at each frame and once more for the summary. The Dart SDK bundles `MockBehaviorProvider`; to use real behavioral data, implement `BehaviorProvider` over your behavior source (see [Providers](/synheart-session/providers#behaviorprovider)). ### Mock Mode ```dart theme={null} import 'package:synheart_session/synheart_session.dart'; final session = SynheartSession.mock( seed: 42, behaviorProvider: MockBehaviorProvider(), ); final config = SessionConfig( mode: SessionMode.focus, durationSec: 30, profile: const ComputeProfile(windowSec: 10, emitIntervalSec: 3), ); session.startSession(config).listen((event) { switch (event) { case SessionFrame(): print('HR: ${event.metrics['hr_mean_bpm']}'); if (event.behavior != null) { print('Stability: ${event.behavior!['stability_index']}'); print('Fragmentation: ${event.behavior!['fragmentation_index']}'); } case SessionSummary(): print('Done: ${event.durationActualSec}s'); if (event.behavior != null) { print('Final stability: ${event.behavior!['stability_index']}'); } default: break; } }); ``` ### Behavioral Fields When present, the `behavior` map on `SessionFrame` and `SessionSummary` includes: | Field | Type | Description | | - | - | - | | `typing_cadence` | `double?` | Keys per second | | `inter_key_latency` | `double?` | Milliseconds between keystrokes | | `burst_length` | `int?` | Keys in current burst | | `scroll_velocity` | `double?` | Pixels per second | | `scroll_acceleration` | `double?` | Pixels per second squared | | `scroll_jitter` | `double?` | Variance in scroll speed | | `tap_rate` | `double?` | Taps per second | | `app_switches_per_minute` | `int` | App switches per minute | | `foreground_duration` | `double?` | Seconds in foreground | | `idle_gap_seconds` | `double?` | Idle gap duration in seconds | | `stability_index` | `double?` | 0.0 to 1.0 | | `fragmentation_index` | `double?` | 0.0 to 1.0 | | `timestamp` | `int` | Capture timestamp (ms since epoch) | > [!NOTE] > > The `behavior` key is only present when a `BehaviorProvider` is configured, reports `isAvailable`, and returns a snapshot. Null optional fields are omitted from the map. ## Complete Example ```dart theme={null} import 'dart:async'; import 'package:flutter/material.dart'; import 'package:synheart_session/synheart_session.dart'; class SessionDemo extends StatefulWidget { const SessionDemo({super.key}); @override State createState() => _SessionDemoState(); } class _SessionDemoState extends State { final _session = SynheartSession.mock(seed: 42); StreamSubscription? _subscription; SessionConfig? _activeConfig; double _hr = 0; bool _running = false; void _start() { final config = SessionConfig( mode: SessionMode.focus, durationSec: 30, profile: const ComputeProfile(windowSec: 10, emitIntervalSec: 3), ); setState(() { _activeConfig = config; _running = true; }); _subscription = _session.startSession(config).listen( (event) { switch (event) { case SessionFrame(): setState(() { _hr = (event.metrics['hr_mean_bpm'] as num?)?.toDouble() ?? 0; }); case SessionSummary(): setState(() => _running = false); default: break; } }, onDone: () => setState(() => _running = false), ); } Future _stop() async { if (_activeConfig != null) { await _session.stopSession(_activeConfig!.sessionId); } } @override void dispose() { _subscription?.cancel(); _session.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('HR: ${_hr.toStringAsFixed(1)} bpm', style: const TextStyle(fontSize: 32)), const SizedBox(height: 16), ElevatedButton( onPressed: _running ? _stop : _start, child: Text(_running ? 'Stop' : 'Start'), ), ], ), ), ); } } ``` ## API Reference ### SynheartSession | Constructor | Description | | - | - | | `SynheartSession({BiosignalProvider? biosignalProvider, BehaviorProvider? behaviorProvider})` | Live mode. Watch commands are sent only when `biosignalProvider` is a `WatchBiosignalProvider` | | `SynheartSession.mock({int? seed, BehaviorProvider? behaviorProvider})` | Mock mode with seeded synthetic data and optional behavioral signals | | Method | Returns | Description | | - | - | - | | `startSession(SessionConfig)` | `Stream` | Start a session. Throws `SessionInvalidStateError` synchronously if a session with the same `sessionId` is running or the instance is disposed | | `stopSession(String sessionId)` | `Future` | Stop a running session (emits `SessionSummary`); also sends `stop_session` to the watch when routing is active | | `getStatus()` | `Future` | Status of an active session, or `null` | | `getWatchStatus()` | `Future` | Watch connectivity; `null` unless `biosignalProvider` is a `WatchBiosignalProvider` | | `ingestHsiMetrics(String sessionId, Map)` | `void` | Supply HRV values to the live engine | | `dispose()` | `void` | Release all resources | ## Resources * **Repository**: [synheart-session-flutter](https://github.com/synheart-ai/synheart-session-flutter) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-session-flutter/issues) # Synheart Session - Kotlin SDK Source: https://docs.synheart.ai/synheart-session/kotlin Native Kotlin SDK for Android with SynheartSession, a typed SharedFlow of events, pluggable providers, and WatchSessionRelay for Wear OS ## Overview The Synheart Session Kotlin SDK provides `SynheartSession`, a timer-driven session engine that buffers heart-rate samples from a `BiosignalProvider`, emits typed `SessionEvent`s on a `SharedFlow`, and delivers a `SessionSummary` when the session ends. An optional `BehaviorProvider` adds behavioral signals to each frame. The bundled wrappers for synheart-wear and synheart-behavior use reflection, so those libraries are only needed at runtime. `WatchSessionRelay` runs a session on a companion Wear OS watch instead and streams the watch's events back. > [!NOTE] > > The SDK computes mean HR locally. HRV (`hr_sdnn_ms`, `rmssd_ms`, `pnn50`) is supplied by the host through `ingestHsiMetrics()` and is `0.0` until then. ## Installation ### Maven Central ```groovy theme={null} dependencies { implementation 'ai.synheart:synheart-session:0.4.0' } ``` `kotlinx-coroutines-core` is an `api` dependency, so `Flow` and `SharedFlow` are available to your code without adding it yourself. ### Local Module ```groovy theme={null} // settings.gradle include ':synheart-session' project(':synheart-session').projectDir = new File('../synheart-session-kotlin') // build.gradle dependencies { implementation project(':synheart-session') } ``` ### Requirements * Android API 21+ (`minSdk 21`) * Java 17 bytecode * The library is built with Kotlin 2.3.0 and depends on `kotlin-stdlib` 2.3.0 ## Quick Start ### Mock Mode (Development) ```kotlin theme={null} import ai.synheart.session.* import android.util.Log import androidx.lifecycle.lifecycleScope import java.util.UUID import kotlinx.coroutines.flow.transformWhile import kotlinx.coroutines.launch val session = SynheartSession() // MockBiosignalProvider by default val config = SessionConfig( sessionId = UUID.randomUUID().toString(), mode = SessionMode.FOCUS, durationSec = 300, profile = ComputeProfile(windowSec = 60, emitIntervalSec = 5) ) lifecycleScope.launch { session.startSession(config) // The SharedFlow never completes: stop after the terminal event. .transformWhile { event -> emit(event) event !is SessionSummary && event !is SessionErrorEvent } .collect { event -> when (event) { is SessionStarted -> Log.d("Session", "Started") is SessionFrame -> Log.d("Session", "HR: ${event.metrics["hr_mean_bpm"]} bpm") is BiosignalFrame -> Log.d("Session", "Raw samples: ${event.samples.size}") is SessionSummary -> Log.d("Session", "Complete: ${event.durationActualSec}s") is SessionErrorEvent -> Log.e("Session", "Error [${event.code.value}]: ${event.message}") } } } // Stop early (optional) — emits SessionSummary session.stopSession(config.sessionId) ``` `startSession` returns a hot `SharedFlow` that replays up to 1024 events, so a collector that subscribes after the start still sees `SessionStarted`. The flow never completes on its own; end collection on `SessionSummary` or `SessionErrorEvent` (for example with `transformWhile`, as above). ### Real BLE Heart Rate Data ```kotlin theme={null} import ai.synheart.session.* // bleHrmProvider is a connected synheart-wear BleHrmProvider (passed as Any, read via reflection) val provider = WearBiosignalProvider(bleHrmProvider) val session = SynheartSession(provider) val events = session.startSession(config) // Same event handling — metrics are now computed from real HR data ``` If the BLE HRM is not connected when the session starts, the session emits a `SessionErrorEvent` with `SENSOR_UNAVAILABLE` and ends. ### Health Connect Heart Rate Data ```kotlin theme={null} import ai.synheart.session.* // healthConnectAdapter is an initialized synheart-wear HealthConnectAdapter val provider = HealthConnectBiosignalProvider(healthConnectAdapter, context) if (provider.isAvailable) { val session = SynheartSession(provider) val events = session.startSession(config) } ``` The provider polls the adapter's `readSnapshot()` every 2 seconds by default (`pollIntervalMs`). Each sample's `rr_intervals_ms` is derived from BPM (`60000 / bpm`), not measured. ## Session Configuration ```kotlin theme={null} val config = SessionConfig( sessionId = UUID.randomUUID().toString(), mode = SessionMode.FOCUS, // FOCUS, BREATHING, or TYPING durationSec = 60, // session duration in seconds profile = ComputeProfile( windowSec = 10, // sliding window size emitIntervalSec = 3 // session frame interval ) ) ``` ### SessionConfig | Parameter | Type | Required | Default | Description | | - | - | - | - | - | | `sessionId` | `String` | Yes | - | Unique session identifier | | `mode` | `SessionMode` | Yes | - | `FOCUS`, `BREATHING`, or `TYPING` | | `durationSec` | `Int` | Yes | - | Session duration in seconds | | `profile` | `ComputeProfile` | No | 60s/5s | Window and emit configuration | | `windowLabel` | `String?` | No | `null` | Optional label for the session window | | `includeRawSamples` | `Boolean` | No | `false` | Enable raw biosignal frames | ### ComputeProfile | Parameter | Type | Default | Description | | - | - | - | - | | `windowSec` | `Int` | 60 | Sliding window size in seconds | | `emitIntervalSec` | `Int` | 5 | Session frame emission interval in seconds | | `rawEmitIntervalSec` | `Int?` | `null` | Raw biosignal frame interval (defaults to `emitIntervalSec`) | ## Session Events `SessionEvent` is a sealed class. Every subclass has `sessionId` and `toMap()`, which returns the snake\_case wire map shared with the other SDKs. ### SessionStarted Emitted immediately by `startSession`. | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `startedAtMs` | `Long` | Unix timestamp in milliseconds | ### SessionFrame Emitted every `emitIntervalSec` while the window holds at least one sample (frames are skipped while it is empty). ```kotlin theme={null} is SessionFrame -> { val hr = event.metrics["hr_mean_bpm"] as? Double val rmssd = event.metrics["rmssd_ms"] as? Double // 0.0 unless ingested val behavior = event.behavior // null without a BehaviorProvider } ``` | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `seq` | `Int` | Frame sequence number (1-based) | | `emittedAtMs` | `Long` | Unix timestamp in milliseconds | | `metrics` | `Map` | Flat metrics (see below) | | `behavior` | `Map?` | Behavioral snapshot, when a `BehaviorProvider` returns one | **`metrics` keys:** | Key | Type | Description | | - | - | - | | `hr_mean_bpm` | `Double` | Mean heart rate (BPM), one decimal | | `hr_sdnn_ms` | `Double` | From `ingestHsiMetrics` (`hrv.sdnn_ms`), else `0.0` | | `rmssd_ms` | `Double` | From `ingestHsiMetrics` (`hrv.rmssd_ms`), else `0.0` | | `pnn50` | `Double` | From `ingestHsiMetrics` (`hrv.pnn50`), else `0.0` | | `sample_count` | `Int` | Number of HR samples in the window | | `start_ms` | `Long` | First sample timestamp in the window (ms) | | `end_ms` | `Long` | Last sample timestamp in the window (ms) | ### BiosignalFrame Emitted every `rawEmitIntervalSec` when `includeRawSamples = true` and the window is not empty. `seq` is a separate counter from `SessionFrame.seq`. ```kotlin theme={null} is BiosignalFrame -> event.samples.forEach { sample -> val bpm = sample["bpm"] as? Double @Suppress("UNCHECKED_CAST") val rr = sample["rr_intervals_ms"] as? List // plural, list of ms val source = sample["source"] as? String } ``` Each sample map has `timestamp_ms`, `bpm`, `source`, and, when the provider supplies them, `rr_intervals_ms` and `device_id`. ### SessionSummary Emitted once when the duration elapses or `stopSession` is called. | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `durationActualSec` | `Int` | Actual session duration in seconds | | `metrics` | `Map` | Metrics over the final window (same keys as `SessionFrame`) | | `behavior` | `Map?` | Behavioral snapshot taken at the end | ### SessionErrorEvent Emitted instead of a summary when the session ends abnormally — for example when the provider throws from `startStreaming`, which ends the session with `SENSOR_UNAVAILABLE`. | Field | Type | Description | | - | - | - | | `sessionId` | `String` | Session identifier | | `code` | `SessionErrorCode` | Error code | | `message` | `String` | Human-readable message | On the wire (`toMap()`), the code is under `error_code`. **Error codes (`SessionErrorCode`):** | Value | Wire string | Description | | - | - | - | | `PERMISSION_DENIED` | `permission_denied` | Health data permissions not granted | | `SENSOR_UNAVAILABLE` | `sensor_unavailable` | Heart rate sensor not available | | `INVALID_STATE` | `invalid_state` | Invalid session state | | `LOW_BATTERY` | `low_battery` | Device battery too low | | `OS_TERMINATED` | `os_terminated` | Operating system terminated the session | API misuse throws instead: `startSession` throws `SessionError.InvalidState` if any session is already running (whatever its id) or the instance is disposed, and `stopSession` throws it if no session is running or the id does not match. See [Errors](/synheart-session/errors). ## HRV Metrics ```kotlin theme={null} session.ingestHsiMetrics(config.sessionId, mapOf( "hrv.sdnn_ms" to 48.2, "hrv.rmssd_ms" to 36.5, "hrv.pnn50" to 14.0, )) ``` The latest map replaces the previous one and is used for every following frame and the summary. The call is a no-op after `dispose()` or when `sessionId` does not match the running session. ## Behavioral Signals `SynheartSession` accepts an optional `BehaviorProvider`. The engine pulls a snapshot at each frame and once more for the summary. ### Mock Behavior (Development) ```kotlin theme={null} val session = SynheartSession(behaviorProvider = MockBehaviorProvider()) lifecycleScope.launch { session.startSession(config) .transformWhile { emit(it); it !is SessionSummary && it !is SessionErrorEvent } .collect { event -> if (event is SessionFrame) { Log.d("Session", "Stability: ${event.behavior?.get("stability_index")}") } } } ``` ### Production (via synheart-behavior) ```kotlin theme={null} // Wrap a synheart-behavior SynheartBehavior instance (reflection-based) val behaviorProvider = BehaviorSdkProvider(behaviorSdkInstance) val session = SynheartSession(behaviorProvider = behaviorProvider) ``` `BehaviorSdkProvider` reports `isAvailable` from the SDK's `isInitialized()` and reads `getCurrentStats()` at each frame. The `behavior` field is only present when a `BehaviorProvider` is configured, reports `isAvailable`, and returns a snapshot. ## Companion Watch Sessions (Wear OS) `WatchSessionRelay` drives a session on a paired Wear OS watch over the Wearable Data Layer. The watch's companion app runs the session; the relay sends commands and decodes the watch's events into `SessionEvent`s. It is independent of `SynheartSession`. The Play Services libraries are `compileOnly` in the SDK, so a host that uses the relay must add them itself: ```groovy theme={null} dependencies { implementation 'ai.synheart:synheart-session:0.4.0' implementation 'com.google.android.gms:play-services-wearable:18.2.0' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3' } ``` The relay uses `await()` from `kotlinx-coroutines-play-services`. Without `play-services-wearable` (or on a device without Google Play services), `status()` reports `supported = false` and `startSession` emits a `SessionErrorEvent` rather than crashing. ```kotlin theme={null} import ai.synheart.session.* import kotlinx.coroutines.launch val relay = WatchSessionRelay(context) lifecycleScope.launch { val status = relay.status() if (!status.canStartSession) return@launch // Completes after the watch's SessionSummary or SessionErrorEvent. relay.startSession(config).collect { event -> when (event) { is SessionFrame -> Log.d("Watch", "HR: ${event.metrics["hr_mean_bpm"]}") is SessionErrorEvent -> Log.e("Watch", event.message) else -> Unit } } } // Later, from a coroutine: // relay.stopSession(config.sessionId) ``` | Member | Description | | - | - | | `suspend fun status(): WatchStatus` | Connectivity snapshot. Never throws | | `fun startSession(config): Flow` | Sends `start_session` to every connected node and emits the watch's events. Completes on the watch's `SessionSummary` or `SessionErrorEvent` | | `suspend fun stopSession(sessionId)` | Sends `stop_session`. Best-effort; the watch also stops on its own duration timer | | `fun hrSamples(): Flow` | Heart-rate readings the watch sends (`timestampMs`, `bpm`), independent of the session flow | `startSession` emits a `SessionErrorEvent` with `SENSOR_UNAVAILABLE` instead of throwing when Play Services is unavailable, when no node accepts the command, or when the watch sends nothing within 10 seconds. A node can accept the message while no app answers it — the Data Layer delivers only between apps with the same package name and signing certificate. `WatchStatus` has `supported`, `reachable`, `paired`, `installed`, and `canStartSession` (`supported && reachable`). Wear OS gives no separate paired/installed signal, so `paired` and `installed` track `reachable`. The message format is described in [Watch Protocol](/synheart-session/watch-protocol). ## Architecture ```text theme={null} SynheartSession(provider: BiosignalProvider = MockBiosignalProvider(), behaviorProvider: BehaviorProvider? = null) | +-- BiosignalProvider (interface, callback-based) | +-- MockBiosignalProvider (sinusoidal mock, 1 Hz) | +-- WearBiosignalProvider (wraps synheart-wear BleHrmProvider, reflection-based) | +-- HealthConnectBiosignalProvider (wraps synheart-wear HealthConnectAdapter, reflection-based) | +-- BehaviorProvider (interface, pull-based) | +-- MockBehaviorProvider (stable mid-range values) | +-- BehaviorSdkProvider (wraps synheart-behavior, reflection-based) | +-- SampleRingBuffer (thread-safe sliding window) +-- SessionError (sealed exception class with 5 subclasses) WatchSessionRelay(context) (Wear OS companion sessions over the Wearable Data Layer) ``` ## Custom Provider Any class implementing `BiosignalProvider` can drive the session: ```kotlin theme={null} class MyProvider : BiosignalProvider { override val isAvailable = true override val name = "my_source" override fun startStreaming(onSample: (BiosignalSample) -> Unit) { // Push samples into the callback, e.g. // onSample(BiosignalSample(timestampMs = now, bpm = 72.0, source = name)) } override fun stopStreaming() { } } val session = SynheartSession(MyProvider()) ``` ## API Reference ### SynheartSession | Constructor | Description | | - | - | | `SynheartSession()` | Default `MockBiosignalProvider`, no behavior | | `SynheartSession(provider)` | Custom biosignal provider | | `SynheartSession(provider, behaviorProvider)` | Custom biosignal + behavioral providers | | `SynheartSession(behaviorProvider = bp)` | Default mock biosignal + behavioral provider | | Method | Description | | - | - | | `startSession(config): SharedFlow` | Start a session. Throws `SessionError.InvalidState` if a session is already running or the instance is disposed | | `stopSession(sessionId)` | Stop the running session and emit `SessionSummary`. Throws `SessionError.InvalidState` if no session is running or the id does not match. No-op after `dispose()` | | `getStatus(): SessionStatus?` | `SessionStatus(sessionId, active, lastSeq)`, or `null` if no session is running | | `ingestHsiMetrics(sessionId, hsiMetrics)` | Supply HRV values for the running session | | `dispose()` | Stop timers and the provider and release state. Later `startSession` calls throw | ## Resources * **Repository**: [synheart-session-kotlin](https://github.com/synheart-ai/synheart-session-kotlin) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-session-kotlin/issues) # Session Lifecycle and State Source: https://docs.synheart.ai/synheart-session/lifecycle Event-stream lifecycle, who drives each transition, watch sessions without fallback, and disposal Each SDK runs a small timer-driven engine: Dart `LiveSessionEngine` and `MockSessionEngine` behind `SynheartSession`, and `SynheartSession` itself in Kotlin and Swift. None of them exposes a state enum; a session is either running or not, and `getStatus()` reports which. ## Session status ```dart theme={null} class SessionStatus { final String sessionId; final bool active; final int lastSeq; } ``` `getStatus()` returns a `SessionStatus` while a session is running (`active` is always `true`) and `null` otherwise. Kotlin and Swift return the same shape (`SessionStatus(sessionId, active, lastSeq)`), and return `null` after `dispose()`. `lastSeq` is the last `SessionFrame` sequence number. Kotlin and Swift run one session at a time per `SynheartSession`. The Dart `SynheartSession` refuses only a second start with the same `sessionId`. ## Event-stream lifecycle ```text theme={null} SessionStarted (emitted immediately by startSession) → SessionFrame (seq=1) → SessionFrame (seq=2) → ... [interleaved BiosignalFrame events when includeRawSamples — Kotlin, Swift, Dart mock] → SessionSummary (duration elapsed or stopSession) OR → SessionError (Kotlin / Swift: the provider failed to start) ``` How the stream ends: | SDK | Stream type | After `SessionSummary` / error | | - | - | - | | Dart | `Stream` (broadcast) | Closes | | Swift | `AsyncStream` | Finishes | | Kotlin | `SharedFlow` (replay 1024) | Never completes — stop collecting on `SessionSummary` / `SessionErrorEvent` yourself | ## Who drives transitions | Transition | Driver | | - | - | | Start | `startSession(config)`. The engine emits `SessionStarted` right away, then starts the provider and the frame timer, plus a separate duration timer. In Flutter, when the provider is a `WatchBiosignalProvider`, `SynheartSession` also sends `start_session` to the watch after the engine has subscribed to the provider. | | Provider failure (Kotlin / Swift) | If `startStreaming` throws, the engine emits a `sensor_unavailable` error event and resets; no frames follow. | | Frame tick | Kotlin / Swift: emit a `SessionFrame` if the window holds at least one sample, otherwise skip the tick. Dart: increment `seq`; if `durationSec` has elapsed, finish the session, otherwise emit a frame (the live engine emits even when the window is empty). | | Duration elapsed | The duration timer stops the provider, computes the final metrics, and emits `SessionSummary`. | | `stopSession(id)` | Same as duration elapsed. In Flutter with watch routing, a `stop_session` command is also sent to the watch. | ### Window Kotlin and Swift keep every sample within `windowSec` of the newest sample. The Dart live engine keeps the last `windowSec` samples and uses those within `windowSec` of the current time. `hr_mean_bpm` is the mean of the window; HRV values come from `ingestHsiMetrics()`. ## Phone-watch lifecycle (Flutter) When the provider is a `WatchBiosignalProvider`, two sessions run: * **Watch session**: the companion app reads the sensor and sends session events to the phone over WatchConnectivity / Wearable Data Layer. * **Phone session** (Dart `LiveSessionEngine`): fed by `WatchBiosignalProvider`, which turns the watch's events into `BiosignalSample`s. The host receives the phone engine's events only. The watch's own frames and summary are consumed as HR input and are not passed through, so this re-windowing gives the host a single `Stream` whatever the source. The phone subscribes to the provider inside `startSession`, before the `start_session` command is sent, so early watch events are not missed. In Kotlin, `WatchSessionRelay` works differently: no phone engine is involved, and the watch's events are decoded and emitted as they arrive. In Swift there is no phone-side relay. ## Fallback semantics There is no automatic fallback to a different provider. When the watch is unreachable but a `WatchBiosignalProvider` is configured, the phone engine still emits `SessionStarted` (the provider reports `isAvailable = true` optimistically), and the start command is not sent. The HR buffer stays empty, so frames fire on schedule with `sample_count` 0 and `hr_mean_bpm` 0.0. For a different source, construct another `SynheartSession` with a different `BiosignalProvider` (for example `MockBiosignalProvider`, or your own provider over a BLE HRM). `WatchBiosignalProvider` has a synthesis path: when the watch sends only `SessionFrame` events (no raw samples), it derives one `BiosignalSample` per frame from `metrics.hr_mean_bpm`, with `rrIntervalMs = 60000.0 / bpm`. Frames with `hr_mean_bpm` 0 or missing produce no sample. ## Reconnect behaviour If the watch disconnects mid-session: * `WatchBiosignalProvider` swallows channel errors as non-fatal. * The phone session keeps running and emits frames from whatever samples arrive. * The session does **not** auto-stop. Hosts that want strict reachability must poll `getWatchStatus()` and stop manually. ## Frame sequencing `SessionFrame.seq` starts at `1`. `BiosignalFrame.seq` is a separate counter, also starting at `1`, in Kotlin, Swift, and the Dart mock engine. `emittedAtMs` is wall-clock epoch ms at the producer. Treat watch and phone timestamps as the same clock, but don't assume sub-second sync. ## Disposal | SDK | `dispose()` | | - | - | | Dart | Cancels running sessions and closes their streams without a `SessionSummary`, and stops the provider. Afterwards `startSession`, `stopSession`, `getStatus`, and `getWatchStatus` throw `SessionInvalidStateError("SynheartSession has been disposed")`; `ingestHsiMetrics` and `dispose` are no-ops. | | Kotlin | Cancels timers and stops the provider without emitting a summary. Afterwards `startSession` throws `SessionError.InvalidState`; `stopSession`, `ingestHsiMetrics`, and `dispose` are no-ops; `getStatus` returns `null`. | | Swift | Cancels timers, stops the provider, and finishes the stream without a summary. Afterwards `startSession` throws `SessionError.invalidState`; `stopSession`, `ingestHsiMetrics`, and `dispose` are no-ops; `getStatus` returns `nil`. | In Flutter, `dispose()` does not send `stop_session` to the watch — only `stopSession(id)` does. If the host disposes mid-session without stopping, the watch keeps running until its own duration timer ends the session. ## Related * [Providers](/synheart-session/providers) — what feeds the engine. * [Watch Protocol](/synheart-session/watch-protocol) — the commands and events on the wire. * [Errors](/synheart-session/errors) — error events and thrown exceptions. # Synheart Session Overview Source: https://docs.synheart.ai/synheart-session/overview Timed sessions with a typed event stream, mean HR computed on-device, HRV supplied by the host, and optional behavioral signals ## What is Synheart Session? Synheart Session is an SDK for running timed biometric sessions. A session buffers heart-rate samples from a pluggable `BiosignalProvider` in a sliding window, emits a `SessionFrame` with flat metrics at a fixed interval, and delivers a `SessionSummary` when the session ends. A `BehaviorProvider` can add timing-based behavioral signals to each frame. The SDK computes mean heart rate on-device. It does **not** compute HRV: `hr_sdnn_ms`, `rmssd_ms`, and `pnn50` come from the host through `ingestHsiMetrics()` (typically from the Synheart runtime) and are `0.0` until the host supplies them. For real-time data from a smartwatch, Synheart's companion watch apps (watchOS and Wear OS) run the session on the watch and stream events to the phone. The phone SDKs relay start/stop commands and receive those events. There is no automatic fallback to a phone-side source: if no watch is reachable, the session gets no heart-rate data. See [Lifecycle](/synheart-session/lifecycle). ## Key Features ### Session Lifecycle * **Configurable sessions**: Set mode (`focus`, `breathing`, `typing`), duration, and compute profile * **Streaming session frames**: Periodic frames with flat metrics during the session * **Session summary**: A final frame computed when the session ends * **Typed event stream**: `SessionStarted`, `SessionFrame`, `BiosignalFrame`, `SessionSummary`, `SessionError` * **Optional raw biosignal streaming**: Opt-in `includeRawSamples` for a live HR trace ### Pluggable Providers * **BiosignalProvider**: HR source — mock (sinusoidal), BLE HRM and Health Connect (Kotlin, via synheart-wear), HealthKit and BLE HRM (Swift, via synheart-wear), companion watch (Flutter) * **BehaviorProvider**: Optional pull-based behavioral source — mock, or synheart-behavior (bundled wrapper in Kotlin and Swift) * Providers are constructor arguments of `SynheartSession` and are optional; the Kotlin and Swift default biosignal provider is the mock ### Phone-Watch Streaming * **Flutter**: pass a `WatchBiosignalProvider` and the SDK sends start/stop commands to the companion app on Apple Watch (WatchConnectivity) or Wear OS (Wearable Data Layer) * **Kotlin**: `WatchSessionRelay` drives a session on a Wear OS watch and returns the watch's events as a `Flow` * **Swift**: the Swift SDK runs sessions on the device it is linked into (including watchOS); it does not include a phone-side relay ### Cross-Platform * **Flutter/Dart**: `SynheartSession()` (live) and `SynheartSession.mock()` (simulated) * **Kotlin**: `SynheartSession` returning a `SharedFlow` * **Swift**: `SynheartSession` returning an `AsyncStream` * **Wire format**: every SDK serializes events to the same snake\_case map (`toJson()` / `toMap()` / `toDictionary()`) ## Architecture ```text theme={null} Host app | startSession(config) v SynheartSession |-- BiosignalProvider --> samples --> sliding window (windowSec) |-- BehaviorProvider --> snapshot pulled at each frame |-- ingestHsiMetrics() --> HRV values from the host v Stream of SessionEvent SessionStarted -> SessionFrame* (+ BiosignalFrame*) -> SessionSummary ``` With a companion watch, the session on the watch produces the events and the phone receives them: ```text theme={null} Phone Watch companion app start_session (JSON command) ---> runs the session <--- session events (JSON) session_started, session_frame, ... stop_session (JSON command) ---> emits session_summary ``` See [Watch Protocol](/synheart-session/watch-protocol) for the message format. ### Event Flow 1. You call `startSession(config)`, which returns a stream of `SessionEvent`s 2. `SessionStarted` is emitted immediately 3. `SessionFrame` events arrive every `emitIntervalSec` 4. If `includeRawSamples` is `true`, `BiosignalFrame` events also arrive every `rawEmitIntervalSec` (defaults to `emitIntervalSec`) — Kotlin, Swift, and the Flutter mock engine 5. When the duration elapses or you call `stopSession`, a `SessionSummary` is emitted 6. The Flutter stream and the Swift stream finish after the summary. The Kotlin `SharedFlow` never completes, so stop collecting on `SessionSummary` or `SessionErrorEvent` ## Session Modes | Mode | Description | | - | - | | `focus` | Focus or attention session | | `breathing` | Breathing session | | `typing` | Typing session: the host brackets a keyboard lifecycle with a watch session | The phone-side engines compute the same metrics in every mode. The mode is carried in the config and forwarded to the watch in the `start_session` command. ## Compute Profile The `ComputeProfile` controls the window size and how often frames are emitted: | Parameter | Default | Description | | - | - | - | | `windowSec` | 60 | Size of the sliding window (seconds) for mean HR | | `emitIntervalSec` | 5 | How often to emit a session frame (seconds) | | `rawEmitIntervalSec` | `null` | How often to emit raw biosignal frames (seconds). Defaults to `emitIntervalSec` when `null` | ### Raw Biosignal Streaming When `includeRawSamples` is enabled in `SessionConfig`, the Kotlin and Swift engines and the Flutter mock engine emit `BiosignalFrame` events alongside session frames. The Flutter live engine does not emit `BiosignalFrame`. Kotlin and Swift samples are maps with these keys: | Key | Type | Description | | - | - | - | | `timestamp_ms` | `Long` / `Int64` | Unix timestamp in milliseconds | | `bpm` | `Double` | Heart rate in BPM | | `source` | `String` | Provider tag (`mock`, `ble_hrm`, `health_connect`, `apple_healthkit`, ...) | | `rr_intervals_ms` | `List?` | RR intervals in milliseconds, when the provider supplies them | | `device_id` | `String?` | Source device, when the provider supplies it | In Dart, `BiosignalFrame.samples` is a `List` with `timestampMs`, `bpm`, `rrIntervalMs`, `accelerometer`, and `spo2`. The mock engine fills `accelerometer` with synthetic values. ## Available SDKs ### Flutter SDK Cross-platform SDK for iOS and Android with a mock mode for development. > [card] [Flutter SDK Documentation](/synheart-session/flutter) > > Flutter integration guide **Installation:** ```yaml theme={null} dependencies: synheart_session: ^0.3.0 ``` **Version**: 0.3.0 **Requirements**: Dart `>=3.8.0 <4.0.0`, Flutter `>=3.22.0` **Repository:** [synheart-session-flutter](https://github.com/synheart-ai/synheart-session-flutter) · [runnable example](https://github.com/synheart-ai/synheart-session-flutter/tree/main/example) ### Swift SDK Native Swift SDK with `SynheartSession` and pluggable `BiosignalProvider` and `BehaviorProvider`. > [card] [Swift SDK Documentation](/synheart-session/swift) > > Swift and watchOS integration guide **Installation:** ```swift theme={null} .package(url: "https://github.com/synheart-ai/synheart-session-swift.git", from: "0.3.0") ``` **Version**: 0.3.0 **Platforms (Swift Package Manager)**: iOS 13.0+ / macOS 13.0+ / watchOS 8.0+ **Repository:** [synheart-session-swift](https://github.com/synheart-ai/synheart-session-swift) ### Kotlin SDK Native Kotlin SDK for Android with `SynheartSession`, pluggable providers (reflection-based wrappers for synheart-wear and synheart-behavior), and `WatchSessionRelay` for Wear OS. > [card] [Kotlin SDK Documentation](/synheart-session/kotlin) > > Android integration guide **Installation:** ```groovy theme={null} dependencies { implementation 'ai.synheart:synheart-session:0.4.0' } ``` **Version**: 0.4.0 **Min OS**: Android API 21+ (Android 5.0) **Repository:** [synheart-session-kotlin](https://github.com/synheart-ai/synheart-session-kotlin) ## Stability Synheart Session is **pre-1.0**. Minor version bumps may include breaking API changes — pin exact versions in production, and read the CHANGELOG before upgrading. Kotlin 0.4.0 and Swift 0.3.0 are minor bumps because the new `typing` mode breaks exhaustive `when` / `switch` statements over `SessionMode`. ## Session Frame Structure Each `SessionFrame` carries a flat `metrics` map. When a `BehaviorProvider` is configured and returns a snapshot, a `behavior` map is included too: ```json theme={null} { "type": "session_frame", "session_id": "abc-123", "seq": 1, "emitted_at_ms": 1700000030000, "metrics": { "hr_mean_bpm": 72.3, "hr_sdnn_ms": 0.0, "rmssd_ms": 0.0, "pnn50": 0.0, "sample_count": 30, "start_ms": 1700000000000, "end_ms": 1700000029000 } } ``` ### Frame Metrics | Key | Type | Description | | - | - | - | | `hr_mean_bpm` | `double` | Mean heart rate in BPM over the window, rounded to one decimal | | `hr_sdnn_ms` | `double` | SDNN (ms), from `ingestHsiMetrics` key `hrv.sdnn_ms`; `0.0` if not supplied | | `rmssd_ms` | `double` | RMSSD (ms), from `ingestHsiMetrics` key `hrv.rmssd_ms`; `0.0` if not supplied | | `pnn50` | `double` | pNN50, from `ingestHsiMetrics` key `hrv.pnn50`; `0.0` if not supplied | | `sample_count` | `int` | Number of HR samples in the window | | `start_ms` | `int` | Timestamp of the first sample in the window (ms since epoch) | | `end_ms` | `int` | Timestamp of the last sample in the window (ms since epoch) | Platform differences: * **Flutter** also puts `session_id`, `mode`, and `seq` inside `metrics`. The Flutter live engine emits frames even when the window is empty (`sample_count` 0, `hr_mean_bpm` 0.0). * **Flutter mock engine** emits synthetic `hr_sdnn_ms` and `rmssd_ms` derived from its generated data, adds `"mock": true`, and does not emit `pnn50`. * **Kotlin and Swift** skip a frame when the window holds no samples. Events relayed from a companion watch app can include extra metric keys that the watch app adds. The phone SDKs do not produce them. ## Next Steps > [card] [Flutter SDK](/synheart-session/flutter) > > Flutter integration guide > [card] [Swift SDK](/synheart-session/swift) > > Swift and watchOS guide > [card] [Kotlin SDK](/synheart-session/kotlin) > > Android integration guide ## Community * **GitHub**: [github.com/synheart-ai](https://github.com/synheart-ai) — every Session SDK lives in its per-language repo (`synheart-session-flutter`, `synheart-session-kotlin`, `synheart-session-swift`). * **Issues**: file against the relevant per-language repo. # Providers Source: https://docs.synheart.ai/synheart-session/providers BiosignalProvider and BehaviorProvider — the two pluggable data sources the engine consumes The session SDK decouples the engine from data sources via two abstractions. This page covers the contracts, the bundled implementations, and how the engine uses them. Providers are constructor arguments of `SynheartSession`, not fields of `SessionConfig`: ```dart theme={null} SynheartSession(biosignalProvider: ..., behaviorProvider: ...) // Dart ``` ```kotlin theme={null} SynheartSession(provider = ..., behaviorProvider = ...) // Kotlin ``` ```swift theme={null} SynheartSession(provider: ..., behaviorProvider: ...) // Swift ``` ## BiosignalProvider The heart-rate source. The engine starts it once per session and stops it when the session ends. ### Contract (Dart) Stream-based: ```dart theme={null} abstract class BiosignalProvider { bool get isAvailable; String get name; Stream startStreaming(); void stopStreaming(); } ``` ### Contract (Kotlin and Swift) Callback-based: ```kotlin theme={null} interface BiosignalProvider { val isAvailable: Boolean val name: String fun startStreaming(onSample: (BiosignalSample) -> Unit) fun stopStreaming() } ``` ```swift theme={null} public protocol BiosignalProvider { var isAvailable: Bool { get } var name: String { get } func startStreaming(onSample: @escaping (BiosignalSample) -> Void) throws func stopStreaming() } ``` `name` is a debug identifier. The Dart live engine skips the subscription when `isAvailable` is `false`. The Kotlin and Swift engines do not check `isAvailable`; they call `startStreaming`, and if it throws, the session emits a `sensor_unavailable` error event and ends. ### BiosignalSample Dart: ```dart theme={null} class BiosignalSample { final int timestampMs; final double bpm; final double? rrIntervalMs; final ({double x, double y, double z})? accelerometer; // record type final double? spo2; } ``` Kotlin and Swift: ```kotlin theme={null} data class BiosignalSample( val timestampMs: Long, val bpm: Double, val rrIntervalsMs: List? = null, val deviceId: String? = null, val source: String ) ``` The Swift struct has the same fields (`timestampMs: Int64`, `bpm`, `rrIntervalsMs`, `deviceId`, `source`). `source` is required and is copied into raw `biosignal_frame` samples. Kotlin and Swift samples have no accelerometer or SpO₂ fields. ### Engine consumption The engine pushes each sample into a sliding window (see [Lifecycle](/synheart-session/lifecycle#window)) and computes `hr_mean_bpm` from it. There is no provider-side rate limiting. RR intervals, accelerometer, and SpO₂ are not used to compute any metric. Kotlin and Swift copy RR intervals into raw `biosignal_frame` samples; the Dart live engine does not emit raw frames. ### Bundled implementations | Implementation | SDK | Notes | | - | - | - | | `MockBiosignalProvider` | all three | 1 Hz sinusoid around 72 BPM with noise. Dart takes an optional `seed`; Kotlin and Swift are unseeded and emit the first sample immediately. Source tag `mock`. | | `WatchBiosignalProvider` | Dart | Bridges watch events through `SessionChannel`. `isAvailable = true` optimistically. Also turns on watch routing in `SynheartSession`. | | `WearBiosignalProvider` | Kotlin, Swift | Bridges a synheart-wear `BleHrmProvider` (BLE heart-rate monitor). Kotlin takes it as `Any` and reads it via reflection; Swift takes `init(bleHrmProvider:)` in the `SynheartSessionWear` product. Throws `SensorUnavailable` from `startStreaming` if the HRM is not connected. Source tag `ble_hrm`. | | `HealthConnectBiosignalProvider` | Kotlin | Wraps a synheart-wear `HealthConnectAdapter` (passed as `Any`, read via reflection) and polls its `readSnapshot()` every 2 seconds by default. RR is derived from BPM. Source tag `health_connect`. | | `HealthKitBiosignalProvider` | Swift | `init(wear:)` in the `SynheartSessionHealthKit` product. Subscribes to `SynheartWear.streamHR(interval: 1.0)`. Source tag `apple_healthkit`. | Seeded mocks are Dart-only. The Dart SDK has no BLE HRM, Health Connect, or HealthKit provider; implement `BiosignalProvider` over your source. ## BehaviorProvider The behavioral signal source. Pull-based: the engine calls `currentSnapshot()` at each frame and once more for the summary. ### Contract ```dart theme={null} abstract class BehaviorProvider { bool get isAvailable; String get name; BehaviorSnapshot? currentSnapshot(); } ``` Kotlin (`interface BehaviorProvider`) and Swift (`protocol BehaviorProvider`) have the same three members. The engine skips the provider when `isAvailable` is `false`. A `null` snapshot means "nothing right now"; the engine omits the `behavior` field on that frame. ### BehaviorSnapshot ```dart theme={null} class BehaviorSnapshot { final int timestamp; // epoch ms when captured // typing final double? typingCadence; final double? interKeyLatency; final int? burstLength; // scrolling final double? scrollVelocity; final double? scrollAcceleration; final double? scrollJitter; // taps and app context final double? tapRate; final int appSwitchesPerMinute; // default 0, not nullable final double? foregroundDuration; final double? idleGapSeconds; // session-level indices final double? stabilityIndex; final double? fragmentationIndex; } ``` The shape is field-for-field aligned with synheart-behavior's `BehaviorStats`, so the two SDKs share a contract without an import dependency. Kotlin and Swift define the same fields. On a frame's `behavior` map, keys are snake\_case and only non-null fields appear; `app_switches_per_minute` and `timestamp` are always present. ### Bundled implementations | Implementation | SDK | Notes | | - | - | - | | `MockBehaviorProvider` | all three | Returns stable mid-range values for tests. | | `BehaviorSdkProvider` | Kotlin, Swift | Wraps synheart-behavior's `SynheartBehavior` and reads `getCurrentStats()`. Kotlin takes the SDK as `Any` (reflection) and reports `isAvailable` from `isInitialized()`; Swift takes `init(sdk:)` in the `SynheartSessionBehavior` product and always reports available. | The Dart SDK does not bundle a synheart\_behavior wrapper; implement `BehaviorProvider` over your behavior source. ## Integration with the engine ```text theme={null} SynheartSession(constructor) ├── biosignal provider → started for the duration of each session └── behavior provider → snapshot pulled at each frame (and once more for SessionSummary) ``` Both are optional. Kotlin and Swift default the biosignal provider to `MockBiosignalProvider`. In the Dart live mode, with no biosignal provider: * `LiveSessionEngine` still emits `SessionStarted`, frames with `sample_count = 0` and `hr_mean_bpm = 0.0`, and a final `SessionSummary`. * This is useful for testing the framing logic itself. ## Provider state machine (informal) ```text theme={null} provider constructed │ Dart: isAvailable = false → engine skips subscription ▼ startStreaming() called (Kotlin / Swift: a throw ends the session with an error event) │ ▼ streaming │ stopStreaming() called (session end / dispose) ▼ stopped ``` Providers must tolerate `stopStreaming()` being called more than once — the Kotlin and Swift engines call it on session end and again on `dispose()`. They should stop emitting after `stopStreaming()` returns. ## Watch provider specifics `WatchBiosignalProvider` (Dart): * `BiosignalFrame` events → each `BiosignalSample` is passed to the engine directly. * `SessionFrame` events → one sample synthesised from `metrics.hr_mean_bpm` (when it is above 0) with `rrIntervalMs = 60000.0 / bpm`. * `SessionStarted`, `SessionSummary`, `SessionError` → ignored (lifecycle, not biosignal data). Channel errors are non-fatal: the provider swallows them so a disconnect does not end the session. ## Authoring a provider A custom `BiosignalProvider` should: * Allocate sensor resources (BLE GATT subscribe, HealthKit authorization, etc.) on `startStreaming()` and release them on `stopStreaming()`. * Dart: emit samples on the `Stream` returned from `startStreaming()`. * Kotlin / Swift: call `onSample` for each sample, with a `source` tag that describes the real source. Throw `SessionError.SensorUnavailable` / `.sensorUnavailable` from `startStreaming` if the source cannot start. * Not block the calling thread — `startStreaming` is called synchronously from `startSession`. A custom `BehaviorProvider` should: * Maintain its own internal accumulators. * Return a fresh `BehaviorSnapshot` on each `currentSnapshot()` call (or `null` when no recent activity). * Use the current epoch milliseconds for the snapshot timestamp. ## Related * [Lifecycle](/synheart-session/lifecycle) — when the engine starts and stops providers. * [Watch Protocol](/synheart-session/watch-protocol) — the watch events `WatchBiosignalProvider` consumes. # Synheart Session - Swift SDK Source: https://docs.synheart.ai/synheart-session/swift Native Swift SDK for iOS, macOS, and watchOS with SynheartSession, a typed AsyncStream of events, and pluggable providers ## Overview The Synheart Session Swift SDK provides `SynheartSession`, a timer-driven session engine that buffers heart-rate samples from a `BiosignalProvider`, emits typed `SessionEvent`s on an `AsyncStream`, and delivers a `.sessionSummary` when the session ends. An optional `BehaviorProvider` adds behavioral signals to each frame. It runs on iOS, macOS, and watchOS. > [!NOTE] > > The SDK computes mean HR locally from sampled biosignals. HRV (`rmssd_ms`, `hr_sdnn_ms`, `pnn50`) is produced upstream (typically by the Synheart runtime) and supplied with `ingestHsiMetrics(sessionId:hsiMetrics:)`. Without that call, HRV fields are `0.0`. ## Installation ### Swift Package Manager Add to your `Package.swift`: ```swift theme={null} dependencies: [ .package(url: "https://github.com/synheart-ai/synheart-session-swift.git", from: "0.3.0") ] ``` Or in Xcode: 1. File > Add Packages... 2. Enter: `https://github.com/synheart-ai/synheart-session-swift.git` The package has four library products: | Product | Contents | | - | - | | `SynheartSession` | Core engine, types, mock providers (no external dependencies) | | `SynheartSessionWear` | `WearBiosignalProvider` (BLE heart-rate monitor via synheart-wear-swift) | | `SynheartSessionHealthKit` | `HealthKitBiosignalProvider` (HealthKit via synheart-wear-swift) | | `SynheartSessionBehavior` | `BehaviorSdkProvider` (synheart-behavior-swift) | ### Requirements * iOS 13.0+ / macOS 13.0+ / watchOS 8.0+ * Swift 5.9+ (swift-tools-version 5.9) ## Quick Start ```swift theme={null} import SynheartSession let session = SynheartSession() // MockBiosignalProvider by default let config = SessionConfig( sessionId: UUID().uuidString, mode: .focus, durationSec: 30, profile: ComputeProfile(windowSec: 10, emitIntervalSec: 3) ) let events = try session.startSession(config: config) Task { for await event in events { switch event { case .sessionStarted(_, let startedAtMs): print("Session started at \(startedAtMs)") case .sessionFrame(_, let seq, _, let metrics, _): let hr = metrics["hr_mean_bpm"] as? Double ?? 0 print("#\(seq) HR: \(hr) bpm") case .biosignalFrame(_, _, _, let samples): print("Raw samples: \(samples.count)") case .sessionSummary(_, let durationActualSec, _, _): print("Session complete: \(durationActualSec)s") case .sessionError(_, let code, let message): print("Error [\(code.rawValue)]: \(message)") } } // The stream finishes after .sessionSummary or .sessionError. } // Stop early — emits .sessionSummary try session.stopSession(sessionId: config.sessionId) ``` The stream buffers events emitted before you start iterating, so `.sessionStarted` is not lost. The engine schedules its timers on `RunLoop.main`, and `MockBiosignalProvider` schedules its timer on the current run loop, so start sessions from the main thread. ## Types ### SessionConfig ```swift theme={null} let config = SessionConfig( sessionId: UUID().uuidString, // unique session identifier mode: .focus, // .focus, .breathing, or .typing durationSec: 60, // session duration in seconds profile: ComputeProfile( windowSec: 10, // sliding window size emitIntervalSec: 3 // frame emission interval ), windowLabel: "morning-check" // optional label ) ``` Set `includeRawSamples: true` to emit `.biosignalFrame` events alongside session frames: ```swift theme={null} let config = SessionConfig( sessionId: UUID().uuidString, mode: .focus, durationSec: 60, profile: ComputeProfile(windowSec: 10, emitIntervalSec: 3, rawEmitIntervalSec: 1), includeRawSamples: true ) ``` You can also create a `SessionConfig` from a dictionary, for example a `start_session` command received over WatchConnectivity: ```swift theme={null} let config = try SessionConfig(from: [ "session_id": "abc-123", "mode": "focus", "duration_sec": 30, "profile": ["window_sec": 10, "emit_interval_sec": 3] ]) ``` It throws `SessionError.invalidState` if `session_id`, `mode`, or `duration_sec` is missing or the mode is unknown. ### SessionMode | Value | Raw | Description | | - | - | - | | `.focus` | `"focus"` | Focus session | | `.breathing` | `"breathing"` | Breathing session | | `.typing` | `"typing"` | Typing session: the host brackets a keyboard lifecycle with a watch session | ### ComputeProfile | Parameter | Type | Default | Description | | - | - | - | - | | `windowSec` | `Int` | 60 | Sliding window size in seconds | | `emitIntervalSec` | `Int` | 5 | Frame emission interval in seconds | | `rawEmitIntervalSec` | `Int?` | `nil` | Raw biosignal frame interval (defaults to `emitIntervalSec`) | ### SessionError `SessionError` is the error type thrown by the API. Each case carries a `String` message; `code` returns the matching `SessionErrorCode`. | Case | `SessionErrorCode` | Raw | Description | | - | - | - | - | | `.permissionDenied(String)` | `.permissionDenied` | `"permission_denied"` | Health data permissions not granted | | `.sensorUnavailable(String)` | `.sensorUnavailable` | `"sensor_unavailable"` | Sensor not available | | `.invalidState(String)` | `.invalidState` | `"invalid_state"` | Invalid engine state | | `.lowBattery(String)` | `.lowBattery` | `"low_battery"` | Device battery too low | | `.osTerminated(String)` | `.osTerminated` | `"os_terminated"` | OS terminated the session | ## Session Events `SessionEvent` is an enum. Every case exposes `sessionId`, and `toDictionary()` returns the snake\_case wire dictionary shared with the other SDKs. | Case | Associated values | | - | - | | `.sessionStarted` | `sessionId`, `startedAtMs: Int64` | | `.sessionFrame` | `sessionId`, `seq: Int`, `emittedAtMs: Int64`, `metrics: [String: Any]`, `behavior: [String: Any]?` | | `.biosignalFrame` | `sessionId`, `seq: Int`, `emittedAtMs: Int64`, `samples: [[String: Any]]` | | `.sessionSummary` | `sessionId`, `durationActualSec: Int`, `metrics: [String: Any]`, `behavior: [String: Any]?` | | `.sessionError` | `sessionId`, `code: SessionErrorCode`, `message: String` | ### session\_frame Emitted every `emitIntervalSec` while the window holds at least one sample (frames are skipped while it is empty). Wire form: ```swift theme={null} ["type": "session_frame", "session_id": "...", "seq": 1, "emitted_at_ms": 1700000003000, "metrics": [ "hr_mean_bpm": 72.3, "hr_sdnn_ms": 0.0, // from ingestHsiMetrics, else 0.0 "rmssd_ms": 0.0, // from ingestHsiMetrics, else 0.0 "pnn50": 0.0, // from ingestHsiMetrics, else 0.0 "sample_count": 10, "start_ms": 1700000000000, "end_ms": 1700000009000 ]] ``` `hr_mean_bpm` is rounded to one decimal. `behavior` is added when a `BehaviorProvider` is configured, reports `isAvailable`, and returns a snapshot. ### biosignal\_frame Emitted every `rawEmitIntervalSec` when `includeRawSamples` is `true` and the window is not empty. Its `seq` is a separate counter from the session frame `seq`. Each sample has `timestamp_ms`, `bpm`, `source`, and, when the provider supplies them, `rr_intervals_ms` and `device_id`: ```swift theme={null} ["type": "biosignal_frame", "session_id": "...", "seq": 1, "emitted_at_ms": 1700000003000, "samples": [ ["timestamp_ms": 1700000002000, "bpm": 72.3, "source": "mock", "rr_intervals_ms": [829.9]], ... ]] ``` ### session\_summary ```swift theme={null} ["type": "session_summary", "session_id": "...", "duration_actual_sec": 30, "metrics": ["hr_mean_bpm": 72.3, ...]] ``` ### session\_error Emitted instead of a summary when the provider throws from `startStreaming` (for example `WearBiosignalProvider` with no connected HRM); the code is `.sensorUnavailable` and the stream finishes. On the wire the code is under `error_code`: ```swift theme={null} ["type": "session_error", "session_id": "...", "error_code": "sensor_unavailable", "message": "..."] ``` ## Providers ### BLE Heart Rate Monitor ```swift theme={null} import SynheartSession import SynheartSessionWear import SynheartWear let bleHrm = BleHrmProvider() let devices = try await bleHrm.scan(timeoutMs: 10000) try await bleHrm.connect(deviceId: devices.first!.deviceId) let session = SynheartSession(provider: WearBiosignalProvider(bleHrmProvider: bleHrm)) ``` ### HealthKit ```swift theme={null} import SynheartSession import SynheartSessionHealthKit import SynheartWear let wear = SynheartWear(config: SynheartWearConfig(enabledAdapters: [.platformHealth])) try await wear.initialize() let session = SynheartSession(provider: HealthKitBiosignalProvider(wear: wear)) ``` Initialize the `SynheartWear` instance before passing it in. The provider subscribes to `streamHR(interval: 1.0)`; when a reading has no RR intervals, it derives one from BPM (`60000 / bpm`). ## HRV Metrics ```swift theme={null} session.ingestHsiMetrics(sessionId: config.sessionId, hsiMetrics: [ "hrv.sdnn_ms": 48.2, "hrv.rmssd_ms": 36.5, "hrv.pnn50": 14.0, ]) ``` The latest dictionary replaces the previous one and is used for every following frame and the summary. Values must be `Double`. The call is a no-op after `dispose()` or when `sessionId` does not match the running session. ## WatchOS Integration The Swift SDK runs on Apple Watch. A watch app can receive commands from the phone over WatchConnectivity and run `SynheartSession` locally. The relay below is an example you write in your watch app, not part of the SDK: ### Watch-Side Relay ```swift theme={null} import WatchConnectivity import SynheartSession class PhoneSessionRelay: NSObject, WCSessionDelegate { // Pass your HR provider, e.g. HealthKitBiosignalProvider(wear:) private let engine = SynheartSession() override init() { super.init() guard WCSession.isSupported() else { return } WCSession.default.delegate = self WCSession.default.activate() } func session(_ session: WCSession, didReceiveMessage message: [String: Any]) { DispatchQueue.main.async { self.handle(message) } } private func handle(_ message: [String: Any]) { guard let command = message["command"] as? String else { return } switch command { case "start_session": do { let config = try SessionConfig(from: message) let events = try engine.startSession(config: config) Task { for await event in events { self.sendToPhone(event.toDictionary()) } } } catch { // Report the failure to the phone } case "stop_session": if let sessionId = message["session_id"] as? String { try? engine.stopSession(sessionId: sessionId) } default: break } } private func sendToPhone(_ event: [String: Any]) { guard WCSession.default.isReachable else { return } WCSession.default.sendMessage(event, replyHandler: nil) } // Required delegate method func session(_ session: WCSession, activationDidCompleteWith state: WCSessionActivationState, error: Error?) {} } ``` ### Phone Side The Swift SDK does not include a phone-side relay. A native iOS app that drives a watch session sends the `start_session` / `stop_session` commands itself and decodes the returned event dictionaries; the message format is described in [Watch Protocol](/synheart-session/watch-protocol). The Flutter SDK's iOS plugin carries its own relay. ### XcodeGen Configuration If you use XcodeGen for your watchOS project, add the SDK as a local package and link WatchConnectivity: ```yaml theme={null} name: SynheartWatchDemo options: deploymentTarget: watchOS: "10.0" packages: SynheartSession: path: path/to/synheart-session-swift targets: SynheartWatchApp: type: application platform: watchOS dependencies: - package: SynheartSession - sdk: WatchConnectivity.framework ``` ## Behavioral Signals `SynheartSession` accepts an optional `BehaviorProvider`. The engine pulls a snapshot at each frame and once more for the summary. ### Mock Behavior (Development) ```swift theme={null} import SynheartSession let session = SynheartSession(behaviorProvider: MockBehaviorProvider()) let events = try session.startSession(config: config) Task { for await event in events { if case .sessionFrame(_, _, _, _, let behavior?) = event { print("Stability: \(behavior["stability_index"] ?? "")") } } } ``` ### Production (via synheart-behavior) ```swift theme={null} import SynheartSession import SynheartSessionBehavior import SynheartBehavior let behaviorSdk = SynheartBehavior() try behaviorSdk.initialize() let session = SynheartSession( provider: myBiosignalProvider, behaviorProvider: BehaviorSdkProvider(sdk: behaviorSdk) ) ``` The `behavior` value is only present in frames when a `BehaviorProvider` is configured and returns data. See [Flutter SDK — Behavioral Fields](/synheart-session/flutter#behavioral-fields) for the keys; they are the same in every SDK. ## API Reference ### SynheartSession | Constructor | Description | | - | - | | `SynheartSession()` | Default `MockBiosignalProvider`, no behavior | | `SynheartSession(provider:)` | Custom biosignal provider | | `SynheartSession(provider:behaviorProvider:)` | Custom biosignal + behavioral providers | | `SynheartSession(behaviorProvider:)` | Default mock biosignal + behavioral provider | | Method | Description | | - | - | | `startSession(config:) throws -> AsyncStream` | Start a session. Throws `SessionError.invalidState` if a session is already running (whatever its id) or the instance is disposed | | `stopSession(sessionId:) throws` | Stop the running session; emits `.sessionSummary` and finishes the stream. Throws if no session is running or the id does not match. No-op after `dispose()` | | `getStatus() -> SessionStatus?` | `SessionStatus(sessionId, active, lastSeq)`, or `nil` if no session is running | | `ingestHsiMetrics(sessionId:hsiMetrics:)` | Supply HRV values for the running session | | `dispose()` | Stop timers and the provider, finish the stream, release state. Later `startSession` calls throw | ## Resources * **Repository**: [synheart-session-swift](https://github.com/synheart-ai/synheart-session-swift) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-session-swift/issues) # Watch Protocol Source: https://docs.synheart.ai/synheart-session/watch-protocol Phone↔watch JSON commands and events over WatchConnectivity and the Wearable Data Layer The phone and the companion watch app exchange JSON-style maps: the phone sends commands, the watch sends session events. There is no protobuf schema. Events use the same snake\_case shape as `SessionEvent.toJson()` (Dart), `toMap()` (Kotlin), and `toDictionary()` (Swift). Phone-side implementations: * **Flutter**: the plugin's native relays (iOS and Android), used when `SynheartSession` has a `WatchBiosignalProvider`. * **Kotlin**: `WatchSessionRelay` (Wear OS). * **Swift**: none. A native iOS app sends the commands itself with `WCSession`. ## Transport | Platform | Phone → watch | Watch → phone | | - | - | - | | iOS + watchOS | `WCSession.sendMessage(_:replyHandler:)` with the command dictionary (no reply handler) | Messages received in `session(_:didReceiveMessage:)` | | Android + Wear OS | `MessageClient.sendMessage` to every connected node on `/synheart/session/command`, payload UTF-8 JSON | Messages on `/synheart/session/event` (session events) and `/synheart/session/hr_sample` (heart-rate samples, read by the Kotlin relay only) | Notes: * The Flutter plugin sends `start_session` only if the watch is reachable at that moment (iOS: `WCSession.isReachable`; Android: at least one connected node). * The Wearable Data Layer delivers messages only between apps with the same package name and signing certificate. A node can accept a message that no app answers; the Kotlin relay therefore gives up with a `sensor_unavailable` error if no event arrives within 10 seconds. * Neither side uses `transferUserInfo` or `DataClient`. ## Phone → watch ### `start_session` ```json theme={null} { "command": "start_session", "session_id": "abc-123", "mode": "focus", "duration_sec": 300, "profile": { "window_sec": 60, "emit_interval_sec": 5 }, "window_label": "morning-check" } ``` | Key | Type | Notes | | - | - | - | | `command` | string | `"start_session"` | | `session_id` | string | Host-supplied identifier | | `mode` | string | `focus`, `breathing`, or `typing` | | `duration_sec` | int | Session duration | | `profile.window_sec` | int | Window size | | `profile.emit_interval_sec` | int | Frame interval | | `window_label` | string | Only present when set | `include_raw_samples` and `raw_emit_interval_sec` are not sent; there is no raw-stream opt-in on the wire. A Swift watch app can build a `SessionConfig` directly from this dictionary with `SessionConfig(from:)` (extra keys such as `command` are ignored). ### `stop_session` ```json theme={null} { "command": "stop_session", "session_id": "abc-123" } ``` Best-effort: the phone does not wait for a reply. The watch answers with its final `session_summary`. There is no status command. Watch status is read locally on the phone (`WCSession` properties on iOS, connected nodes on Android) — see `getWatchStatus()` (Flutter) and `WatchSessionRelay.status()` (Kotlin). ## Watch → phone ### Session events Each message is one event map: | `type` | Keys | | - | - | | `session_started` | `session_id`, `started_at_ms` | | `session_frame` | `session_id`, `seq`, `emitted_at_ms`, `metrics`, `behavior` (optional) | | `biosignal_frame` | `session_id`, `seq`, `emitted_at_ms`, `samples` | | `session_summary` | `session_id`, `duration_actual_sec`, `metrics`, `behavior` (optional) | | `session_error` | `session_id`, `error_code`, `message` | Example frame (the keys inside `metrics` depend on the watch app): ```json theme={null} { "type": "session_frame", "session_id": "abc-123", "seq": 3, "emitted_at_ms": 1700000015000, "metrics": { "hr_mean_bpm": 71.8, "sample_count": 15, "start_ms": 1700000000000, "end_ms": 1700000014000 } } ``` `metrics` is a flat map. The phone SDKs pass it through without validating keys, so a watch app can add its own. `session_summary` and `session_error` are terminal: the Kotlin relay's flow completes after either, and the Flutter relays stop forwarding for that session. Decoding differences: * Kotlin decodes events with `SessionEvent.fromMap`; an event that fails to decode is logged and dropped. An unknown `error_code` becomes `INVALID_STATE`. * Flutter decodes with `SessionEvent.fromJson`. Its `session_error` decoder reads the code from `code`, not `error_code`, and its `biosignal_frame` decoder reads samples with `timestamp_ms`, `bpm`, `rr_interval_ms`, `accelerometer`, and `spo2` (the Kotlin and Swift engines write `rr_intervals_ms` as a list, plus `source` and `device_id`). * In Flutter, decoded events feed `WatchBiosignalProvider` as heart-rate input; they are not passed to the host stream. See [Lifecycle](/synheart-session/lifecycle#phone-watch-lifecycle-flutter). ### Heart-rate samples (Wear OS) On `/synheart/session/hr_sample`, one reading per message: ```json theme={null} { "ts_ms": 1700000014000, "bpm": 72.0 } ``` The Kotlin relay exposes these as `WatchSessionRelay.hrSamples()` (`WatchHrSample(timestampMs, bpm)`), independent of any session flow. A missing `ts_ms` is replaced with the phone's current time. ## Flutter channel surface The Dart layer talks to the native relays through `MethodChannel("ai.synheart.session/methods")` and `EventChannel("ai.synheart.session/events")`: ```dart theme={null} class SessionChannel { Future startSession(SessionConfig config); // native builds start_session Future stopSession(String sessionId); // native sends stop_session Future getStatus(); // native returns null Future getWatchStatus(); Stream get events; // EventChannel-backed } ``` `getWatchStatus()` returns the connectivity snapshot: ```dart theme={null} class WatchStatus { final bool supported; // iOS: WatchConnectivity supported; Android: Play services available final bool reachable; // iOS: WCSession.isReachable; Android: a node is connected final bool paired; // iOS: a watch is paired; Android: same as reachable final bool installed; // iOS: companion app installed; Android: same as reachable } ``` ## Ordering * `session_started` precedes frames and the summary for a given `session_id`. * `seq` increases within a session; gaps can appear if the transport drops a message. * `session_summary` and `session_error` are mutually exclusive. * Use `emitted_at_ms` and sample timestamps for chronological alignment rather than arrival order. ## Privacy posture * Raw samples are not requested over the wire. * No PII fields are defined — `session_id` is a host-supplied identifier (Dart defaults to a UUID v4), and `window_label` is free-form; keep it free of PII. ## Related * [Lifecycle](/synheart-session/lifecycle) — how the phone and watch sessions relate. * [Providers](/synheart-session/providers) — `WatchBiosignalProvider` and how it consumes these events. * [Errors](/synheart-session/errors) — error codes and the `error_code` / `code` key difference. # Vendor Adapters Source: https://docs.synheart.ai/synheart-wear/adapters Per-vendor flow, capabilities, and RAMEN 🍜 delivery semantics `synheart-wear` ships a stable adapter layer per vendor. This page is the reference for what each adapter does, what it produces, and how it interacts with cloud streaming. ## Adapter matrix | Vendor | Local source | Cloud / push source | RAMEN delivery hint | Status | | - | - | - | - | - | | Apple Watch | HealthKit (`apple_healthkit`) | — | n/a | Ready | | Health Connect (Android) | Health Connect API | — | n/a | Ready | | BLE HRM (any) | GATT 0x180D Heart Rate Profile | — | n/a | Ready | | WHOOP | Broadcast HR via BLE | OAuth + webhooks | `stream` (full payload inline) | Ready | | Garmin (Cloud) | — | OAuth + Connect API webhooks | `ping` (REST pull required) | Ready | | Garmin Health SDK (RTS) | Native real-time streaming | — | n/a | On-demand, license-gated | | Fitbit | — | OAuth via Synheart Wear API | `ping` | Ready | | Oura | — | OAuth via Synheart Wear API | `ping` | Ready | | Samsung Watch | (planned) | — | n/a | Planned | The `DeviceAdapter` enums differ per SDK: * **Dart:** `platformHealth`, `fitbit`, `garmin`, `whoop`, `samsungHealth` (no adapter behind it yet). Oura is reached through `OuraProvider` and BLE HRM through `BleHrmProvider`, not the enum. * **Kotlin:** `HEALTH_CONNECT`, `SAMSUNG_HEALTH`, `FITBIT`, `GARMIN`, `OURA`, `WHOOP`, `BLE_HRM`. * **Swift:** `platformHealth`, `fitbit`, `garmin`, `oura`, `whoop`, `bleHrm`. ## Apple HealthKit Capabilities: * HR (instantaneous + samples). * HRV: HealthKit gives SDNN; the SDK stores that one value under both `hrv_sdnn` and `hrv_rmssd`. * Steps, calories, distance. * RR intervals via the HealthKit RR channel (workout-mode only on most Apple Watch models). * Health profile snapshot (DOB, sex, height, weight) for personalization context. * Workout events. Permissions: standard HealthKit `HKObjectType` set, requested once via `requestPermissions`. `source` field on `WearMetrics`: `"apple_healthkit"`. ## Health Connect (Android) Capabilities: * HR, HRV (when the recording app provides it; otherwise SDNN/RMSSD are unavailable). * Steps, calories, distance. * Sleep records (sleep stages from compatible apps). Health Connect retention is capped per record type by the platform (typically \~30 days for HR, longer for sleep). Hosts that need older data must use the Apple XML backfill path (Apple users) or an OAuth cloud adapter. `source` field: `"health_connect"` on Kotlin. The Flutter SDK reads Health Connect through its `platformHealth` adapter, which currently labels the data `source: "apple_healthkit"` with an `applewatch_…` device id on Android too. ## BLE HRM Direct connection over BLE GATT Heart Rate Profile (0x180D). No vendor cloud, no OAuth. Compatible devices: * WHOOP (Broadcast HR mode). * Polar chest straps (H10, OH1). * Wahoo TICKR family. * Garmin HRM-Pro / HRM-Dual. * Any HRM advertising 0x180D Heart Rate Service. Capabilities: * HR (every second per Bluetooth profile). * RR intervals when the device advertises the optional RR field. The bridge runs its own permission/scan/connect/disconnect lifecycle independent of `requestPermissions`. See [BLE Heart Rate Monitor](/synheart-wear/ble-hrm) for the detailed flow. `source` field: `"ble_hrm"`. ## WHOOP Two modes: | Mode | Path | | - | - | | OAuth + webhooks | Cloud-side handles OAuth + webhook ingest, publishes `wear.events`, RAMEN delivers to client. `DeliveryHint.stream` (full payload inline). | | BLE Broadcast HR | Local-only via `BleHrmProvider`. No cloud round-trip; no recovery/strain/sleep. | `WhoopProvider` exposes: * `fetchRecovery`, `fetchSleep`, `fetchWorkouts`, `fetchCycles` — date-range record queries (Flutter also has `fetchRawData`). * Real-time HR via webhooks (mode A) or BLE (mode B). * Workout events. `source` field: `"whoop"` for the OAuth path. The cloud-vs-BLE distinction lives in `meta.source_type` (`"whoop_cloud"`); WHOOP via BLE Broadcast HR uses the shared BLE HRM adapter (`source = "ble_hrm"`). ## Garmin (Cloud) Path: OAuth → Garmin Connect API webhooks → cloud → RAMEN. Delivery hint: `ping` — vendor only sends a notification; client must pull the full record via REST when needed. `GarminProvider` exposes: * Backfill queries for the Garmin Health API summary types: `fetchDailies`, `fetchEpochs`, `fetchSleeps`, `fetchStressDetails`, `fetchHRV`, `fetchUserMetrics`, `fetchBodyComps`, `fetchPulseOx`, `fetchRespiration`, `fetchHealthSnapshot`, `fetchBloodPressures`, `fetchSkinTemp` (Flutter also has `fetchActivities`). Each returns `WearMetrics`; on Flutter the vendor record is kept in `meta.garmin_data`. The `GarminWellnessData`, `GarminSleepData`, `GarminConnectionState` and `GarminRealtimeData` models belong to the `GarminHealth` (RTS) layer below, not to `GarminProvider`. `source` field: `"garmin"` for the OAuth Connect API path; `meta.source_type` carries the more specific `"garmin_cloud"`. ## Garmin Health SDK (Real-Time Streaming) Native RTS path — direct device pairing without going through Garmin Connect cloud. **Requires a separate Garmin license** and is bundled on demand for licensed integrations only. The underlying Garmin Health SDK code is proprietary; this SDK exposes a `GarminHealth` provider façade that wraps it. `source` field: `"garmin_sdk"` (the adapter id from `GarminSdkAdapter`). ## Fitbit OAuth flow mediated by the Synheart Wear API — the device never sees Fitbit access tokens. Cloud delivers a `vendor_user_id` to the app via deep-link callback (`?vendor=fitbit&user_id=...&status=success`); pass that as the `code` argument to `connectWithCode(...)`. `FitbitProvider` exposes: * `fetchHrv`, `fetchSleep`, `fetchActivity` — date-range record queries. * `fetchUserProfile` — Fitbit profile snapshot (Flutter only). `source` field: `"fitbit"`. ## Oura `OuraProvider` (all three SDKs) uses mediated OAuth via the Synheart Wear API, with the same `vendor_user_id`-via-deep-link contract as Fitbit. `OuraProvider` exposes `fetchReadiness`, `fetchSleep`, `fetchHrv`, `fetchActivity` (Flutter also has `fetchUserProfile`). `source` field: `"oura"`. ## Streaming model Today, cloud providers (Whoop, Garmin, Fitbit, Oura) are **polled**: `streamHR` / `streamHRV` run a timer (Combine `Timer.publish` on Swift, `kotlinx.coroutines.flow.flow { delay(...) }` on Kotlin) that calls `readMetrics(isRealTime: true)` on each tick. There is no push channel for these vendors yet. `BleHrmProvider` is **push-based** — the BLE characteristic notification feeds a SharedFlow / AsyncStream. On Kotlin and Swift, `readMetrics` and `streamHR` include the latest BLE sample. On Flutter they don't: listen to `BleHrmProvider.onHeartRate` directly. Future work: a `RamenEventDispatcher` on Kotlin / Swift (Flutter already has one) will materialize cloud-side `ping` events into REST pull-backs, replacing the timer-based polling for cloud providers. ## Apple Health XML backfill When a user exports `export.zip` from the iOS Health app: ```text theme={null} User exports export.zip from iOS Health app │ ▼ parse via AppleHealthXmlParser │ ▼ batch into AppleHealthSample records │ ▼ synheart_core_backfill_open(db_path, import_id) │ ▼ insert_batch (batched) synheart_core_backfill_insert_batch(import_id, samples_json) │ ▼ synheart_core_backfill_finalize(import_id) ``` Idempotency keys ensure repeated imports don't duplicate samples in the runtime's SQLite store. The high-level path through `synheart-core` aggregates samples per day and replays them via `Synheart.srmPushWearableDaily(...)` so the imported data populates the user's runtime baselines. ## RAMEN 🍜 integration Each cloud adapter participates in the RAMEN stream when Synheart's cloud ingestion publishes events: ```text theme={null} vendor webhook ↓ Synheart ingestion persists and publishes wear.events ↓ RAMEN gRPC stream → synheart-stream-runtime client ↓ Synheart runtime broadcasts RamenEvent ↓ synheart-core wires WearableEventProcessor onto WearModule ↓ WearModule routes by vendor → adapter handler ↓ WearMetrics emitted on streamHR / streamHRV / readMetrics ``` Each adapter handler decides how to consume `RamenEvent.payload_json`: * `DeliveryHint.stream`: parse inline, emit immediately. * `DeliveryHint.ping`: schedule a REST pull (via the adapter's provider) to fetch the body. * `DeliveryHint.unknown`: treat as `stream` (best-effort) and log. ## Permission flow `SynheartWear.requestPermissions(...)` maps Synheart `PermissionType` values to OS permission scopes for the platform health store: | SDK | Signature | Returns | Notes | | - | - | - | - | | Flutter | `requestPermissions({permissions, reason})` | `Map` | Shows the HealthKit / Health Connect prompt. All-or-nothing: every type gets the same status. `reason` is accepted but not shown. Can run before `initialize()`. | | Kotlin | `requestPermissions(permissions)` | `Map` | Needs `initialize()` first. Reports current grants; it does not show the Health Connect screen (use `PermissionController`). | | Swift | `requestPermissions(_:)` | `[PermissionType: Bool]` | Needs `initialize()` first. Shows the HealthKit sheet; the returned map reflects write status, so read-only grants read as `false`. | BLE HRM (Bluetooth prompts) and cloud OAuth (app navigation) handle their own UX outside this method. ## Related * [Wear Overview](/synheart-wear/overview) — full SDK surface. * [Data Schema](/synheart-wear/data-schema) — what each adapter writes into the unified `WearMetrics`. * [BLE Heart Rate Monitor](/synheart-wear/ble-hrm) — direct BLE HRM flow. # BLE Heart Rate Monitor Source: https://docs.synheart.ai/synheart-wear/ble-hrm Direct Bluetooth LE heart rate monitor support for real-time HR streaming ## Overview Synheart Wear supports direct Bluetooth LE connections to any standard heart rate monitor. This enables real-time HR streaming without requiring a cloud API or vendor-specific SDK. **Supported devices include:** * **WHOOP** (Broadcast Heart Rate mode) * **Polar** sensors (H10 chest strap, OH1 / Verity Sense optical arm bands) * **Wahoo** TICKR, TICKR X * **Garmin** HRM-Pro, HRM-Dual * **Gym equipment** with BLE HR broadcast * Any device implementing the standard **BLE Heart Rate Profile (0x180D)** ## How It Works The BLE HRM provider connects to devices advertising the standard Bluetooth Heart Rate Service (`0x180D`), subscribes to the Heart Rate Measurement characteristic (`0x2A37`), and parses incoming data per the Bluetooth SIG specification. ```text theme={null} Phone (iOS/Android) │ │── BLE Scan (filter: 0x180D service) │ ▼ BLE Heart Rate Monitor │ │── Subscribe to HR Measurement (0x2A37) │ ▼ Real-time HR samples → HeartRateSample stream │ │── bpm, rr_intervals_ms, device_id, timestamp │ ▼ Your App ``` ## Platform Setup ### iOS Add to `Info.plist`: ```xml theme={null} NSBluetoothAlwaysUsageDescription This app uses Bluetooth to connect to heart rate monitors. ``` ### Android Add to `AndroidManifest.xml`: ```xml theme={null} ``` **Note:** Android 12+ requires runtime permission requests for `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT`. **Flutter on Android** also needs, because the plugin's `minSdk` is 28 and it streams through a `dataSync` foreground service: ```xml theme={null} ``` Request the Bluetooth permissions at runtime yourself on Android: Flutter's `BleHrmProvider.requestPermission()` is iOS-only. ## Usage > [tab] Flutter/Dart > > ```dart theme={null} > import 'package:synheart_wear/synheart_wear.dart'; > > final bleHrm = BleHrmProvider(); > > // Scan for nearby HR monitors (default timeout 5 s) > final devices = await bleHrm.scan( > timeoutMs: 10000, > namePrefix: 'Polar', // optional filter > ); > if (devices.isEmpty) return; > > // Connect to a device > await bleHrm.connect( > deviceId: devices.first.deviceId, > sessionId: 'my-session', // optional > ); > > // Listen to heart rate samples > final sub = bleHrm.onHeartRate.listen((sample) { > print('BPM: ${sample.bpm}'); > if (sample.rrIntervalsMs.isNotEmpty) { > print('RR: ${sample.rrIntervalsMs}'); > } > }); > > // Disconnect when done > await sub.cancel(); > await bleHrm.disconnect(); > ``` > [tab] Swift > > ```swift theme={null} > import SynheartWear > > let config = SynheartWearConfig(enabledAdapters: [.bleHrm]) > let synheartWear = SynheartWear(config: config) > > guard let bleHrm = synheartWear.bleHrm else { return } > > // Scan (default timeout 10 s) > let devices = try await bleHrm.scan(timeoutMs: 10000, namePrefix: "Polar") > guard let device = devices.first else { return } > > // Connect > try await bleHrm.connect(deviceId: device.deviceId) > > // Stream in its own task: onHeartRate doesn't finish on its own > let reader = Task { > for await sample in bleHrm.onHeartRate { > print("BPM: \(sample.bpm)") > } > } > > // Disconnect when done > reader.cancel() > try await bleHrm.disconnect() > ``` > [tab] Kotlin > > ```kotlin theme={null} > import ai.synheart.wear.SynheartWear > import ai.synheart.wear.models.DeviceAdapter > > val synheartWear = SynheartWear( > context = this, > config = SynheartWearConfig( > enabledAdapters = setOf(DeviceAdapter.BLE_HRM) > ) > ) > > lifecycleScope.launch { > synheartWear.initialize() // bleHrm is null until this runs > val bleHrm = synheartWear.bleHrm ?: return@launch > > // Scan (default timeout 10 s) > val devices = bleHrm.scan(timeoutMs = 10000, namePrefix = "Polar") > val device = devices.firstOrNull() ?: return@launch > > // Connect > bleHrm.connect(deviceId = device.deviceId) > > // Collect in its own job: heartRateFlow never completes > val job = launch { > bleHrm.heartRateFlow.collect { sample -> > Log.d(TAG, "BPM: ${sample.bpm}") > } > } > > // Disconnect when done > job.cancel() > bleHrm.disconnect() > } > ``` ## API Reference ### Methods | Method | Description | Returns | | - | - | - | | `scan(timeoutMs, namePrefix?)` | Scan for nearby BLE HR monitors (default timeout 5 s on Flutter, 10 s on Kotlin/Swift) | `List` | | `connect(deviceId, sessionId?, enableBattery?)` | Connect to a device and start HR streaming | `void` | | `disconnect()` | Disconnect from the current device | `void` | | `isConnected()` | Check if a device is currently connected | `bool` | | `dispose()` | Release the provider | `void` | Flutter also has `requestPermission()` (iOS only), `warmAdapter()`, `getBondedHrDevices()`, and Polar H10 accelerometer streaming: `connect(enableMotion: true, motionSampleRateHz: 50)` with the `onMotion` stream. ### BleHrmDevice Returned from `scan()`: | Field | Type | Description | | - | - | - | | `deviceId` | `String` | MAC address on Android, CoreBluetooth peripheral UUID on iOS | | `name` | `String?` | Device advertised name (Flutter: `String`, empty when unnamed) | | `rssi` | `int` | Signal strength (dBm) | ### HeartRateSample Emitted on the heart rate stream: | Field | Type | Description | | - | - | - | | `tsMs` | `int` | Phone receipt timestamp (ms since epoch) | | `bpm` | `int` (Flutter: `double`) | Heart rate in beats per minute | | `source` | `String` | Always `"ble_hrm"` | | `deviceId` | `String` (Flutter: `String?`) | Device id as above | | `deviceName` | `String?` | Device advertised name | | `sessionId` | `String?` | Session tag (passed during connect) | | `rrIntervalsMs` | `List?` (Flutter: non-null, empty when absent) | RR intervals in milliseconds | **Note:** `rrIntervalsMs` availability depends on the device. Polar chest straps typically include RR intervals; WHOOP Broadcast typically does not. ### Error Codes Errors surface as `BleHrmError` with a `BleHrmErrorCode` on Flutter, `BleHrmException(errorCode)` on Kotlin, and `SynheartWearError.bleHrm(code, message)` on Swift. | Code | Meaning | | - | - | | `PERMISSION_DENIED` | Bluetooth permission not granted | | `BLUETOOTH_OFF` | Bluetooth adapter is disabled | | `DEVICE_NOT_FOUND` | Device not found or connection timed out | | `SUBSCRIBE_FAILED` | Failed to subscribe to HR characteristic | | `DISCONNECTED` | Device disconnected unexpectedly | ## WHOOP Broadcast Setup To use WHOOP as a BLE heart rate monitor: 1. Open the **WHOOP app** on your phone 2. Go to **Device Settings** (tap your WHOOP device) 3. Enable **Broadcast Heart Rate** 4. Your WHOOP will now appear in BLE scans as a standard HR monitor **Note:** WHOOP Broadcast HR provides BPM only (no RR intervals). For full WHOOP data (recovery, sleep, strain), use the WHOOP cloud provider instead. ## Reconnection The BLE HRM provider automatically handles disconnections: * **Kotlin and Swift:** 3 retry attempts with exponential backoff (1 s, 2 s, 4 s) * **Flutter:** Android retries 5 times, 3 s apart; iOS waits up to 30 s for CoreBluetooth to reconnect * After that, a `DISCONNECTED` error is emitted on the stream * Your app can then prompt the user to reconnect ## Limitations * **Single device**: Only one BLE HRM device can be connected at a time (v1) * **Phone-side only**: Requires the phone to be in BLE range of the HR monitor * **No HRV calculation**: Raw RR intervals are provided when available, but HRV calculation is not performed by the provider * **Battery dependent**: Battery level monitoring is optional (`enableBattery: true` during connect) ## Architecture The BLE HRM provider is implemented natively on each platform: | Platform | Implementation | Streaming Pattern | | - | - | - | | **iOS** | CoreBluetooth (`CBCentralManager`) | `AsyncStream` | | **Android** | Android BLE (`BluetoothLeScanner`, `BluetoothGatt`) | `SharedFlow` | | **Flutter** | Platform Channels (MethodChannel + EventChannel) | `Stream` | All platforms parse HR data identically per the Bluetooth SIG Heart Rate Profile specification (flags byte, uint8/uint16 BPM, optional RR intervals at 1/1024s resolution). # Data shape Source: https://docs.synheart.ai/synheart-wear/data-schema WearMetrics — the unified output every adapter normalises to `WearMetrics` is the single shape every adapter writes into. Downstream layers (`synheart-session`, `synheart-core`, the runtime ingest queue) read this shape; they do not consume vendor-specific JSON. ## `WearMetrics` ```dart theme={null} class WearMetrics { final DateTime timestamp; final String deviceId; final String source; final Map metrics; final Map meta; final List? rrIntervalsMs; } ``` This is the Flutter class. Kotlin and Swift carry the same fields with a few differences: RR intervals are `rrIntervals`, `meta` holds strings only, and battery is a metric (`BATTERY` / `.battery`) instead of `meta.battery`. JSON shape (canonical, Flutter `toJson()`): ```json theme={null} { "timestamp": "2025-10-20T18:30:00Z", "device_id": "applewatch_1234", "source": "apple_healthkit", "metrics": { "hr": 72, "hrv_rmssd": 45, "hrv_sdnn": 62, "steps": 1045, "calories": 120.4, "distance": 2.5, "stress": 23 }, "meta": { "battery": 0.82, "synced": true }, "rr_ms": [800, 850, 820] } ``` ## Top-level fields | Field | Type | Notes | | - | - | - | | `timestamp` | ISO-8601 UTC string | Time the measurement applies to (sample time, not emit time). Always UTC. | | `device_id` | string | Stable identifier for this physical device. Format is vendor-shaped (e.g. `"applewatch_1234"`, `"whoop_"`; for a BLE HRM, the MAC address on Android and the CoreBluetooth peripheral UUID on iOS). | | `source` | string | Lowercase snake\_case adapter id. Stable across versions of the same adapter. | | `metrics` | object | Keyed by metric short-name (see below). Values may be `null` when the adapter knows the metric is not available; missing keys mean "not produced by this sample". | | `meta` | object | Free-form per-sample metadata. Stable keys are documented below; adapters may add vendor-specific keys. | | `rr_ms` | array of doubles \| absent | Inter-beat intervals in milliseconds when the source provides them. Absent when not available. | ## `metrics` keys Maps from the `MetricType` enum: | Key | Type | Unit | Source | | - | - | - | - | | `hr` | number | bpm | HR sample. | | `hrv_rmssd` | number | ms | HRV over the adapter's window. | | `hrv_sdnn` | number | ms | HRV over the adapter's window. | | `steps` | number | count | Period total (since the previous sample, or per-day depending on adapter). | | `calories` | number | kcal | Active energy. | | `distance` | number | km (Flutter), meters (Kotlin) | Total distance over the period. Swift doesn't read distance from HealthKit. | | `stress` | number | unitless | Vendor-specific score (e.g. Garmin `0–100`); adapters do not normalise this across vendors. | HealthKit and Health Connect each report a single HRV figure (SDNN and RMSSD respectively). The SDK stores it under **both** `hrv_rmssd` and `hrv_sdnn`, so the two keys hold the same value for platform-health data. Adapters MAY emit additional vendor-specific metric keys but downstream consumers MUST tolerate unknown keys. Stable keys above are the normalised contract. ## `meta` keys (stable) | Key | Type | Notes | | - | - | - | | `battery` | number 0–1 | Device battery level. | | `synced` | bool | `true` when the sample came from a vendor sync or backfill (WHOOP and Garmin cloud set it). Read back as `WearMetrics.isSynced`. | Adapter-specific meta on Flutter: Garmin cloud adds `garmin_data` (the vendor record), `body_battery`, `vo2_max`, `fitness_age` and `source_type`; when Garmin reports no stress value, `stress` falls back to `100 - body_battery`. WHOOP cloud adds `recovery_score`, `strain_score`, `sleep_score`, `whoop_data` and `source_type`. ## `rr_ms` semantics When present: * Each value is one inter-beat interval in milliseconds. * Order is the order observed by the device (chronological). * The list is per sample, not cumulative — multiple samples at the same `timestamp` can share an `rr_ms` payload via the meta field. * Range gates apply downstream: the runtime's RR push rejects values outside `[200, 6000]`. ## Adapter source IDs The top-level `source` field carries the **adapter id** — typically the bare vendor/source name. More specific flavor information (cloud vs BLE, etc.) lives in `meta.source_type`. | `source` value | Adapter | `meta.source_type` flavor | | - | - | - | | `"apple_healthkit"` | Apple HealthKit | — | | `"health_connect"` | Android Health Connect (Kotlin) | — (the Flutter SDK currently labels Health Connect data `"apple_healthkit"`) | | `"ble_hrm"` | BLE Heart Rate Profile | — | | `"whoop"` | WHOOP | `"whoop_cloud"` for OAuth + webhooks; WHOOP via BLE Broadcast HR uses `source = "ble_hrm"` | | `"garmin"` | Garmin via Connect API | `"garmin_cloud"` | | `"garmin_sdk"` | Garmin Health SDK (RTS, license-gated) | — | | `"fitbit"` | Fitbit | — | | `"oura"` | Oura | — (cloud OAuth provider) | Consumers MUST tolerate unknown `source` and `meta.source_type` values. When new adapters land, they take new stable strings. Existing strings do not change meaning. ## Compatibility rules The shape is unversioned. Compatibility rules: * Producers MAY add new metric keys, new meta keys, and new `source` values. * Producers MUST NOT remove or rename existing keys. * Consumers MUST tolerate unknown metric keys and unknown `source` values. * A future change to the top-level shape would be a breaking change; the SDK would expose both producers in parallel during migration. ## Vendor → schema mapping (informal) This table is informational only. Each adapter is the authoritative source for its mapping; this is a reading aid. | Vendor field | Maps to | Notes | | - | - | - | | HealthKit `HKQuantityTypeIdentifierHeartRate` | `metrics.hr` | Average per query window. | | HealthKit RR samples | `rr_ms` | Workout-mode only on most Apple Watch models. | | Health Connect `HeartRateRecord` | `metrics.hr` | One sample per record. | | WHOOP webhook `recovery_score` | `meta.recovery_score` | Not part of the canonical metric set. | | Garmin Connect `restingHeartRate` | `metrics.hr` | Daily resting HR baseline. | | BLE GATT 0x180D HR characteristic | `metrics.hr` | Plus optional RR field → `rr_ms`. | | Apple XML `HKQuantityTypeIdentifierHeartRateVariabilitySDNN` | `metrics.hrv_sdnn` | Backfill only. | ## How downstream uses this `synheart-session` turns wear readings into its own `BiosignalSample`s: * **Swift:** `HealthKitBiosignalProvider(wear:)` reads `streamHR`, and `WearBiosignalProvider(bleHrmProvider:)` bridges a BLE HRM, carrying its RR intervals as a list. * **Kotlin:** `WearBiosignalProvider` bridges a BLE HRM; `HealthConnectBiosignalProvider` polls Health Connect. * **Flutter:** the session SDK gets HR from the watch (`WatchBiosignalProvider`), not from `synheart_wear`. `synheart-core` forwards the same shape into the runtime via `pushHr` / `pushRr` after consent gating. ## Related * [Wear Overview](/synheart-wear/overview) — full SDK surface. * [Adapters](/synheart-wear/adapters) — per-vendor flow. * [Errors](/synheart-wear/errors) — failure modes. # Errors Source: https://docs.synheart.ai/synheart-wear/errors What each Synheart Wear SDK throws, and when Each SDK has its own error type. This page lists what the released SDKs (Flutter 0.6.2, Kotlin 0.4.2, Swift 0.4.2) actually throw. ## Flutter ### `SynheartWearError` ```dart theme={null} class SynheartWearError implements Exception { final String message; final String? code; final Exception? originalException; } ``` | Thrown by | `code` | When | | - | - | - | | `initialize()` | `NO_WEARABLE_DATA` | No enabled adapter returned any data. | | `initialize()` | `STALE_DATA` | The newest sample is more than 24 hours old. | | `initialize()`, `readMetrics()` | — | Any other failure, wrapped with the cause in the message. | | Cache calls | — | Cache read, write or encryption failed, or caching is disabled. | `PermissionDeniedError` (a `SynheartWearError` with code `PERMISSION_DENIED`) is thrown when the user denies the platform permission request. `DeviceUnavailableError` (`DEVICE_UNAVAILABLE`) and `NetworkError` (`NETWORK_ERROR`) are defined but not thrown by 0.6.2. ```dart theme={null} try { await synheart.initialize(); } on PermissionDeniedError { // Explain why the app needs access, then ask again } on SynheartWearError catch (e) { switch (e.code) { case 'NO_WEARABLE_DATA': // nothing synced yet: ask the user to check their device case 'STALE_DATA': // data older than 24 h: ask the user to sync default: // log e.message } } ``` ### Cloud providers `WhoopProvider`, `GarminProvider`, `FitbitProvider` and `OuraProvider` throw a plain `Exception` with a descriptive message (for example when `userId` is missing or the Synheart Wear API returns an error), and `StateError` for misuse. Catch `Exception` around provider calls. ### BLE heart-rate monitors `BleHrmProvider` throws `BleHrmError`, whose `code` is a `BleHrmErrorCode`: `permissionDenied`, `bluetoothOff`, `deviceNotFound`, `subscribeFailed` or `disconnected`. Unknown native errors map to `subscribeFailed`. Errors on the `onHeartRate` stream use the same type. See [BLE Heart Rate Monitor](/synheart-wear/ble-hrm). ### Garmin Health SDK (RTS) `GarminHealth` throws `GarminSDKError` subclasses, each a `SynheartWearError` with a `GARMIN_*` code: `GarminInitializationError`, `GarminLicenseError`, `GarminScanError`, `GarminPairingError`, `GarminConnectionError`, `GarminStreamingError`, `GarminSyncError`, `GarminDataError` and `GarminPlatformError`. ### Apple Health XML import Failures throw the sealed `AppleHealthXmlError`: `ZipReadFailed`, `XmlNotFound`, `ParseFailed`, `IngestFailed` or `ImportCancelled`. ## Kotlin SDK calls throw `SynheartWearException(message, cause, code)`: * any call before `initialize()` ("SDK not initialized"); * `initialize()` failures, wrapped; * `getProvider()` when the vendor isn't enabled or `cloudConfig` is missing; * every `GarminHealth` data call in the Maven Central build, which doesn't include the licensed Garmin binary. BLE calls throw `BleHrmException`, whose `errorCode` is a `BleHrmErrorCode` (`PERMISSION_DENIED`, `BLUETOOTH_OFF`, `DEVICE_NOT_FOUND`, `SUBSCRIBE_FAILED`, `DISCONNECTED`). ## Swift SDK calls throw `SynheartWearError`: | Case | When | | - | - | | `notInitialized` | A call before `initialize()`. | | `healthKitNotAvailable`, `healthKitTypeNotAvailable` | HealthKit or a requested type isn't available on this device. | | `permissionDenied` | Access was refused. | | `invalidData`, `cacheError(String)` | Bad data, or a cache failure. | | `noConnection`, `timeout`, `hostUnreachable`, `invalidResponse` | Network failures reaching the Synheart Wear API. | | `notConnected`, `authenticationFailed`, `tokenExpired`, `rateLimitExceeded`, `serverError(Int, String?)`, `apiError(String)` | Cloud provider failures. `apiError` is also thrown by `getProvider(_:)` when a vendor isn't configured. | | `bleHrm(BleHrmErrorCode, String)` | BLE heart-rate monitor failures. | The Apple Health XML import throws `AppleHealthXmlError`: `zipReadFailed`, `xmlNotFound`, `parseFailed(line:column:message:)`, `ingestFailed` or `cancelled`. ## Retries The SDKs don't retry cloud requests or back off on rate limits; handle retries in your app. The only automatic retry is BLE reconnection after an unexpected disconnect (see [BLE Heart Rate Monitor](/synheart-wear/ble-hrm#reconnection)). ## Logging policy The SDK logs at `info`/`warn` and never logs: * Vendor OAuth tokens. * Personal `device_id`s in plain (debug builds may; production ones do not). * Raw HRV/RR sample bytes. * XML payloads beyond malformed-record line numbers. `WearMetrics` snapshots are not logged. Hosts that need observability should collect them at the consumer layer. ## Related * [Wear Overview](/synheart-wear/overview) — config flags that influence error paths. * [Adapters](/synheart-wear/adapters) — per-vendor flow. * [Data Schema](/synheart-wear/data-schema) — null-vs-missing semantics. # Synheart Wear - Flutter SDK Source: https://docs.synheart.ai/synheart-wear/flutter Cross-platform wearable SDK for Flutter apps (iOS + Android) ## Overview The Synheart Wear Flutter SDK provides a unified API for streaming biometric data from Apple Health, Health Connect, WHOOP, Garmin, Fitbit, Oura and BLE heart-rate straps in Flutter applications. **Key Features:** * Cross-platform support (iOS + Android) * Real-time HR and HRV streaming * Unified data schema across all devices * Optional encrypted local cache (AES-256) * Consent-based permissions ## Installation Add to your `pubspec.yaml`: ```yaml theme={null} dependencies: synheart_wear: ^0.6.2 ``` Install dependencies: ```bash theme={null} flutter pub get ``` **Requirements:** Flutter 3.32+ (Dart 3.8+), iOS 16.0+, Android `minSdk` 28. ## Platform Configuration ### iOS Configuration Add to `ios/Runner/Info.plist`: ```xml theme={null} NSHealthShareUsageDescription This app needs access to your health data to provide insights. ``` Since 0.6.1 the SDK only reads health data, so `NSHealthUpdateUsageDescription` is not needed. ### Android Configuration Add to `android/app/src/main/AndroidManifest.xml`: ```xml theme={null} ``` **Important:** Your `MainActivity` must extend `FlutterFragmentActivity` (not `FlutterActivity`) for Android 14+. ## Basic Usage **Recommended Pattern (Explicit Permission Control):** ```dart theme={null} import 'dart:io'; import 'package:flutter/widgets.dart'; import 'package:synheart_wear/synheart_wear.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // Step 1: Create SDK instance final adapters = { DeviceAdapter.platformHealth, // Apple HealthKit on iOS, Health Connect on Android }; // Use withAdapters() to explicitly specify which adapters to enable // Note: Default constructor includes fitbit by default, so use withAdapters() for clarity final synheart = SynheartWear( config: SynheartWearConfig.withAdapters(adapters), ); // Step 2: Request permissions final result = await synheart.requestPermissions( permissions: { PermissionType.heartRate, PermissionType.steps, PermissionType.calories, }, ); // Step 3: Initialize SDK (validates permissions and data availability) if (result.values.any((s) => s == ConsentStatus.granted)) { try { await synheart.initialize(); // Step 4: Read metrics final metrics = await synheart.readMetrics(); print('HR: ${metrics.getMetric(MetricType.hr)} bpm'); print('Steps: ${metrics.getMetric(MetricType.steps)}'); } on SynheartWearError catch (e) { print('Initialization failed: $e'); // Handle errors: NO_WEARABLE_DATA, STALE_DATA, etc. } } } ``` **Alternative Pattern (Simplified):** If you don't need to control when the permission prompt appears, let `initialize()` request permissions itself: ```dart theme={null} final synheart = SynheartWear( config: SynheartWearConfig.withAdapters({DeviceAdapter.platformHealth}), ); // Initialize will request permissions internally if needed await synheart.initialize(); final metrics = await synheart.readMetrics(); ``` **Note:** `initialize()` validates that wearable data is available and not stale (>24 hours old). If no data is available or data is too old, it will throw a `SynheartWearError` with codes `NO_WEARABLE_DATA` or `STALE_DATA`. ## Real-Time Streaming ```dart theme={null} // Stream heart rate every 5 seconds // Note: Streams are created lazily when first listener subscribes // Multiple calls to streamHR() return the same stream controller final hrSubscription = synheart.streamHR(interval: Duration(seconds: 5)) .listen((metrics) { final hr = metrics.getMetric(MetricType.hr); if (hr != null) print('Current HR: $hr bpm'); }, onError: (error) { print('Stream error: $error'); }); // Stream HRV in 5-second windows final hrvSubscription = synheart.streamHRV(windowSize: Duration(seconds: 5)) .listen((metrics) { final hrv = metrics.getMetric(MetricType.hrvRmssd); if (hrv != null) print('HRV RMSSD: $hrv ms'); }, onError: (error) { print('HRV stream error: $error'); }); // Don't forget to cancel subscriptions when done // hrSubscription.cancel(); // hrvSubscription.cancel(); ``` ## Complete Example ```dart theme={null} import 'dart:async'; import 'package:flutter/material.dart'; import 'package:synheart_wear/synheart_wear.dart'; class HealthMonitor extends StatefulWidget { @override _HealthMonitorState createState() => _HealthMonitorState(); } class _HealthMonitorState extends State { late SynheartWear _sdk; StreamSubscription? _hrSubscription; WearMetrics? _latestMetrics; bool _isConnected = false; @override void initState() { super.initState(); _sdk = SynheartWear( config: SynheartWearConfig.withAdapters({ DeviceAdapter.platformHealth, }), ); } Future _connect() async { try { // Step 1: Request permissions final result = await _sdk.requestPermissions( permissions: { PermissionType.heartRate, PermissionType.steps, PermissionType.calories, }, ); // Step 2: Initialize if permissions granted if (result.values.any((s) => s == ConsentStatus.granted)) { await _sdk.initialize(); // Step 3: Read initial metrics final metrics = await _sdk.readMetrics(); setState(() { _isConnected = true; _latestMetrics = metrics; }); } else { setState(() { _isConnected = false; // Show error: permissions denied }); } } on SynheartWearError catch (e) { // Handle SDK-specific errors (NO_WEARABLE_DATA, STALE_DATA, etc.) print('SDK Error: $e'); setState(() { _isConnected = false; // Show error message }); } catch (e) { // Handle other errors print('Error: $e'); setState(() { _isConnected = false; }); } } void _startStreaming() { _hrSubscription = _sdk .streamHR(interval: Duration(seconds: 3)) .listen( (metrics) { setState(() => _latestMetrics = metrics); }, onError: (error) { print('Stream error: $error'); // Handle stream errors }, ); } void _stopStreaming() { _hrSubscription?.cancel(); _hrSubscription = null; } @override void dispose() { _hrSubscription?.cancel(); _sdk.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Health Monitor')), body: _isConnected ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_latestMetrics != null) ...[ Text( 'HR: ${_latestMetrics!.getMetric(MetricType.hr) ?? "--"} bpm', style: TextStyle(fontSize: 32), ), SizedBox(height: 16), Text('Steps: ${_latestMetrics!.getMetric(MetricType.steps) ?? "--"}'), Text('Calories: ${_latestMetrics!.getMetric(MetricType.calories) ?? "--"} kcal'), SizedBox(height: 24), ], ElevatedButton( onPressed: _hrSubscription == null ? _startStreaming : _stopStreaming, child: Text(_hrSubscription == null ? 'Start Streaming' : 'Stop Streaming'), ), ], ) : Center( child: ElevatedButton( onPressed: _connect, child: Text('Connect to Health'), ), ), ); } } ``` ## Data Schema Access metrics using the `WearMetrics` object: ```dart theme={null} final metrics = await synheart.readMetrics(); // Basic metrics final hr = metrics.getMetric(MetricType.hr); // Heart rate (bpm) final steps = metrics.getMetric(MetricType.steps); // Steps final calories = metrics.getMetric(MetricType.calories); // Calories (kcal) final distance = metrics.getMetric(MetricType.distance); // Distance (km) // HRV metrics: the platform gives one HRV figure (SDNN on iOS, RMSSD on // Health Connect), and the SDK stores it under both keys final hrvRmssd = metrics.getMetric(MetricType.hrvRmssd); // HRV (ms) final hrvSdnn = metrics.getMetric(MetricType.hrvSdnn); // same value // RR intervals (nullable; non-null only when the adapter exposes RR samples) final rrIntervals = metrics.rrIntervalsMs; // List? // Metadata final batteryLevel = metrics.batteryLevel; // 0.0-1.0 final synced = metrics.isSynced; // true for vendor sync/backfill data final deviceId = metrics.deviceId; // String final source = metrics.source; // String final timestamp = metrics.timestamp; // DateTime ``` ## Error Handling ```dart theme={null} try { // Request permissions final result = await synheart.requestPermissions( permissions: {PermissionType.heartRate, PermissionType.steps}, ); if (result.values.any((s) => s == ConsentStatus.granted)) { // Initialize (may throw if no data or stale data) await synheart.initialize(); // Read metrics final metrics = await synheart.readMetrics(); if (metrics.hasValidData) { print('Data available'); } } } on PermissionDeniedError catch (e) { print('Permission denied: ${e.message}'); // User denied permissions - show message or retry } on SynheartWearError catch (e) { // Handle SDK-specific errors if (e.code == 'NO_WEARABLE_DATA') { print('No wearable data available. Please check device connection.'); } else if (e.code == 'STALE_DATA') { print('Data is stale. Please sync your wearable device.'); } else { print('SDK error: ${e.message}'); } } catch (e) { print('Unexpected error: $e'); } ``` **Common Error Codes:** * `NO_WEARABLE_DATA`: No health data available from connected devices * `STALE_DATA`: Latest data is older than 24 hours * `PERMISSION_DENIED`: User denied required permissions (thrown as `PermissionDeniedError`) `requestPermissions()` accepts a `reason:` argument, but the SDK doesn't show it anywhere; explain the request in your own UI before calling it. ## BLE Heart Rate Monitor Connect directly to any standard Bluetooth LE heart rate monitor (WHOOP Broadcast, Polar, Wahoo, Garmin HRM straps) for real-time HR streaming. No cloud backend needed. ### Platform Setup **Android** — Add to `AndroidManifest.xml`: ```xml theme={null} ``` On Android, request `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT` at runtime yourself (for example with `permission_handler`). `BleHrmProvider.requestPermission()` is iOS-only; on Android it throws `MissingPluginException`. **iOS** — Add to `Info.plist`: ```xml theme={null} NSBluetoothAlwaysUsageDescription This app uses Bluetooth to connect to heart rate monitors. ``` ### Usage ```dart theme={null} import 'dart:io'; import 'package:synheart_wear/synheart_wear.dart'; final bleHrm = BleHrmProvider(); // iOS only: show the Bluetooth permission prompt if (Platform.isIOS) await bleHrm.requestPermission(); // Scan for nearby HR monitors (default timeout 5 s; optional name prefix) final devices = await bleHrm.scan(timeoutMs: 10000, namePrefix: 'Polar'); if (devices.isEmpty) return; await bleHrm.connect( deviceId: devices.first.deviceId, sessionId: 'my-session', ); // Listen to heart rate samples final sub = bleHrm.onHeartRate.listen((sample) { print('BPM: ${sample.bpm}'); if (sample.rrIntervalsMs.isNotEmpty) { print('RR intervals: ${sample.rrIntervalsMs}'); } }); // Check connection status final connected = await bleHrm.isConnected(); // Disconnect when done await sub.cancel(); await bleHrm.disconnect(); ``` Polar H10 straps can also stream their accelerometer: pass `enableMotion: true` (and optionally `motionSampleRateHz`, default 50) to `connect()` and listen to `bleHrm.onMotion`. `getBondedHrDevices()` lists already-bonded straps without scanning. ### HeartRateSample Each sample from the stream contains: | Field | Type | Description | | - | - | - | | `tsMs` | `int` | Phone receipt timestamp (ms since epoch) | | `bpm` | `double` | Heart rate in beats per minute | | `source` | `String` | Always `"ble_hrm"` | | `deviceId` | `String?` | BLE MAC address on Android, CoreBluetooth peripheral UUID on iOS | | `deviceName` | `String?` | Device advertised name | | `sessionId` | `String?` | Optional session tag | | `rrIntervalsMs` | `List` | RR intervals in milliseconds (empty when device doesn't expose RR) | ### Error Handling BLE calls throw `BleHrmError`, whose `code` is a `BleHrmErrorCode`. Errors on the `onHeartRate` stream use the same type: ```dart theme={null} try { await bleHrm.connect(deviceId: id); } on BleHrmError catch (e) { switch (e.code) { case BleHrmErrorCode.permissionDenied: // Bluetooth permission not granted case BleHrmErrorCode.bluetoothOff: // Bluetooth adapter is disabled case BleHrmErrorCode.deviceNotFound: // not found, or connection timed out case BleHrmErrorCode.subscribeFailed: // HR notifications failed (also unknown native errors) case BleHrmErrorCode.disconnected: // device disconnected } } ``` ### Notes * WHOOP devices require "Broadcast Heart Rate" enabled in the WHOOP app settings * RR intervals are available on some devices (e.g. Polar chest straps) but not all * Reconnection is automatic. Android retries 5 times, 3 s apart; iOS waits up to 30 s for CoreBluetooth to reconnect. After that `disconnected` is reported * Only one BLE HRM device can be connected at a time ## Cloud Providers ### WhoopProvider ```dart theme={null} final whoopProvider = WhoopProvider( appId: 'your-app-id', userId: 'user-123', ); // Historical data methods final recovery = await whoopProvider.fetchRecovery( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final sleep = await whoopProvider.fetchSleep( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final workouts = await whoopProvider.fetchWorkouts( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final cycles = await whoopProvider.fetchCycles( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); ``` ### GarminProvider (Cloud) Full Garmin Connect integration via OAuth PKCE. Supports 12 summary types through the Garmin Health API backfill endpoint, plus activities (`fetchActivities()`): **dailies**, **epochs**, **sleeps**, **stressDetails**, **hrv**, **userMetrics**, **bodyComps**, **pulseox**, **respiration**, **healthSnapshot**, **bloodPressures**, and **skinTemp**. ```dart theme={null} final garminProvider = GarminProvider( appId: 'your-app-id', userId: 'user-123', ); // Backfill API — fetch any of the 12 summary types final dailies = await garminProvider.fetchDailies( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final sleeps = await garminProvider.fetchSleeps( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final hrv = await garminProvider.fetchHRV( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); final stress = await garminProvider.fetchStressDetails( start: DateTime.now().subtract(Duration(days: 7)), end: DateTime.now(), ); // Additional methods: fetchEpochs(), fetchUserMetrics(), fetchBodyComps(), // fetchPulseOx(), fetchRespiration(), fetchHealthSnapshot(), // fetchBloodPressures(), fetchSkinTemp() ``` ### GarminHealth (Native RTS) The `GarminHealth` facade provides native Garmin device integration for scanning, pairing, and real-time streaming. All method signatures use generic SDK-owned types (`ScannedDevice`, `PairedDevice`, `WearMetrics`), never Garmin-specific types. > **Important:** The Garmin Health SDK Real-Time Streaming (RTS) capability requires a separate license from Garmin. This facade is available on demand for licensed integrations. The underlying Garmin Health SDK code is proprietary to Garmin and is not distributed as open source. ```dart theme={null} final garmin = GarminHealth(licenseKey: 'your-garmin-sdk-key'); await garmin.initialize(); // Scan for devices garmin.scannedDevicesStream.listen((devices) { print('Found ${devices.length} devices'); }); await garmin.startScanning(); // Pair with a device final paired = await garmin.pairDevice(scannedDevice); // Stream real-time metrics garmin.realTimeStream.listen((metrics) { final hr = metrics.getMetric(MetricType.hr); print('HR: $hr bpm'); }); await garmin.startStreaming(device: paired); // Read unified metrics final metrics = await garmin.readMetrics(); ``` ## Platform-Specific Notes ### Android * HRV: Only `HRV_RMSSD` is supported by Health Connect * Distance: Uses `DISTANCE_DELTA` type * Requires Health Connect app installed * MainActivity must extend `FlutterFragmentActivity` ### iOS * Requires iOS 16+ and the HealthKit capability enabled in Xcode * No HealthKit background delivery: reads happen when your app calls the SDK * Real-time reads look back 2 minutes and run at most every 10 s; calls in between return no new data ## API Reference ### `SynheartWear` Main SDK class for interacting with wearable devices. **Constructor:** ```dart theme={null} SynheartWear({ SynheartWearConfig? config, // defaults to SynheartWearConfig() Map? adapters, // custom adapter overrides GarminHealth? garminHealth, }) ``` **Methods:** | Method | Description | Returns | | - | - | - | | `requestPermissions()` | Request health data permissions | `Future>` | | `initialize()` | Initialize the SDK | `Future` | | `getPermissionStatus()` | Current grant per permission | `Map` | | `revokeAllPermissions()` | Revoke the SDK's grants (does not clear the cache) | `Future` | | `readMetrics({isRealTime, startTime, endTime})` | Read latest metrics | `Future` | | `streamHR({interval})` | Stream heart rate | `Stream` | | `streamHRV({windowSize})` | Stream HRV | `Stream` | | `getCachedSessions()` / `getCacheStats()` / `clearOldCache()` | Local cache | `Future<…>` | | `garminHealth` | The `GarminHealth` passed to the constructor | `GarminHealth?` | | `dispose()` | Cleanup resources | `void` | ### `SynheartWearConfig` Configuration for the SDK. **Constructor:** ```dart theme={null} const SynheartWearConfig({ Set enabledAdapters, // default includes platformHealth Duration streamInterval = const Duration(seconds: 2), Duration hrvWindowSize = const Duration(seconds: 5), bool enableLocalCaching = true, bool enableEncryption = true, String? encryptionKeyPath, Map adapterConfig = const {}, }) SynheartWearConfig.withAdapters(Set adapters) // other fields default SynheartWearConfig.development() SynheartWearConfig.production() config.copyWith(...) ``` ### `WearMetrics` Biometric data container. **Methods:** | Method | Description | Returns | | - | - | - | | `getMetric(MetricType type)` | Get specific metric | `num?` | | `hasValidData` | Check if data is valid | `bool` | **Properties:** | Property | Type | Description | | - | - | - | | `timestamp` | `DateTime` | When data was recorded | | `deviceId` | `String` | Device identifier | | `source` | `String` | Data source | | `rrIntervalsMs` | `List?` | RR intervals (ms); non-null only when the adapter exposes them | | `batteryLevel` | `double?` | Battery level (0.0-1.0); pulled from `meta.battery` | | `isSynced` | `bool` | `true` when the sample came from a vendor sync or backfill (`meta.synced`) | ## Resources * **Repository**: [synheart-wear-flutter](https://github.com/synheart-ai/synheart-wear-flutter) * **pub.dev**: [synheart\_wear](https://pub.dev/packages/synheart_wear) * **API Docs**: [API Reference](https://pub.dev/documentation/synheart_wear/latest/) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-wear-flutter/issues) # Synheart Wear - Kotlin/Android SDK Source: https://docs.synheart.ai/synheart-wear/kotlin Native Android SDK with Health Connect integration ## Overview The Synheart Wear Kotlin SDK provides native Android support for reading biometric data from wearables via Health Connect, vendor cloud APIs (WHOOP, Garmin, Fitbit, Oura), and direct BLE heart-rate sensors. ## Installation ### Gradle (Kotlin DSL) Published to **Maven Central** as `ai.synheart:synheart-wear`: ```kotlin theme={null} repositories { mavenCentral() } dependencies { implementation("ai.synheart:synheart-wear:0.4.2") } ``` ### Requirements * Android `minSdk` 21, `compileSdk` 34, Java 17 * The library is built with Kotlin 2.3 and depends on `kotlin-stdlib` 2.3.0, so your project needs a Kotlin compiler that can read 2.3 metadata * Health Connect installed on the device (built in on Android 14+, otherwise from the Play Store) ## Quick Start ### Create the SDK ```kotlin theme={null} import ai.synheart.wear.SynheartWear import ai.synheart.wear.config.SynheartWearConfig import ai.synheart.wear.models.DeviceAdapter val synheartWear = SynheartWear( context = this, config = SynheartWearConfig( enabledAdapters = setOf(DeviceAdapter.HEALTH_CONNECT) ) ) ``` ### Initialize, then ask for Health Connect access Call `initialize()` first: every other call throws `SynheartWearException` ("SDK not initialized") until it has run. `requestPermissions()` does **not** show the Health Connect permission screen. It reports which of the requested permissions are already granted. Show the screen yourself with Health Connect's `PermissionController` contract, which needs an Activity: ```kotlin theme={null} import androidx.health.connect.client.PermissionController import androidx.health.connect.client.permission.HealthPermission import androidx.health.connect.client.records.HeartRateRecord import androidx.health.connect.client.records.StepsRecord import androidx.health.connect.client.records.TotalCaloriesBurnedRecord private val hcPermissions = setOf( HealthPermission.getReadPermission(HeartRateRecord::class), HealthPermission.getReadPermission(StepsRecord::class), HealthPermission.getReadPermission(TotalCaloriesBurnedRecord::class), ) private val requestHc = registerForActivityResult( PermissionController.createRequestPermissionResultContract() ) { granted -> if (granted.containsAll(hcPermissions)) readNow() } fun start() { lifecycleScope.launch { synheartWear.initialize() requestHc.launch(hcPermissions) } } fun readNow() { lifecycleScope.launch { val status = synheartWear.getPermissionStatus() // Map val metrics = synheartWear.readMetrics() Log.d(TAG, "HR: ${metrics.getMetric(MetricType.HR)} bpm") } } ``` ### Real-Time Streaming ```kotlin theme={null} lifecycleScope.launch { synheartWear.streamHR(intervalMs = 5000L).collect { metrics -> val hr = metrics.getMetric(MetricType.HR) Log.d(TAG, "Current HR: $hr bpm") } } ``` `streamHRV(windowMs = 5000L)` emits HRV the same way. ## Health Connect Reads from any wearable companion app that syncs to Jetpack Health Connect — Fitbit, Garmin Connect, Samsung Health, Google Fit, Polar Flow, etc. (Apple Watch is **not** supported on Android — it only syncs to Apple Health on iOS.) ### AndroidManifest.xml The SDK's own manifest declares 17 Health Connect read permissions plus `READ_HEALTH_DATA_IN_BACKGROUND`, and the `` block for the Health Connect app, so your app inherits them. That list includes types the SDK does not read today (oxygen saturation, respiratory rate, body temperature, weight, height, body fat, lean body mass, speed). If your app doesn't use them, remove them so Play review doesn't ask you to justify them: ```xml theme={null} ``` Play policy requires a permissions-rationale screen and a privacy-policy entry point. Add both to your own manifest: ```xml theme={null} ``` ### Record types read `HealthConnectAdapter` reads `HeartRateRecord`, `HeartRateVariabilityRmssdRecord`, `StepsRecord`, `TotalCaloriesBurnedRecord`, `ActiveCaloriesBurnedRecord`, `DistanceRecord` (reported in **meters**), `ExerciseSessionRecord` and `SleepSessionRecord`. ### Sleep and overnight history `HealthConnectAdapter` also implements `HealthHistoryReader`, which returns per-night summaries keyed by local date: ```kotlin theme={null} import ai.synheart.wear.adapters.HealthConnectAdapter import java.time.Instant import java.time.ZoneId import java.time.temporal.ChronoUnit val hc = HealthConnectAdapter(context) val end = Instant.now() val start = end.minus(14, ChronoUnit.DAYS) val zone = ZoneId.systemDefault() val nights = hc.fetchSleepNights(start, end, zone) // Map val physiology = hc.fetchOvernightPhysiology(start, end, zone) // Map ``` `SleepNightSummary` carries `totalAsleepMinutes`, `deepMinutes` and `remMinutes`. `OvernightPhysiologySummary` carries `hrvRmssdMs` and `restingHrBpm`. ### Availability ```kotlin theme={null} val availability = HealthConnectAdapter(context).getAvailabilityStatus() if (!availability.isAvailable()) { // Health Connect missing or needs an update: send the user to the Play Store } // Or, without an instance: HealthConnectAdapter.isAvailable(context) HealthConnectAdapter.getSdkStatus(context) ``` Per-record retention is platform-controlled (typically \~30 days for HR, longer for sleep). For older data use a cloud provider. ## Cloud providers (WHOOP / Garmin / Fitbit / Oura) Cloud providers exist only when you pass a `CloudConfig` and list the vendor in `enabledAdapters`. They are created during `initialize()`. ```kotlin theme={null} import ai.synheart.wear.config.CloudConfig val synheartWear = SynheartWear( context = this, config = SynheartWearConfig( enabledAdapters = setOf( DeviceAdapter.HEALTH_CONNECT, DeviceAdapter.WHOOP, DeviceAdapter.GARMIN, ), cloudConfig = CloudConfig( appId = "your-app-id", redirectUri = "yourapp://oauth/callback", // default: synheart://oauth/callback // baseUrl defaults to https://api.synheart.ai/wear ), ) ) synheartWear.initialize() val whoop = synheartWear.getProvider(DeviceAdapter.WHOOP) val garmin = synheartWear.getProvider(DeviceAdapter.GARMIN) val fitbit = synheartWear.fitbit // FitbitProvider?, also via getProvider(FITBIT) val oura = synheartWear.oura // OuraProvider?, also via getProvider(OURA) ``` `getProvider()` throws `SynheartWearException` when the vendor isn't enabled or `cloudConfig` is missing. `isCloudAdapterEnabled(vendor)` checks without throwing. OAuth is mediated by the Synheart Wear API; the device never sees vendor access tokens. Call `provider.connect()` to get an authorization URL, open it in a browser, then call `provider.connectWithCode(code, state, redirectUri)` from your deep-link handler. `readMetricsFromProvider(...)` reads a connected vendor's data as `WearMetrics`. Full code sample in the SDK [README's Cloud Wearables section](https://github.com/synheart-ai/synheart-wear-kotlin#%EF%B8%8F-cloud-wearables-integration). ## BLE Heart Rate Monitor Connect directly to any standard Bluetooth LE heart rate monitor for real-time HR streaming. ### Setup Add to `AndroidManifest.xml`: ```xml theme={null} ``` Request `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT` at runtime on Android 12+ before scanning. ### Usage `bleHrm` is `null` until `initialize()` has run. ```kotlin theme={null} val synheartWear = SynheartWear( context = this, config = SynheartWearConfig( enabledAdapters = setOf(DeviceAdapter.BLE_HRM) ) ) lifecycleScope.launch { synheartWear.initialize() val bleHrm = synheartWear.bleHrm ?: return@launch // Scan for nearby HR monitors (default timeout 10 s) val devices = bleHrm.scan(timeoutMs = 10_000, namePrefix = "Polar") val device = devices.firstOrNull() ?: return@launch bleHrm.connect(deviceId = device.deviceId, sessionId = "my-session") // heartRateFlow never completes: collect it in its own job val job = launch { bleHrm.heartRateFlow.collect { sample -> Log.d(TAG, "BPM: ${sample.bpm}") sample.rrIntervalsMs?.let { rr -> Log.d(TAG, "RR: $rr") } } } // Later, when you're done: job.cancel() bleHrm.disconnect() } ``` Errors throw `BleHrmException`, whose `errorCode` is a `BleHrmErrorCode`: `PERMISSION_DENIED`, `BLUETOOTH_OFF`, `DEVICE_NOT_FOUND`, `SUBSCRIBE_FAILED` or `DISCONNECTED`. After an unexpected disconnect the provider retries three times (1 s, 2 s, 4 s) before giving up. ### Supported Devices Works with any BLE device implementing the standard Heart Rate Profile (0x180D): * WHOOP (Broadcast HR mode) * Polar H10, OH1 * Wahoo TICKR * Garmin HRM-Pro / HRM-Dual ## Garmin Health SDK (Native RTS) The `GarminHealth` facade provides native Garmin device integration for scanning, pairing, and real-time streaming using generic SDK-owned types. > **Important:** The Garmin Health SDK Real-Time Streaming (RTS) capability requires a separate license from Garmin. The underlying Garmin Health SDK code is proprietary to Garmin and is not distributed as open source. In the Maven Central build, `initialize()` succeeds but every data call throws `SynheartWearException`; licensed integrations build with the Garmin overlay. ```kotlin theme={null} import ai.synheart.wear.adapters.GarminHealth val garmin = GarminHealth(licenseKey = "your-garmin-sdk-key") garmin.initialize() synheartWear.setGarminHealth(garmin) lifecycleScope.launch { launch { garmin.scannedDevicesFlow.collect { devices -> Log.d(TAG, "Found ${devices.size} devices") } } garmin.startScanning(timeoutSeconds = 30) } // Once the user picks a device: val paired = garmin.pairDevice(scannedDevice) garmin.startStreaming(paired) ``` For cloud-based Garmin data (OAuth + webhooks), use the `GARMIN` cloud provider instead. ## Local cache `SynheartWearConfig.enableLocalCaching` (default `true`) keeps recent readings on the device; `getCachedSessions()`, `getCacheStats()` and `clearOldCache()` manage it, and `purgeAllData()` clears the cache and revokes consents. > [!WARNING] > > `enableEncryption` is accepted but not applied in 0.4.2: the Kotlin cache is > written unencrypted. Don't rely on it for data that must be encrypted at rest. ## Errors SDK calls throw `SynheartWearException(message, cause, code)`. BLE calls throw `BleHrmException` (see above). ## Resources * **Repository**: [synheart-wear-kotlin](https://github.com/synheart-ai/synheart-wear-kotlin) * **Full README**: [View on GitHub](https://github.com/synheart-ai/synheart-wear-kotlin#readme) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-wear-kotlin/issues) # Synheart Wear Overview Source: https://docs.synheart.ai/synheart-wear/overview Unified wearable SDK for streaming biometric data across devices and platforms ## What is Synheart Wear? Synheart Wear is a unified wearable SDK ecosystem that streams biometric data (HR, HRV, steps, calories, distance) from Apple Health, Health Connect, WHOOP, Garmin, Fitbit, Oura and BLE heart-rate straps through a single, standardized API across Flutter, Android, and iOS applications. > [!NOTE] > > Wondering what data you actually get from each device — and what you don't? > [Wearable signals](/synheart-wear/signals) is the reality check: the access > gates, the raw signals, and what the data becomes downstream. ## Key Features ### Cross-Platform Support * **Flutter**: Cross-platform mobile apps (iOS 16+ / Android API 28+, Flutter 3.32+) * **Native Android**: Kotlin SDK with Health Connect integration (Android API 21+, `compileSdk` 34) * **Native iOS**: Swift SDK with HealthKit integration (iOS 13+, watchOS 8+, macOS 13+) ### Multi-Device Support | Device | Flutter | Android | iOS | Status | | - | - | - | - | - | | **Apple Watch** | ✅ | — | ✅ (via HealthKit) | Ready | | **Health Connect** | ✅ | ✅ (Native) | ❌ | Ready | | **WHOOP** | ✅ | ✅ | ✅ | Ready | | **BLE Heart Rate Monitors** | ✅ | ✅ | ✅ | Ready | | **Fitbit (Cloud OAuth)** | ✅ | ✅ | ✅ | Ready | | **Garmin (Cloud)** | ✅ | ✅ | ✅ | Ready | | **Garmin (Native RTS)** | ✅ | ✅ | ✅ | On demand (licensed) | | **Samsung Health** | 📋 | 📋 | ❌ | Planned | | **Oura Ring (Cloud OAuth)** | ✅ | ✅ | ✅ | Ready | > **Garmin Native RTS:** The Garmin Health SDK Real-Time Streaming (RTS) capability requires a separate license from Garmin. The `GarminHealth` facade is available on demand for licensed integrations. The underlying Garmin Health SDK code is proprietary to Garmin and is not distributed as open source. For cloud-based Garmin data (OAuth + webhooks), use `GarminProvider`. **Legend:** ✅ Ready | 📋 Planned ### BLE Heart Rate Monitor Support Direct Bluetooth LE connection to any standard heart rate monitor — no cloud API required. Works with devices implementing the standard BLE Heart Rate Profile (0x180D), including: * WHOOP (Broadcast Heart Rate mode) * Polar chest straps (H10, OH1) * Wahoo TICKR * Garmin HRM-Pro / HRM-Dual ### Unified data shape Every SDK reports readings as `WearMetrics`. The Flutter SDK serializes it with `WearMetrics.toJson()`: ```json theme={null} { "timestamp": "2025-10-20T18:30:00Z", "device_id": "applewatch_1234", "source": "apple_healthkit", "metrics": { "hr": 72, "hrv_rmssd": 45, "hrv_sdnn": 62, "steps": 1045, "calories": 120.4, "distance": 2.5 }, "meta": { "battery": 0.82 }, "rr_ms": [800, 850, 820] } ``` `timestamp`, `device_id`, `source`, `metrics`, and `meta` are required. `metrics` keys are scoped by the `MetricType` enum (`hr`, `hrv_rmssd`, `hrv_sdnn`, `steps`, `calories`, `distance`, `stress`); adapters set the keys they actually have. `meta` is a free-form `Map` — `meta.battery` and `meta.synced` are read back by the SDK (`WearMetrics.batteryLevel`, `WearMetrics.isSynced`). The native SDKs differ in a few places: | | Flutter | Kotlin | Swift | | - | - | - | - | | Serializer | `toJson()` | `toMap()` | `toDict()` | | RR intervals | `rrIntervalsMs` (`rr_ms`) | `rrIntervals` | `rrIntervals` | | `meta` | `Map` | `Map` | `[String: String]` | | Battery | `meta.battery` | `MetricType.BATTERY` | `.battery` | | `distance` | km | meters | not read from HealthKit | The two HRV keys usually hold the same value: each platform reports one HRV figure (SDNN from HealthKit, RMSSD from Health Connect), and the SDK stores it under both. ### Privacy & security * **Consent-first design** — reads are gated by the permissions the user granted. On Flutter, `requestPermissions` is all-or-nothing: every requested type gets the same status. * **Local cache encryption** — on Flutter, the local cache is encrypted with AES-256 (CTR mode) when `enableEncryption` is set. The Kotlin and Swift SDKs accept `enableEncryption` but currently write the cache **unencrypted**. * **No persistent IDs** — the SDK does not generate or persist a user-level identifier; integrations supply their own pseudonymous ID. * **Right to revoke** — Kotlin and Swift `purgeAllData()` clears the local cache and revokes consents. On Flutter, `revokeAllPermissions()` revokes grants and `clearOldCache()` clears the cache; they are separate calls. ## Architecture ```text theme={null} ┌──────────────────────────────────────────────────────┐ │ Synheart Wear Ecosystem │ └──────────────────────────────────────────────────────┘ │ ┌────────────────┼────────────────┐ │ │ │ ┌───────▼────────┐ ┌─────▼─────┐ ┌───────▼────────┐ │ synheart-wear- │ │synheart- │ │ synheart-wear- │ │ flutter │ │wear-kotlin│ │ swift │ │ (Flutter) │ │ (Android) │ │ (iOS) │ └────────────────┘ └───────────┘ └────────────────┘ ``` ### SDK Architecture Each SDK implements a consistent architecture: ```text theme={null} ┌─────────────────────────┐ │ synheart_wear SDK │ ├─────────────────────────┤ │ Device Adapters Layer │ │ (Apple, Fitbit, etc.) │ ├─────────────────────────┤ │ Normalization Engine │ │ (standard output schema)│ ├─────────────────────────┤ │ Local Cache & Storage │ │ (encrypted, offline) │ └─────────────────────────┘ ``` ## Available SDKs ### Flutter SDK Cross-platform SDK for iOS and Android apps. > [card] [Flutter SDK Documentation](/synheart-wear/flutter) > > Complete guide for Flutter integration **Installation:** ```yaml theme={null} dependencies: synheart_wear: ^0.6.2 ``` **Repository:** [synheart-wear-flutter](https://github.com/synheart-ai/synheart-wear-flutter) · [runnable example](https://github.com/synheart-ai/synheart-wear-flutter/tree/main/example) ### Android (Kotlin) SDK Native Android SDK with Health Connect integration. > [card] [Kotlin SDK Documentation](/synheart-wear/kotlin) > > Complete guide for Android integration **Installation:** ```kotlin theme={null} implementation("ai.synheart:synheart-wear:0.4.2") ``` **Repository:** [synheart-wear-kotlin](https://github.com/synheart-ai/synheart-wear-kotlin) ### iOS (Swift) SDK Native iOS SDK with HealthKit integration. > [card] [Swift SDK Documentation](/synheart-wear/swift) > > Complete guide for iOS integration **Installation:** ```swift theme={null} .package(url: "https://github.com/synheart-ai/synheart-wear-swift.git", from: "0.4.2") ``` **Repository:** [synheart-wear-swift](https://github.com/synheart-ai/synheart-wear-swift) ## Stability Synheart Wear is **pre-1.0**. Minor version bumps may include breaking API changes — pin exact versions (or a tight constraint like `^0.6.2`) in production, and read each SDK's CHANGELOG before upgrading. Individual wearable adapters are versioned independently of the SDK; adapter-specific changes are called out in the [Adapters](/synheart-wear/adapters) page. ## Use Cases ### Wellness Apps Monitor heart rate, HRV, and activity metrics for wellness coaching: ```dart theme={null} final synheart = SynheartWear( config: SynheartWearConfig.withAdapters({ DeviceAdapter.platformHealth, }), ); synheart.streamHR(interval: Duration(seconds: 5)) .listen((metrics) { final hr = metrics.getMetric(MetricType.hr); if (hr != null && hr > 120) { showAlert('High heart rate detected!'); } }); ``` ### Mental Health Platforms Stream biosignals into [Synheart Core](/synheart-core/overview) for HSI fusion (focus, capacity, recovery, strain): ```dart theme={null} synheart.streamHRV(windowSize: Duration(seconds: 60)) .listen((metrics) { // Forward to Synheart Core for on-device HSI computation }); ``` ### Research Applications Collect biometric data for scientific studies: ```dart theme={null} final synheart = SynheartWear( config: SynheartWearConfig( enableLocalCaching: true, enableEncryption: true, ), ); final whoopProvider = WhoopProvider( appId: 'your-app-id', userId: 'user-123', ); ``` ## Next Steps > [card] [Quick Start](/quickstart#track-b) > > Get started in 5 minutes > [card] [Flutter SDK](/synheart-wear/flutter) > > Flutter integration guide > [card] [Kotlin SDK](/synheart-wear/kotlin) > > Android integration guide > [card] [Swift SDK](/synheart-wear/swift) > > iOS integration guide ## Community * **GitHub**: [github.com/synheart-ai](https://github.com/synheart-ai) — every Wear SDK lives in its per-language repo (`synheart-wear-flutter`, `synheart-wear-kotlin`, `synheart-wear-swift`). * **Issues**: file against the relevant per-language repo. # Wearable signals Source: https://docs.synheart.ai/synheart-wear/signals What data you actually get from each supported wearable — the three access gates, the raw signals, and the processed human-state output. A wearable *having* a sensor and your app being able to *read* it are two different things. This page is the reality check: what each supported wearable actually delivers into Synheart Wear, what it does **not**, and what the data becomes once it is downstream. ## The three gates A physiological signal reaches your app only if it clears all three gates: 1. **The device has the sensor.** No optical SpO2 sensor on the strap means no SpO2, regardless of software. 2. **The vendor exposes the data.** Many sensors feed only the vendor's own app and are never published on a public API, SDK, or standard BLE profile. A sensor that exists but is not exposed is, for an integrator, the same as no sensor. 3. **Synheart Wear has an adapter for that path.** Synheart Wear normalises the paths a vendor *does* expose — HealthKit, Health Connect, standard BLE, OAuth cloud APIs, the licensed Garmin Health SDK. It does not reverse-engineer private protocols. A signal that clears all three is still either **real-time** (streamed as it is measured) or **historical** (delivered in batches after the device syncs). That distinction is as important as availability — see the matrix below. ## What Synheart Wear delivers Every adapter normalises into the unified [`WearMetrics`](/synheart-wear/data-schema) shape. These keys are the stable, cross-vendor contract: | Signal | `metrics` key | Typical path | Notes | | - | - | - | - | | Heart rate | `hr` | Real-time (BLE) or historical | Produced by every adapter. | | Heart rate variability | `hrv_rmssd`, `hrv_sdnn` | Historical | Computed over the adapter's window; SDNN may be derived on-device from RR. | | Inter-beat (RR) intervals | `rr_ms` (top-level) | Real-time when the source provides it | The highest-fidelity cardiac signal — see [tiers](#from-raw-signals-to-processed-state). | | Steps, calories, distance | `steps`, `calories`, `distance` | Historical | Period totals. | | Stress | `stress` | Historical | A **vendor-specific** score (e.g. Garmin `0–100`); not normalised across vendors. | Signals that are **not** part of the normalised `WearMetrics` contract today: | Signal | Status | | - | - | | SpO2 / blood oxygen | Not a normalised `WearMetrics` key. Real-time SpO2 is available only through the licensed Garmin Health SDK (see [Garmin](#garmin)). Garmin cloud Pulse Ox is available raw through `GarminProvider.fetchPulseOx()` (the vendor record lands in `meta.garmin_data` on Flutter); other cloud vendors' values are not surfaced. | | ECG | Not exposed by any adapter. | | Skin / wrist temperature | Not a normalised key. Garmin cloud skin temperature is available raw through `GarminProvider.fetchSkinTemp()`. | | EDA (electrodermal activity) | Not available from any supported wearable — see below. | ## EDA: why it is not here Electrodermal activity is the most restricted signal in consumer wearables. There is currently **no supported device that gives a third-party integrator open EDA access**: * **Apple Watch, WHOOP, Oura** — no EDA sensor on any model. * **Fitbit Sense / Sense 2** — *have* an EDA sensor, but Fitbit never exposes EDA scan data through the Web API; it stays inside the Fitbit app. * **Samsung Galaxy Watch** — exposes EDA only through Samsung's partner-gated privileged SDK, not the open Health Connect path. The Synheart pipeline already *recognises* an `eda` signal as a [`physiological` modality](/synheart-core/hsi-specification#modality--tier-derivation-in-the-sdk), so if a source ever exposes EDA it can flow through unchanged. But no Wear adapter produces it today, and these docs will not claim otherwise. If your use case depends on EDA, treat it as unavailable until a device vendor opens that path. ## Per-device reality | Wearable | Access path | Real-time signals | Historical signals | Gate | | - | - | - | - | - | | Apple Watch | HealthKit | HR (companion watchOS app) | HRV, RR (workout), steps, calories, distance | Live HR needs a companion watchOS app | | WHOOP | BLE Broadcast / cloud API | HR (BLE) | recovery, strain, sleep (cloud) | OAuth for the cloud path | | Garmin (Connect) | Cloud API | — | HR, HRV, stress, sleep | OAuth + program approval | | Garmin (Health SDK) | On-device RTS | HR, RR, respiration, stress, SpO2 | — | Garmin commercial license | | Fitbit | Cloud API | — | HR, HRV, sleep, activity | OAuth | | Oura | Cloud API | — | readiness, HRV, sleep, activity | OAuth | | BLE HRM | BLE Heart Rate Profile (0x180D) | HR, RR (optional) | — | Bluetooth permission | | Samsung | — | planned | planned | planned | ### Apple Watch HealthKit is the only public path — there is no raw-sensor or BLE API on Apple Watch. HR, HRV (SDNN), steps, calories, and distance arrive as historical samples. Real-time HR is possible, but only with a companion watch app — see [Smartwatches need a companion app](#smartwatches-need-a-companion-app) below. ### WHOOP WHOOP illustrates gate 2 directly. The strap has more sensors than it publishes — but it *does* expose HR through standard **BLE Broadcast Heart Rate** mode (BPM only; RR intervals are typically not included), so HR is supported, in real time, via the shared [BLE HRM](/synheart-wear/ble-hrm) adapter. The WHOOP cloud API adds recovery, strain, and sleep as historical summaries over OAuth. WHOOP has no EDA sensor; its 4.0-and-later SpO2 and skin-temperature values live in the cloud API but Synheart Wear surfaces neither today. ### Garmin Garmin has two paths with very different gates: * **Garmin Connect API** — cloud, historical only: HR, HRV, stress, sleep, Pulse Ox. Delivered as summaries after the device syncs. * **Garmin Health SDK (Real-Time Streaming)** — on-device streaming of HR, beat-to-beat RR, respiration, stress, and **SpO2 / Pulse Ox**. This is the direct integration that yields real-time SpO2. The Health SDK RTS path is **commercially licensed by Garmin**. The `GarminHealth` façade is bundled on demand for licensed integrations only; without that license, Garmin data is limited to the historical Connect API. See [Adapters → Garmin Health SDK](/synheart-wear/adapters#garmin-health-sdk-real-time-streaming). ### Fitbit and Oura Both are cloud OAuth integrations mediated by the Synheart Wear API — the device never sees vendor access tokens. They deliver **historical, sync-based** data only: there is no real-time path. Through Synheart Wear, Fitbit provides HRV, sleep and activity, and Oura provides readiness, sleep, HRV and activity. Neither exposes EDA or ECG to integrators. ### BLE heart rate monitors The standard [BLE Heart Rate Profile](/synheart-wear/ble-hrm) (`0x180D`) carries exactly two things: HR and — when the device sets the optional flag — RR intervals. Nothing else. What you get is real-time HR + RR from any compliant strap, with no cloud and no OAuth. One exception on Flutter: the Polar H10's accelerometer can be streamed over Polar's PMD service (`connect(enableMotion: true)`, then `onMotion`). Other vendor data, such as Polar raw ECG, isn't used. ## Smartwatches need a companion app A smartwatch — Apple Watch or a Wear OS device — is not like a BLE chest strap. The strap streams HR and RR over a standard Bluetooth profile the moment you connect. A smartwatch does not: its OS gates continuous sensor access behind an app **running on the watch itself**. **Without a watch app:** * **watchOS** — an iPhone-only app reads HealthKit, but there is no live stream. Background delivery is batched and throttled to roughly a handful of updates per hour. You get historical samples, not real-time data. * **Wear OS** — an Android phone app reads Health Connect, but the same limit applies: passive monitoring delivers batched, low-frequency data, with no continuous stream to a phone-only app. **With a small companion watch app:** * The app holds an active workout/exercise session, which keeps the optical sensor running at high frequency. * It streams frames to the phone in real time over the platform's watch channel (WatchConnectivity on watchOS, the Wearable Data Layer on Wear OS). * It can compute HR/HRV metrics **on the watch** — so the phone receives derived metrics, not just a raw HR trace. [Synheart Session](/synheart-session/overview) is the SDK for exactly this. Synheart's companion watch apps (watchOS and Wear OS) compute session frames on the watch and stream them to the phone; on the phone, Synheart Session relays start/stop commands and receives the frames. There is no automatic fallback: when no watch is reachable, a session started for the watch gets no heart-rate data. If your app needs continuous or real-time data from a smartwatch, this is the path. | Capability | BLE chest strap | Smartwatch, phone-only | Smartwatch + companion app | | - | - | - | - | | Real-time HR | ✅ direct | ❌ batched / throttled | ✅ streamed from the watch | | RR intervals | ✅ when device sends them | ❌ | ✅ | | On-watch metrics | n/a | ❌ | ✅ HR/HRV computed on the watch | | Extra app to build | none | none | a small watch app | That tradeoff is the core decision for any smartwatch integration: phone-only is simpler but historical; a companion app is the only route to real-time data. ## From raw signals to processed state Synheart Wear gives you **normalised raw readings**. It does not interpret them — it will not tell you the user is stressed, recovered, or focused. That interpretation is a separate layer. ```text theme={null} wearable ──► Synheart Wear ──► normalised WearMetrics (HR, HRV, RR, …) │ ▼ add Synheart Core Synheart Runtime feature pipeline → HSV inference → flux │ ▼ HSI 1.3 (focus, capacity, recovery, strain, emotion, sleep) ``` * **Synheart Wear alone** — raw normalised readings. Right for displaying live numbers, threshold alerts, and logging. * **Synheart Wear + [Synheart Core](/synheart-core/overview)** — the runtime fuses the signals on-device and emits **processed human state** as [HSI 1.3](/hsi/overview). Right for "is the user recovered / focused / strained" questions. Signal fidelity carries all the way through. The runtime caps inference confidence by how good the raw signal was — native beat-to-beat RR is tier 1 and supports high-confidence inference; a lone HR snapshot is tier 4 and is capped low. So the *quality* of what you get out of a wearable directly bounds the quality of the processed state. See the [tier-capped confidence table](/synheart-core/hsv-specification#tier-capped-confidence). ## Related * [Wear Overview](/synheart-wear/overview) — full SDK surface and device matrix. * [Adapters](/synheart-wear/adapters) — per-vendor flow and capabilities. * [Data shape](/synheart-wear/data-schema) — the `WearMetrics` contract in detail. * [BLE Heart Rate Monitor](/synheart-wear/ble-hrm) — direct BLE HRM flow. * [How it fits together](/guides/how-it-fits-together) — where Wear sits in the stack. # Synheart Wear - Swift/iOS SDK Source: https://docs.synheart.ai/synheart-wear/swift Native iOS SDK with HealthKit integration ## Overview The Synheart Wear Swift SDK provides native iOS support for streaming biometric data from Apple Watch via HealthKit, vendor cloud APIs (WHOOP, Garmin, Fitbit, Oura), direct BLE heart-rate sensors, and offline Apple Health `export.xml` backfill. ## Installation ### Swift Package Manager Add to your `Package.swift`: ```swift theme={null} dependencies: [ .package(url: "https://github.com/synheart-ai/synheart-wear-swift.git", from: "0.4.2") ] ``` Or in Xcode: 1. File → Add Packages... 2. Enter: `https://github.com/synheart-ai/synheart-wear-swift.git` ### Requirements * iOS 13.0+, watchOS 8+, macOS 13+ * Swift 5.9+ * Xcode 15.0+ ## Quick Start ### Configure HealthKit Add to `Info.plist`: ```xml theme={null} NSHealthShareUsageDescription We need access to your health data ``` Enable HealthKit capability in Xcode: * Target → Signing & Capabilities → + Capability → HealthKit ### Initialize SDK ```swift theme={null} import SynheartWear let config = SynheartWearConfig( enabledAdapters: [.platformHealth], enableLocalCaching: true ) let synheartWear = SynheartWear(config: config) ``` ### Initialize, Request Permissions & Read Data Call `initialize()` first: every other call throws `SynheartWearError.notInitialized` until it has run. ```swift theme={null} Task { try await synheartWear.initialize() // Shows the HealthKit permission sheet _ = try await synheartWear.requestPermissions([.heartRate, .steps, .calories]) let metrics = try await synheartWear.readMetrics() print("Heart Rate: \(metrics.getMetric(.hr) ?? 0) bpm") } ``` > [!NOTE] > > HealthKit never tells an app whether **read** access was granted. The map > returned by `requestPermissions(_:)` and `getPermissionStatus()` reflects > HealthKit's sharing (write) status, so for read-only access it reports `false` > even when the user allowed reading. Don't gate on it: read, and treat an empty > result as "no data or no access". ### Real-Time Streaming `streamHR(interval:)` returns a Combine `AnyPublisher`. Use `streamHRAsync(interval:)` if you prefer `AsyncStream`. ```swift theme={null} import Combine var cancellables = Set() synheartWear.streamHR(interval: 5.0) .sink( receiveCompletion: { _ in }, receiveValue: { metrics in if let hr = metrics.getMetric(.hr) { print("Current HR: \(hr) bpm") } } ) .store(in: &cancellables) // HRV over a rolling window: streamHRV(window: 5.0) // Async/await alternative: Task { for await metrics in synheartWear.streamHRAsync(interval: 5.0) { if let hr = metrics.getMetric(.hr) { print("Current HR: \(hr) bpm") } } } ``` ## BLE Heart Rate Monitor Connect directly to any standard Bluetooth LE heart rate monitor for real-time HR streaming. ### Setup Add to `Info.plist`: ```xml theme={null} NSBluetoothAlwaysUsageDescription This app uses Bluetooth to connect to heart rate monitors. ``` ### Usage ```swift theme={null} import SynheartWear let config = SynheartWearConfig(enabledAdapters: [.bleHrm]) let synheartWear = SynheartWear(config: config) // The BLE HRM provider exists once .bleHrm is enabled guard let bleHrm = synheartWear.bleHrm else { return } // Scan for nearby HR monitors (default timeout 10 s) let devices = try await bleHrm.scan(timeoutMs: 10000, namePrefix: "Polar") guard let device = devices.first else { return } try await bleHrm.connect(deviceId: device.deviceId, sessionId: "my-session") // onHeartRate doesn't finish on its own: read it in its own task let reader = Task { for await sample in bleHrm.onHeartRate { print("BPM: \(sample.bpm)") if let rr = sample.rrIntervalsMs { print("RR: \(rr)") } } } // Later, when you're done: reader.cancel() try await bleHrm.disconnect() ``` BLE errors throw `SynheartWearError.bleHrm(code, message)`, where `code` is a `BleHrmErrorCode` (`permissionDenied`, `bluetoothOff`, `deviceNotFound`, `subscribeFailed`, `disconnected`). ### Supported Devices Works with any BLE device implementing the standard Heart Rate Profile (0x180D): * WHOOP (Broadcast HR mode) * Polar H10, OH1 * Wahoo TICKR * Garmin HRM-Pro / HRM-Dual ## Cloud providers (WHOOP / Garmin / Fitbit / Oura) Cloud providers exist only when the config carries an `appId` and lists the vendor in `enabledAdapters`: ```swift theme={null} let config = SynheartWearConfig( enabledAdapters: [.platformHealth, .whoop, .garmin, .fitbit, .oura], appId: "your-app-id", redirectUri: "yourapp://oauth/callback" // baseUrl: optional override of the Synheart Wear API ) let synheartWear = SynheartWear(config: config) let whoop = try synheartWear.getProvider(.whoop) // no typed accessor for WHOOP let garmin: GarminProvider? = synheartWear.garmin let fitbit: FitbitProvider? = synheartWear.fitbit let oura: OuraProvider? = synheartWear.oura ``` `getProvider(_:)` throws `SynheartWearError.apiError` when the vendor isn't enabled or `appId` is missing. OAuth is mediated by the Synheart Wear API; the device never sees vendor access tokens. Call `provider.connect()` to launch the system browser at the authorize URL, then `provider.connectWithCode(code:state:redirectUri:)` from your deep-link handler. For Fitbit and Oura, the cloud delivers a `vendor_user_id` directly via deep link — pass that as the `code` argument. ## Sleep and overnight history `HealthKitHistoryReader` returns per-night summaries: ```swift theme={null} let reader = HealthKitHistoryReader() let end = Date() let start = Calendar.current.date(byAdding: .day, value: -14, to: end)! let nights = try await reader.fetchSleepNights(start: start, end: end, timeZone: .current) let physiology = try await reader.fetchOvernightPhysiology(start: start, end: end, timeZone: .current) ``` `SleepNightSummary` carries `totalAsleepMinutes`, `deepMinutes` and `remMinutes`; `OvernightPhysiologySummary` carries `hrvRmssdMs` and `restingHrBpm`. Both maps are keyed by the night's date. ## Apple Health XML Backfill `AppleHealthXmlImport` (part of the `SynheartWear` module) ingests an Apple Health `export.xml` (the file produced by the Health app's "Export All Health Data" feature) and converts it into a stream of `AppleHealthSample` records. The streaming SAX parser stays under a 200 MB working-set budget regardless of file size, so multi-hundred-MB exports are safe. ```swift theme={null} import SynheartWear let xmlURL: URL = ... // path to unzipped export.xml let importer = AppleHealthXmlImport( xmlURL: xmlURL, sink: MyIngestSink() // conforms to AppleXmlIngestSink ) // Synchronous: run it off the main thread let result = try importer.parse(progress: { fraction in print(fraction) }) print("imported \(result.inserted) of \(result.totalSamples) samples") ``` An `AppleXmlIngestSink` implements `open(importId:)`, `insertBatch(_:) -> (inserted: Int, skipped: Int)` and `finalize() -> ImportResult`. Failures throw `AppleHealthXmlError`. Each sample's stable identity is computed by `IdempotencyKey` (SHA-256 over a canonical subset of fields), so re-running the import on the same file produces the same keys and downstream sinks can dedupe safely. ## Garmin Health SDK (Native RTS) The `GarminHealth` facade provides native Garmin device integration for scanning, pairing, and real-time streaming using generic SDK-owned types. > **Important:** The Garmin Health SDK Real-Time Streaming (RTS) capability requires a separate license from Garmin. This facade is available on demand for licensed integrations. The underlying Garmin Health SDK code is proprietary to Garmin and is not distributed as open source. ```swift theme={null} import SynheartWear let garmin = GarminHealth(licenseKey: "your-garmin-sdk-key") try await garmin.initialize() let synheartWear = SynheartWear(config: config, garminHealth: garmin) // The stream doesn't finish on its own: read it in its own task let scan = Task { for await devices in garmin.scannedDevicesStream() { print("Found \(devices.count) devices") } } try await garmin.startScanning(timeoutSeconds: 30) // Once the user picks a device: let paired = try await garmin.pairDevice(scannedDevice) try await garmin.startStreaming(device: paired) scan.cancel() ``` For cloud-based Garmin data (OAuth + webhooks), use `GarminProvider` instead. ## Local cache `enableLocalCaching` (default `true`) keeps recent readings on the device; `getCachedSessions()`, `getCacheStats()` and `clearOldCache(maxAge:)` manage it, and `purgeAllData()` clears the cache and revokes consents. > [!WARNING] > > `enableEncryption` is accepted but not applied in 0.4.2: the Swift cache is > written unencrypted. Don't rely on it for data that must be encrypted at rest. ## Errors SDK calls throw `SynheartWearError`: `notInitialized`, `healthKitNotAvailable`, `healthKitTypeNotAvailable`, `permissionDenied`, `invalidData`, `cacheError`, network cases (`noConnection`, `timeout`, `hostUnreachable`, `invalidResponse`), cloud cases (`notConnected`, `authenticationFailed`, `tokenExpired`, `apiError`, `rateLimitExceeded`, `serverError`) and `bleHrm(code, message)`. ## Resources * **Repository**: [synheart-wear-swift](https://github.com/synheart-ai/synheart-wear-swift) * **Full README**: [View on GitHub](https://github.com/synheart-ai/synheart-wear-swift#readme) * **Issues**: [GitHub Issues](https://github.com/synheart-ai/synheart-wear-swift/issues) For comprehensive documentation, see the [full README on GitHub](https://github.com/synheart-ai/synheart-wear-swift#readme). # Install Source: https://docs.synheart.ai/syni-spec/install How syni-spec is distributed, and how SDKs consume it. You usually don't install `syni-spec` directly. The Syni SDKs (`syni-flutter`, `syni-swift`, `syni-kotlin`) and the Syni Cloud Gateway all embed a pinned spec version at build time — so for most app developers, adding the SDK is enough. This page describes the underlying distribution channel for the rare cases where you do need direct access (writing a new SDK, running validation tooling, building a gateway). ## Distribution channel Spec releases are published to the Synheart CDN at `dist.synheart.ai`, the same publishing pipeline used for the Synheart runtime, the CLI, and every other Synheart artifact. Each release `vX.Y.Z` ships: ```text theme={null} dist.synheart.ai/syni-spec/vX.Y.Z/ ├── manifest.json # version + integrity metadata ├── spec.tar.gz # canonical spec payload (schemas, personas, grammars, …) └── checksums.json # SHA-256 per file in the payload ``` The payload structure is canonical — `schemas/`, `personas/`, `grammars/`, `rules/`, `safety/`, `budgets/`, `registries/`, `compatibility/`, `prompts/` — with `conformance/` and language wrappers excluded. ## Install via the Synheart CLI The `synheart` CLI resolves the latest spec for your project, downloads it, verifies checksums, and writes the pinned version into `synheart.lock`: ```bash theme={null} synheart install spec ``` This is the recommended path for backends, gateways, and SDK development. It uses the same lockfile-driven flow as [`synheart install runtime`](/setup/install-runtime), so reruns are reproducible and CI replays from `synheart.lock`. Pin a specific version: ```bash theme={null} synheart install spec --version vX.Y.Z ``` Pick an explicit `vX.Y.Z` from the published releases — never track a moving channel for production. ## Consuming from an SDK If you're building an app on top of `syni-flutter`, `syni-swift`, or `syni-kotlin`, the SDK already bundles the spec it was built against. You load personas by id — the SDK handles the asset resolution: ```dart theme={null} final persona = await SyniSpecPersona.load('focus.coach.v1'); ``` Each SDK declares the spec version it supports; mismatched spec versions fail safely rather than silently disagreeing. ## Integrity rules Regardless of how you consume the spec, every consumer MUST: * pin to an explicit `vX.Y.Z` — never track a moving channel for production * verify `checksums.json` against the unpacked payload * reject unknown or unsigned releases # Overview Source: https://docs.synheart.ai/syni-spec/overview The canonical behavioral and safety specification for Syni. `syni-spec` is the single source of truth for how Syni behaves across every platform and environment. It defines what Syni is allowed to do, how it is allowed to behave, what it must never do, and what it must always guarantee. Every Syni SDK (Dart, Swift, Kotlin) and the Syni Cloud Gateway conforms to this spec. > If it's in `syni-spec`, it is a contract. If it's not here, it is an > implementation detail. ## What syni-spec is * a **behavioral contract**, not an implementation * a **versioned, immutable** spec — released artifacts are append-only, never edited in place * the **canonical source** of personas, schemas, grammars, safety rules, and budgets consumed by every Syni SDK * distributed as signed, pinned artifacts via [`dist.synheart.ai`](/syni-spec/install) ## What syni-spec is not * not an SDK * not a runtime * not a place for feature flags, dynamic configuration, or anything that executes code ## What you get on disk After running `synheart install spec`, the spec payload lands under your project's `synheart/vendor/syni-spec/` tree: ```text theme={null} syni-spec/ ├── VERSION ├── LICENSE ├── schemas/ # JSON Schemas for outputs and persona meta-schemas ├── personas/ # core / research / prod persona definitions ├── grammars/ # GBNF grammars bound to output schemas ├── rules/ # behavior rules referenced by personas ├── safety/ # global safety policies ├── budgets/ # per-persona resource budgets ├── registries/ # canonical id → file mappings ├── compatibility/ # version compatibility matrices └── prompts/ # persona prompt fragments ``` Paths inside the payload are identical across language ecosystems — a persona at `personas/prod/focus.coach.v1.json` lives at the same relative path whether you consume the spec from Dart, Swift, Kotlin, or a backend service. Files released under `personas/prod/`, `schemas/`, and `grammars/` are **immutable once a version ships** — behavior changes require a new persona / schema version and a new spec release. ## Personas in the current spec | Id | Purpose | Capability tier | | - | - | - | | `focus.coach.v1` | Proposes one tiny next action when the user is stuck; summarizes recent session state on request | standard | | `stress.coach.v1` | Validates feelings; offers gentle regulation steps when the user is overwhelmed | standard | | `cognitive.companion.v1` | Adapts cognitive load to capacity and recovery signals | standard | | `performance.coach.v1` | Schedules peak windows; prioritizes recovery when scores are low | standard | | `wellness.guide.v1` | Favors rest under high stress / low recovery; nudges light movement when sedentary | standard | Every persona produces output conforming to the `coach.response.v1` JSON Schema, with `global.no_harmful_content` and `global.no_medical_diagnosis` applied as safety constraints. The `capability_tier` column is the persona's preferred cloud-model lane (`fast` / `standard` / `deep`). The Syni Cloud Gateway uses it to pick a route when the caller hasn't pinned a model — each tier maps to a different model on the backend, with its own latency and per-day token budget. Empty / unknown tiers resolve to `standard`, so personas without the field stay on the default lane. Synheart ships additional app-specific personas (tuned to particular Synheart products) that aren't part of the general persona catalog above. They follow the same spec contract — including `capability_tier`, safety rules, output schema — but their system prompts and rules are coupled to a single Synheart app's surface, so they aren't useful as generic building blocks for tenant apps. Tenants creating their own personas should model after the general personas in the table above. ## Distribution Releases are published to `dist.synheart.ai/syni-spec/vX.Y.Z/` with: * `spec.tar.gz` — the canonical payload (the tree above, packed) * `checksums.json` — SHA-256 per file in the payload * `manifest.json` — release metadata * `SHA256SUMS` — top-level archive checksum Same publishing pipeline used for the Synheart Runtime and the Syni Runtime. See [Install](/syni-spec/install) for how to consume the spec from each language ecosystem. # Syni — Flutter SDK Source: https://docs.synheart.ai/syni/flutter Adaptive on-device LLM inference with hybrid local/cloud chat, persona conditioning, and a streaming API designed for the UI thread. ## Overview The Syni Flutter SDK (`package:syni`) is the Dart/Flutter consumer of the [Syni runtime](/syni/runtime-ffi). It wraps the C FFI in a Dart agent API: install lifecycle, persona binding, streaming chat, and hybrid local/cloud routing. **Key features** * **On-device inference** — Qwen 2 / 2.5 and Gemma 3 GGUF models out of the box; bring your own GGUF for other supported architectures. * **Hybrid local / cloud** — same agent API, choose execution mode per call (`localFirst`, `cloudFirst`, `localOnly`, `cloudOnly`). * **Versioned personas** — load by id from bundled [`syni-spec`](/syni-spec/overview); the same id resolves to the same behavior on client and server. * **Worker isolate** so engine load + token generation don't block the UI thread. * **Verified model downloads** — pinned SHA-256 per model, checked at install time. * **Streaming chat** with token-level deltas plus a final structured response. ## Platform support | Android | iOS | macOS | Linux | Windows | Web | | :-: | :-: | :-: | :-: | :-: | :-: | | ✅ | ✅ | 🚧 | 🚧 | 🚧 | ❌ | Android + iOS are the supported targets today. Desktop targets are in the works. Web is out of scope. ## Installation ### 1. Pull the native runtime artifacts The Flutter plugin doesn't ship the native engine — that's [Syni Runtime](/syni/runtime-ffi), distributed separately via the Synheart CLI: ```bash theme={null} synheart install syni # runtime + spec (entitled subset) ``` This lands `SyniRuntime.xcframework/`, `android/jniLibs//libsyni_ffi.so`, and the spec payload under your app's `synheart/vendor/` tree. The plugin's `build.gradle` / `Podspec` resolve these paths automatically. Re-run any time you want a fresher version — installs are idempotent. ### 2. Add the Dart package ```bash theme={null} flutter pub add syni ``` ```yaml theme={null} # pubspec.yaml dependencies: syni: ^0.1.0 ``` ## Basic usage ```dart theme={null} import 'package:flutter/material.dart'; import 'package:syni/agent.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); final agent = SyniAgent(); // Load a persona by id from the bundled spec assets. final persona = await SyniSpecPersona.load('focus.coach.v1'); // First-run install: download + verify the model, load the engine, // bind the persona. Emits lifecycle events on agent.installState. await agent.install( persona: persona, model: SyniModels.qwen25_15bInstructQ4, ); // Single-turn chat. final response = await agent.chat('How can I focus right now?'); debugPrint(response.displayText); } ``` ## Streaming ```dart theme={null} agent.chatStream('hello').listen((event) { switch (event) { case SyniChatDelta(:final delta): stdout.write(delta); case SyniChatFinal(:final response): print('\n[${response.displayText.length} chars]'); } }); ``` ## Hybrid local / cloud ```dart theme={null} final agent = SyniAgent( cloudConfig: SyniCloudConfig( baseUrl: 'https://api.synheart.ai', authToken: () async => '', tenantId: '', userId: '', ), ); await agent.chat( 'how was my recent session?', mode: SyniExecutionMode.cloudFirst, // try cloud, fall back to local ); ``` Execution policy can be set per call (`SyniExecutionMode.{localFirst, cloudFirst, localOnly, cloudOnly}`) or pinned by the persona via its `execution_policy` field in the spec. ## Where this fits `package:syni` is the **agent layer** — inference, install lifecycle, persona binding, chat orchestration. It does not own: * HSI signal collection (the [`synheart_core`](/synheart-core/flutter) SDK does), or * the four-authority gate (consent + capability + activation + session; also a host concern). Synheart-ecosystem apps typically depend on both `synheart_core` and `syni`, and use `Synheart.syni` (in `synheart_core`) which wraps the agent with those layers. Standalone use of `package:syni` is fully supported when you don't need the wider Synheart contract. ## Models Two pre-pinned entries ship in `SyniModels`: * `qwen25_15bInstructQ4` (Qwen 2.5 1.5B Instruct Q4\_K\_M, \~1.1 GB) * `gemma3_1bInstructQ4` (Gemma 3 1B Instruct Q4\_K\_M, \~770 MB, Synheart-hosted mirror) Both ship with pinned SHA-256 verified at install time. Bring your own GGUF for other supported architectures via `SyniModelSpec`. ## API reference The full Dart API is on [pub.dev](https://pub.dev/documentation/syni/latest/). Surface highlights: * `SyniAgent` — install lifecycle, model catalog, persona binding, `chat` / `chatStream` orchestration, hybrid local/cloud routing. * `SyniInstaller` — model download, tokenizer fetch, SHA-256 verification, cold-start restore. * `SyniCloudClient` — HTTP + SSE client for the Syni cloud chat endpoint; sticky session id; HSI forwarded as request `context`. * `SyniSpecPersona.load(id)` — resolves persona JSON from bundled spec assets so the same id consistently produces the same behavior on client and server. * `SyniRuntime` — worker-isolate wrapper over the on-device inference engine. ## Related * [Syni overview](/syni/overview) — how the pieces fit * [Syni Runtime FFI](/syni/runtime-ffi) — the C ABI under the hood * [Syni Spec](/syni-spec/overview) — persona / safety / schema contracts * Package on pub.dev: [`syni`](https://pub.dev/packages/syni) # Kotlin Source: https://docs.synheart.ai/syni/kotlin syni-kotlin — Android SDK for Syni's adaptive on-device LLM inference with hybrid local/cloud chat. ## Overview `syni-kotlin` is the **Android consumer SDK** for Syni. Same agent surface as the [Flutter sibling](/syni/flutter) and the [Swift sibling](/syni/swift), idiomatic for Kotlin (`suspend` calls, `Flow` streaming, `StateFlow` for the install lifecycle). ## Platform support * Android 8.0+ (`minSdk 26`) * Kotlin 2.0+ · Java 17 toolchain · AGP 9.0+ * Native runtime delivered by the `synheart` CLI for `arm64-v8a`, `armeabi-v7a`, `x86_64`, `x86` (see install steps below) ## Installation ```kotlin theme={null} // build.gradle.kts dependencies { implementation("ai.synheart:syni:0.0.3") } ``` ### Native runtime The AAR ships Kotlin sources only. Install the native runtime once into your project with the `synheart` CLI: ```bash theme={null} curl -fsSL https://synheart.sh/install | bash synheart install runtime syni ``` This writes `libsyni_ffi.so` for every Android ABI under `/synheart/vendor/syni/android/jniLibs/`. Wire the vendor path into your **app** module's `build.gradle.kts` so JNA can find the library at runtime: ```kotlin theme={null} // app/build.gradle.kts android { sourceSets { getByName("main").jniLibs.srcDirs( file("${rootProject.projectDir}/synheart/vendor/syni/android/jniLibs"), ) } } ``` The SDK uses JNA (`Native.load`) to resolve `libsyni_ffi` at runtime, so the AAR compiles standalone — calls into the runtime fail with a clear error if the install step hasn't been run. ## Basic usage ```kotlin theme={null} import ai.synheart.syni.SyniAgent import ai.synheart.syni.SyniModels import ai.synheart.syni.SyniSpecPersona val agent = SyniAgent(context = application) // Load a persona by id from bundled spec assets. val persona = SyniSpecPersona.load(context, "focus.coach.v1") // First-run install: download + verify the model, load the engine, // bind the persona. Emits lifecycle events on agent.installState. agent.install( persona = persona, model = SyniModels.qwen25_15bInstructQ4, ) // Single-turn chat. val response = agent.chat("How can I focus right now?") println(response.displayText) ``` ## Streaming `chatStream` returns a `Flow` — token-level `Delta` events followed by exactly one `Final` carrying the structured response. ```kotlin theme={null} agent.chatStream("hello").collect { event -> when (event) { is SyniChatEvent.Delta -> print(event.delta) is SyniChatEvent.Final -> println("\n[${event.response.displayText.length} chars]") } } ``` ## Hybrid local / cloud ```kotlin theme={null} val agent = SyniAgent( context = application, cloudConfig = SyniCloudConfig( baseUrl = "https://api.synheart.ai", authToken = { "" }, tenantId = "", userId = "", ), ) agent.chat( message = "how was my recent session?", mode = SyniExecutionMode.CLOUD_FIRST, // try cloud, fall back to local ) ``` `SyniExecutionMode` values: `LOCAL_FIRST` (default), `CLOUD_FIRST`, `LOCAL_ONLY`, `CLOUD_ONLY`. ## Install lifecycle Wire `installState` into your UI to surface progress: ```kotlin theme={null} agent.installState.collect { state -> when (state) { SyniInstallState.NotInstalled -> showInstallPrompt() is SyniInstallState.Installing -> showProgress(state.stage, state.progress) is SyniInstallState.Installed -> showReady() is SyniInstallState.Failed -> showError(state.reason) } } ``` Stages: `DOWNLOADING_MODEL` → `VERIFYING_MODEL` → `LOADING_ENGINE` → `BINDING_PERSONA`. ## Where this fits `syni-kotlin` is the **agent layer** — inference, install lifecycle, persona binding, chat orchestration. It does NOT own: * HSI signal collection (the [synheart-core](/synheart-core/kotlin) SDK does), or * the four-authority gate (consent + capability + activation + session; also a host concern). Synheart-ecosystem apps typically depend on `synheart-core` and use `SyniModule`, which wraps this SDK with those layers. Standalone use of `syni-kotlin` is fully supported when you don't need the wider Synheart contract. ## Models Out-of-the-box GGUF models exposed under `SyniModels`: * `qwen25_15bInstructQ4` (default, \~1.5 GB) * `qwen2_05bInstructQ4` (\~500 MB) * `gemma3_1bInstructQ4` Pinned SHA-256 per model; verified at install time. Bring your own GGUF via a custom `SyniModelSpec`. ## API reference | Surface | Notes | | - | - | | `SyniAgent` | Constructed with `context` + optional `installer` / `cloudConfig`. Exposes `installState` / `currentState` / `isInstalled` / `hasCloud`. | | `SyniAgent.install / restoreInstallIfReady / uninstall / dispose` | `suspend`; emit install-state transitions. | | `SyniAgent.chat / chatStream` | `suspend` / `Flow`. | | `SyniInstallState` | Sealed class: `NotInstalled`, `Installing(stage, progress)`, `Installed(...)`, `Failed(reason, cause?)`. | | `SyniChatResponse` | `displayText`, `message`, `suggestions`, `kind` (`chat` / `coach` / `suggestions` / `unknown`). | | `SyniSpecPersona` | `load(context, personaId)` — bundled persona JSON. | | `SyniModelCatalog` | List local + cloud model options; bundled defaults under `SyniModelCatalog.bundled`. | | `SyniCloudConfig` | `baseUrl`, `authToken: () -> String?`, `tenantId`, `userId`. | | `SyniExecutionMode` | `LOCAL_FIRST`, `CLOUD_FIRST`, `LOCAL_ONLY`, `CLOUD_ONLY`. | ## Related * [Syni overview](/syni/overview) * [Syni spec](/syni-spec/overview) * [synheart-core/kotlin](/synheart-core/kotlin) — host SDK with `SyniModule` consent gate # Overview Source: https://docs.synheart.ai/syni/overview Adaptive on-device LLM inference for Synheart apps — what Syni is and how the pieces fit together. **Syni** is Synheart's on-device LLM stack. It runs adaptive, persona-conditioned language model inference locally on the user's device, with an optional cloud fallback for higher-capability requests. Syni is composed of four artifacts, each released independently and pinned by the consumer at install time: | Piece | What it is | Released as | | - | - | - | | [Syni Flutter SDK](/syni/flutter) | Dart/Flutter consumer SDK — agent, install lifecycle, persona binding, streaming chat | `package:syni` on pub.dev | | [Syni Runtime](/syni/runtime-ffi) | Native inference engine with a stable C ABI (FFI). The native artifact every SDK calls. | `dist.synheart.ai/syni-runtime/` | | [Syni Spec](/syni-spec/overview) | Canonical persona / safety / schema / grammar contracts | `dist.synheart.ai/syni-spec/` | | Syni Cloud Gateway | HTTP + SSE chat endpoint for cloud-fallback inference, persona-aware | `api.synheart.ai` | The same persona id resolves to the same behavior whether served by the local runtime or the cloud gateway. That's the entire point of the spec — it pins behavior independently of model choice. ## What "adaptive" means Syni adapts its output to the user's current physiological and behavioral state. The runtime's `PromptBuilder` reads an opaque conditioning map passed in via the `hsi:` parameter on every request, and shapes the prompt — system context, persona modulation, and decoded structured fields — based on what's in it. Synheart-stack apps populate that map with [HSI](/hsi/overview), Synheart's unified Human State Interface derived from biosignal SDKs (wear, behavior, session) via [`synheart_core`](/synheart-core/overview). Non-Synheart apps can pass any `Map` — an ad-hoc context dict, a stress score from another source, or `null` for unconditioned inference — and the same persona will resolve to a coherent response. In short: Syni is the LLM substrate; HSI is the differentiator that makes it adapt rather than just respond. ## Install The Synheart CLI handles the runtime + spec on disk: ```bash theme={null} synheart install syni # both runtime + spec (entitled subset) synheart install runtime syni # just the LLM engine synheart install spec # just the persona contracts ``` Lands artifacts under `synheart/vendor/syni-runtime/` and `synheart/vendor/syni-spec/`. The verb shape is product + component: product nouns (`syni`, `core`) install every component you're entitled to; component nouns (`runtime`, `spec`) fan out across products; two-arg forms pin to one canonical package. The Flutter SDK is added separately via `pub`: ```bash theme={null} flutter pub add syni ``` It uses the runtime artifacts that the CLI dropped into your app's `synheart/vendor/syni-runtime/` tree. ## Why Syni is split this way * **Runtime ≠ SDK.** The native runtime + C ABI is the slow-changing artifact. SDKs in three languages (Dart, Swift, Kotlin) layer over the same ABI. * **Spec ≠ code.** Persona behavior, safety rails, output schemas, and grammars are versioned contracts that can ship independently of any inference change. Same spec id → same behavior on local + cloud. * **Cloud is opt-in.** Every persona declares an `execution_policy` (`local` / `cloud` / `hybrid`). Apps can run fully offline, or fall back to cloud per call. ## Persona model Personas are JSON contracts in [`syni-spec`](/syni-spec/overview). Each one declares: * a stable id (e.g. `focus.coach.v1`) * `output_schema_id` — the JSON Schema the response must satisfy * `safety_rule_ids` — global policies that constrain output * `execution_policy` — local / cloud / hybrid * `capability_tier` *(optional)* — preferred cloud-model lane: `fast` / `standard` / `deep`. The cloud gateway uses it to pick a route when the caller hasn't pinned a model. Omit (or set `standard`) for the default lane; pick `fast` for conversational personas that don't need deep reasoning; pick `deep` for long-range analytical personas that do. Unknown values fall back to the default lane. * `privacy` — what data may leave the device * `budget` — token / request limits Production-tier personas in the current spec: * `focus.coach.v1` * `stress.coach.v1` * `cognitive.companion.v1` * `performance.coach.v1` * `wellness.guide.v1` Apps load them by id. Out-of-spec ids fail closed. ## Related * [Syni Flutter SDK](/syni/flutter) — getting started in a Flutter app * [Syni Runtime FFI](/syni/runtime-ffi) — the C ABI for SDK authors * [Syni Spec](/syni-spec/overview) — persona / safety / schema contracts * [Install via CLI](/syni-spec/install) — `synheart install syni` # Syni — Runtime FFI Source: https://docs.synheart.ai/syni/runtime-ffi The stable C ABI for the on-device LLM engine consumed by the Syni SDKs (Flutter, Swift, Kotlin). ## When you'd care Most application developers consume Syni through a language SDK — the [Flutter SDK](/syni/flutter), and (later) Swift / Kotlin equivalents — and never see the C ABI. This page is for the people who do: * **SDK authors** adding a new language binding over the same engine. * **Native integrators** plugging the runtime into a non-Flutter / non-mobile surface (a CLI tool, a server worker, a desktop app). * **Debuggers** chasing symbol-level issues across the FFI boundary. ## ABI rules * The C ABI is the stable boundary. Runtime internals are not. * Symbols, struct shapes, error codes, and lifetimes documented here are the contract — they MUST NOT change without a major version bump on the runtime package. * Every handle has a `_destroy` counterpart. Leaks are the caller's fault. * All strings are UTF-8, NUL-terminated, owned by the caller of the API unless explicitly documented otherwise. ## Install Runtime artifacts are distributed via `dist.synheart.ai` and installed by the Synheart CLI: ```bash theme={null} synheart install runtime syni # just the runtime synheart install syni # runtime + spec (entitled subset) synheart install runtime syni --version v0.1.0 # pin a version ``` The CLI drops a vendor-ready tree under your project: ```text theme={null} synheart/vendor/syni-runtime/ ├── android/ │ └── jniLibs/ │ ├── arm64-v8a/libsyni_ffi.so │ ├── armeabi-v7a/libsyni_ffi.so │ └── x86_64/libsyni_ffi.so ├── SyniRuntime.xcframework/ # iOS device + sim slices ├── device/libsyni_ffi.a # iOS device archive ├── sim/libsyni_ffi.a # iOS sim lipo'd archive └── headers/ └── syni_ffi.h # the canonical C header ``` The same artifact layout is the source of truth for all language bindings. ## 1. Handle and lifecycle The engine is opaque — callers hold a single `SyniRuntimeHandle*` for the lifetime of a load. ```c theme={null} SyniRuntimeHandle* syni_runtime_create(const SyniRuntimeConfig* config); SyniStatus syni_runtime_load(SyniRuntimeHandle* h); void syni_runtime_destroy(SyniRuntimeHandle* h); ``` Lifecycle: ```text theme={null} create → load → (generate*) → destroy ``` * `create` validates config and allocates resources but does **not** mmap the model file. * `load` mmaps the model, materialises tokenizer + grammar, and is the expensive call (\~hundreds of ms cold). * `destroy` is safe to call at any state. Subsequent calls on the handle are undefined. ## 2. Configuration ```c theme={null} typedef struct { const char* model_path; // absolute path to .gguf const char* tokenizer_path; // absolute path to tokenizer.json SyniBackend backend; // CANDLE | LLAMA uint32_t n_ctx; // context window uint32_t n_threads; // 0 = auto bool metal; // enable Metal on Apple platforms bool cuda; // enable CUDA where available } SyniRuntimeConfig; ``` Per-platform notes: * **Apple**: set `metal = true` for GPU acceleration. Falls back to CPU automatically if Metal is unavailable. * **Android**: CPU only — the `metal` and `cuda` flags are ignored. * **Backend**: `CANDLE` is the default — it's what the published artifacts on `dist.synheart.ai` ship with. `LLAMA` requires a runtime variant built with the llama.cpp backend enabled, which is not part of the default published artifacts today. ## 3. Generation Generation is request/response, optionally streamed via a callback. ```c theme={null} typedef struct { const char* prompt; // ready-made prompt const char* grammar_gbnf; // optional GBNF for structured JSON uint32_t max_tokens; float temperature; float top_p; int32_t seed; // -1 = random } SyniGenerateRequest; typedef int (*SyniTokenCallback)(const char* token, void* user_data); SyniStatus syni_generate( SyniRuntimeHandle* h, const SyniGenerateRequest* req, SyniTokenCallback on_token, // NULL = no streaming void* user_data, char** out_full, // owned by callee; free with syni_string_free uint32_t* out_full_len ); void syni_string_free(char* s); ``` The streaming callback returns `0` to continue, non-zero to cancel. On cancel, `syni_generate` returns `SYNI_STATUS_CANCELLED` and `out_full` contains the partial response so far. ## 4. Grammar-constrained decoding When `grammar_gbnf` is non-NULL, the runtime constrains decoding to outputs valid against the GBNF. Bind grammars to schemas via the [Syni Spec registry](/syni-spec/overview): ```c theme={null} const char* gbnf = read_file_to_string("synheart/vendor/syni-spec/grammars/coach.response.v1.gbnf"); SyniGenerateRequest req = { .prompt = "…", .grammar_gbnf = gbnf, .max_tokens = 512, .temperature = 0.7, }; ``` GBNF parse failures surface as `SYNI_STATUS_INVALID_GRAMMAR` at request time, not at generation time. ## 5. Status codes ```c theme={null} typedef enum { SYNI_STATUS_OK = 0, SYNI_STATUS_INVALID_CONFIG = 1, SYNI_STATUS_MODEL_NOT_FOUND = 2, SYNI_STATUS_LOAD_FAILED = 3, SYNI_STATUS_INVALID_GRAMMAR = 4, SYNI_STATUS_OOM = 5, SYNI_STATUS_CANCELLED = 6, SYNI_STATUS_INTERNAL = 7, } SyniStatus; ``` Status semantics: * `OK` — success. * `INVALID_CONFIG` / `MODEL_NOT_FOUND` — caller bug; surface verbatim. * `LOAD_FAILED` — likely corrupted model file or unsupported architecture. * `INVALID_GRAMMAR` — GBNF didn't parse against the schema. * `OOM` — model too large for device; suggest a smaller variant. * `CANCELLED` — caller-initiated; not an error. * `INTERNAL` — bug in the runtime; capture logs and file an issue. ## 6. Memory management * Every `*_create` has a matching `*_destroy`. Caller owns the handle. * Returned C strings (`out_full`) are heap-allocated by the runtime and must be freed with `syni_string_free`. * The runtime is **thread-safe per handle**: concurrent calls on the same `SyniRuntimeHandle` are serialised internally; concurrent calls on different handles run in parallel. ## 7. Backends | Backend | Default in published artifacts | | - | - | | Candle | ✅ | | llama.cpp | ❌ | Only the Candle backend is published to `dist.synheart.ai` today. The llama.cpp backend exists in the runtime but is not part of the default published variant; treat it as a future option rather than something you can opt into from the released artifacts. ## Symbols this page does not document This page covers the **stable** surface only. The runtime exports a number of internal symbols (`_dbg_*`, `_unstable_*`) for diagnostics — these **may change without notice** between patch releases. ## Related * [Syni overview](/syni/overview) — how the runtime fits with the Flutter SDK and the spec * [Syni Flutter SDK](/syni/flutter) — the Dart wrapper over this ABI * [Syni Spec](/syni-spec/overview) — persona / grammar / safety contracts the runtime consumes * C header: `synheart/vendor/syni-runtime/headers/syni_ffi.h` after install # Swift Source: https://docs.synheart.ai/syni/swift syni-swift — iOS / macOS SDK for Syni's adaptive on-device LLM inference with hybrid local/cloud chat. ## Overview `syni-swift` is the **iOS / macOS consumer SDK** for Syni. Same agent surface as the [Flutter sibling](/syni/flutter) and the [Kotlin sibling](/syni/kotlin), idiomatic for Swift (`async`/`await`, `AsyncThrowingStream` for streaming, Combine `AnyPublisher` for the install lifecycle). ## Platform support * iOS 16.0+ · macOS 13.0+ * Swift 5.9+ · Xcode 15+ * Native runtime delivered by the `synheart` CLI as `SyniRuntime.xcframework` (see install steps below) ## Installation ### Swift Package Manager ```swift theme={null} // Package.swift dependencies: [ .package(url: "https://github.com/synheart-ai/syni-swift.git", from: "0.0.4"), ], targets: [ .target( name: "YourApp", dependencies: [ .product(name: "Syni", package: "syni-swift"), ] ), ] ``` ### CocoaPods ```ruby theme={null} # Podfile pod 'Syni', '~> 0.0.4' ``` ### Native runtime Both install paths ship Swift sources only. Install the native runtime once with the `synheart` CLI: ```bash theme={null} curl -fsSL https://synheart.sh/install | bash synheart install runtime syni ``` This writes `SyniRuntime.xcframework` to `/synheart/vendor/syni-runtime/`. Add the framework to your Xcode target under **General → Frameworks, Libraries, and Embedded Content**. The Swift package resolves all C symbols at runtime via `dlsym(RTLD_DEFAULT)`, so the package compiles standalone — calls into the runtime fail with a clear error if the install step hasn't been run. ## Basic usage ```swift theme={null} import Syni let agent = SyniAgent() // Load a persona by id from bundled spec assets. let persona = try await SyniSpecPersona.load("focus.coach.v1") // First-run install: download + verify the model, load the engine, // bind the persona. Emits lifecycle events on agent.installState. try await agent.install( persona: persona, model: SyniModels.qwen25_15bInstructQ4 ) // Single-turn chat. let response = try await agent.chat("How can I focus right now?") print(response.displayText) ``` ## Streaming `chatStream` returns an `AsyncThrowingStream` — token-level `.delta` events followed by exactly one `.final` carrying the structured response. ```swift theme={null} for try await event in agent.chatStream("hello") { switch event { case let .delta(text): print(text, terminator: "") case let .final(response): print("\n[\(response.displayText.count) chars]") } } ``` ## Hybrid local / cloud ```swift theme={null} let agent = SyniAgent( cloudConfig: SyniCloudConfig( baseUrl: "https://api.synheart.ai", authToken: { "" }, tenantId: "", userId: "" ) ) let response = try await agent.chat( "how was my recent session?", mode: .cloudFirst // try cloud, fall back to local ) ``` `SyniExecutionMode` cases: `.localFirst` (default), `.cloudFirst`, `.localOnly`, `.cloudOnly`. ## Install lifecycle Wire `installState` into SwiftUI to surface progress: ```swift theme={null} @Observable final class InstallVM { var state: SyniInstallState = .notInstalled private var cancellable: AnyCancellable? func observe(_ agent: SyniAgent) { cancellable = agent.installState.sink { [weak self] in self?.state = $0 } } } // In your view switch vm.state { case .notInstalled: Button("Install model") { /* trigger install */ } case let .installing(stage, p): ProgressView("\(stage)", value: p) case .installed: ChatView() case let .failed(reason, _): Text("Install failed: \(reason)") } ``` Stages: `.downloadingModel` → `.verifyingModel` → `.loadingEngine` → `.bindingPersona`. ## Where this fits `syni-swift` is the **agent layer** — inference, install lifecycle, persona binding, chat orchestration. It does NOT own: * HSI signal collection (the [synheart-core](/synheart-core/swift) SDK does), or * the four-authority gate (consent + capability + activation + session; also a host concern). Synheart-ecosystem apps typically depend on `SynheartCore` and use `SyniModule`, which wraps this SDK with those layers. Standalone use of `Syni` is fully supported when you don't need the wider Synheart contract. ## Models Out-of-the-box GGUF models exposed under `SyniModels`: * `qwen25_15bInstructQ4` (default, \~1.5 GB) * `qwen2_05bInstructQ4` (\~500 MB) * `gemma3_1bInstructQ4` Pinned SHA-256 per model; verified at install time. Bring your own GGUF via a custom `SyniModelSpec`. Swift also supports Apple Foundation Models as an execution target where available (`.appleFoundationModels` in `RoutingPolicy.preferredEngines`). ## API reference | Surface | Notes | | - | - | | `SyniAgent` | Constructed with optional `installer` / `cloudConfig`. Exposes `installState` / `currentState` / `isInstalled` / `hasCloud`. | | `SyniAgent.install / restoreInstallIfReady / uninstall / dispose` | `async` / `throws`; emit install-state transitions. | | `SyniAgent.chat / chatStream` | `async throws` / `AsyncThrowingStream`. | | `SyniInstallState` | Enum: `.notInstalled`, `.installing(stage:progress:)`, `.installed(...)`, `.failed(reason:cause:)`. | | `SyniChatResponse` | `displayText`, `message`, `suggestions`, `kind` (`.chat` / `.coach` / `.suggestions` / `.unknown`). | | `SyniSpecPersona` | `load(id)` — bundled persona JSON. | | `SyniModelCatalog` | List local + cloud model options; bundled defaults under `SyniModelCatalog.bundled`. | | `SyniCloudConfig` | `baseUrl`, `authToken: () -> String?`, `tenantId`, `userId`. | | `SyniExecutionMode` | `.localFirst`, `.cloudFirst`, `.localOnly`, `.cloudOnly`. | ## Related * [Syni overview](/syni/overview) * [Syni spec](/syni-spec/overview) * [synheart-core/swift](/synheart-core/swift) — host SDK with `SyniModule` consent gate