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

# 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.

***

## 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<String, String>` 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<WearData> 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 = await 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 unit tests, set `allowUnsignedCapabilities: true` in `SynheartConfig`. This bypasses signature verification on the capability token so you can hand-roll a token with the tier you want to test:

```dart theme={null}
await Synheart.initialize(
  userId: 'test_user',
  config: SynheartConfig(
    allowUnsignedCapabilities: true,
    capabilityToken: testTokenJson, // unsigned token with desired tier
  ),
);
```

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}
   // Before (Core)
   print(hsi.affect.arousalIndex);

   // After (Extended)
   print(hsi.affect.arousalIndex);
   print(hsi.affect.valenceStability);  // Now available
   print(hsi.embedding.vector);         // Full 64D now available
   ```
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
