> For the complete documentation index, see [llms.txt](https://docs.algenta.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.algenta.ai/http-api/explorer.md).

# API explorer (live)

Every endpoint below renders live from the Algenta OpenAPI specification. Expand an operation to see parameters, request and response schemas, and example payloads, then use **Test it** to call the API directly from this page with your own key.

{% hint style="info" %}
Generated from the canonical OpenAPI spec, so it always matches the deployed engine. Set your base URL (your self-hosted deployment or `https://api.algenta.ai`) and API key in the **Test it** panel. For a flat index see the [endpoint reference](/http-api/reference.md); for prose, the [API overview](/http-api/overview.md).
{% endhint %}

## Account

### `GET /v1/me`

## GET /v1/me

> Get current user and org info

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"MeResponse":{"properties":{"user":{"$ref":"#/components/schemas/UserInfo"},"org":{"$ref":"#/components/schemas/OrgInfo"}},"type":"object","required":["user","org"],"title":"MeResponse"},"UserInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"email":{"type":"string","title":"Email"},"name":{"type":"string","title":"Name"},"role":{"type":"string","title":"Role"},"email_verified":{"type":"boolean","title":"Email Verified"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","email","name","role","email_verified","created_at"],"title":"UserInfo"},"OrgInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"plan":{"type":"string","title":"Plan"},"status":{"type":"string","title":"Status"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","slug","plan","status","created_at"],"title":"OrgInfo"}}},"paths":{"/v1/me":{"get":{"tags":["Account"],"summary":"Get current user and org info","operationId":"me_v1_me_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeResponse"}}}}}}}}}
```

### `PATCH /v1/me`

## PATCH /v1/me

> Update current user and/or org name

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"UpdateMeRequest":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":255,"minLength":1},{"type":"null"}],"title":"Name"},"org_name":{"anyOf":[{"type":"string","maxLength":255,"minLength":1},{"type":"null"}],"title":"Org Name"}},"type":"object","title":"UpdateMeRequest"},"MeResponse":{"properties":{"user":{"$ref":"#/components/schemas/UserInfo"},"org":{"$ref":"#/components/schemas/OrgInfo"}},"type":"object","required":["user","org"],"title":"MeResponse"},"UserInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"email":{"type":"string","title":"Email"},"name":{"type":"string","title":"Name"},"role":{"type":"string","title":"Role"},"email_verified":{"type":"boolean","title":"Email Verified"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","email","name","role","email_verified","created_at"],"title":"UserInfo"},"OrgInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"plan":{"type":"string","title":"Plan"},"status":{"type":"string","title":"Status"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","slug","plan","status","created_at"],"title":"OrgInfo"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/me":{"patch":{"tags":["Account"],"summary":"Update current user and/or org name","operationId":"update_me_v1_me_patch","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateMeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/usage`

## GET /v1/usage

> Get usage summary for current billing period

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"UsageResponse":{"properties":{"org_id":{"type":"string","format":"uuid","title":"Org Id"},"billing_period":{"type":"string","title":"Billing Period"},"simulations_run":{"type":"integer","title":"Simulations Run"},"api_calls":{"type":"integer","title":"Api Calls"},"quota_limit":{"type":"integer","title":"Quota Limit"},"quota_used_pct":{"type":"number","title":"Quota Used Pct"}},"type":"object","required":["org_id","billing_period","simulations_run","api_calls","quota_limit","quota_used_pct"],"title":"UsageResponse"}}},"paths":{"/v1/usage":{"get":{"tags":["Account"],"summary":"Get usage summary for current billing period","operationId":"usage_v1_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UsageResponse"}}}}}}}}}
```

### `GET /v1/limits`

## GET /v1/limits

> Get rate limits and quotas for current plan

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"LimitsResponse":{"properties":{"plan":{"type":"string","title":"Plan"},"max_simulations_per_month":{"type":"integer","title":"Max Simulations Per Month"},"max_runs_per_simulation":{"type":"integer","title":"Max Runs Per Simulation"},"max_batch_items":{"type":"integer","title":"Max Batch Items"},"rate_limit_per_minute":{"type":"integer","title":"Rate Limit Per Minute"},"async_jobs_enabled":{"type":"boolean","title":"Async Jobs Enabled"},"webhooks_enabled":{"type":"boolean","title":"Webhooks Enabled"}},"type":"object","required":["plan","max_simulations_per_month","max_runs_per_simulation","max_batch_items","rate_limit_per_minute","async_jobs_enabled","webhooks_enabled"],"title":"LimitsResponse"}}},"paths":{"/v1/limits":{"get":{"tags":["Account"],"summary":"Get rate limits and quotas for current plan","operationId":"limits_v1_limits_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LimitsResponse"}}}}}}}}}
```

### `GET /v1/distributions`

## GET /v1/distributions

> List supported distribution types

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DistributionInfo":{"properties":{"name":{"type":"string","title":"Name"},"description":{"type":"string","title":"Description"},"required_params":{"items":{"type":"string"},"type":"array","title":"Required Params"},"optional_params":{"items":{"type":"string"},"type":"array","title":"Optional Params"}},"type":"object","required":["name","description","required_params","optional_params","example"],"title":"DistributionInfo"},"DistributionListResponse":{"properties":{"distributions":{"items":{"$ref":"#/components/schemas/DistributionInfo"},"type":"array","title":"Distributions"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["distributions","total","page","limit","pages"],"title":"DistributionListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/distributions":{"get":{"tags":["Account"],"summary":"List supported distribution types","operationId":"distributions_v1_distributions_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}],"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/DistributionInfo"}},{"$ref":"#/components/schemas/DistributionListResponse"}],"title":"Response Distributions V1 Distributions Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/templates`

## GET /v1/templates

> List built-in simulation templates

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"TemplateInfo":{"properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"description":{"type":"string","title":"Description"},"category":{"type":"string","title":"Category"},"example_request":{"type":"object","title":"Example Request"}},"type":"object","required":["id","name","description","category","example_request"],"title":"TemplateInfo"},"TemplateListResponse":{"properties":{"templates":{"items":{"$ref":"#/components/schemas/TemplateInfo"},"type":"array","title":"Templates"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["templates","total","page","limit","pages"],"title":"TemplateListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/templates":{"get":{"tags":["Account"],"summary":"List built-in simulation templates","operationId":"templates_v1_templates_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}],"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/TemplateInfo"}},{"$ref":"#/components/schemas/TemplateListResponse"}],"title":"Response Templates V1 Templates Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/api-keys`

## GET /v1/api-keys

> List active API keys

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"APIKeyInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"label":{"type":"string","title":"Label"},"key_prefix":{"type":"string","title":"Key Prefix"},"device_limit":{"type":"integer","minimum":0,"title":"Device Limit","description":"Max registered devices for this key on the local runtime path. 0 preserves the plan's unlimited or no-local-runtime behavior."},"status":{"type":"string","title":"Status"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"last_used_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Used At"},"expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Expires At"}},"type":"object","required":["id","label","key_prefix","device_limit","status","created_at"],"title":"APIKeyInfo","description":"API key info shown in list (never includes hash or raw key)."},"APIKeyListResponse":{"properties":{"api_keys":{"items":{"$ref":"#/components/schemas/APIKeyInfo"},"type":"array","title":"Api Keys"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["api_keys","total","page","limit","pages"],"title":"APIKeyListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/api-keys":{"get":{"tags":["Account"],"summary":"List active API keys","operationId":"list_api_keys_v1_api_keys_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}],"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/APIKeyInfo"}},{"$ref":"#/components/schemas/APIKeyListResponse"}],"title":"Response List Api Keys V1 Api Keys Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/api-keys`

## POST /v1/api-keys

> Create a new API key

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"CreateAPIKeyRequest":{"properties":{"label":{"type":"string","maxLength":255,"minLength":1,"title":"Label"},"expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Expires At"},"device_limit":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Device Limit"}},"type":"object","required":["label"],"title":"CreateAPIKeyRequest"},"APIKeyCreated":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"label":{"type":"string","title":"Label"},"key_prefix":{"type":"string","title":"Key Prefix"},"device_limit":{"type":"integer","minimum":0,"title":"Device Limit","description":"Max registered devices for this key on the local runtime path. 0 preserves the plan's unlimited or no-local-runtime behavior."},"raw_key":{"type":"string","title":"Raw Key","description":"The full API key — shown ONCE, store it securely."},"created_at":{"type":"string","format":"date-time","title":"Created At"},"expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Expires At"}},"type":"object","required":["id","label","key_prefix","device_limit","raw_key","created_at"],"title":"APIKeyCreated","description":"Returned once at key creation — raw key shown here only."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/api-keys":{"post":{"tags":["Account"],"summary":"Create a new API key","operationId":"create_api_key_v1_api_keys_post","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAPIKeyRequest"}}}},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/APIKeyCreated"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/api-keys/{key_id}`

## DELETE /v1/api-keys/{key\_id}

> Revoke an API key

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/api-keys/{key_id}":{"delete":{"tags":["Account"],"summary":"Revoke an API key","operationId":"revoke_api_key_v1_api_keys__key_id__delete","parameters":[{"name":"key_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Key Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Async Jobs

### `GET /v1/jobs/list`

## List async jobs for this org

> Paginated list of all jobs for the authenticated org.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/jobs/list":{"get":{"tags":["Async Jobs"],"summary":"List async jobs for this org","description":"Paginated list of all jobs for the authenticated org.","operationId":"list_jobs_v1_jobs_list_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":200,"minimum":1,"default":25,"title":"Limit"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response List Jobs V1 Jobs List Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/jobs`

## Submit an async simulation job

> Submit a large simulation to run asynchronously. Returns a job\_id immediately. Poll /v1/jobs/{job\_id} for status. Provide a callback\_url to receive a webhook when complete.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"SubmitJobRequest":{"properties":{"request":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Request","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}},"callback_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Callback Url","description":"URL to POST when the job completes. Must be HTTPS in production."}},"type":"object","required":["request"],"title":"SubmitJobRequest","description":"Request to submit an async simulation job."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"SubmitJobResponse":{"properties":{"job_id":{"type":"string","format":"uuid","title":"Job Id"},"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status"},"poll_url":{"type":"string","title":"Poll Url"},"message":{"type":"string","title":"Message","default":"Job queued. Poll the poll_url for status updates."}},"type":"object","required":["job_id","run_id","status","poll_url"],"title":"SubmitJobResponse","description":"Returned immediately on job submission."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/jobs":{"post":{"tags":["Async Jobs"],"summary":"Submit an async simulation job","description":"Submit a large simulation to run asynchronously. Returns a job_id immediately. Poll /v1/jobs/{job_id} for status. Provide a callback_url to receive a webhook when complete.","operationId":"submit_job_v1_jobs_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmitJobRequest"}}},"required":true},"responses":{"202":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SubmitJobResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/jobs/{job_id}`

## GET /v1/jobs/{job\_id}

> Poll job status

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"JobStatusResponse":{"properties":{"job_id":{"type":"string","format":"uuid","title":"Job Id"},"run_id":{"type":"string","format":"uuid","title":"Run Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"status":{"type":"string","title":"Status"},"queue_name":{"type":"string","title":"Queue Name"},"retry_count":{"type":"integer","title":"Retry Count"},"callback_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Callback Url"},"callback_status":{"type":"string","title":"Callback Status"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"started_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Started At"},"completed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Completed At"},"ttl_expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Ttl Expires At"},"poll_url":{"type":"string","title":"Poll Url"}},"type":"object","required":["job_id","run_id","org_id","status","queue_name","retry_count","callback_url","callback_status","error_message","created_at","started_at","completed_at","ttl_expires_at","poll_url"],"title":"JobStatusResponse","description":"Job status returned by poll endpoint."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/jobs/{job_id}":{"get":{"tags":["Async Jobs"],"summary":"Poll job status","operationId":"get_job_status_v1_jobs__job_id__get","parameters":[{"name":"job_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Job Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobStatusResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/jobs/{job_id}/result`

## Fetch job result

> Returns the full result if completed, or 202 with status if still processing.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/jobs/{job_id}/result":{"get":{"tags":["Async Jobs"],"summary":"Fetch job result","description":"Returns the full result if completed, or 202 with status if still processing.","operationId":"get_job_result_endpoint_v1_jobs__job_id__result_get","parameters":[{"name":"job_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Job Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Job Result Endpoint V1 Jobs  Job Id  Result Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/jobs/{job_id}/cancel`

## POST /v1/jobs/{job\_id}/cancel

> Cancel a job

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"JobStatusResponse":{"properties":{"job_id":{"type":"string","format":"uuid","title":"Job Id"},"run_id":{"type":"string","format":"uuid","title":"Run Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"status":{"type":"string","title":"Status"},"queue_name":{"type":"string","title":"Queue Name"},"retry_count":{"type":"integer","title":"Retry Count"},"callback_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Callback Url"},"callback_status":{"type":"string","title":"Callback Status"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"started_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Started At"},"completed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Completed At"},"ttl_expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Ttl Expires At"},"poll_url":{"type":"string","title":"Poll Url"}},"type":"object","required":["job_id","run_id","org_id","status","queue_name","retry_count","callback_url","callback_status","error_message","created_at","started_at","completed_at","ttl_expires_at","poll_url"],"title":"JobStatusResponse","description":"Job status returned by poll endpoint."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/jobs/{job_id}/cancel":{"post":{"tags":["Async Jobs"],"summary":"Cancel a job","operationId":"cancel_job_endpoint_v1_jobs__job_id__cancel_post","parameters":[{"name":"job_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Job Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobStatusResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/webhooks/test`

## Test webhook delivery

> Send a test webhook payload to a URL and return the delivery result.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"WebhookTestRequest":{"properties":{"callback_url":{"type":"string","title":"Callback Url","description":"URL to send test webhook to"}},"type":"object","required":["callback_url"],"title":"WebhookTestRequest"},"WebhookTestResponse":{"properties":{"success":{"type":"boolean","title":"Success"},"status_code":{"type":"integer","title":"Status Code"},"message":{"type":"string","title":"Message"}},"type":"object","required":["success","status_code","message"],"title":"WebhookTestResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/webhooks/test":{"post":{"tags":["Async Jobs"],"summary":"Test webhook delivery","description":"Send a test webhook payload to a URL and return the delivery result.","operationId":"test_webhook_v1_webhooks_test_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookTestRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebhookTestResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Auth

### `POST /auth/signup`

## Create a new account

> Self-serve signup. Creates an organization, user account, and first API key in one step. The raw API key is shown \*\*once\*\* in the response — store it securely.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/auth/signup":{"post":{"tags":["Auth"],"summary":"Create a new account","description":"Self-serve signup. Creates an organization, user account, and first API key in one step. The raw API key is shown **once** in the response — store it securely.","operationId":"signup_auth_signup_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignUpRequest"}}},"required":true},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignUpResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"SignUpRequest":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","maxLength":128,"minLength":8,"title":"Password"},"name":{"type":"string","maxLength":255,"minLength":1,"title":"Name"}},"type":"object","required":["email","password","name"],"title":"SignUpRequest"},"SignUpResponse":{"properties":{"user":{"$ref":"#/components/schemas/UserInfo"},"org":{"$ref":"#/components/schemas/OrgInfo"},"api_key":{"$ref":"#/components/schemas/APIKeyCreated"},"message":{"type":"string","title":"Message","default":"Account created successfully. Your API key is shown once — store it securely."}},"type":"object","required":["user","org","api_key"],"title":"SignUpResponse"},"UserInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"email":{"type":"string","title":"Email"},"name":{"type":"string","title":"Name"},"role":{"type":"string","title":"Role"},"email_verified":{"type":"boolean","title":"Email Verified"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","email","name","role","email_verified","created_at"],"title":"UserInfo"},"OrgInfo":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"plan":{"type":"string","title":"Plan"},"status":{"type":"string","title":"Status"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","slug","plan","status","created_at"],"title":"OrgInfo"},"APIKeyCreated":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"label":{"type":"string","title":"Label"},"key_prefix":{"type":"string","title":"Key Prefix"},"device_limit":{"type":"integer","minimum":0,"title":"Device Limit","description":"Max registered devices for this key on the local runtime path. 0 preserves the plan's unlimited or no-local-runtime behavior."},"raw_key":{"type":"string","title":"Raw Key","description":"The full API key — shown ONCE, store it securely."},"created_at":{"type":"string","format":"date-time","title":"Created At"},"expires_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Expires At"}},"type":"object","required":["id","label","key_prefix","device_limit","raw_key","created_at"],"title":"APIKeyCreated","description":"Returned once at key creation — raw key shown here only."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

### `POST /auth/login`

## Login and get a session token

> Returns a JWT bearer token valid for 7 days. Use as \`Authorization: Bearer \<token>\`.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/auth/login":{"post":{"tags":["Auth"],"summary":"Login and get a session token","description":"Returns a JWT bearer token valid for 7 days. Use as `Authorization: Bearer <token>`.","operationId":"login_auth_login_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TokenResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"LoginRequest":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"}},"type":"object","required":["email","password"],"title":"LoginRequest"},"TokenResponse":{"properties":{"access_token":{"type":"string","title":"Access Token"},"token_type":{"type":"string","title":"Token Type","default":"bearer"},"expires_in":{"type":"integer","title":"Expires In"}},"type":"object","required":["access_token","expires_in"],"title":"TokenResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

### `GET /auth/verify`

## Verify email address via token link

> Verify a user's email address. Token sent on signup.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/auth/verify":{"get":{"tags":["Auth"],"summary":"Verify email address via token link","description":"Verify a user's email address. Token sent on signup.","operationId":"verify_email_auth_verify_get","parameters":[{"name":"token","in":"query","required":true,"schema":{"type":"string","description":"Verification token from email","title":"Token"},"description":"Verification token from email"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Verify Email Auth Verify Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

### `POST /auth/forgot-password`

## Request a password reset email

> Send a password reset link to the user's email.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/auth/forgot-password":{"post":{"tags":["Auth"],"summary":"Request a password reset email","description":"Send a password reset link to the user's email.","operationId":"forgot_password_auth_forgot_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForgotPasswordRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Forgot Password Auth Forgot Password Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"ForgotPasswordRequest":{"properties":{"email":{"type":"string","format":"email","title":"Email"}},"type":"object","required":["email"],"title":"ForgotPasswordRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

### `POST /auth/reset-password`

## Complete password reset with token

> Reset a user's password using a valid reset token.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/auth/reset-password":{"post":{"tags":["Auth"],"summary":"Complete password reset with token","description":"Reset a user's password using a valid reset token.","operationId":"reset_password_auth_reset_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResetPasswordRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Reset Password Auth Reset Password Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"ResetPasswordRequest":{"properties":{"token":{"type":"string","minLength":1,"title":"Token"},"new_password":{"type":"string","maxLength":128,"minLength":8,"title":"New Password"}},"type":"object","required":["token","new_password"],"title":"ResetPasswordRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

## Billing

### `POST /v1/billing/checkout`

## POST /v1/billing/checkout

> Create Stripe Checkout session

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/billing/checkout":{"post":{"tags":["Billing"],"summary":"Create Stripe Checkout session","operationId":"checkout_v1_billing_checkout_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Checkout V1 Billing Checkout Post"}}}}}}}}}
```

### `POST /v1/billing/portal`

## POST /v1/billing/portal

> Create Stripe Billing Portal session

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/billing/portal":{"post":{"tags":["Billing"],"summary":"Create Stripe Billing Portal session","operationId":"portal_v1_billing_portal_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Portal V1 Billing Portal Post"}}}}}}}}}
```

### `GET /v1/billing/info`

## GET /v1/billing/info

> Get current billing info

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/billing/info":{"get":{"tags":["Billing"],"summary":"Get current billing info","operationId":"billing_info_v1_billing_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Billing Info V1 Billing Info Get"}}}}}}}}}
```

## Calibration

### `GET /v1/calibration`

## Get confidence calibration status

> Returns the org's historical prediction accuracy metrics computed from all recorded outcomes (\`PATCH /v1/decisions/{id}/outcome\`). The \`confidence\_multiplier\` is applied automatically to every simulation and recommendation once \`n\_samples >= 5\`.\
> \
> \*\*Key fields\*\*\
> \- \`bias\`: mean relative error — negative means over-optimistic\
> \- \`hit\_rate\`: fraction of predictions within ±20% of actual\
> \- \`confidence\_multiplier\`: factor currently applied to raw simulation confidence\
> \- \`is\_reliable\`: false until 5+ outcomes are recorded

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"CalibrationResponse":{"properties":{"org_id":{"type":"string","title":"Org Id"},"is_reliable":{"type":"boolean","title":"Is Reliable"},"n_samples":{"type":"integer","title":"N Samples"},"bias":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Bias"},"rmse_pct":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rmse Pct"},"hit_rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Hit Rate"},"direction":{"type":"string","title":"Direction"},"confidence_multiplier":{"type":"number","title":"Confidence Multiplier"},"summary":{"type":"string","title":"Summary"},"last_updated":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last Updated"}},"type":"object","required":["org_id","is_reliable","n_samples","bias","rmse_pct","hit_rate","direction","confidence_multiplier","summary","last_updated"],"title":"CalibrationResponse","description":"Org-level confidence calibration state."}}},"paths":{"/v1/calibration":{"get":{"tags":["Calibration"],"summary":"Get confidence calibration status","description":"Returns the org's historical prediction accuracy metrics computed from all recorded outcomes (`PATCH /v1/decisions/{id}/outcome`). The `confidence_multiplier` is applied automatically to every simulation and recommendation once `n_samples >= 5`.\n\n**Key fields**\n- `bias`: mean relative error — negative means over-optimistic\n- `hit_rate`: fraction of predictions within ±20% of actual\n- `confidence_multiplier`: factor currently applied to raw simulation confidence\n- `is_reliable`: false until 5+ outcomes are recorded","operationId":"get_calibration_status_v1_calibration_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CalibrationResponse"}}}}}}}}}
```

## Data

### `POST /v1/data/connect`

## POST /v1/data/connect

> Connect data, pick a dataset, and make it queryable.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectDataRequest":{"properties":{"connection_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Connection Type","description":"database | api | object_storage | file_upload"},"dataset_name":{"type":"string","title":"Dataset Name","description":"Public dataset name."},"provider":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Provider","description":"Specific provider such as postgres, snowflake, s3, rest."},"connector":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connector","description":"Canonical connector envelope with type/location/auth/options. Preferred for cross-SDK and MCP compatibility."},"connection_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Connection Id","description":"Reuse an existing saved connection."},"connection_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Connection Name","description":"Optional saved connection label."},"connection_config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection Config","description":"Connector credentials/config."},"selection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Selection","description":"Chosen table/query/path."},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"visibility":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Visibility","description":"private | shared"},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64"}},"type":"object","required":["dataset_name"],"title":"ConnectDataRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data/connect":{"post":{"tags":["Data"],"summary":"Connect data, pick a dataset, and make it queryable.","operationId":"connect_dataset_v1_data_connect_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectDataRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Connect Dataset V1 Data Connect Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/data`

## GET /v1/data

> List visible datasets for the caller.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data":{"get":{"tags":["Data"],"summary":"List visible datasets for the caller.","operationId":"list_data_v1_data_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},{"name":"source_name","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name"}},{"name":"compact","in":"query","required":false,"schema":{"type":"boolean","default":false,"title":"Compact"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response List Data V1 Data Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/data/{dataset_id}/summary`

## GET /v1/data/{dataset\_id}/summary

> Get low-token discovery summary for one dataset.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data/{dataset_id}/summary":{"get":{"tags":["Data"],"summary":"Get low-token discovery summary for one dataset.","operationId":"get_data_summary_v1_data__dataset_id__summary_get","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Data Summary V1 Data  Dataset Id  Summary Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/data/{dataset_id}`

## GET /v1/data/{dataset\_id}

> Get one dataset plus its schema.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data/{dataset_id}":{"get":{"tags":["Data"],"summary":"Get one dataset plus its schema.","operationId":"get_data_v1_data__dataset_id__get","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Data V1 Data  Dataset Id  Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/data/{dataset_id}`

## DELETE /v1/data/{dataset\_id}

> Disconnect data by deleting the dataset.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data/{dataset_id}":{"delete":{"tags":["Data"],"summary":"Disconnect data by deleting the dataset.","operationId":"disconnect_data_v1_data__dataset_id__delete","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Disconnect Data V1 Data  Dataset Id  Delete"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/data/{dataset_id}/refresh`

## POST /v1/data/{dataset\_id}/refresh

> Refresh a dataset from its saved origin.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/data/{dataset_id}/refresh":{"post":{"tags":["Data"],"summary":"Refresh a dataset from its saved origin.","operationId":"refresh_data_v1_data__dataset_id__refresh_post","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Refresh Data V1 Data  Dataset Id  Refresh Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Data Connectors

### `GET /v1/connectors`

## GET /v1/connectors

> List data connectors

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorResponse":{"properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"connector_type":{"type":"string","title":"Connector Type"},"status":{"type":"string","title":"Status"},"visibility":{"type":"string","title":"Visibility"},"last_tested_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Tested At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","connector_type","status","visibility","last_tested_at","error_message","created_at"],"title":"ConnectorResponse"},"ConnectorListResponse":{"properties":{"connectors":{"items":{"$ref":"#/components/schemas/ConnectorResponse"},"type":"array","title":"Connectors"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["connectors","total","page","limit","pages"],"title":"ConnectorListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors":{"get":{"tags":["Data Connectors"],"summary":"List data connectors","operationId":"list_connectors_v1_connectors_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}],"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/ConnectorResponse"}},{"$ref":"#/components/schemas/ConnectorListResponse"}],"title":"Response List Connectors V1 Connectors Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/connectors`

## POST /v1/connectors

> Create a data connector with credentials

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorCreate":{"properties":{"name":{"type":"string","title":"Name"},"connector_type":{"type":"string","title":"Connector Type"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"visibility":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Visibility"},"config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Config"}},"type":"object","required":["name","connector_type"],"title":"ConnectorCreate"},"ConnectorResponse":{"properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"connector_type":{"type":"string","title":"Connector Type"},"status":{"type":"string","title":"Status"},"visibility":{"type":"string","title":"Visibility"},"last_tested_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Tested At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","connector_type","status","visibility","last_tested_at","error_message","created_at"],"title":"ConnectorResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors":{"post":{"tags":["Data Connectors"],"summary":"Create a data connector with credentials","operationId":"create_connector_v1_connectors_post","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorCreate"}}}},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/connectors/{connector_id}`

## GET /v1/connectors/{connector\_id}

> Get one data connector

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorResponse":{"properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"connector_type":{"type":"string","title":"Connector Type"},"status":{"type":"string","title":"Status"},"visibility":{"type":"string","title":"Visibility"},"last_tested_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Tested At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","connector_type","status","visibility","last_tested_at","error_message","created_at"],"title":"ConnectorResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/{connector_id}":{"get":{"tags":["Data Connectors"],"summary":"Get one data connector","operationId":"get_connector_v1_connectors__connector_id__get","parameters":[{"name":"connector_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Connector Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `PATCH /v1/connectors/{connector_id}`

## PATCH /v1/connectors/{connector\_id}

> Update connector name or config

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorUpdate":{"properties":{"name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Name"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"visibility":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Visibility"},"config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Config"}},"type":"object","title":"ConnectorUpdate"},"ConnectorResponse":{"properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"connector_type":{"type":"string","title":"Connector Type"},"status":{"type":"string","title":"Status"},"visibility":{"type":"string","title":"Visibility"},"last_tested_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Tested At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"},"created_at":{"type":"string","format":"date-time","title":"Created At"}},"type":"object","required":["id","name","connector_type","status","visibility","last_tested_at","error_message","created_at"],"title":"ConnectorResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/{connector_id}":{"patch":{"tags":["Data Connectors"],"summary":"Update connector name or config","operationId":"update_connector_v1_connectors__connector_id__patch","parameters":[{"name":"connector_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Connector Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorUpdate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/connectors/{connector_id}`

## DELETE /v1/connectors/{connector\_id}

> Delete a data connector

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/{connector_id}":{"delete":{"tags":["Data Connectors"],"summary":"Delete a data connector","operationId":"delete_connector_v1_connectors__connector_id__delete","parameters":[{"name":"connector_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Connector Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/connectors/types`

## GET /v1/connectors/types

> List supported connector types

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/connectors/types":{"get":{"tags":["Data Connectors"],"summary":"List supported connector types","operationId":"list_connector_types_v1_connectors_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object","title":"Response List Connector Types V1 Connectors Types Get"}}}}}}}}}
```

### `POST /v1/connectors/{connector_id}/test`

## POST /v1/connectors/{connector\_id}/test

> Test connector — real connection attempt

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorTestResult":{"properties":{"success":{"type":"boolean","title":"Success"},"message":{"type":"string","title":"Message"},"latency_ms":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Latency Ms"},"status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"},"error_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Type"},"recoverable":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Recoverable"}},"type":"object","required":["success","message"],"title":"ConnectorTestResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/{connector_id}/test":{"post":{"tags":["Data Connectors"],"summary":"Test connector — real connection attempt","operationId":"test_connector_v1_connectors__connector_id__test_post","parameters":[{"name":"connector_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Connector Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorTestResult"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/connectors/test`

## POST /v1/connectors/test

> Test an inline connector preview without saving it

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorPreviewRequest":{"properties":{"connector_type":{"type":"string","title":"Connector Type"},"config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Config"}},"type":"object","required":["connector_type"],"title":"ConnectorPreviewRequest"},"ConnectorTestResult":{"properties":{"success":{"type":"boolean","title":"Success"},"message":{"type":"string","title":"Message"},"latency_ms":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Latency Ms"},"status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"},"error_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Type"},"recoverable":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Recoverable"}},"type":"object","required":["success","message"],"title":"ConnectorTestResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/test":{"post":{"tags":["Data Connectors"],"summary":"Test an inline connector preview without saving it","operationId":"test_connector_preview_v1_connectors_test_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorPreviewRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorTestResult"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/connectors/{connector_id}/browse`

## GET /v1/connectors/{connector\_id}/browse

> Browse connector schema — list tables, files, or datasets

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"BrowseResult":{"properties":{"connector_type":{"type":"string","title":"Connector Type"},"items":{"items":{"type":"object"},"type":"array","title":"Items"},"total":{"type":"integer","title":"Total"},"message":{"type":"string","title":"Message"},"labels":{"type":"object","title":"Labels"},"discovery":{"type":"object","title":"Discovery"}},"type":"object","required":["connector_type","items","total","message","labels","discovery"],"title":"BrowseResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/{connector_id}/browse":{"get":{"tags":["Data Connectors"],"summary":"Browse connector schema — list tables, files, or datasets","operationId":"browse_connector_v1_connectors__connector_id__browse_get","parameters":[{"name":"connector_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Connector Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BrowseResult"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/connectors/browse`

## POST /v1/connectors/browse

> Browse an inline connector preview without saving it

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ConnectorPreviewRequest":{"properties":{"connector_type":{"type":"string","title":"Connector Type"},"config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Config"}},"type":"object","required":["connector_type"],"title":"ConnectorPreviewRequest"},"BrowseResult":{"properties":{"connector_type":{"type":"string","title":"Connector Type"},"items":{"items":{"type":"object"},"type":"array","title":"Items"},"total":{"type":"integer","title":"Total"},"message":{"type":"string","title":"Message"},"labels":{"type":"object","title":"Labels"},"discovery":{"type":"object","title":"Discovery"}},"type":"object","required":["connector_type","items","total","message","labels","discovery"],"title":"BrowseResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/connectors/browse":{"post":{"tags":["Data Connectors"],"summary":"Browse an inline connector preview without saving it","operationId":"browse_connector_preview_v1_connectors_browse_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConnectorPreviewRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BrowseResult"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Data Mapping

### `GET /v1/map/{map_id}`

## Poll for deep analysis (join keys + derived relationships)

> When \`POST /v1/map\` returns \`deep\_analysis\_pending: true\`, poll this endpoint with the \`map\_id\` to retrieve join keys, derived relationships, and the simulation payload once Phase 2 analysis completes.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/map/{map_id}":{"get":{"tags":["Data Mapping"],"summary":"Poll for deep analysis (join keys + derived relationships)","description":"When `POST /v1/map` returns `deep_analysis_pending: true`, poll this endpoint with the `map_id` to retrieve join keys, derived relationships, and the simulation payload once Phase 2 analysis completes.","operationId":"get_deep_analysis_v1_map__map_id__get","parameters":[{"name":"map_id","in":"path","required":true,"schema":{"type":"string","title":"Map Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Deep Analysis V1 Map  Map Id  Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/map`

## Instantly map any dataset — no schema, no ETL

> \*\*Connect and understand any dataset instantly.\*\*\
> \
> Drop in CSV files, JSON records, or table names from multiple sources. Get back a unified schema with every field mapped, explained, and ready to run decisions on.\
> \
> \*\*What it detects:\*\*\
> \- Matching fields across sources (revenue ↔ sales, qty ↔ quantity)\
> \- Value distributions (lognormal for prices, triangular for ranges)\
> \- Polarity (cost → negative, revenue → positive)\
> \- Join keys between tables (background if slow)\
> \- Derived formulas A×B≈C (background if slow)\
> \- Confidence and plain-English reasoning for every mapping\
> \
> \*\*Two-speed pipeline:\*\* Phase 1 (schema + column matches) returns in <300ms. Phase 2 (join detection + relation detection) is embedded in the response if it finishes within 200ms, otherwise \`deep\_analysis\_pending: true\` is set and results can be retrieved via \`GET /v1/map/{map\_id}\`.\
> \
> \*\*The data funnel:\*\* Upload → Map → Query → Decide → Optimize

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"MapRequest":{"properties":{"sources":{"items":{"$ref":"#/components/schemas/DataSource"},"type":"array","minItems":1,"title":"Sources","description":"Data sources to map (CSV, JSON records, or table name)"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","description":"Minimum confidence threshold for mappings (default: 0.5)","default":0.5},"include_statistics":{"type":"boolean","title":"Include Statistics","description":"Include value distribution statistics in response","default":true}},"type":"object","required":["sources"],"title":"MapRequest","description":"Drop in any data sources. Get back semantic field mappings and a unified schema.\n\nNo configuration required. The engine auto-detects:\n- Which fields represent the same concept across sources\n- Distribution shapes for numeric fields\n- Polarity (revenue → positive, cost → negative)\n- Primary/foreign keys for joins\n- Confidence and reasoning for every mapping"},"DataSource":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this source (e.g., 'sales', 'orders')"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source."},"source_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Id","description":"Registered source ID; fastest path and avoids re-uploading data."},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"Inline JSON records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str","description":"Raw JSON array/object text (nested auto-flattened)"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"HTTP URL — format auto-detected"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64","description":"Excel .xlsx file, base64-encoded"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64","description":"Parquet file, base64-encoded"},"connection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection","description":"Connector config dict — see DataSource docstring for all types"},"table":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Table","description":"Legacy field — use connection instead"}},"type":"object","required":["name"],"title":"DataSource","description":"A data source to map. Every format normalizes to list[dict] internally.\n\nInline (no external dependency):\n  `records`    — JSON array of objects (fastest)\n  `csv`        — raw CSV text\n  `json_str`   — raw JSON array/object text (nested JSON is auto-flattened)\n  `url`        — HTTP(S) URL; format auto-detected from Content-Type / extension\n\nBinary files (base64-encoded for API transport):\n  `excel_b64`  — Excel .xlsx file, base64-encoded\n  `parquet_b64`— Parquet file, base64-encoded\n\nConnector config (routes through ConnectorRegistry):\n  `connection` — dict with `type` + connector-specific keys:\n    {\"type\": \"sql\",        \"connection_string\": \"postgresql+asyncpg://...\",\n     \"query\": \"SELECT ...\"}\n    {\"type\": \"sql\",        \"connection_string\": \"sqlite+aiosqlite:///db.sqlite\", \"query\": \"...\"}\n    {\"type\": \"rest_api\",   \"url\": \"https://...\", \"data_path\": \"data.items\"}\n    {\"type\": \"s3\",         \"bucket\": \"my-bucket\", \"key\": \"data/sales.parquet\"}\n    {\"type\": \"gcs\",        \"bucket\": \"my-bucket\", \"blob\": \"data/orders.csv\"}\n    {\"type\": \"azure_blob\", \"connection_string\": \"DefaultEndpointsProtocol=...\",\n                           \"container\": \"data\", \"blob\": \"sales.parquet\"}"},"MapResponse":{"properties":{"map_id":{"type":"string","title":"Map Id"},"sources_analyzed":{"type":"integer","title":"Sources Analyzed"},"total_fields":{"type":"integer","title":"Total Fields"},"mappings":{"items":{"$ref":"#/components/schemas/FieldMapping"},"type":"array","title":"Mappings"},"unified_schema":{"items":{"$ref":"#/components/schemas/SchemaField"},"type":"array","title":"Unified Schema"},"join_keys":{"items":{"type":"object"},"type":"array","title":"Join Keys"},"derived_relationships":{"items":{"type":"object"},"type":"array","title":"Derived Relationships"},"simulation_ready":{"type":"boolean","title":"Simulation Ready"},"simulation_payload":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Simulation Payload"},"deep_analysis_pending":{"type":"boolean","title":"Deep Analysis Pending","default":false},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["map_id","sources_analyzed","total_fields","mappings","unified_schema","join_keys","derived_relationships","simulation_ready","simulation_payload","latency_ms"],"title":"MapResponse"},"FieldMapping":{"properties":{"source_field":{"type":"string","title":"Source Field"},"source":{"type":"string","title":"Source"},"target_field":{"type":"string","title":"Target Field"},"target":{"type":"string","title":"Target"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"reason":{"items":{"type":"string"},"type":"array","title":"Reason"},"match_type":{"type":"string","title":"Match Type"}},"type":"object","required":["source_field","source","target_field","target","confidence","reason","match_type"],"title":"FieldMapping"},"SchemaField":{"properties":{"name":{"type":"string","title":"Name"},"sources":{"items":{"type":"string"},"type":"array","title":"Sources"},"distribution":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Distribution"},"unit":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Unit"},"polarity":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Polarity"},"sample_values":{"items":{},"type":"array","title":"Sample Values","default":[]}},"type":"object","required":["name","sources"],"title":"SchemaField"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/map":{"post":{"tags":["Data Mapping"],"summary":"Instantly map any dataset — no schema, no ETL","description":"**Connect and understand any dataset instantly.**\n\nDrop in CSV files, JSON records, or table names from multiple sources. Get back a unified schema with every field mapped, explained, and ready to run decisions on.\n\n**What it detects:**\n- Matching fields across sources (revenue ↔ sales, qty ↔ quantity)\n- Value distributions (lognormal for prices, triangular for ranges)\n- Polarity (cost → negative, revenue → positive)\n- Join keys between tables (background if slow)\n- Derived formulas A×B≈C (background if slow)\n- Confidence and plain-English reasoning for every mapping\n\n**Two-speed pipeline:** Phase 1 (schema + column matches) returns in <300ms. Phase 2 (join detection + relation detection) is embedded in the response if it finishes within 200ms, otherwise `deep_analysis_pending: true` is set and results can be retrieved via `GET /v1/map/{map_id}`.\n\n**The data funnel:** Upload → Map → Query → Decide → Optimize","operationId":"map_sources_v1_map_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MapResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Datasets

### `POST /v1/datasets/onboard`

## Onboard a dataset — zero-config schema profiling + auto-training

> \*\*Drop in data → instantly queryable.\*\*\
> \
> \- Accepts JSON records, inline CSV, or column names only\
> \- Profiles schema and role-classifies every column automatically\
> \- Auto-suggests domain aliases (PPA → per/person/average, etc.)\
> \- Fires background semantic training immediately when the training runtime is installed\
> \- Returns model tier — queries work immediately via base/deterministic fallback\
> \
> For file uploads (CSV, Excel, Parquet, JSON) use \`POST /v1/datasets/onboard/file\`.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"OnboardRequest":{"properties":{"name":{"type":"string","title":"Name","description":"Human-readable dataset name","default":"dataset"},"source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name","description":"Table name used in the schema"},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"JSON records (list of row dicts)"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text with header row"},"columns":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Columns","description":"Column names only — no data required"},"domain_aliases":{"anyOf":[{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object"},{"type":"null"}],"title":"Domain Aliases","description":"Manual alias map. Auto-suggested from column names when omitted."},"async_train":{"type":"boolean","title":"Async Train","description":"Fire background semantic training immediately","default":true},"epochs":{"type":"integer","maximum":500,"minimum":5,"title":"Epochs","default":80},"batch_size":{"type":"integer","maximum":256,"minimum":8,"title":"Batch Size","default":32}},"type":"object","title":"OnboardRequest","description":"Register any data source for semantic querying.\n\nProvide data via ONE of:\n  records  — list of row dicts (JSON records)\n  csv      — raw CSV text (headers in first row)\n  columns  — list of column name strings (schema-only, no samples)\n\nFor file uploads use POST /v1/datasets/onboard/file."},"OnboardResponse":{"properties":{"dataset_id":{"type":"string","title":"Dataset Id"},"name":{"type":"string","title":"Name"},"schema_hash":{"type":"string","title":"Schema Hash"},"status":{"type":"string","title":"Status"},"model_tier":{"type":"string","title":"Model Tier"},"decision_mode":{"type":"string","title":"Decision Mode"},"source_names":{"items":{"type":"string"},"type":"array","title":"Source Names"},"column_count":{"type":"integer","title":"Column Count"},"domain_aliases":{"anyOf":[{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object"},{"type":"null"}],"title":"Domain Aliases"},"registered_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Registered At"},"updated_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Updated At"},"schema":{"type":"object","title":"Schema"},"suggested_aliases":{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object","title":"Suggested Aliases"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["dataset_id","name","schema_hash","status","model_tier","decision_mode","source_names","column_count","domain_aliases","registered_at","updated_at","schema","suggested_aliases","latency_ms"],"title":"OnboardResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/datasets/onboard":{"post":{"tags":["Datasets"],"summary":"Onboard a dataset — zero-config schema profiling + auto-training","description":"**Drop in data → instantly queryable.**\n\n- Accepts JSON records, inline CSV, or column names only\n- Profiles schema and role-classifies every column automatically\n- Auto-suggests domain aliases (PPA → per/person/average, etc.)\n- Fires background semantic training immediately when the training runtime is installed\n- Returns model tier — queries work immediately via base/deterministic fallback\n\nFor file uploads (CSV, Excel, Parquet, JSON) use `POST /v1/datasets/onboard/file`.","operationId":"onboard_dataset_v1_datasets_onboard_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OnboardRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OnboardResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/datasets/onboard/file`

## POST /v1/datasets/onboard/file

> Onboard from file upload — CSV, Excel, Parquet, JSON, JSONL

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"Body_onboard_file_v1_datasets_onboard_file_post":{"properties":{"file":{"type":"string","format":"binary","title":"File"},"name":{"type":"string","title":"Name","default":"dataset"},"source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name"},"domain_aliases_json":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Domain Aliases Json"},"async_train":{"type":"boolean","title":"Async Train","default":true},"epochs":{"type":"integer","title":"Epochs","default":80},"batch_size":{"type":"integer","title":"Batch Size","default":32}},"type":"object","required":["file"],"title":"Body_onboard_file_v1_datasets_onboard_file_post"},"OnboardResponse":{"properties":{"dataset_id":{"type":"string","title":"Dataset Id"},"name":{"type":"string","title":"Name"},"schema_hash":{"type":"string","title":"Schema Hash"},"status":{"type":"string","title":"Status"},"model_tier":{"type":"string","title":"Model Tier"},"decision_mode":{"type":"string","title":"Decision Mode"},"source_names":{"items":{"type":"string"},"type":"array","title":"Source Names"},"column_count":{"type":"integer","title":"Column Count"},"domain_aliases":{"anyOf":[{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object"},{"type":"null"}],"title":"Domain Aliases"},"registered_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Registered At"},"updated_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Updated At"},"schema":{"type":"object","title":"Schema"},"suggested_aliases":{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object","title":"Suggested Aliases"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["dataset_id","name","schema_hash","status","model_tier","decision_mode","source_names","column_count","domain_aliases","registered_at","updated_at","schema","suggested_aliases","latency_ms"],"title":"OnboardResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/datasets/onboard/file":{"post":{"tags":["Datasets"],"summary":"Onboard from file upload — CSV, Excel, Parquet, JSON, JSONL","operationId":"onboard_file_v1_datasets_onboard_file_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_onboard_file_v1_datasets_onboard_file_post"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OnboardResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/datasets/{dataset_id}/status`

## GET /v1/datasets/{dataset\_id}/status

> Live status and model tier for a dataset

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DatasetStatusResponse":{"properties":{"dataset_id":{"type":"string","title":"Dataset Id"},"name":{"type":"string","title":"Name"},"schema_hash":{"type":"string","title":"Schema Hash"},"status":{"type":"string","title":"Status"},"model_tier":{"type":"string","title":"Model Tier"},"decision_mode":{"type":"string","title":"Decision Mode"},"source_names":{"items":{"type":"string"},"type":"array","title":"Source Names"},"column_count":{"type":"integer","title":"Column Count"},"domain_aliases":{"anyOf":[{"additionalProperties":{"items":{"type":"string"},"type":"array"},"type":"object"},{"type":"null"}],"title":"Domain Aliases"},"registered_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Registered At"},"updated_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Updated At"}},"type":"object","required":["dataset_id","name","schema_hash","status","model_tier","decision_mode","source_names","column_count","domain_aliases","registered_at","updated_at"],"title":"DatasetStatusResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/datasets/{dataset_id}/status":{"get":{"tags":["Datasets"],"summary":"Live status and model tier for a dataset","operationId":"get_dataset_status_v1_datasets__dataset_id__status_get","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatasetStatusResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/datasets`

## GET /v1/datasets

> List all datasets registered for this org

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/datasets":{"get":{"tags":["Datasets"],"summary":"List all datasets registered for this org","operationId":"list_datasets_v1_datasets_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},{"name":"source_name","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name"}},{"name":"compact","in":"query","required":false,"schema":{"type":"boolean","default":false,"title":"Compact"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response List Datasets V1 Datasets Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/datasets/{dataset_id}/retrain`

## POST /v1/datasets/{dataset\_id}/retrain

> Re-trigger semantic training for a dataset

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/datasets/{dataset_id}/retrain":{"post":{"tags":["Datasets"],"summary":"Re-trigger semantic training for a dataset","operationId":"retrain_dataset_v1_datasets__dataset_id__retrain_post","parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"string","title":"Dataset Id"}},{"name":"epochs","in":"query","required":false,"schema":{"type":"integer","default":80,"title":"Epochs"}},{"name":"batch_size","in":"query","required":false,"schema":{"type":"integer","default":32,"title":"Batch Size"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Retrain Dataset V1 Datasets  Dataset Id  Retrain Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Decision

### `POST /v1/recommend`

## Compare actions and get a recommendation

> Run simulations for 2–10 named actions and return them ranked by expected value. The top-ranked action is returned as \`recommended\_action\`.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RecommendRequest":{"properties":{"actions":{"items":{"$ref":"#/components/schemas/NamedAction"},"type":"array","maxItems":10,"minItems":2,"title":"Actions"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"}},"type":"object","required":["actions"],"title":"RecommendRequest","description":"Request body for /v1/recommend — compare 2-10 named actions."},"NamedAction":{"properties":{"name":{"type":"string","maxLength":200,"minLength":1,"title":"Name"},"request":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Request","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}}},"type":"object","required":["name","request"],"title":"NamedAction","description":"A named simulation scenario for comparison."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"RecommendResponse":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"action_results":{"items":{"$ref":"#/components/schemas/ActionResult"},"type":"array","title":"Action Results"},"total_actions":{"type":"integer","title":"Total Actions"},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary with all ranked options. Best entry point for LLMs and dashboards — contains recommended_action, expected_value, risk (p5/p95/PoL), all options ranked, rationale, and integrity hashes."}},"type":"object","required":["recommended_action","confidence","rationale","action_results","total_actions"],"title":"RecommendResponse","description":"Response from /v1/recommend."},"ActionResult":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","title":"Rank"},"envelope":{"$ref":"#/components/schemas/DecisionEnvelope"},"expected_value":{"type":"number","title":"Expected Value"},"probability_of_loss":{"type":"number","title":"Probability Of Loss"},"score":{"type":"number","title":"Score"}},"type":"object","required":["name","rank","envelope","expected_value","probability_of_loss","score"],"title":"ActionResult","description":"Result for a single action in a recommend response."},"DecisionEnvelope":{"properties":{"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status","default":"completed"},"engine_version":{"type":"string","title":"Engine Version"},"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"metrics":{"$ref":"#/components/schemas/MetricsSummary"},"percentiles":{"$ref":"#/components/schemas/PercentileSummary"},"scenarios_run":{"type":"integer","title":"Scenarios Run"},"execution_ms":{"type":"integer","title":"Execution Ms"},"metadata":{"$ref":"#/components/schemas/RunMetadata"},"simulation_model":{"type":"string","title":"Simulation Model","description":"Which simulation algorithm was used. Possible values: monte_carlo | qmc_sobol | lhs | bootstrap | scenario | sensitivity | mcmc | decision_tree | time_series | compare | importance_sampling","default":"monte_carlo"},"engine_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Type","description":"Engine that ran the simulation (e.g. 'mojo-native-expr', 'lhs', 'mcmc')"},"simulation_class":{"type":"string","title":"Simulation Class","description":"High-level simulation contract class. Examples: predictive, scenario_analysis, sensitivity_analysis, decision_tree.","default":"predictive"},"model_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Revision","description":"Stable engine or model revision used to generate this result."},"assumptions_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assumptions Hash","description":"Stable fingerprint of the validated simulation assumptions executed by the engine."},"validated_inputs":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Validated Inputs","description":"Normalized summary of the validated request inputs used for execution. Includes mode, runs, variable counts, and model selection."},"confidence_interval":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Confidence Interval","description":"Primary outcome confidence interval derived from the simulated distribution."},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Correlation identifier propagated from the API request."},"scenario_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Scenario Analysis","description":"Populated for simulation_model='scenario': expected_value, best_case, scenarios list"},"sensitivity_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Sensitivity Analysis","description":"Populated for simulation_model='sensitivity': tornado_chart, first_order_sobol, variable_importance"},"bootstrap_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Bootstrap Result","description":"Populated for simulation_model='bootstrap': statistic, observed_value, CI, bias, SE"},"mcmc_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Mcmc Result","description":"Populated for simulation_model='mcmc': posterior summaries, R-hat, acceptance_rate"},"importance_sampling_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Importance Sampling Result","description":"Populated for simulation_model='importance_sampling'. Contains: tail_direction, target_threshold, tail_probability, tail_probability_se, cvar_tail, weighted_mean, weighted_std, theta (tilt parameter), tilt_variable, effective_sample_size, nominal_sample_size, variance_reduction_factor, naive_tail_count."},"scenario_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Scenario Ranking"},"sensitivity_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Sensitivity Ranking"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score"},"score_breakdown":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Score Breakdown"},"created_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Created At"},"decision_tree_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Decision Tree Result","description":"Populated for simulation_model='decision_tree': n_paths, expected_value, paths[]"},"time_series_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Time Series Result","description":"Populated for simulation_model='time_series'. Contains: model, granularity, dt_years, initial_value, n_steps, fan_chart (per-horizon p5/p25/p50/p75/p95), terminal distribution, max_drawdown_pct, and optional sample_paths for visualization."},"formatted_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Formatted Result","description":"Human-readable formatted output values with units. Populated when output_unit_specs or unit_spec is provided. Contains: mean_formatted, p5_formatted, p95_formatted, unit, unit_type, etc."},"unit_context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Unit Context","description":"Unit metadata for all variables and outputs. Contains per-variable unit type, code, precision, and display scale. Use this to reconstruct formatted values client-side."},"unit_warnings":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Unit Warnings","description":"Non-fatal unit validation warnings (e.g. negative currency, out-of-range probability). Simulation still ran — these are advisory only."},"charts":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Charts","description":"Pre-computed Vega-Lite compatible chart specs for instant rendering. Populated when include_charts=true in the request or automatically for sensitivity/time_series engine types. Keys: 'histogram', 'cdf', 'tornado', 'fan_chart', 'scatter'. Each value is a complete Vega-Lite spec that can be passed to vega-embed."},"histogram_data":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Histogram Data","description":"Pre-computed histogram bins (50 bins) for the primary output distribution."},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary. Always populated by /v1/simulate and /v1/recommend. Contains: recommended_action, confidence, expected_value, risk (p5/p95/PoL), all ranked options, rationale, and integrity hashes."},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash","description":"SHA-256 fingerprint of the INPUT payload (variables, distributions, objective function, seed). Cryptographic proof of what data was used to make this decision. Computed at submission time before simulation runs. Format: hex string, 64 chars."},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash","description":"SHA-256 fingerprint of this decision OUTPUT (64-char hex). Covers: run_id, request_hash (input binding), recommended_action, confidence, rationale, metrics, percentiles, scenarios_run, engine_version, simulation_model. Binds the decision to both its inputs AND outputs. Use to verify the decision has not been tampered with. Also returned as X-Decision-Hash response header."}},"type":"object","required":["run_id","engine_version","recommended_action","confidence","rationale","metrics","percentiles","scenarios_run","execution_ms","metadata"],"title":"DecisionEnvelope","description":"Full decision output returned by /v1/simulate, /v1/recommend, and /v1/score."},"MetricsSummary":{"properties":{"expected_value":{"type":"number","title":"Expected Value"},"median":{"type":"number","title":"Median"},"std_deviation":{"type":"number","title":"Std Deviation"},"variance":{"type":"number","title":"Variance"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95"},"cvar_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cvar 95"}},"type":"object","required":["expected_value","median","std_deviation","variance","probability_of_loss"],"title":"MetricsSummary"},"PercentileSummary":{"properties":{"p5":{"type":"number","title":"P5"},"p10":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P10"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p90":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P90"},"p95":{"type":"number","title":"P95"},"p99":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P99"}},"type":"object","required":["p5","p25","p50","p75","p95"],"title":"PercentileSummary"},"RunMetadata":{"properties":{"mode":{"type":"string","title":"Mode"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"billing_units":{"type":"integer","title":"Billing Units"},"engine_version":{"type":"string","title":"Engine Version"}},"type":"object","required":["mode","billing_units","engine_version"],"title":"RunMetadata"},"DecisionPlan":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"options":{"items":{"$ref":"#/components/schemas/DecisionOption"},"type":"array","title":"Options","description":"All alternatives ranked by expected value. Single-element for simulate, multi for recommend."},"rationale":{"type":"string","title":"Rationale"},"integrity":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Integrity","description":"Cryptographic proof of inputs/outputs: {request_hash, result_hash}."},"calibration":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Calibration","description":"Human-readable calibration summary, e.g. '12 outcomes | bias=-8.3% (over-optimistic) | hit_rate=75%'. Null until MIN_SAMPLES (5) outcomes are recorded for this org."}},"type":"object","required":["recommended_action","confidence","expected_value","risk","rationale"],"title":"DecisionPlan","description":"Structured, LLM-readable summary of the decision output.\n\nThis is the headline object — it surfaces all decision-critical fields\nin a compact, consistent shape regardless of simulation model used.\nPopulate ``options`` with all ranked alternatives when using /v1/recommend."},"RiskProfile":{"properties":{"p5":{"type":"number","title":"P5","description":"5th-percentile outcome (downside risk floor)"},"p95":{"type":"number","title":"P95","description":"95th-percentile outcome (upside ceiling)"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss","description":"P(outcome < 0)"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95","description":"Value-at-Risk at 95% confidence"}},"type":"object","required":["p5","p95","probability_of_loss"],"title":"RiskProfile","description":"Quantified downside and upside for a single outcome distribution."},"DecisionOption":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","minimum":1,"title":"Rank"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score","description":"Composite score (0–1)"}},"type":"object","required":["name","rank","expected_value","risk"],"title":"DecisionOption","description":"One named alternative in a multi-option decision comparison."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/recommend":{"post":{"tags":["Decision"],"summary":"Compare actions and get a recommendation","description":"Run simulations for 2–10 named actions and return them ranked by expected value. The top-ranked action is returned as `recommended_action`.","operationId":"recommend_v1_recommend_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RecommendRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RecommendResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/score`

## POST /v1/score

> Score a simulation with custom weights

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ScoreRequest":{"properties":{"request":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Request","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}},"scoring_weights":{"anyOf":[{"additionalProperties":{"type":"number"},"type":"object"},{"type":"null"}],"title":"Scoring Weights","description":"Custom scoring weights. Keys: 'expected_value', 'downside_risk'. Must sum to 1.0."}},"type":"object","required":["request"],"title":"ScoreRequest","description":"Request body for /v1/score."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"ScoreResponse":{"properties":{"envelope":{"$ref":"#/components/schemas/DecisionEnvelope"},"score":{"type":"number","maximum":1,"minimum":0,"title":"Score"},"score_breakdown":{"additionalProperties":{"type":"number"},"type":"object","title":"Score Breakdown"}},"type":"object","required":["envelope","score","score_breakdown"],"title":"ScoreResponse","description":"Response from /v1/score — DecisionEnvelope with score breakdown."},"DecisionEnvelope":{"properties":{"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status","default":"completed"},"engine_version":{"type":"string","title":"Engine Version"},"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"metrics":{"$ref":"#/components/schemas/MetricsSummary"},"percentiles":{"$ref":"#/components/schemas/PercentileSummary"},"scenarios_run":{"type":"integer","title":"Scenarios Run"},"execution_ms":{"type":"integer","title":"Execution Ms"},"metadata":{"$ref":"#/components/schemas/RunMetadata"},"simulation_model":{"type":"string","title":"Simulation Model","description":"Which simulation algorithm was used. Possible values: monte_carlo | qmc_sobol | lhs | bootstrap | scenario | sensitivity | mcmc | decision_tree | time_series | compare | importance_sampling","default":"monte_carlo"},"engine_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Type","description":"Engine that ran the simulation (e.g. 'mojo-native-expr', 'lhs', 'mcmc')"},"simulation_class":{"type":"string","title":"Simulation Class","description":"High-level simulation contract class. Examples: predictive, scenario_analysis, sensitivity_analysis, decision_tree.","default":"predictive"},"model_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Revision","description":"Stable engine or model revision used to generate this result."},"assumptions_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assumptions Hash","description":"Stable fingerprint of the validated simulation assumptions executed by the engine."},"validated_inputs":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Validated Inputs","description":"Normalized summary of the validated request inputs used for execution. Includes mode, runs, variable counts, and model selection."},"confidence_interval":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Confidence Interval","description":"Primary outcome confidence interval derived from the simulated distribution."},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Correlation identifier propagated from the API request."},"scenario_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Scenario Analysis","description":"Populated for simulation_model='scenario': expected_value, best_case, scenarios list"},"sensitivity_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Sensitivity Analysis","description":"Populated for simulation_model='sensitivity': tornado_chart, first_order_sobol, variable_importance"},"bootstrap_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Bootstrap Result","description":"Populated for simulation_model='bootstrap': statistic, observed_value, CI, bias, SE"},"mcmc_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Mcmc Result","description":"Populated for simulation_model='mcmc': posterior summaries, R-hat, acceptance_rate"},"importance_sampling_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Importance Sampling Result","description":"Populated for simulation_model='importance_sampling'. Contains: tail_direction, target_threshold, tail_probability, tail_probability_se, cvar_tail, weighted_mean, weighted_std, theta (tilt parameter), tilt_variable, effective_sample_size, nominal_sample_size, variance_reduction_factor, naive_tail_count."},"scenario_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Scenario Ranking"},"sensitivity_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Sensitivity Ranking"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score"},"score_breakdown":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Score Breakdown"},"created_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Created At"},"decision_tree_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Decision Tree Result","description":"Populated for simulation_model='decision_tree': n_paths, expected_value, paths[]"},"time_series_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Time Series Result","description":"Populated for simulation_model='time_series'. Contains: model, granularity, dt_years, initial_value, n_steps, fan_chart (per-horizon p5/p25/p50/p75/p95), terminal distribution, max_drawdown_pct, and optional sample_paths for visualization."},"formatted_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Formatted Result","description":"Human-readable formatted output values with units. Populated when output_unit_specs or unit_spec is provided. Contains: mean_formatted, p5_formatted, p95_formatted, unit, unit_type, etc."},"unit_context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Unit Context","description":"Unit metadata for all variables and outputs. Contains per-variable unit type, code, precision, and display scale. Use this to reconstruct formatted values client-side."},"unit_warnings":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Unit Warnings","description":"Non-fatal unit validation warnings (e.g. negative currency, out-of-range probability). Simulation still ran — these are advisory only."},"charts":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Charts","description":"Pre-computed Vega-Lite compatible chart specs for instant rendering. Populated when include_charts=true in the request or automatically for sensitivity/time_series engine types. Keys: 'histogram', 'cdf', 'tornado', 'fan_chart', 'scatter'. Each value is a complete Vega-Lite spec that can be passed to vega-embed."},"histogram_data":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Histogram Data","description":"Pre-computed histogram bins (50 bins) for the primary output distribution."},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary. Always populated by /v1/simulate and /v1/recommend. Contains: recommended_action, confidence, expected_value, risk (p5/p95/PoL), all ranked options, rationale, and integrity hashes."},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash","description":"SHA-256 fingerprint of the INPUT payload (variables, distributions, objective function, seed). Cryptographic proof of what data was used to make this decision. Computed at submission time before simulation runs. Format: hex string, 64 chars."},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash","description":"SHA-256 fingerprint of this decision OUTPUT (64-char hex). Covers: run_id, request_hash (input binding), recommended_action, confidence, rationale, metrics, percentiles, scenarios_run, engine_version, simulation_model. Binds the decision to both its inputs AND outputs. Use to verify the decision has not been tampered with. Also returned as X-Decision-Hash response header."}},"type":"object","required":["run_id","engine_version","recommended_action","confidence","rationale","metrics","percentiles","scenarios_run","execution_ms","metadata"],"title":"DecisionEnvelope","description":"Full decision output returned by /v1/simulate, /v1/recommend, and /v1/score."},"MetricsSummary":{"properties":{"expected_value":{"type":"number","title":"Expected Value"},"median":{"type":"number","title":"Median"},"std_deviation":{"type":"number","title":"Std Deviation"},"variance":{"type":"number","title":"Variance"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95"},"cvar_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cvar 95"}},"type":"object","required":["expected_value","median","std_deviation","variance","probability_of_loss"],"title":"MetricsSummary"},"PercentileSummary":{"properties":{"p5":{"type":"number","title":"P5"},"p10":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P10"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p90":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P90"},"p95":{"type":"number","title":"P95"},"p99":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P99"}},"type":"object","required":["p5","p25","p50","p75","p95"],"title":"PercentileSummary"},"RunMetadata":{"properties":{"mode":{"type":"string","title":"Mode"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"billing_units":{"type":"integer","title":"Billing Units"},"engine_version":{"type":"string","title":"Engine Version"}},"type":"object","required":["mode","billing_units","engine_version"],"title":"RunMetadata"},"DecisionPlan":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"options":{"items":{"$ref":"#/components/schemas/DecisionOption"},"type":"array","title":"Options","description":"All alternatives ranked by expected value. Single-element for simulate, multi for recommend."},"rationale":{"type":"string","title":"Rationale"},"integrity":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Integrity","description":"Cryptographic proof of inputs/outputs: {request_hash, result_hash}."},"calibration":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Calibration","description":"Human-readable calibration summary, e.g. '12 outcomes | bias=-8.3% (over-optimistic) | hit_rate=75%'. Null until MIN_SAMPLES (5) outcomes are recorded for this org."}},"type":"object","required":["recommended_action","confidence","expected_value","risk","rationale"],"title":"DecisionPlan","description":"Structured, LLM-readable summary of the decision output.\n\nThis is the headline object — it surfaces all decision-critical fields\nin a compact, consistent shape regardless of simulation model used.\nPopulate ``options`` with all ranked alternatives when using /v1/recommend."},"RiskProfile":{"properties":{"p5":{"type":"number","title":"P5","description":"5th-percentile outcome (downside risk floor)"},"p95":{"type":"number","title":"P95","description":"95th-percentile outcome (upside ceiling)"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss","description":"P(outcome < 0)"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95","description":"Value-at-Risk at 95% confidence"}},"type":"object","required":["p5","p95","probability_of_loss"],"title":"RiskProfile","description":"Quantified downside and upside for a single outcome distribution."},"DecisionOption":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","minimum":1,"title":"Rank"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score","description":"Composite score (0–1)"}},"type":"object","required":["name","rank","expected_value","risk"],"title":"DecisionOption","description":"One named alternative in a multi-option decision comparison."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/score":{"post":{"tags":["Decision"],"summary":"Score a simulation with custom weights","operationId":"score_v1_score_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScoreRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScoreResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/batch`

## Run multiple simulations in one request

> Submit 1–100 simulation requests. Partial failures are allowed; failed items include an error message.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"BatchRequest":{"properties":{"items":{"items":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}},"type":"array","maxItems":100,"minItems":1,"title":"Items"}},"type":"object","required":["items"],"title":"BatchRequest","description":"Request body for /v1/batch."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"BatchResponse":{"properties":{"total":{"type":"integer","title":"Total"},"succeeded":{"type":"integer","title":"Succeeded"},"failed":{"type":"integer","title":"Failed"},"results":{"items":{"$ref":"#/components/schemas/BatchItemResult"},"type":"array","title":"Results"}},"type":"object","required":["total","succeeded","failed","results"],"title":"BatchResponse","description":"Response from /v1/batch."},"BatchItemResult":{"properties":{"index":{"type":"integer","title":"Index"},"success":{"type":"boolean","title":"Success"},"envelope":{"anyOf":[{"$ref":"#/components/schemas/DecisionEnvelope"},{"type":"null"}]},"error":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error"}},"type":"object","required":["index","success"],"title":"BatchItemResult","description":"Result for one item in a batch."},"DecisionEnvelope":{"properties":{"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status","default":"completed"},"engine_version":{"type":"string","title":"Engine Version"},"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"metrics":{"$ref":"#/components/schemas/MetricsSummary"},"percentiles":{"$ref":"#/components/schemas/PercentileSummary"},"scenarios_run":{"type":"integer","title":"Scenarios Run"},"execution_ms":{"type":"integer","title":"Execution Ms"},"metadata":{"$ref":"#/components/schemas/RunMetadata"},"simulation_model":{"type":"string","title":"Simulation Model","description":"Which simulation algorithm was used. Possible values: monte_carlo | qmc_sobol | lhs | bootstrap | scenario | sensitivity | mcmc | decision_tree | time_series | compare | importance_sampling","default":"monte_carlo"},"engine_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Type","description":"Engine that ran the simulation (e.g. 'mojo-native-expr', 'lhs', 'mcmc')"},"simulation_class":{"type":"string","title":"Simulation Class","description":"High-level simulation contract class. Examples: predictive, scenario_analysis, sensitivity_analysis, decision_tree.","default":"predictive"},"model_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Revision","description":"Stable engine or model revision used to generate this result."},"assumptions_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assumptions Hash","description":"Stable fingerprint of the validated simulation assumptions executed by the engine."},"validated_inputs":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Validated Inputs","description":"Normalized summary of the validated request inputs used for execution. Includes mode, runs, variable counts, and model selection."},"confidence_interval":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Confidence Interval","description":"Primary outcome confidence interval derived from the simulated distribution."},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Correlation identifier propagated from the API request."},"scenario_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Scenario Analysis","description":"Populated for simulation_model='scenario': expected_value, best_case, scenarios list"},"sensitivity_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Sensitivity Analysis","description":"Populated for simulation_model='sensitivity': tornado_chart, first_order_sobol, variable_importance"},"bootstrap_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Bootstrap Result","description":"Populated for simulation_model='bootstrap': statistic, observed_value, CI, bias, SE"},"mcmc_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Mcmc Result","description":"Populated for simulation_model='mcmc': posterior summaries, R-hat, acceptance_rate"},"importance_sampling_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Importance Sampling Result","description":"Populated for simulation_model='importance_sampling'. Contains: tail_direction, target_threshold, tail_probability, tail_probability_se, cvar_tail, weighted_mean, weighted_std, theta (tilt parameter), tilt_variable, effective_sample_size, nominal_sample_size, variance_reduction_factor, naive_tail_count."},"scenario_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Scenario Ranking"},"sensitivity_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Sensitivity Ranking"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score"},"score_breakdown":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Score Breakdown"},"created_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Created At"},"decision_tree_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Decision Tree Result","description":"Populated for simulation_model='decision_tree': n_paths, expected_value, paths[]"},"time_series_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Time Series Result","description":"Populated for simulation_model='time_series'. Contains: model, granularity, dt_years, initial_value, n_steps, fan_chart (per-horizon p5/p25/p50/p75/p95), terminal distribution, max_drawdown_pct, and optional sample_paths for visualization."},"formatted_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Formatted Result","description":"Human-readable formatted output values with units. Populated when output_unit_specs or unit_spec is provided. Contains: mean_formatted, p5_formatted, p95_formatted, unit, unit_type, etc."},"unit_context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Unit Context","description":"Unit metadata for all variables and outputs. Contains per-variable unit type, code, precision, and display scale. Use this to reconstruct formatted values client-side."},"unit_warnings":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Unit Warnings","description":"Non-fatal unit validation warnings (e.g. negative currency, out-of-range probability). Simulation still ran — these are advisory only."},"charts":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Charts","description":"Pre-computed Vega-Lite compatible chart specs for instant rendering. Populated when include_charts=true in the request or automatically for sensitivity/time_series engine types. Keys: 'histogram', 'cdf', 'tornado', 'fan_chart', 'scatter'. Each value is a complete Vega-Lite spec that can be passed to vega-embed."},"histogram_data":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Histogram Data","description":"Pre-computed histogram bins (50 bins) for the primary output distribution."},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary. Always populated by /v1/simulate and /v1/recommend. Contains: recommended_action, confidence, expected_value, risk (p5/p95/PoL), all ranked options, rationale, and integrity hashes."},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash","description":"SHA-256 fingerprint of the INPUT payload (variables, distributions, objective function, seed). Cryptographic proof of what data was used to make this decision. Computed at submission time before simulation runs. Format: hex string, 64 chars."},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash","description":"SHA-256 fingerprint of this decision OUTPUT (64-char hex). Covers: run_id, request_hash (input binding), recommended_action, confidence, rationale, metrics, percentiles, scenarios_run, engine_version, simulation_model. Binds the decision to both its inputs AND outputs. Use to verify the decision has not been tampered with. Also returned as X-Decision-Hash response header."}},"type":"object","required":["run_id","engine_version","recommended_action","confidence","rationale","metrics","percentiles","scenarios_run","execution_ms","metadata"],"title":"DecisionEnvelope","description":"Full decision output returned by /v1/simulate, /v1/recommend, and /v1/score."},"MetricsSummary":{"properties":{"expected_value":{"type":"number","title":"Expected Value"},"median":{"type":"number","title":"Median"},"std_deviation":{"type":"number","title":"Std Deviation"},"variance":{"type":"number","title":"Variance"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95"},"cvar_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cvar 95"}},"type":"object","required":["expected_value","median","std_deviation","variance","probability_of_loss"],"title":"MetricsSummary"},"PercentileSummary":{"properties":{"p5":{"type":"number","title":"P5"},"p10":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P10"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p90":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P90"},"p95":{"type":"number","title":"P95"},"p99":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P99"}},"type":"object","required":["p5","p25","p50","p75","p95"],"title":"PercentileSummary"},"RunMetadata":{"properties":{"mode":{"type":"string","title":"Mode"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"billing_units":{"type":"integer","title":"Billing Units"},"engine_version":{"type":"string","title":"Engine Version"}},"type":"object","required":["mode","billing_units","engine_version"],"title":"RunMetadata"},"DecisionPlan":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"options":{"items":{"$ref":"#/components/schemas/DecisionOption"},"type":"array","title":"Options","description":"All alternatives ranked by expected value. Single-element for simulate, multi for recommend."},"rationale":{"type":"string","title":"Rationale"},"integrity":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Integrity","description":"Cryptographic proof of inputs/outputs: {request_hash, result_hash}."},"calibration":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Calibration","description":"Human-readable calibration summary, e.g. '12 outcomes | bias=-8.3% (over-optimistic) | hit_rate=75%'. Null until MIN_SAMPLES (5) outcomes are recorded for this org."}},"type":"object","required":["recommended_action","confidence","expected_value","risk","rationale"],"title":"DecisionPlan","description":"Structured, LLM-readable summary of the decision output.\n\nThis is the headline object — it surfaces all decision-critical fields\nin a compact, consistent shape regardless of simulation model used.\nPopulate ``options`` with all ranked alternatives when using /v1/recommend."},"RiskProfile":{"properties":{"p5":{"type":"number","title":"P5","description":"5th-percentile outcome (downside risk floor)"},"p95":{"type":"number","title":"P95","description":"95th-percentile outcome (upside ceiling)"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss","description":"P(outcome < 0)"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95","description":"Value-at-Risk at 95% confidence"}},"type":"object","required":["p5","p95","probability_of_loss"],"title":"RiskProfile","description":"Quantified downside and upside for a single outcome distribution."},"DecisionOption":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","minimum":1,"title":"Rank"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score","description":"Composite score (0–1)"}},"type":"object","required":["name","rank","expected_value","risk"],"title":"DecisionOption","description":"One named alternative in a multi-option decision comparison."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/batch":{"post":{"tags":["Decision"],"summary":"Run multiple simulations in one request","description":"Submit 1–100 simulation requests. Partial failures are allowed; failed items include an error message.","operationId":"batch_v1_batch_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/BatchResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/compare`

## Side-by-side scenario comparison

> Run and compare 2–10 named scenarios. Returns full results with deltas versus the winning scenario.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"CompareRequest":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/NamedScenario"},"type":"array","maxItems":10,"minItems":2,"title":"Scenarios"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"}},"type":"object","required":["scenarios"],"title":"CompareRequest","description":"Request body for /v1/compare."},"NamedScenario":{"properties":{"name":{"type":"string","maxLength":200,"minLength":1,"title":"Name"},"request":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Request","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}}},"type":"object","required":["name","request"],"title":"NamedScenario","description":"A named scenario for side-by-side comparison."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"CompareResponse":{"properties":{"winner":{"type":"string","title":"Winner"},"margin":{"$ref":"#/components/schemas/ComparisonDelta"},"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioComparison"},"type":"array","title":"Scenarios"}},"type":"object","required":["winner","margin","scenarios"],"title":"CompareResponse","description":"Response from /v1/compare."},"ComparisonDelta":{"properties":{"expected_value_delta":{"type":"number","title":"Expected Value Delta"},"probability_of_loss_delta":{"type":"number","title":"Probability Of Loss Delta"},"score_delta":{"type":"number","title":"Score Delta"}},"type":"object","required":["expected_value_delta","probability_of_loss_delta","score_delta"],"title":"ComparisonDelta","description":"Delta between a scenario and the best scenario."},"ScenarioComparison":{"properties":{"name":{"type":"string","title":"Name"},"envelope":{"$ref":"#/components/schemas/DecisionEnvelope"},"delta_vs_best":{"$ref":"#/components/schemas/ComparisonDelta"}},"type":"object","required":["name","envelope","delta_vs_best"],"title":"ScenarioComparison","description":"One scenario in the comparison table."},"DecisionEnvelope":{"properties":{"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status","default":"completed"},"engine_version":{"type":"string","title":"Engine Version"},"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"metrics":{"$ref":"#/components/schemas/MetricsSummary"},"percentiles":{"$ref":"#/components/schemas/PercentileSummary"},"scenarios_run":{"type":"integer","title":"Scenarios Run"},"execution_ms":{"type":"integer","title":"Execution Ms"},"metadata":{"$ref":"#/components/schemas/RunMetadata"},"simulation_model":{"type":"string","title":"Simulation Model","description":"Which simulation algorithm was used. Possible values: monte_carlo | qmc_sobol | lhs | bootstrap | scenario | sensitivity | mcmc | decision_tree | time_series | compare | importance_sampling","default":"monte_carlo"},"engine_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Type","description":"Engine that ran the simulation (e.g. 'mojo-native-expr', 'lhs', 'mcmc')"},"simulation_class":{"type":"string","title":"Simulation Class","description":"High-level simulation contract class. Examples: predictive, scenario_analysis, sensitivity_analysis, decision_tree.","default":"predictive"},"model_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Revision","description":"Stable engine or model revision used to generate this result."},"assumptions_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assumptions Hash","description":"Stable fingerprint of the validated simulation assumptions executed by the engine."},"validated_inputs":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Validated Inputs","description":"Normalized summary of the validated request inputs used for execution. Includes mode, runs, variable counts, and model selection."},"confidence_interval":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Confidence Interval","description":"Primary outcome confidence interval derived from the simulated distribution."},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Correlation identifier propagated from the API request."},"scenario_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Scenario Analysis","description":"Populated for simulation_model='scenario': expected_value, best_case, scenarios list"},"sensitivity_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Sensitivity Analysis","description":"Populated for simulation_model='sensitivity': tornado_chart, first_order_sobol, variable_importance"},"bootstrap_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Bootstrap Result","description":"Populated for simulation_model='bootstrap': statistic, observed_value, CI, bias, SE"},"mcmc_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Mcmc Result","description":"Populated for simulation_model='mcmc': posterior summaries, R-hat, acceptance_rate"},"importance_sampling_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Importance Sampling Result","description":"Populated for simulation_model='importance_sampling'. Contains: tail_direction, target_threshold, tail_probability, tail_probability_se, cvar_tail, weighted_mean, weighted_std, theta (tilt parameter), tilt_variable, effective_sample_size, nominal_sample_size, variance_reduction_factor, naive_tail_count."},"scenario_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Scenario Ranking"},"sensitivity_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Sensitivity Ranking"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score"},"score_breakdown":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Score Breakdown"},"created_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Created At"},"decision_tree_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Decision Tree Result","description":"Populated for simulation_model='decision_tree': n_paths, expected_value, paths[]"},"time_series_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Time Series Result","description":"Populated for simulation_model='time_series'. Contains: model, granularity, dt_years, initial_value, n_steps, fan_chart (per-horizon p5/p25/p50/p75/p95), terminal distribution, max_drawdown_pct, and optional sample_paths for visualization."},"formatted_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Formatted Result","description":"Human-readable formatted output values with units. Populated when output_unit_specs or unit_spec is provided. Contains: mean_formatted, p5_formatted, p95_formatted, unit, unit_type, etc."},"unit_context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Unit Context","description":"Unit metadata for all variables and outputs. Contains per-variable unit type, code, precision, and display scale. Use this to reconstruct formatted values client-side."},"unit_warnings":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Unit Warnings","description":"Non-fatal unit validation warnings (e.g. negative currency, out-of-range probability). Simulation still ran — these are advisory only."},"charts":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Charts","description":"Pre-computed Vega-Lite compatible chart specs for instant rendering. Populated when include_charts=true in the request or automatically for sensitivity/time_series engine types. Keys: 'histogram', 'cdf', 'tornado', 'fan_chart', 'scatter'. Each value is a complete Vega-Lite spec that can be passed to vega-embed."},"histogram_data":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Histogram Data","description":"Pre-computed histogram bins (50 bins) for the primary output distribution."},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary. Always populated by /v1/simulate and /v1/recommend. Contains: recommended_action, confidence, expected_value, risk (p5/p95/PoL), all ranked options, rationale, and integrity hashes."},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash","description":"SHA-256 fingerprint of the INPUT payload (variables, distributions, objective function, seed). Cryptographic proof of what data was used to make this decision. Computed at submission time before simulation runs. Format: hex string, 64 chars."},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash","description":"SHA-256 fingerprint of this decision OUTPUT (64-char hex). Covers: run_id, request_hash (input binding), recommended_action, confidence, rationale, metrics, percentiles, scenarios_run, engine_version, simulation_model. Binds the decision to both its inputs AND outputs. Use to verify the decision has not been tampered with. Also returned as X-Decision-Hash response header."}},"type":"object","required":["run_id","engine_version","recommended_action","confidence","rationale","metrics","percentiles","scenarios_run","execution_ms","metadata"],"title":"DecisionEnvelope","description":"Full decision output returned by /v1/simulate, /v1/recommend, and /v1/score."},"MetricsSummary":{"properties":{"expected_value":{"type":"number","title":"Expected Value"},"median":{"type":"number","title":"Median"},"std_deviation":{"type":"number","title":"Std Deviation"},"variance":{"type":"number","title":"Variance"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95"},"cvar_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cvar 95"}},"type":"object","required":["expected_value","median","std_deviation","variance","probability_of_loss"],"title":"MetricsSummary"},"PercentileSummary":{"properties":{"p5":{"type":"number","title":"P5"},"p10":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P10"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p90":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P90"},"p95":{"type":"number","title":"P95"},"p99":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P99"}},"type":"object","required":["p5","p25","p50","p75","p95"],"title":"PercentileSummary"},"RunMetadata":{"properties":{"mode":{"type":"string","title":"Mode"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"billing_units":{"type":"integer","title":"Billing Units"},"engine_version":{"type":"string","title":"Engine Version"}},"type":"object","required":["mode","billing_units","engine_version"],"title":"RunMetadata"},"DecisionPlan":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"options":{"items":{"$ref":"#/components/schemas/DecisionOption"},"type":"array","title":"Options","description":"All alternatives ranked by expected value. Single-element for simulate, multi for recommend."},"rationale":{"type":"string","title":"Rationale"},"integrity":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Integrity","description":"Cryptographic proof of inputs/outputs: {request_hash, result_hash}."},"calibration":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Calibration","description":"Human-readable calibration summary, e.g. '12 outcomes | bias=-8.3% (over-optimistic) | hit_rate=75%'. Null until MIN_SAMPLES (5) outcomes are recorded for this org."}},"type":"object","required":["recommended_action","confidence","expected_value","risk","rationale"],"title":"DecisionPlan","description":"Structured, LLM-readable summary of the decision output.\n\nThis is the headline object — it surfaces all decision-critical fields\nin a compact, consistent shape regardless of simulation model used.\nPopulate ``options`` with all ranked alternatives when using /v1/recommend."},"RiskProfile":{"properties":{"p5":{"type":"number","title":"P5","description":"5th-percentile outcome (downside risk floor)"},"p95":{"type":"number","title":"P95","description":"95th-percentile outcome (upside ceiling)"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss","description":"P(outcome < 0)"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95","description":"Value-at-Risk at 95% confidence"}},"type":"object","required":["p5","p95","probability_of_loss"],"title":"RiskProfile","description":"Quantified downside and upside for a single outcome distribution."},"DecisionOption":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","minimum":1,"title":"Rank"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score","description":"Composite score (0–1)"}},"type":"object","required":["name","rank","expected_value","risk"],"title":"DecisionOption","description":"One named alternative in a multi-option decision comparison."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/compare":{"post":{"tags":["Decision"],"summary":"Side-by-side scenario comparison","description":"Run and compare 2–10 named scenarios. Returns full results with deltas versus the winning scenario.","operationId":"compare_v1_compare_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompareRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompareResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Decision Memory

### `POST /v1/decisions`

## Log a decision

> Record a decision that was made. Link it to a simulation run\_id to bind the full DecisionPlan context. Call PATCH /outcome later to close the loop.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"LogDecisionRequest":{"properties":{"run_id":{"anyOf":[{"type":"string","format":"uuid"},{"type":"null"}],"title":"Run Id","description":"ID of the simulation run that produced this decision (links DecisionPlan -> DecisionLog)."},"context":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}],"title":"Context","description":"Free-text description of the business situation when this decision was made."},"chosen_action":{"type":"string","maxLength":200,"title":"Chosen Action","description":"The action that was chosen."},"options_considered":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Options Considered","description":"All option names that were evaluated before choosing."},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Confidence"},"rationale":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}],"title":"Rationale"},"risk_p5":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P5"},"risk_p95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P95"},"risk_pol":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Risk Pol","description":"Probability of loss at decision time"},"request_hash":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}],"title":"Request Hash"},"result_hash":{"anyOf":[{"type":"string","maxLength":64},{"type":"null"}],"title":"Result Hash"}},"type":"object","required":["chosen_action"],"title":"LogDecisionRequest","description":"Body for POST /v1/decisions — log a decision that was made."},"DecisionLogResponse":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"run_id":{"anyOf":[{"type":"string","format":"uuid"},{"type":"null"}],"title":"Run Id"},"context":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Context"},"chosen_action":{"type":"string","title":"Chosen Action"},"options_considered":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Options Considered"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"},"risk_p5":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P5"},"risk_p95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P95"},"risk_pol":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Pol"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"actual_outcome":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Actual Outcome"},"outcome_delta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Outcome Delta"},"outcome_notes":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Outcome Notes"},"outcome_recorded_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Outcome Recorded At"},"executed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Executed At"},"execution_status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Status"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"execution_response_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Execution Response Code"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"updated_at":{"type":"string","format":"date-time","title":"Updated At"}},"type":"object","required":["id","org_id","run_id","context","chosen_action","options_considered","expected_value","confidence","rationale","risk_p5","risk_p95","risk_pol","request_hash","result_hash","actual_outcome","outcome_delta","outcome_notes","outcome_recorded_at","executed_at","execution_status","execution_webhook_url","execution_response_code","created_at","updated_at"],"title":"DecisionLogResponse","description":"Single decision log entry."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions":{"post":{"tags":["Decision Memory"],"summary":"Log a decision","description":"Record a decision that was made. Link it to a simulation run_id to bind the full DecisionPlan context. Call PATCH /outcome later to close the loop.","operationId":"log_decision_v1_decisions_post","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LogDecisionRequest"}}}},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionLogResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/decisions`

## List logged decisions

> Returns the org's decision history, most recent first. Supports pagination.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DecisionListResponse":{"properties":{"decisions":{"items":{"$ref":"#/components/schemas/DecisionLogResponse"},"type":"array","title":"Decisions"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"},"page_size":{"type":"integer","title":"Page Size"}},"type":"object","required":["decisions","total","page","limit","pages","page_size"],"title":"DecisionListResponse"},"DecisionLogResponse":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"run_id":{"anyOf":[{"type":"string","format":"uuid"},{"type":"null"}],"title":"Run Id"},"context":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Context"},"chosen_action":{"type":"string","title":"Chosen Action"},"options_considered":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Options Considered"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"},"risk_p5":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P5"},"risk_p95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P95"},"risk_pol":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Pol"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"actual_outcome":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Actual Outcome"},"outcome_delta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Outcome Delta"},"outcome_notes":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Outcome Notes"},"outcome_recorded_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Outcome Recorded At"},"executed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Executed At"},"execution_status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Status"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"execution_response_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Execution Response Code"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"updated_at":{"type":"string","format":"date-time","title":"Updated At"}},"type":"object","required":["id","org_id","run_id","context","chosen_action","options_considered","expected_value","confidence","rationale","risk_p5","risk_p95","risk_pol","request_hash","result_hash","actual_outcome","outcome_delta","outcome_notes","outcome_recorded_at","executed_at","execution_status","execution_webhook_url","execution_response_code","created_at","updated_at"],"title":"DecisionLogResponse","description":"Single decision log entry."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions":{"get":{"tags":["Decision Memory"],"summary":"List logged decisions","description":"Returns the org's decision history, most recent first. Supports pagination.","operationId":"list_decisions_v1_decisions_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}},{"name":"page_size","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"description":"Legacy compatibility alias for limit.","title":"Page Size"},"description":"Legacy compatibility alias for limit."},{"name":"with_outcome_only","in":"query","required":false,"schema":{"type":"boolean","description":"When true, return only decisions where actual_outcome has been recorded.","default":false,"title":"With Outcome Only"},"description":"When true, return only decisions where actual_outcome has been recorded."}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionListResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/decisions/{decision_id}`

## GET /v1/decisions/{decision\_id}

> Get a single decision

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DecisionLogResponse":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"run_id":{"anyOf":[{"type":"string","format":"uuid"},{"type":"null"}],"title":"Run Id"},"context":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Context"},"chosen_action":{"type":"string","title":"Chosen Action"},"options_considered":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Options Considered"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"},"risk_p5":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P5"},"risk_p95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P95"},"risk_pol":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Pol"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"actual_outcome":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Actual Outcome"},"outcome_delta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Outcome Delta"},"outcome_notes":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Outcome Notes"},"outcome_recorded_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Outcome Recorded At"},"executed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Executed At"},"execution_status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Status"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"execution_response_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Execution Response Code"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"updated_at":{"type":"string","format":"date-time","title":"Updated At"}},"type":"object","required":["id","org_id","run_id","context","chosen_action","options_considered","expected_value","confidence","rationale","risk_p5","risk_p95","risk_pol","request_hash","result_hash","actual_outcome","outcome_delta","outcome_notes","outcome_recorded_at","executed_at","execution_status","execution_webhook_url","execution_response_code","created_at","updated_at"],"title":"DecisionLogResponse","description":"Single decision log entry."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions/{decision_id}":{"get":{"tags":["Decision Memory"],"summary":"Get a single decision","operationId":"get_decision_v1_decisions__decision_id__get","parameters":[{"name":"decision_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Decision Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionLogResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/decisions/{decision_id}`

## DELETE /v1/decisions/{decision\_id}

> Delete a decision log entry

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions/{decision_id}":{"delete":{"tags":["Decision Memory"],"summary":"Delete a decision log entry","operationId":"delete_decision_v1_decisions__decision_id__delete","parameters":[{"name":"decision_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Decision Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `PATCH /v1/decisions/{decision_id}/outcome`

## Record actual outcome

> Close the feedback loop: record what actually happened after the decision was made. Sets actual\_outcome, computes outcome\_delta = actual - expected, and timestamps the recording.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RecordOutcomeRequest":{"properties":{"actual_outcome":{"type":"number","title":"Actual Outcome","description":"Observed outcome value (e.g. actual monthly revenue)."},"outcome_notes":{"anyOf":[{"type":"string","maxLength":2000},{"type":"null"}],"title":"Outcome Notes"}},"type":"object","required":["actual_outcome"],"title":"RecordOutcomeRequest","description":"Body for PATCH /v1/decisions/{id}/outcome — close the feedback loop."},"DecisionLogResponse":{"properties":{"id":{"type":"string","format":"uuid","title":"Id"},"org_id":{"type":"string","format":"uuid","title":"Org Id"},"run_id":{"anyOf":[{"type":"string","format":"uuid"},{"type":"null"}],"title":"Run Id"},"context":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Context"},"chosen_action":{"type":"string","title":"Chosen Action"},"options_considered":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Options Considered"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"},"risk_p5":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P5"},"risk_p95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk P95"},"risk_pol":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Pol"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"actual_outcome":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Actual Outcome"},"outcome_delta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Outcome Delta"},"outcome_notes":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Outcome Notes"},"outcome_recorded_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Outcome Recorded At"},"executed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Executed At"},"execution_status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Status"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"execution_response_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Execution Response Code"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"updated_at":{"type":"string","format":"date-time","title":"Updated At"}},"type":"object","required":["id","org_id","run_id","context","chosen_action","options_considered","expected_value","confidence","rationale","risk_p5","risk_p95","risk_pol","request_hash","result_hash","actual_outcome","outcome_delta","outcome_notes","outcome_recorded_at","executed_at","execution_status","execution_webhook_url","execution_response_code","created_at","updated_at"],"title":"DecisionLogResponse","description":"Single decision log entry."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions/{decision_id}/outcome":{"patch":{"tags":["Decision Memory"],"summary":"Record actual outcome","description":"Close the feedback loop: record what actually happened after the decision was made. Sets actual_outcome, computes outcome_delta = actual - expected, and timestamps the recording.","operationId":"record_outcome_v1_decisions__decision_id__outcome_patch","parameters":[{"name":"decision_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Decision Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RecordOutcomeRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionLogResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/decisions/{decision_id}/execute`

## Execute a decision via webhook

> Fire the decision to an external webhook URL, turning the logged decision into an automated action. The webhook receives the full decision context (chosen action, expected value, confidence, risk profile, integrity hashes). Execution status and the HTTP response code are persisted back to the decision log for full audit trail. Re-execution is allowed — each call overwrites the prior receipt.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ExecuteDecisionRequest":{"properties":{"webhook_url":{"type":"string","maxLength":2048,"title":"Webhook Url","description":"HTTPS endpoint that will receive and act on this decision."},"timeout_seconds":{"type":"number","maximum":60,"minimum":1,"title":"Timeout Seconds","description":"Webhook request timeout in seconds.","default":10},"force":{"type":"boolean","title":"Force","description":"Override the idempotency gate. Pass true to re-execute a decision that was already delivered. Does NOT override confidence or risk_floor gates.","default":false},"override_safety":{"type":"boolean","title":"Override Safety","description":"Bypass confidence and risk_floor policy gates for this single execution. Requires explicit intent. Logs the override for audit.","default":false},"metadata":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Metadata","description":"Optional extra key-value pairs merged into the webhook payload."}},"type":"object","required":["webhook_url"],"title":"ExecuteDecisionRequest","description":"Body for POST /v1/decisions/{id}/execute — fire the decision to a webhook."},"ExecutionReceipt":{"properties":{"decision_id":{"type":"string","format":"uuid","title":"Decision Id"},"webhook_url":{"type":"string","title":"Webhook Url"},"execution_status":{"type":"string","title":"Execution Status"},"response_code":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Response Code"},"executed_at":{"type":"string","format":"date-time","title":"Executed At"},"payload_summary":{"type":"object","title":"Payload Summary"},"safety_overridden":{"type":"boolean","title":"Safety Overridden","default":false}},"type":"object","required":["decision_id","webhook_url","execution_status","response_code","executed_at","payload_summary"],"title":"ExecutionReceipt","description":"Returned by POST /v1/decisions/{id}/execute."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decisions/{decision_id}/execute":{"post":{"tags":["Decision Memory"],"summary":"Execute a decision via webhook","description":"Fire the decision to an external webhook URL, turning the logged decision into an automated action. The webhook receives the full decision context (chosen action, expected value, confidence, risk profile, integrity hashes). Execution status and the HTTP response code are persisted back to the decision log for full audit trail. Re-execution is allowed — each call overwrites the prior receipt.","operationId":"execute_decision_v1_decisions__decision_id__execute_post","parameters":[{"name":"decision_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Decision Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecuteDecisionRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecutionReceipt"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Deployments

### `GET /v1/deployments/regions`

## List available cloud providers and regions

> Returns all available cloud providers and their supported regions.\
> Regions are fetched live from cloud SDKs when credentials are available,\
> otherwise returns a comprehensive static fallback list.\
> Use the region \`id\` field when creating a deployment.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/deployments/regions":{"get":{"tags":["Deployments"],"summary":"List available cloud providers and regions","description":"Returns all available cloud providers and their supported regions.\nRegions are fetched live from cloud SDKs when credentials are available,\notherwise returns a comprehensive static fallback list.\nUse the region `id` field when creating a deployment.","operationId":"list_regions_v1_deployments_regions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response List Regions V1 Deployments Regions Get"}}}}}}}}}
```

### `GET /v1/deployments`

## Get current org deployment

> Return the active deployment for this org, or None if using shared pool.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DeploymentResponse":{"properties":{"deployment_id":{"type":"string","title":"Deployment Id"},"org_id":{"type":"string","title":"Org Id"},"provider":{"type":"string","title":"Provider"},"region":{"type":"string","title":"Region"},"status":{"type":"string","title":"Status"},"endpoint_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Endpoint Url"},"cost_usd_month":{"type":"number","title":"Cost Usd Month"},"billable_cost_usd_month":{"type":"number","title":"Billable Cost Usd Month"},"billing_markup_pct":{"type":"number","title":"Billing Markup Pct"},"created_at":{"type":"string","title":"Created At"},"provisioned_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Provisioned At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"}},"type":"object","required":["deployment_id","org_id","provider","region","status","endpoint_url","cost_usd_month","billable_cost_usd_month","billing_markup_pct","created_at","provisioned_at","error_message"],"title":"DeploymentResponse"}}},"paths":{"/v1/deployments":{"get":{"tags":["Deployments"],"summary":"Get current org deployment","description":"Return the active deployment for this org, or None if using shared pool.","operationId":"get_deployment_v1_deployments_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"$ref":"#/components/schemas/DeploymentResponse"},{"type":"null"}],"title":"Response Get Deployment V1 Deployments Get"}}}}}}}}}
```

### `POST /v1/deployments`

## Request a new cloud deployment

> Provision an isolated engine deployment on your chosen cloud provider and region. Returns 202 Accepted immediately — provisioning is async (typically 3-5 minutes). Poll GET /v1/deployments to check status. When status=active, all API calls are automatically routed to your isolated deployment. Requires owner role.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DeploymentCreate":{"properties":{"provider":{"type":"string","title":"Provider","description":"Cloud provider: algenta_shared, aws, azure, gcp","default":"algenta_shared"},"region":{"type":"string","title":"Region","description":"Cloud region identifier. Use /v1/deployments/regions to list options.","default":"algenta-shared"},"config":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Config","description":"Optional provider-specific configuration. Supported keys: instance_size (e.g. 'small'|'medium'|'large'), storage_gb, max_concurrent_runs, auto_scale_max."},"billing_markup_pct":{"type":"number","maximum":200,"minimum":0,"title":"Billing Markup Pct","description":"Pass-through cost markup percentage. Default: 20%.","default":20}},"type":"object","title":"DeploymentCreate"},"DeploymentResponse":{"properties":{"deployment_id":{"type":"string","title":"Deployment Id"},"org_id":{"type":"string","title":"Org Id"},"provider":{"type":"string","title":"Provider"},"region":{"type":"string","title":"Region"},"status":{"type":"string","title":"Status"},"endpoint_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Endpoint Url"},"cost_usd_month":{"type":"number","title":"Cost Usd Month"},"billable_cost_usd_month":{"type":"number","title":"Billable Cost Usd Month"},"billing_markup_pct":{"type":"number","title":"Billing Markup Pct"},"created_at":{"type":"string","title":"Created At"},"provisioned_at":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Provisioned At"},"error_message":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Error Message"}},"type":"object","required":["deployment_id","org_id","provider","region","status","endpoint_url","cost_usd_month","billable_cost_usd_month","billing_markup_pct","created_at","provisioned_at","error_message"],"title":"DeploymentResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/deployments":{"post":{"tags":["Deployments"],"summary":"Request a new cloud deployment","description":"Provision an isolated engine deployment on your chosen cloud provider and region. Returns 202 Accepted immediately — provisioning is async (typically 3-5 minutes). Poll GET /v1/deployments to check status. When status=active, all API calls are automatically routed to your isolated deployment. Requires owner role.","operationId":"create_deployment_v1_deployments_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeploymentCreate"}}},"required":true},"responses":{"202":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeploymentResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/deployments/{deployment_id}`

## Deprovision a deployment

> Tear down cloud resources for a deployment. Org will revert to shared pool. Requires owner role.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/deployments/{deployment_id}":{"delete":{"tags":["Deployments"],"summary":"Deprovision a deployment","description":"Tear down cloud resources for a deployment. Org will revert to shared pool. Requires owner role.","operationId":"delete_deployment_v1_deployments__deployment_id__delete","parameters":[{"name":"deployment_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Deployment Id"}}],"responses":{"202":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","additionalProperties":{"type":"string"},"title":"Response Delete Deployment V1 Deployments  Deployment Id  Delete"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/deployments/{deployment_id}/cost`

## GET /v1/deployments/{deployment\_id}/cost

> Get current month cloud cost for a deployment

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/deployments/{deployment_id}/cost":{"get":{"tags":["Deployments"],"summary":"Get current month cloud cost for a deployment","operationId":"get_deployment_cost_v1_deployments__deployment_id__cost_get","parameters":[{"name":"deployment_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Deployment Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Deployment Cost V1 Deployments  Deployment Id  Cost Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Engines

### `GET /v1/engines`

## List all engines

> Return the full Codna OS engine catalogue.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/engines":{"get":{"tags":["Engines"],"summary":"List all engines","description":"Return the full Codna OS engine catalogue.","operationId":"list_engines_v1_engines_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":200,"minimum":1,"default":25,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EngineListResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"EngineListResponse":{"properties":{"count":{"type":"integer","title":"Count"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"},"engines":{"items":{"$ref":"#/components/schemas/EngineResponse"},"type":"array","title":"Engines"}},"type":"object","required":["count","total","page","limit","pages","engines"],"title":"EngineListResponse"},"EngineResponse":{"properties":{"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"description":{"type":"string","title":"Description"},"api_path":{"type":"string","title":"Api Path"},"mojo_libs":{"items":{"type":"string"},"type":"array","title":"Mojo Libs"},"use_cases":{"items":{"type":"string"},"type":"array","title":"Use Cases"},"tier":{"type":"string","title":"Tier"}},"type":"object","required":["name","slug","description","api_path","mojo_libs","use_cases","tier"],"title":"EngineResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

### `GET /v1/engines/tiers`

## Engines by tier

> Return engines grouped by tier: core / advanced / platform.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/engines/tiers":{"get":{"tags":["Engines"],"summary":"Engines by tier","description":"Return engines grouped by tier: core / advanced / platform.","operationId":"engines_by_tier_v1_engines_tiers_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EngineTierResponse"}}}}}}}},"components":{"schemas":{"EngineTierResponse":{"properties":{"core":{"items":{"$ref":"#/components/schemas/EngineResponse"},"type":"array","title":"Core"},"advanced":{"items":{"$ref":"#/components/schemas/EngineResponse"},"type":"array","title":"Advanced"},"platform":{"items":{"$ref":"#/components/schemas/EngineResponse"},"type":"array","title":"Platform"}},"type":"object","required":["core","advanced","platform"],"title":"EngineTierResponse"},"EngineResponse":{"properties":{"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"description":{"type":"string","title":"Description"},"api_path":{"type":"string","title":"Api Path"},"mojo_libs":{"items":{"type":"string"},"type":"array","title":"Mojo Libs"},"use_cases":{"items":{"type":"string"},"type":"array","title":"Use Cases"},"tier":{"type":"string","title":"Tier"}},"type":"object","required":["name","slug","description","api_path","mojo_libs","use_cases","tier"],"title":"EngineResponse"}}}}
```

### `GET /v1/engines/{slug}`

## Engine detail

> Return detail for a single engine by slug.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/engines/{slug}":{"get":{"tags":["Engines"],"summary":"Engine detail","description":"Return detail for a single engine by slug.","operationId":"get_engine_v1_engines__slug__get","parameters":[{"name":"slug","in":"path","required":true,"schema":{"type":"string","title":"Slug"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/EngineResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"EngineResponse":{"properties":{"name":{"type":"string","title":"Name"},"slug":{"type":"string","title":"Slug"},"description":{"type":"string","title":"Description"},"api_path":{"type":"string","title":"Api Path"},"mojo_libs":{"items":{"type":"string"},"type":"array","title":"Mojo Libs"},"use_cases":{"items":{"type":"string"},"type":"array","title":"Use Cases"},"tier":{"type":"string","title":"Tier"}},"type":"object","required":["name","slug","description","api_path","mojo_libs","use_cases","tier"],"title":"EngineResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

## Execution Policy

### `GET /v1/execution/policy`

## Get execution policy

> Returns the org's current autonomous execution safety policy. Gates applied to every POST /v1/decisions/{id}/execute call and trigger auto\_execute:\
> \
> \- \*\*min\_confidence\*\*: decisions below this confidence are blocked\
> \- \*\*risk\_floor\*\*: decisions where worst-case (p5) exceeds this loss are blocked\
> \- \*\*require\_calibration\*\*: auto\_execute waits for ≥5 recorded outcomes\
> \- \*\*allow\_reexecution\*\*: idempotency — prevents double-actions\
> \
> All gates can be bypassed individually: \`force=true\` (idempotency) or \`override\_safety=true\` (confidence + risk\_floor).

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ExecutionPolicyResponse":{"properties":{"org_id":{"type":"string","title":"Org Id"},"min_confidence":{"type":"number","title":"Min Confidence"},"risk_floor":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Floor"},"require_calibration":{"type":"boolean","title":"Require Calibration"},"allow_reexecution":{"type":"boolean","title":"Allow Reexecution"},"updated_at":{"type":"string","title":"Updated At"}},"type":"object","required":["org_id","min_confidence","risk_floor","require_calibration","allow_reexecution","updated_at"],"title":"ExecutionPolicyResponse","description":"Current execution policy for the calling org."}}},"paths":{"/v1/execution/policy":{"get":{"tags":["Execution Policy"],"summary":"Get execution policy","description":"Returns the org's current autonomous execution safety policy. Gates applied to every POST /v1/decisions/{id}/execute call and trigger auto_execute:\n\n- **min_confidence**: decisions below this confidence are blocked\n- **risk_floor**: decisions where worst-case (p5) exceeds this loss are blocked\n- **require_calibration**: auto_execute waits for ≥5 recorded outcomes\n- **allow_reexecution**: idempotency — prevents double-actions\n\nAll gates can be bypassed individually: `force=true` (idempotency) or `override_safety=true` (confidence + risk_floor).","operationId":"get_execution_policy_v1_execution_policy_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecutionPolicyResponse"}}}}}}}}}
```

### `PATCH /v1/execution/policy`

## Update execution policy

> Partial update — only supplied fields are changed. Changes take effect immediately for all subsequent executions. Audit logs record every update.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"UpdatePolicyRequest":{"properties":{"min_confidence":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Min Confidence","description":"Minimum confidence to allow execution (0–1). Default: 0.5."},"risk_floor":{"anyOf":[{"type":"number","minimum":0},{"type":"null"}],"title":"Risk Floor","description":"Maximum tolerable downside loss (absolute). If p5 < -risk_floor the execution is blocked. Set to null to disable the check."},"require_calibration":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Require Calibration","description":"When true, trigger auto_execute is disabled until the org has ≥5 recorded outcomes. Manual execution is always allowed."},"allow_reexecution":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Allow Reexecution","description":"When true, already-executed decisions can fire again without force=true."}},"type":"object","title":"UpdatePolicyRequest","description":"Partial update — only supplied fields are changed."},"ExecutionPolicyResponse":{"properties":{"org_id":{"type":"string","title":"Org Id"},"min_confidence":{"type":"number","title":"Min Confidence"},"risk_floor":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Risk Floor"},"require_calibration":{"type":"boolean","title":"Require Calibration"},"allow_reexecution":{"type":"boolean","title":"Allow Reexecution"},"updated_at":{"type":"string","title":"Updated At"}},"type":"object","required":["org_id","min_confidence","risk_floor","require_calibration","allow_reexecution","updated_at"],"title":"ExecutionPolicyResponse","description":"Current execution policy for the calling org."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/execution/policy":{"patch":{"tags":["Execution Policy"],"summary":"Update execution policy","description":"Partial update — only supplied fields are changed. Changes take effect immediately for all subsequent executions. Audit logs record every update.","operationId":"update_execution_policy_v1_execution_policy_patch","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdatePolicyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecutionPolicyResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Export

### `GET /v1/runs/{run_id}/export.{fmt}`

## Export simulation run results

> Export a simulation run in the requested format.\
> \
> \| Format | Content-Type | Dependency |\
> \|--------|-------------|------------|\
> \| \`csv\`  | text/csv    | stdlib — always available |\
> \| \`xlsx\` | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | \`openpyxl\` |\
> \| \`pdf\`  | application/pdf | \`fpdf2\` |\
> \| \`json\` | application/json | stdlib — always available |\
> \
> If the optional dependency is not installed the endpoint returns \*\*503\*\*.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/runs/{run_id}/export.{fmt}":{"get":{"tags":["Export"],"summary":"Export simulation run results","description":"Export a simulation run in the requested format.\n\n| Format | Content-Type | Dependency |\n|--------|-------------|------------|\n| `csv`  | text/csv    | stdlib — always available |\n| `xlsx` | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | `openpyxl` |\n| `pdf`  | application/pdf | `fpdf2` |\n| `json` | application/json | stdlib — always available |\n\nIf the optional dependency is not installed the endpoint returns **503**.","operationId":"export_run_v1_runs__run_id__export__fmt__get","parameters":[{"name":"run_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","description":"Simulation run UUID","title":"Run Id"},"description":"Simulation run UUID"},{"name":"fmt","in":"path","required":true,"schema":{"type":"string","description":"Export format: csv | xlsx | pdf | json","title":"Fmt"},"description":"Export format: csv | xlsx | pdf | json"}],"responses":{"200":{"description":"Export file bytes","content":{"application/json":{"schema":{}}}},"400":{"description":"Unsupported format"},"404":{"description":"Run not found"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}},"503":{"description":"Export dependency not installed"}}}}}}
```

## Infrastructure

### `GET /v1/infrastructure`

## Real compute infrastructure health

> Return real engine health status and compute node information.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"InfrastructureResponse":{"properties":{"deployment_mode":{"type":"string","title":"Deployment Mode"},"engine_version":{"type":"string","title":"Engine Version"},"api_version":{"type":"string","title":"Api Version"},"nodes":{"items":{"$ref":"#/components/schemas/NodeInfo"},"type":"array","title":"Nodes"},"uptime_30d_pct":{"type":"number","title":"Uptime 30D Pct"},"avg_latency_ms":{"type":"number","title":"Avg Latency Ms"},"p95_latency_ms":{"type":"number","title":"P95 Latency Ms"},"throughput_rpm":{"type":"number","title":"Throughput Rpm"},"last_health_check":{"type":"string","format":"date-time","title":"Last Health Check"},"engine_mode":{"type":"string","title":"Engine Mode","default":"binary"}},"type":"object","required":["deployment_mode","engine_version","api_version","nodes","uptime_30d_pct","avg_latency_ms","p95_latency_ms","throughput_rpm","last_health_check"],"title":"InfrastructureResponse"},"NodeInfo":{"properties":{"node_id":{"type":"string","title":"Node Id"},"status":{"type":"string","title":"Status"},"engine_version":{"type":"string","title":"Engine Version"},"cpu_pct":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cpu Pct"},"memory_gb":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Memory Gb"},"jobs_per_sec":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Jobs Per Sec"},"region":{"type":"string","title":"Region"},"last_heartbeat":{"type":"string","format":"date-time","title":"Last Heartbeat"}},"type":"object","required":["node_id","status","engine_version","cpu_pct","memory_gb","jobs_per_sec","region","last_heartbeat"],"title":"NodeInfo"}}},"paths":{"/v1/infrastructure":{"get":{"tags":["Infrastructure"],"summary":"Real compute infrastructure health","description":"Return real engine health status and compute node information.","operationId":"get_infrastructure_v1_infrastructure_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/InfrastructureResponse"}}}}}}}}}
```

### `POST /v1/nodes/register`

## Register a self-hosted compute node

> Called by self-hosted Codna workers on startup to register with the API.\
> The node will appear in GET /v1/infrastructure for the org.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"NodeRegisterRequest":{"properties":{"node_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Node Id"},"region":{"type":"string","title":"Region","default":"local"},"engine_version":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Version"},"cpu_count":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Cpu Count"},"memory_gb":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Memory Gb"},"capabilities":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Capabilities"}},"type":"object","title":"NodeRegisterRequest"},"NodeRegisterResponse":{"properties":{"node_id":{"type":"string","title":"Node Id"},"registered_at":{"type":"string","title":"Registered At"},"message":{"type":"string","title":"Message"}},"type":"object","required":["node_id","registered_at","message"],"title":"NodeRegisterResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/nodes/register":{"post":{"tags":["Infrastructure"],"summary":"Register a self-hosted compute node","description":"Called by self-hosted Codna workers on startup to register with the API.\nThe node will appear in GET /v1/infrastructure for the org.","operationId":"register_node_v1_nodes_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NodeRegisterRequest"}}},"required":true},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/NodeRegisterResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/nodes/heartbeat`

## Worker node heartbeat

> Update node status and metrics. Call every 30s from worker nodes.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"NodeHeartbeatRequest":{"properties":{"node_id":{"type":"string","title":"Node Id"},"cpu_pct":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cpu Pct"},"memory_gb":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Memory Gb"},"jobs_per_sec":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Jobs Per Sec"},"status":{"type":"string","title":"Status","default":"live"}},"type":"object","required":["node_id"],"title":"NodeHeartbeatRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/nodes/heartbeat":{"post":{"tags":["Infrastructure"],"summary":"Worker node heartbeat","description":"Update node status and metrics. Call every 30s from worker nodes.","operationId":"node_heartbeat_v1_nodes_heartbeat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NodeHeartbeatRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Node Heartbeat V1 Nodes Heartbeat Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/nodes/{node_id}`

## Deregister a node

> Gracefully deregister a self-hosted worker node.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/nodes/{node_id}":{"delete":{"tags":["Infrastructure"],"summary":"Deregister a node","description":"Gracefully deregister a self-hosted worker node.","operationId":"deregister_node_v1_nodes__node_id__delete","parameters":[{"name":"node_id","in":"path","required":true,"schema":{"type":"string","title":"Node Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Ingest

### `POST /v1/ingest`

## Instant data ingestion — zero-config simulation from any table

> \*\*Drop in your data. Get back a ready-to-run simulation.\*\*\
> \
> \- Paste CSV text or send JSON records\
> \- Multiple tables: auto-detects join keys and merges\
> \- Auto-detects distributions, polarity, units, and objective function\
> \- Selects the best simulation engine for your data shape\
> \- Set \`auto\_run: true\` to get simulation results immediately\
> \
> Powered by the Codna FieldMapper — same logic as \`field\_mapper.mojo\`.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"IngestRequest":{"properties":{"tables":{"items":{"$ref":"#/components/schemas/IngestTable"},"type":"array","minItems":1,"title":"Tables","description":"One or more data tables. First table is primary."},"domain":{"type":"string","title":"Domain","description":"Optional domain hint (finance, supply_chain, hr, etc.) for better field mapping","default":""},"runs":{"type":"integer","maximum":1000000,"minimum":1000,"title":"Runs","description":"Scenarios to evaluate","default":10000},"auto_run":{"type":"boolean","title":"Auto Run","description":"If true, run the simulation immediately and return results","default":false},"join_on":{"anyOf":[{"additionalProperties":{"type":"string"},"type":"object"},{"type":"null"}],"title":"Join On","description":"Explicit join keys: {'table_a_field': 'table_b_field'}. If omitted, auto-detected."}},"type":"object","required":["tables"],"title":"IngestRequest","description":"Drop in your data. Get back a ready-to-run simulation.\n\nSupports:\n- Single table: records or CSV text\n- Multiple tables: auto-detects join keys, merges, then analyzes\n\nNo configuration required. The engine auto-detects everything."},"IngestTable":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this table","default":"table"},"records":{"items":{"type":"object"},"type":"array","title":"Records","description":"Array of records (list of dicts). Omit if providing csv."},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text. Parsed automatically."}},"type":"object","title":"IngestTable","description":"A single table of data."},"IngestResponse":{"properties":{"ingest_id":{"type":"string","title":"Ingest Id"},"records_analyzed":{"type":"integer","title":"Records Analyzed"},"fields_detected":{"type":"integer","title":"Fields Detected"},"join_applied":{"type":"boolean","title":"Join Applied"},"join_key":{"anyOf":[{"additionalProperties":{"type":"string"},"type":"object"},{"type":"null"}],"title":"Join Key"},"variables":{"items":{"type":"object"},"type":"array","title":"Variables"},"objective_function":{"type":"string","title":"Objective Function"},"engine":{"type":"string","title":"Engine"},"engine_reason":{"type":"string","title":"Engine Reason"},"field_analysis":{"type":"object","title":"Field Analysis"},"simulation_payload":{"type":"object","title":"Simulation Payload"},"simulation_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Simulation Result"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["ingest_id","records_analyzed","fields_detected","join_applied","join_key","variables","objective_function","engine","engine_reason","field_analysis","simulation_payload","latency_ms"],"title":"IngestResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/ingest":{"post":{"tags":["Ingest"],"summary":"Instant data ingestion — zero-config simulation from any table","description":"**Drop in your data. Get back a ready-to-run simulation.**\n\n- Paste CSV text or send JSON records\n- Multiple tables: auto-detects join keys and merges\n- Auto-detects distributions, polarity, units, and objective function\n- Selects the best simulation engine for your data shape\n- Set `auto_run: true` to get simulation results immediately\n\nPowered by the Codna FieldMapper — same logic as `field_mapper.mojo`.","operationId":"ingest_v1_ingest_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/IngestResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Logs

### `GET /v1/logs`

## Stream structured logs via Server-Sent Events

> SSE stream of API log events.\
> \
> Query params:\
> \- node\_id: filter by compute node ID\
> \- level: filter by log level (info, warning, error)\
> \
> Connect with:\
> &#x20;   const es = new EventSource('/v1/logs', { headers: { Authorization: 'Bearer sk\_...' } })

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/logs":{"get":{"tags":["Logs"],"summary":"Stream structured logs via Server-Sent Events","description":"SSE stream of API log events.\n\nQuery params:\n- node_id: filter by compute node ID\n- level: filter by log level (info, warning, error)\n\nConnect with:\n    const es = new EventSource('/v1/logs', { headers: { Authorization: 'Bearer sk_...' } })","operationId":"stream_logs_v1_logs_get","parameters":[{"name":"node_id","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Node Id"}},{"name":"level","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Level"}}],"responses":{"200":{"description":"Successful Response","content":{"text/event-stream":{}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Playground

### `POST /v1/playground`

## Try Codna — no API key required

> \*\*No sign-up. No API key. Just try it.\*\*\
> \
> Run a decision analysis, optimization, simulation, or forecast in one API call. Rate limited at 10 requests/minute per IP.\
> \
> Upgrade at \[codna.ai/dashboard]\(<https://codna.ai/dashboard>) for:\
> \- 500 simulations/month free\
> \- Up to 1,000,000 scenarios per request\
> \- All 12 engines

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/playground":{"post":{"tags":["Playground"],"summary":"Try Codna — no API key required","description":"**No sign-up. No API key. Just try it.**\n\nRun a decision analysis, optimization, simulation, or forecast in one API call. Rate limited at 10 requests/minute per IP.\n\nUpgrade at [codna.ai/dashboard](https://codna.ai/dashboard) for:\n- 500 simulations/month free\n- Up to 1,000,000 scenarios per request\n- All 12 engines","operationId":"playground_v1_playground_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PlaygroundRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PlaygroundResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"PlaygroundRequest":{"properties":{"mode":{"type":"string","title":"Mode","description":"What to run: decision, optimize, simulate, forecast","default":"decision"},"inputs":{"type":"object","title":"Inputs","description":"Your input variables as name → value (or name → {value, low, high})"},"objective":{"type":"string","title":"Objective","description":"What to optimize (for optimize mode): 'maximize profit', 'minimize cost', etc.","default":"maximize_value"},"runs":{"type":"integer","maximum":5000,"minimum":100,"title":"Runs","description":"Scenarios to evaluate (playground cap: 5,000 — upgrade for 1,000,000+)","default":1000},"history":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"History","description":"Historical values for forecast mode (most recent last, min 3)"}},"type":"object","title":"PlaygroundRequest","description":"Describe what you want to analyze. No statistics knowledge required.\n\nModes:\n  decision  → What should I do? Returns proceed/pause/reject + why\n  optimize  → Find the best value. Returns optimal config + improvement\n  simulate  → What's the range of outcomes? Returns distribution\n  forecast  → What will happen? Returns future periods with CI\n\nExample:\n  {\n    \"mode\": \"decision\",\n    \"inputs\": {\"revenue\": 120000, \"cost\": 70000},\n    \"runs\": 1000\n  }"},"PlaygroundResponse":{"properties":{"playground_id":{"type":"string","title":"Playground Id"},"mode":{"type":"string","title":"Mode"},"action":{"type":"string","title":"Action"},"value":{"type":"number","title":"Value"},"confidence":{"type":"number","title":"Confidence"},"why":{"items":{"type":"string"},"type":"array","title":"Why"},"details":{"type":"object","title":"Details"},"latency_ms":{"type":"number","title":"Latency Ms"},"upgrade_hint":{"type":"string","title":"Upgrade Hint"}},"type":"object","required":["playground_id","mode","action","value","confidence","why","details","latency_ms","upgrade_hint"],"title":"PlaygroundResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}
```

## Products

### `POST /v1/decision`

## Get an optimal decision

> Give Codna your inputs and constraints. Get back the optimal action with confidence, risk, and plain-English reasoning.\
> \
> Evaluates thousands of possible scenarios in milliseconds using the Codna API — no statistics or simulation expertise required.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DecisionRequest":{"properties":{"inputs":{"items":{"$ref":"#/components/schemas/DecisionInput"},"type":"array","title":"Inputs","description":"Business inputs with optional uncertainty ranges"},"objective":{"type":"string","title":"Objective","description":"What to optimize: maximize_value, minimize_risk, maximize_profit, minimize_cost","default":"maximize_value"},"risk_tolerance":{"type":"string","title":"Risk Tolerance","description":"How much risk is acceptable: low, medium, high","default":"medium"},"scenarios":{"type":"integer","maximum":1000000,"minimum":1000,"title":"Scenarios","description":"How many scenarios to evaluate (more = higher confidence)","default":10000},"engine":{"type":"string","title":"Engine","description":"Simulation engine. 'auto' (default) selects the best engine automatically based on your data shape. Options: monte_carlo, lhs, qmc_sobol, bootstrap, mcmc, importance_sampling, time_series, sensitivity","default":"auto"},"label":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Label","description":"Optional label for this decision"}},"type":"object","required":["inputs"],"title":"DecisionRequest","description":"Ask Codna: given these inputs and constraints, what should I do?\n\nCodna tests thousands of possible outcomes and returns the optimal action\nwith confidence, risk, and reasoning — no statistics knowledge required."},"DecisionInput":{"properties":{"name":{"type":"string","title":"Name","description":"Variable name, e.g. 'revenue'"},"value":{"type":"number","title":"Value","description":"Expected / central value"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low","description":"Pessimistic value (optional)"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High","description":"Optimistic value (optional)"},"unit":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Unit","description":"Unit label, e.g. 'USD'"}},"type":"object","required":["name","value"],"title":"DecisionInput","description":"A named input value with optional uncertainty range."},"DecisionResponse":{"properties":{"decision_id":{"type":"string","title":"Decision Id"},"action":{"type":"string","title":"Action","description":"Recommended action: proceed, pause, reject, or custom"},"confidence":{"type":"number","title":"Confidence","description":"Confidence in this recommendation (0–1)"},"reasoning":{"type":"string","title":"Reasoning","description":"Plain-English explanation"},"why":{"items":{"type":"string"},"type":"array","title":"Why","description":"3 crisp reasons behind this recommendation"},"expected_outcome":{"type":"number","title":"Expected Outcome","description":"Expected value in your input units"},"downside_risk":{"type":"number","title":"Downside Risk","description":"Value at 5th percentile (worst-case)"},"upside_potential":{"type":"number","title":"Upside Potential","description":"Value at 95th percentile (best-case)"},"probability_of_loss":{"type":"number","title":"Probability Of Loss","description":"Probability of negative outcome"},"scenarios_evaluated":{"type":"integer","title":"Scenarios Evaluated"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["decision_id","action","confidence","reasoning","why","expected_outcome","downside_risk","upside_potential","probability_of_loss","scenarios_evaluated","latency_ms"],"title":"DecisionResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/decision":{"post":{"tags":["Products"],"summary":"Get an optimal decision","description":"Give Codna your inputs and constraints. Get back the optimal action with confidence, risk, and plain-English reasoning.\n\nEvaluates thousands of possible scenarios in milliseconds using the Codna API — no statistics or simulation expertise required.","operationId":"decision_v1_decision_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/agent/run`

## Run an AI agent task

> Give the Codna Agent Engine a task. It breaks it down, uses tools (search, simulate, optimize, calculate), and returns a structured result.\
> \
> Direct replacement for LangChain and LangGraph agent pipelines.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"AgentRunRequest":{"properties":{"task":{"type":"string","minLength":5,"title":"Task","description":"What should the agent do?"},"context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Context","description":"Additional context or data"},"tools":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Tools","description":"Tools to make available: search, simulate, optimize, calculate, summarize"},"max_steps":{"type":"integer","maximum":50,"minimum":1,"title":"Max Steps","description":"Maximum execution steps","default":10},"output_format":{"type":"string","title":"Output Format","description":"Output format: text, json, markdown","default":"text"}},"type":"object","required":["task"],"title":"AgentRunRequest","description":"Give Codna a task. It plans, executes tools, and returns a structured result.\n\nDrop-in replacement for LangChain / LangGraph agent workflows."},"AgentRunResponse":{"properties":{"run_id":{"type":"string","title":"Run Id"},"status":{"type":"string","title":"Status"},"result":{"anyOf":[{"type":"string"},{"type":"object"}],"title":"Result"},"steps":{"items":{"$ref":"#/components/schemas/AgentStep"},"type":"array","title":"Steps"},"tools_used":{"items":{"type":"string"},"type":"array","title":"Tools Used"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["run_id","status","result","steps","tools_used","latency_ms"],"title":"AgentRunResponse"},"AgentStep":{"properties":{"step":{"type":"integer","title":"Step"},"action":{"type":"string","title":"Action"},"tool":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tool"},"result":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result"},"status":{"type":"string","title":"Status","default":"completed"}},"type":"object","required":["step","action"],"title":"AgentStep"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/agent/run":{"post":{"tags":["Products"],"summary":"Run an AI agent task","description":"Give the Codna Agent Engine a task. It breaks it down, uses tools (search, simulate, optimize, calculate), and returns a structured result.\n\nDirect replacement for LangChain and LangGraph agent pipelines.","operationId":"agent_run_v1_agent_run_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/optimize`

## Optimize a business variable

> Find the optimal value for pricing, routing, scheduling, or resource allocation.\
> \
> Describe your objective and constraints in plain English — Codna finds the best configuration across thousands of iterations.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"OptimizeRequest":{"properties":{"objective":{"type":"string","title":"Objective","description":"What to optimize, e.g. 'maximize profit', 'minimize cost', 'maximize throughput'"},"variables":{"items":{"$ref":"#/components/schemas/OptimizeVariable"},"type":"array","title":"Variables","description":"Variables to optimize with their allowed ranges"},"constraints":{"items":{"$ref":"#/components/schemas/OptimizeConstraint"},"type":"array","title":"Constraints","description":"Business constraints that must be satisfied"},"iterations":{"type":"integer","maximum":100000,"minimum":100,"title":"Iterations","description":"Search iterations","default":1000},"engine":{"type":"string","title":"Engine","description":"Simulation engine. 'auto' selects the best engine automatically. Options: lhs (recommended for optimization), monte_carlo, qmc_sobol","default":"auto"}},"type":"object","required":["objective","variables"],"title":"OptimizeRequest","description":"Find the best value given inputs, constraints, and an objective.\n\nUse cases: pricing, routing, scheduling, resource allocation.\nNo math required — just describe what you're optimizing."},"OptimizeVariable":{"properties":{"name":{"type":"string","title":"Name"},"min":{"type":"number","title":"Min"},"max":{"type":"number","title":"Max"},"step":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Step"},"unit":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Unit"}},"type":"object","required":["name","min","max"],"title":"OptimizeVariable"},"OptimizeConstraint":{"properties":{"expression":{"type":"string","title":"Expression","description":"e.g. 'margin > 0.2', 'cost < 50000'"},"required":{"type":"boolean","title":"Required","default":true}},"type":"object","required":["expression"],"title":"OptimizeConstraint"},"OptimizeResponse":{"properties":{"optimization_id":{"type":"string","title":"Optimization Id"},"status":{"type":"string","title":"Status"},"optimal_values":{"additionalProperties":{"type":"number"},"type":"object","title":"Optimal Values"},"objective_value":{"type":"number","title":"Objective Value"},"improvement_vs_midpoint":{"type":"number","title":"Improvement Vs Midpoint","description":"% improvement vs naive midpoint solution"},"constraints_satisfied":{"type":"boolean","title":"Constraints Satisfied"},"iterations_run":{"type":"integer","title":"Iterations Run"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["optimization_id","status","optimal_values","objective_value","improvement_vs_midpoint","constraints_satisfied","iterations_run","latency_ms"],"title":"OptimizeResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/optimize":{"post":{"tags":["Products"],"summary":"Optimize a business variable","description":"Find the optimal value for pricing, routing, scheduling, or resource allocation.\n\nDescribe your objective and constraints in plain English — Codna finds the best configuration across thousands of iterations.","operationId":"optimize_v1_optimize_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptimizeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptimizeResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/retrieve`

## Search a knowledge base

> Search documents or a connected data source and get ranked, relevant results.\
> \
> Combines BM25 keyword search, dense vector similarity, and cross-encoder reranking for enterprise-grade accuracy. No setup required — pass documents inline or connect a data source.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RetrieveRequest":{"properties":{"query":{"type":"string","minLength":3,"title":"Query","description":"What are you looking for?"},"documents":{"anyOf":[{"items":{"$ref":"#/components/schemas/RetrieveDocument"},"type":"array"},{"type":"null"}],"title":"Documents","description":"Documents to search (inline mode)"},"collection_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Collection Id","description":"ID of a connected data source to search"},"top_k":{"type":"integer","maximum":50,"minimum":1,"title":"Top K","description":"Number of results to return","default":5},"rerank":{"type":"boolean","title":"Rerank","description":"Apply cross-encoder reranking for higher accuracy","default":true}},"type":"object","required":["query"],"title":"RetrieveRequest","description":"Search your knowledge base and get ranked, relevant results.\n\nPlug-and-play enterprise search and RAG pipeline.\nPass documents inline or reference a connected collection."},"RetrieveDocument":{"properties":{"id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Id"},"content":{"type":"string","title":"Content"},"metadata":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Metadata"}},"type":"object","required":["content"],"title":"RetrieveDocument"},"RetrieveResponse":{"properties":{"retrieval_id":{"type":"string","title":"Retrieval Id"},"query":{"type":"string","title":"Query"},"results":{"items":{"$ref":"#/components/schemas/RetrieveResult"},"type":"array","title":"Results"},"total_searched":{"type":"integer","title":"Total Searched"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["retrieval_id","query","results","total_searched","latency_ms"],"title":"RetrieveResponse"},"RetrieveResult":{"properties":{"rank":{"type":"integer","title":"Rank"},"document_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Document Id"},"content":{"type":"string","title":"Content"},"relevance_score":{"type":"number","title":"Relevance Score"},"snippet":{"type":"string","title":"Snippet"}},"type":"object","required":["rank","document_id","content","relevance_score","snippet"],"title":"RetrieveResult"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/retrieve":{"post":{"tags":["Products"],"summary":"Search a knowledge base","description":"Search documents or a connected data source and get ranked, relevant results.\n\nCombines BM25 keyword search, dense vector similarity, and cross-encoder reranking for enterprise-grade accuracy. No setup required — pass documents inline or connect a data source.","operationId":"retrieve_v1_retrieve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RetrieveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RetrieveResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/forecast`

## Forecast a business metric

> Forecast any metric — revenue, demand, capacity — using historical data.\
> \
> Combines time-series analysis with Monte Carlo uncertainty quantification. Returns point forecasts with confidence intervals for each period.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ForecastRequest":{"properties":{"metric":{"type":"string","title":"Metric","description":"What you're forecasting, e.g. 'monthly_revenue'"},"history":{"items":{"type":"number"},"type":"array","maxItems":1000,"minItems":3,"title":"History","description":"Historical values (most recent last)"},"horizon":{"type":"integer","maximum":120,"minimum":1,"title":"Horizon","description":"How many periods ahead to forecast","default":12},"seasonality":{"type":"boolean","title":"Seasonality","description":"Account for seasonal patterns","default":true},"confidence_level":{"type":"number","maximum":0.99,"minimum":0.5,"title":"Confidence Level","description":"Confidence interval width","default":0.9}},"type":"object","required":["metric","history"],"title":"ForecastRequest","description":"Forecast what will happen based on historical data and business drivers.\n\nUse cases: demand forecasting, revenue projection, capacity planning."},"ForecastResponse":{"properties":{"forecast_id":{"type":"string","title":"Forecast Id"},"metric":{"type":"string","title":"Metric"},"baseline":{"type":"number","title":"Baseline","description":"Most recent historical value"},"forecast_mean":{"type":"number","title":"Forecast Mean","description":"Expected value at end of horizon"},"total_change_pct":{"type":"number","title":"Total Change Pct","description":"Expected % change over horizon"},"periods":{"items":{"$ref":"#/components/schemas/ForecastPeriod"},"type":"array","title":"Periods"},"scenarios_evaluated":{"type":"integer","title":"Scenarios Evaluated"},"latency_ms":{"type":"number","title":"Latency Ms"}},"type":"object","required":["forecast_id","metric","baseline","forecast_mean","total_change_pct","periods","scenarios_evaluated","latency_ms"],"title":"ForecastResponse"},"ForecastPeriod":{"properties":{"period":{"type":"integer","title":"Period"},"forecast":{"type":"number","title":"Forecast"},"lower_bound":{"type":"number","title":"Lower Bound"},"upper_bound":{"type":"number","title":"Upper Bound"},"trend":{"type":"string","title":"Trend"}},"type":"object","required":["period","forecast","lower_bound","upper_bound","trend"],"title":"ForecastPeriod"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/forecast":{"post":{"tags":["Products"],"summary":"Forecast a business metric","description":"Forecast any metric — revenue, demand, capacity — using historical data.\n\nCombines time-series analysis with Monte Carlo uncertainty quantification. Returns point forecasts with confidence intervals for each period.","operationId":"forecast_v1_forecast_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForecastRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForecastResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Runs

### `GET /v1/runs`

## List simulation runs for this org

> Return paginated simulation run history for the authenticated org.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RunsResponse":{"properties":{"runs":{"items":{"$ref":"#/components/schemas/RunSummary"},"type":"array","title":"Runs"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","minimum":1,"title":"Page"},"limit":{"type":"integer","maximum":200,"minimum":1,"title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["runs","total","page","limit","pages"],"title":"RunsResponse"},"RunSummary":{"properties":{"run_id":{"type":"string","title":"Run Id"},"mode":{"type":"string","title":"Mode"},"status":{"type":"string","title":"Status"},"scenarios_run":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Scenarios Run"},"duration_ms":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Duration Ms"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"execution_type":{"type":"string","title":"Execution Type"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"completed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Completed At"},"recommended_action":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Recommended Action"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"probability_of_loss":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Probability Of Loss"},"std_deviation":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std Deviation"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"}},"type":"object","required":["run_id","mode","status","execution_type","created_at"],"title":"RunSummary"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/runs":{"get":{"tags":["Runs"],"summary":"List simulation runs for this org","description":"Return paginated simulation run history for the authenticated org.","operationId":"list_runs_v1_runs_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":200,"minimum":1,"default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Offset"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},{"name":"mode","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Mode"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunsResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/runs/{run_id}`

## Get a single simulation run

> Return details for a single simulation run (org-scoped).

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RunSummary":{"properties":{"run_id":{"type":"string","title":"Run Id"},"mode":{"type":"string","title":"Mode"},"status":{"type":"string","title":"Status"},"scenarios_run":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Scenarios Run"},"duration_ms":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Duration Ms"},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash"},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash"},"execution_type":{"type":"string","title":"Execution Type"},"created_at":{"type":"string","format":"date-time","title":"Created At"},"completed_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Completed At"},"recommended_action":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Recommended Action"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"probability_of_loss":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Probability Of Loss"},"std_deviation":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std Deviation"},"rationale":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rationale"}},"type":"object","required":["run_id","mode","status","execution_type","created_at"],"title":"RunSummary"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/runs/{run_id}":{"get":{"tags":["Runs"],"summary":"Get a single simulation run","description":"Return details for a single simulation run (org-scoped).","operationId":"get_run_v1_runs__run_id__get","parameters":[{"name":"run_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Run Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RunSummary"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/analytics`

## Aggregated analytics for dashboard charts

> Return aggregated analytics using real SQL GROUP BY — O(1) in DB, not O(n) in Python.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"AnalyticsSummary":{"properties":{"total_runs":{"type":"integer","title":"Total Runs"},"runs_by_day":{"items":{"type":"object"},"type":"array","title":"Runs By Day"},"runs_by_status":{"additionalProperties":{"type":"integer"},"type":"object","title":"Runs By Status"},"runs_by_mode":{"additionalProperties":{"type":"integer"},"type":"object","title":"Runs By Mode"},"avg_duration_ms":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Avg Duration Ms"},"p95_duration_ms":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"P95 Duration Ms"}},"type":"object","required":["total_runs","runs_by_day","runs_by_status","runs_by_mode","avg_duration_ms","p95_duration_ms"],"title":"AnalyticsSummary","description":"Aggregated analytics for dashboard charts."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/analytics":{"get":{"tags":["Runs"],"summary":"Aggregated analytics for dashboard charts","description":"Return aggregated analytics using real SQL GROUP BY — O(1) in DB, not O(n) in Python.","operationId":"get_analytics_v1_analytics_get","parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","maximum":365,"minimum":1,"default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AnalyticsSummary"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Semantic Query

### `POST /v1/resolve`

## Resolve structured intent into an exact executable plan

> \*\*Bounded deterministic planner.\*\*\
> \
> This endpoint resolves structured intent into an exact plan for \`POST /v1/query\`.\
> It only uses registered-source metadata, join graph metadata, planner cache, and precomputed statistics. It does not scan datasets or execute queries.\
> \
> \*\*Scope rules:\*\*\
> \- Provide \`dataset\_id\` for dataset-scoped planning, or\
> \- set \`allow\_org\_scope=true\` to plan across all visible datasets.\
> \
> \*\*Deterministic guarantees:\*\*\
> \- identical intent\_signature + schema\_revision + scope => identical output\
> \- ambiguity clarifies or rejects; it never expands search\
> \- no fallback to slower planning paths exists

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"ResolveRequest":{"properties":{"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source. Required unless allow_org_scope=true or only one visible dataset exists."},"metric":{"$ref":"#/components/schemas/MetricSpec"},"group_by":{"items":{"type":"string"},"type":"array","title":"Group By"},"preferred_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Preferred Source"},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","default":false},"min_source_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Source Confidence","default":0},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit","description":"Top-N limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"raw_text":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Raw Text","description":"Optional non-authoritative raw text hint. Structured intent remains the source of truth."},"include_explanation":{"type":"boolean","title":"Include Explanation","default":false},"allow_org_scope":{"type":"boolean","title":"Allow Org Scope","description":"When true, resolve can consider all visible datasets in the org.","default":false}},"additionalProperties":false,"type":"object","title":"ResolveRequest","description":"Bounded planning request that returns an exact executable plan."},"MetricSpec":{"properties":{"role":{"type":"string","title":"Role","description":"Structural role. One of: base_measure, category, component, derived_measure, identifier, metric, ratio, text, time, unit_measure. derived_measure = computed aggregate (revenue, total value). base_measure = count/quantity. unit_measure = price/rate. ratio = percentage/margin. metric = best numeric column.","default":"derived_measure"},"hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Hint","description":"Optional weak signal — a word from the user's question. Used only as a tiebreaker when multiple columns share the same role. Never the primary signal. Examples: 'revenue', 'quantity', 'price'."}},"type":"object","title":"MetricSpec","description":"Structural role target. The LLM selects based on what the user wants.\n\nUse 'derived_measure' for revenue, spend, total value — the computed aggregate.\nUse 'base_measure' for counts, quantities, discrete amounts.\nUse 'unit_measure' for prices, rates, per-unit values.\nUse 'ratio' for percentages, margins, fill rates.\nUse 'metric' to let the engine pick the best numeric column."},"FilterSpec":{"properties":{"time_filter":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Time Filter","description":"Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year."},"conditions":{"items":{"$ref":"#/components/schemas/FilterConditionSpec"},"type":"array","title":"Conditions","description":"Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null."}},"type":"object","title":"FilterSpec","description":"Time or value filter."},"FilterConditionSpec":{"properties":{"column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Column","description":"Exact source column name for this filter when schema is known."},"dimension_hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dimension Hint","description":"Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters."},"op":{"type":"string","enum":["eq","in","gt","gte","lt","lte","is_null","is_not_null"],"title":"Op","description":"Deterministic filter operator.","default":"eq"},"value":{"anyOf":[{},{"type":"null"}],"title":"Value","description":"Scalar comparison value for eq/gt/gte/lt/lte."},"values":{"anyOf":[{"items":{},"type":"array"},{"type":"null"}],"title":"Values","description":"List comparison values for in."}},"additionalProperties":false,"type":"object","title":"FilterConditionSpec"},"ConstraintSpec":{"properties":{"requires_derived":{"type":"boolean","title":"Requires Derived","description":"Reject if metric column is not a derived_measure (formula-proven).","default":false},"no_cross_source":{"type":"boolean","title":"No Cross Source","description":"Reject if query requires a cross-source join.","default":false},"min_column_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Column Confidence","description":"Reject if column_confidence component < this value.","default":0},"max_join_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Join Hops","description":"Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).","default":4}},"type":"object","title":"ConstraintSpec"},"ResolveResponse":{"properties":{"resolved_plan":{"anyOf":[{"$ref":"#/components/schemas/ResolvedPlan-Output"},{"type":"null"}]},"confidence":{"type":"number","title":"Confidence"},"plan":{"items":{"type":"string"},"type":"array","title":"Plan"},"explanation":{"items":{"type":"string"},"type":"array","title":"Explanation"},"resolved_column":{"type":"string","title":"Resolved Column","default":""},"resolved_role":{"type":"string","title":"Resolved Role","default":""},"resolved_source":{"type":"string","title":"Resolved Source","default":""},"candidates":{"items":{"$ref":"#/components/schemas/CandidateColumn"},"type":"array","title":"Candidates"},"source_scores":{"additionalProperties":{"type":"number"},"type":"object","title":"Source Scores"},"latency_ms":{"type":"number","title":"Latency Ms"},"decision_path":{"type":"string","title":"Decision Path"},"plan_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Plan Hash"},"schema_revision":{"type":"string","title":"Schema Revision"},"validated":{"type":"boolean","title":"Validated"},"deterministic_scope":{"type":"string","title":"Deterministic Scope"},"confidence_source":{"type":"string","title":"Confidence Source"},"clarification_required":{"type":"boolean","title":"Clarification Required","default":false},"rejection_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rejection Reason"},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"intent_signature":{"type":"string","title":"Intent Signature"},"source_set":{"items":{"type":"string"},"type":"array","title":"Source Set"},"join_path":{"items":{"type":"object"},"type":"array","title":"Join Path"},"planner_mode":{"type":"string","title":"Planner Mode","default":"registry_planner"}},"type":"object","required":["confidence","plan","latency_ms","decision_path","schema_revision","validated","deterministic_scope","confidence_source","intent_signature"],"title":"ResolveResponse"},"ResolvedPlan-Output":{"properties":{"source_name":{"type":"string","title":"Source Name"},"metric_column":{"type":"string","title":"Metric Column"},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column"},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}]},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"schema_revision":{"type":"string","title":"Schema Revision"}},"additionalProperties":false,"type":"object","required":["source_name","metric_column","schema_revision"],"title":"ResolvedPlan"},"JoinPathSpec":{"properties":{"base_source":{"type":"string","title":"Base Source","description":"Source that owns the metric column and anchors the path."},"group_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Source","description":"Final source expected to provide the group column, if different from base_source."},"edges":{"items":{"$ref":"#/components/schemas/JoinEdgeSpec"},"type":"array","title":"Edges","description":"Ordered join edges from base_source toward the dimension source."},"max_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Hops","description":"Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).","default":4},"min_path_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Path Confidence","description":"Minimum acceptable composed confidence across the full join path.","default":0},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Reject if more than one viable path exists with insufficient score separation.","default":true},"reject_on_fanout":{"type":"boolean","title":"Reject On Fanout","description":"Reject if estimated path fanout exceeds safe execution thresholds.","default":true}},"additionalProperties":false,"type":"object","required":["base_source"],"title":"JoinPathSpec","description":"Explicit multi-hop join contract replacing single-hop join fields."},"JoinEdgeSpec":{"properties":{"left_source":{"type":"string","title":"Left Source","description":"Source on the left side of the join edge."},"right_source":{"type":"string","title":"Right Source","description":"Source on the right side of the join edge."},"left_key":{"type":"string","title":"Left Key","description":"Exact join key column in left_source."},"right_key":{"type":"string","title":"Right Key","description":"Exact join key column in right_source."},"join_type":{"type":"string","title":"Join Type","description":"Join type. Initial implementation supports inner.","default":"inner"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","description":"Minimum acceptable confidence for this hop.","default":0},"expected_cardinality":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Expected Cardinality","description":"Optional expected cardinality such as one_to_many, many_to_one, or many_to_many."},"allow_many_to_many":{"type":"boolean","title":"Allow Many To Many","description":"If false, planner/executor must reject many_to_many fanout on this hop.","default":false}},"additionalProperties":false,"type":"object","required":["left_source","right_source","left_key","right_key"],"title":"JoinEdgeSpec","description":"One explicit edge in a multi-hop join path."},"CandidateColumn":{"properties":{"source":{"type":"string","title":"Source"},"column":{"type":"string","title":"Column"},"role":{"type":"string","title":"Role"},"magnitude":{"type":"string","title":"Magnitude"},"formula":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Formula"},"confidence":{"type":"number","title":"Confidence"},"score_components":{"additionalProperties":{"type":"number"},"type":"object","title":"Score Components"},"notes":{"items":{"type":"string"},"type":"array","title":"Notes"}},"type":"object","required":["source","column","role","magnitude","formula","confidence"],"title":"CandidateColumn"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/resolve":{"post":{"tags":["Semantic Query"],"summary":"Resolve structured intent into an exact executable plan","description":"**Bounded deterministic planner.**\n\nThis endpoint resolves structured intent into an exact plan for `POST /v1/query`.\nIt only uses registered-source metadata, join graph metadata, planner cache, and precomputed statistics. It does not scan datasets or execute queries.\n\n**Scope rules:**\n- Provide `dataset_id` for dataset-scoped planning, or\n- set `allow_org_scope=true` to plan across all visible datasets.\n\n**Deterministic guarantees:**\n- identical intent_signature + schema_revision + scope => identical output\n- ambiguity clarifies or rejects; it never expands search\n- no fallback to slower planning paths exists","operationId":"resolve_sources_v1_resolve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResolveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ResolveResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/query`

## Execute a structured query — schema-free, zero domain assumptions

> \*\*Structured query execution engine.\*\*\
> \
> This endpoint takes structured intent — produced by an LLM from the user's natural-language question. It does NOT accept raw text.\
> \
> \*\*Separation of concerns:\*\*\
> \- LLM: language → structured intent, ambiguity resolution, user interaction\
> \- Codna: schema understanding, math relationships, fast execution, correctness\
> \
> \*\*Role resolution:\*\*\
> 1\. Detect derived formulas across all numeric column triples (Mojo, \~100ms)\
> 2\. Assign structural roles: derived\_measure, base\_measure, unit\_measure…\
> 3\. Match requested role → best column\
> 4\. Execute aggregation, return result + all candidates for LLM disambiguation\
> \
> \*\*Ambiguity handling:\*\*\
> If confidence < 0.7, check \`candidates\` — multiple columns may match the role. The LLM can present options to the user or pick the most contextually appropriate one.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"QueryRequest":{"properties":{"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source. When provided, query execution is scoped to that one registered dataset."},"source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name","description":"EXACT source name from the registry (e.g. 'Bookings'). Bypasses source resolver entirely. Get this from POST /v1/sources/schema or the registration response."},"metric_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Metric Column","description":"EXACT column name for the metric (e.g. 'EXT_PRICE'). Bypasses column resolver. The engine validates this column exists in source_name."},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column","description":"EXACT column name for group-by (e.g. 'CUSTOMER'). Bypasses group resolver. Can be in source_name or in the terminal source of join_path."},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}],"description":"Explicit multi-hop join graph. Breaking replacement for single-hop join fields. Defaults to a safe 4-hop budget; explicit opt-in can raise this to 6 hops (7 tables) with per-edge constraints and path-level confidence gates."},"sources":{"items":{"$ref":"#/components/schemas/DataSource"},"type":"array","title":"Sources","description":"Raw data sources (inline CSV/JSON). Usually empty — use registry.","default":[]},"metric":{"$ref":"#/components/schemas/MetricSpec"},"group_by":{"items":{"type":"string"},"type":"array","title":"Group By","description":"Hint mode only: dimension words from the user's question (e.g. ['customer', 'region']). Ignored when group_column is set.","default":[]},"preferred_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Preferred Source","description":"Hint mode only: source name the LLM believes is correct. Hard-locks the source resolver. Ignored when source_name is set."},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Hint mode only: when True and resolver confidence < 0.40, return null result with source candidates instead of guessing.","default":false},"min_source_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Source Confidence","description":"Hint mode only: minimum resolver confidence threshold.","default":0},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit","description":"Top-N limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","default":0.5},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"resolved_plan":{"anyOf":[{"$ref":"#/components/schemas/ResolvedPlan-Input"},{"type":"null"}],"description":"Exact plan returned by POST /v1/resolve."}},"additionalProperties":false,"type":"object","title":"QueryRequest","description":"Structured query execution request.\n\n═══════════════════════════════════════════════════════════\nPRIMARY PATH  —  Exact spec  (use after reading the schema)\n═══════════════════════════════════════════════════════════\nThe correct flow:\n  1. Call POST /v1/sources/register or POST /v1/sources/schema\n  2. LLM reads the returned schema (column names, roles, formulas)\n  3. LLM sends exact column names — Mojo validates and executes\n\nExample (top 5 customers by revenue):\n  {\n    \"source_name\": \"S0\",\n    \"metric_column\": \"measure_total\",\n    \"group_column\": \"dimension_label\",\n    \"aggregation\": \"sum\",\n    \"limit\": 5\n  }\n\nFor multi-hop joins:\n  {\n    \"source_name\": \"S0\",\n    \"metric_column\": \"measure_total\",\n    \"group_column\": \"dimension_label\",\n    \"join_path\": {\n      \"base_source\": \"S0\",\n      \"group_source\": \"S2\",\n      \"edges\": [\n        {\n          \"left_source\": \"S0\",\n          \"right_source\": \"S1\",\n          \"left_key\": \"k01_left\",\n          \"right_key\": \"k01_right\"\n        },\n        {\n          \"left_source\": \"S1\",\n          \"right_source\": \"S2\",\n          \"left_key\": \"k12_left\",\n          \"right_key\": \"k12_right\"\n        }\n      ]\n    },\n    \"aggregation\": \"sum\"\n  }\n\n═══════════════════════════════════════════════════════════\nFALLBACK PATH  —  Hint spec  (when schema is not yet known)\n═══════════════════════════════════════════════════════════\nThe engine resolves source and columns from structural role hints.\nUse this ONLY for exploratory queries. Always migrate to exact spec\nonce you have the schema — it is faster and never ambiguous.\n\nExample:\n  {\n    \"metric\": {\"role\": \"derived_measure\", \"hint\": \"total value\"},\n    \"group_by\": [\"segment\"],\n    \"aggregation\": \"sum\",\n    \"limit\": 5\n  }"},"JoinPathSpec":{"properties":{"base_source":{"type":"string","title":"Base Source","description":"Source that owns the metric column and anchors the path."},"group_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Source","description":"Final source expected to provide the group column, if different from base_source."},"edges":{"items":{"$ref":"#/components/schemas/JoinEdgeSpec"},"type":"array","title":"Edges","description":"Ordered join edges from base_source toward the dimension source."},"max_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Hops","description":"Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).","default":4},"min_path_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Path Confidence","description":"Minimum acceptable composed confidence across the full join path.","default":0},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Reject if more than one viable path exists with insufficient score separation.","default":true},"reject_on_fanout":{"type":"boolean","title":"Reject On Fanout","description":"Reject if estimated path fanout exceeds safe execution thresholds.","default":true}},"additionalProperties":false,"type":"object","required":["base_source"],"title":"JoinPathSpec","description":"Explicit multi-hop join contract replacing single-hop join fields."},"JoinEdgeSpec":{"properties":{"left_source":{"type":"string","title":"Left Source","description":"Source on the left side of the join edge."},"right_source":{"type":"string","title":"Right Source","description":"Source on the right side of the join edge."},"left_key":{"type":"string","title":"Left Key","description":"Exact join key column in left_source."},"right_key":{"type":"string","title":"Right Key","description":"Exact join key column in right_source."},"join_type":{"type":"string","title":"Join Type","description":"Join type. Initial implementation supports inner.","default":"inner"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","description":"Minimum acceptable confidence for this hop.","default":0},"expected_cardinality":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Expected Cardinality","description":"Optional expected cardinality such as one_to_many, many_to_one, or many_to_many."},"allow_many_to_many":{"type":"boolean","title":"Allow Many To Many","description":"If false, planner/executor must reject many_to_many fanout on this hop.","default":false}},"additionalProperties":false,"type":"object","required":["left_source","right_source","left_key","right_key"],"title":"JoinEdgeSpec","description":"One explicit edge in a multi-hop join path."},"DataSource":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this source (e.g., 'sales', 'orders')"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source."},"source_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Id","description":"Registered source ID; fastest path and avoids re-uploading data."},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"Inline JSON records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str","description":"Raw JSON array/object text (nested auto-flattened)"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"HTTP URL — format auto-detected"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64","description":"Excel .xlsx file, base64-encoded"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64","description":"Parquet file, base64-encoded"},"connection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection","description":"Connector config dict — see DataSource docstring for all types"},"table":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Table","description":"Legacy field — use connection instead"}},"type":"object","required":["name"],"title":"DataSource","description":"A data source to map. Every format normalizes to list[dict] internally.\n\nInline (no external dependency):\n  `records`    — JSON array of objects (fastest)\n  `csv`        — raw CSV text\n  `json_str`   — raw JSON array/object text (nested JSON is auto-flattened)\n  `url`        — HTTP(S) URL; format auto-detected from Content-Type / extension\n\nBinary files (base64-encoded for API transport):\n  `excel_b64`  — Excel .xlsx file, base64-encoded\n  `parquet_b64`— Parquet file, base64-encoded\n\nConnector config (routes through ConnectorRegistry):\n  `connection` — dict with `type` + connector-specific keys:\n    {\"type\": \"sql\",        \"connection_string\": \"postgresql+asyncpg://...\",\n     \"query\": \"SELECT ...\"}\n    {\"type\": \"sql\",        \"connection_string\": \"sqlite+aiosqlite:///db.sqlite\", \"query\": \"...\"}\n    {\"type\": \"rest_api\",   \"url\": \"https://...\", \"data_path\": \"data.items\"}\n    {\"type\": \"s3\",         \"bucket\": \"my-bucket\", \"key\": \"data/sales.parquet\"}\n    {\"type\": \"gcs\",        \"bucket\": \"my-bucket\", \"blob\": \"data/orders.csv\"}\n    {\"type\": \"azure_blob\", \"connection_string\": \"DefaultEndpointsProtocol=...\",\n                           \"container\": \"data\", \"blob\": \"sales.parquet\"}"},"MetricSpec":{"properties":{"role":{"type":"string","title":"Role","description":"Structural role. One of: base_measure, category, component, derived_measure, identifier, metric, ratio, text, time, unit_measure. derived_measure = computed aggregate (revenue, total value). base_measure = count/quantity. unit_measure = price/rate. ratio = percentage/margin. metric = best numeric column.","default":"derived_measure"},"hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Hint","description":"Optional weak signal — a word from the user's question. Used only as a tiebreaker when multiple columns share the same role. Never the primary signal. Examples: 'revenue', 'quantity', 'price'."}},"type":"object","title":"MetricSpec","description":"Structural role target. The LLM selects based on what the user wants.\n\nUse 'derived_measure' for revenue, spend, total value — the computed aggregate.\nUse 'base_measure' for counts, quantities, discrete amounts.\nUse 'unit_measure' for prices, rates, per-unit values.\nUse 'ratio' for percentages, margins, fill rates.\nUse 'metric' to let the engine pick the best numeric column."},"FilterSpec":{"properties":{"time_filter":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Time Filter","description":"Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year."},"conditions":{"items":{"$ref":"#/components/schemas/FilterConditionSpec"},"type":"array","title":"Conditions","description":"Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null."}},"type":"object","title":"FilterSpec","description":"Time or value filter."},"FilterConditionSpec":{"properties":{"column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Column","description":"Exact source column name for this filter when schema is known."},"dimension_hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dimension Hint","description":"Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters."},"op":{"type":"string","enum":["eq","in","gt","gte","lt","lte","is_null","is_not_null"],"title":"Op","description":"Deterministic filter operator.","default":"eq"},"value":{"anyOf":[{},{"type":"null"}],"title":"Value","description":"Scalar comparison value for eq/gt/gte/lt/lte."},"values":{"anyOf":[{"items":{},"type":"array"},{"type":"null"}],"title":"Values","description":"List comparison values for in."}},"additionalProperties":false,"type":"object","title":"FilterConditionSpec"},"ConstraintSpec":{"properties":{"requires_derived":{"type":"boolean","title":"Requires Derived","description":"Reject if metric column is not a derived_measure (formula-proven).","default":false},"no_cross_source":{"type":"boolean","title":"No Cross Source","description":"Reject if query requires a cross-source join.","default":false},"min_column_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Column Confidence","description":"Reject if column_confidence component < this value.","default":0},"max_join_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Join Hops","description":"Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).","default":4}},"type":"object","title":"ConstraintSpec"},"ResolvedPlan-Input":{"properties":{"source_name":{"type":"string","title":"Source Name"},"metric_column":{"type":"string","title":"Metric Column"},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column"},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}]},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"schema_revision":{"type":"string","title":"Schema Revision"}},"additionalProperties":false,"type":"object","required":["source_name","metric_column","schema_revision"],"title":"ResolvedPlan"},"QueryResponse":{"properties":{"query_id":{"type":"string","title":"Query Id"},"result":{"title":"Result"},"result_type":{"type":"string","title":"Result Type"},"confidence":{"type":"number","title":"Confidence"},"plan":{"items":{"type":"string"},"type":"array","title":"Plan"},"resolved_column":{"type":"string","title":"Resolved Column"},"resolved_role":{"type":"string","title":"Resolved Role"},"resolved_source":{"type":"string","title":"Resolved Source"},"row_count":{"type":"integer","title":"Row Count"},"candidates":{"items":{"$ref":"#/components/schemas/CandidateColumn"},"type":"array","title":"Candidates"},"source_scores":{"additionalProperties":{"type":"number"},"type":"object","title":"Source Scores"},"ambiguous":{"type":"boolean","title":"Ambiguous"},"exact_spec":{"type":"boolean","title":"Exact Spec"},"explanation":{"items":{"type":"string"},"type":"array","title":"Explanation","default":[]},"latency_ms":{"type":"number","title":"Latency Ms"},"decision_path":{"type":"string","title":"Decision Path"},"plan_hash":{"type":"string","title":"Plan Hash"},"schema_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Schema Revision"},"validated":{"type":"boolean","title":"Validated"},"deterministic_scope":{"type":"string","title":"Deterministic Scope"},"confidence_source":{"type":"string","title":"Confidence Source"},"clarification_required":{"type":"boolean","title":"Clarification Required","default":false},"rejection_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rejection Reason"},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"source_set":{"items":{"type":"string"},"type":"array","title":"Source Set","default":[]},"join_path":{"items":{"type":"object"},"type":"array","title":"Join Path","default":[]},"planner_mode":{"type":"string","title":"Planner Mode","default":"planner_hint"}},"type":"object","required":["query_id","result","result_type","confidence","plan","resolved_column","resolved_role","resolved_source","row_count","candidates","source_scores","ambiguous","exact_spec","latency_ms","decision_path","plan_hash","validated","deterministic_scope","confidence_source"],"title":"QueryResponse"},"CandidateColumn":{"properties":{"source":{"type":"string","title":"Source"},"column":{"type":"string","title":"Column"},"role":{"type":"string","title":"Role"},"magnitude":{"type":"string","title":"Magnitude"},"formula":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Formula"},"confidence":{"type":"number","title":"Confidence"},"score_components":{"additionalProperties":{"type":"number"},"type":"object","title":"Score Components"},"notes":{"items":{"type":"string"},"type":"array","title":"Notes"}},"type":"object","required":["source","column","role","magnitude","formula","confidence"],"title":"CandidateColumn"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/query":{"post":{"tags":["Semantic Query"],"summary":"Execute a structured query — schema-free, zero domain assumptions","description":"**Structured query execution engine.**\n\nThis endpoint takes structured intent — produced by an LLM from the user's natural-language question. It does NOT accept raw text.\n\n**Separation of concerns:**\n- LLM: language → structured intent, ambiguity resolution, user interaction\n- Codna: schema understanding, math relationships, fast execution, correctness\n\n**Role resolution:**\n1. Detect derived formulas across all numeric column triples (Mojo, ~100ms)\n2. Assign structural roles: derived_measure, base_measure, unit_measure…\n3. Match requested role → best column\n4. Execute aggregation, return result + all candidates for LLM disambiguation\n\n**Ambiguity handling:**\nIf confidence < 0.7, check `candidates` — multiple columns may match the role. The LLM can present options to the user or pick the most contextually appropriate one.","operationId":"query_sources_v1_query_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/sources/schema`

## Infer and return the structural schema of data sources

> \*\*Call this once when a user connects a data source.\*\*\
> \
> Returns the full Codna structural schema: column roles, detected formulas, cardinality, and \`query\_hints\` the LLM should use when calling \`POST /v1/query\`.\
> \
> The schema is also embedded as Arrow metadata in the returned Parquet bytes (\`parquet\_b64\`), which the LLM agent can store and reuse — no re-profiling on subsequent queries.\
> \
> \*\*Flow:\*\*\
> 1\. User connects data source\
> 2\. Call \`POST /v1/sources/schema\` — \~1-2s, runs once\
> 3\. LLM reads \`schema\` JSON and \`query\_hints\`\
> 4\. User asks questions → LLM produces structured intent → \`POST /v1/query\` (\~200ms, cached)

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"SchemaRequest":{"properties":{"sources":{"items":{"$ref":"#/components/schemas/DataSource"},"type":"array","title":"Sources","description":"Data sources to profile. Pass an empty list (or omit) to return schemas for ALL sources registered for this org via POST /v1/sources/register.","default":[]}},"type":"object","title":"SchemaRequest"},"DataSource":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this source (e.g., 'sales', 'orders')"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source."},"source_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Id","description":"Registered source ID; fastest path and avoids re-uploading data."},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"Inline JSON records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str","description":"Raw JSON array/object text (nested auto-flattened)"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"HTTP URL — format auto-detected"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64","description":"Excel .xlsx file, base64-encoded"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64","description":"Parquet file, base64-encoded"},"connection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection","description":"Connector config dict — see DataSource docstring for all types"},"table":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Table","description":"Legacy field — use connection instead"}},"type":"object","required":["name"],"title":"DataSource","description":"A data source to map. Every format normalizes to list[dict] internally.\n\nInline (no external dependency):\n  `records`    — JSON array of objects (fastest)\n  `csv`        — raw CSV text\n  `json_str`   — raw JSON array/object text (nested JSON is auto-flattened)\n  `url`        — HTTP(S) URL; format auto-detected from Content-Type / extension\n\nBinary files (base64-encoded for API transport):\n  `excel_b64`  — Excel .xlsx file, base64-encoded\n  `parquet_b64`— Parquet file, base64-encoded\n\nConnector config (routes through ConnectorRegistry):\n  `connection` — dict with `type` + connector-specific keys:\n    {\"type\": \"sql\",        \"connection_string\": \"postgresql+asyncpg://...\",\n     \"query\": \"SELECT ...\"}\n    {\"type\": \"sql\",        \"connection_string\": \"sqlite+aiosqlite:///db.sqlite\", \"query\": \"...\"}\n    {\"type\": \"rest_api\",   \"url\": \"https://...\", \"data_path\": \"data.items\"}\n    {\"type\": \"s3\",         \"bucket\": \"my-bucket\", \"key\": \"data/sales.parquet\"}\n    {\"type\": \"gcs\",        \"bucket\": \"my-bucket\", \"blob\": \"data/orders.csv\"}\n    {\"type\": \"azure_blob\", \"connection_string\": \"DefaultEndpointsProtocol=...\",\n                           \"container\": \"data\", \"blob\": \"sales.parquet\"}"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/sources/schema":{"post":{"tags":["Semantic Query","Semantic Query"],"summary":"Infer and return the structural schema of data sources","description":"**Call this once when a user connects a data source.**\n\nReturns the full Codna structural schema: column roles, detected formulas, cardinality, and `query_hints` the LLM should use when calling `POST /v1/query`.\n\nThe schema is also embedded as Arrow metadata in the returned Parquet bytes (`parquet_b64`), which the LLM agent can store and reuse — no re-profiling on subsequent queries.\n\n**Flow:**\n1. User connects data source\n2. Call `POST /v1/sources/schema` — ~1-2s, runs once\n3. LLM reads `schema` JSON and `query_hints`\n4. User asks questions → LLM produces structured intent → `POST /v1/query` (~200ms, cached)","operationId":"infer_schema_v1_sources_schema_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SchemaRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Infer Schema V1 Sources Schema Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/query/batch`

## POST /v1/query/batch

> Execute multiple governed exact queries in one request

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"QueryBatchRequest":{"properties":{"defaults":{"anyOf":[{"$ref":"#/components/schemas/QueryBatchDefaults"},{"type":"null"}]},"queries":{"items":{"$ref":"#/components/schemas/QueryBatchItemRequest"},"type":"array","minItems":1,"title":"Queries"}},"additionalProperties":false,"type":"object","required":["queries"],"title":"QueryBatchRequest"},"QueryBatchDefaults":{"properties":{"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id"},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit"},"order":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Order"}},"additionalProperties":false,"type":"object","title":"QueryBatchDefaults"},"FilterSpec":{"properties":{"time_filter":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Time Filter","description":"Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year."},"conditions":{"items":{"$ref":"#/components/schemas/FilterConditionSpec"},"type":"array","title":"Conditions","description":"Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null."}},"type":"object","title":"FilterSpec","description":"Time or value filter."},"FilterConditionSpec":{"properties":{"column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Column","description":"Exact source column name for this filter when schema is known."},"dimension_hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dimension Hint","description":"Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters."},"op":{"type":"string","enum":["eq","in","gt","gte","lt","lte","is_null","is_not_null"],"title":"Op","description":"Deterministic filter operator.","default":"eq"},"value":{"anyOf":[{},{"type":"null"}],"title":"Value","description":"Scalar comparison value for eq/gt/gte/lt/lte."},"values":{"anyOf":[{"items":{},"type":"array"},{"type":"null"}],"title":"Values","description":"List comparison values for in."}},"additionalProperties":false,"type":"object","title":"FilterConditionSpec"},"QueryBatchItemRequest":{"properties":{"key":{"type":"string","minLength":1,"title":"Key"},"request":{"$ref":"#/components/schemas/QueryRequest"}},"additionalProperties":false,"type":"object","required":["key","request"],"title":"QueryBatchItemRequest"},"QueryRequest":{"properties":{"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source. When provided, query execution is scoped to that one registered dataset."},"source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name","description":"EXACT source name from the registry (e.g. 'Bookings'). Bypasses source resolver entirely. Get this from POST /v1/sources/schema or the registration response."},"metric_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Metric Column","description":"EXACT column name for the metric (e.g. 'EXT_PRICE'). Bypasses column resolver. The engine validates this column exists in source_name."},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column","description":"EXACT column name for group-by (e.g. 'CUSTOMER'). Bypasses group resolver. Can be in source_name or in the terminal source of join_path."},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}],"description":"Explicit multi-hop join graph. Breaking replacement for single-hop join fields. Defaults to a safe 4-hop budget; explicit opt-in can raise this to 6 hops (7 tables) with per-edge constraints and path-level confidence gates."},"sources":{"items":{"$ref":"#/components/schemas/DataSource"},"type":"array","title":"Sources","description":"Raw data sources (inline CSV/JSON). Usually empty — use registry.","default":[]},"metric":{"$ref":"#/components/schemas/MetricSpec"},"group_by":{"items":{"type":"string"},"type":"array","title":"Group By","description":"Hint mode only: dimension words from the user's question (e.g. ['customer', 'region']). Ignored when group_column is set.","default":[]},"preferred_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Preferred Source","description":"Hint mode only: source name the LLM believes is correct. Hard-locks the source resolver. Ignored when source_name is set."},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Hint mode only: when True and resolver confidence < 0.40, return null result with source candidates instead of guessing.","default":false},"min_source_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Source Confidence","description":"Hint mode only: minimum resolver confidence threshold.","default":0},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit","description":"Top-N limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","default":0.5},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"resolved_plan":{"anyOf":[{"$ref":"#/components/schemas/ResolvedPlan-Input"},{"type":"null"}],"description":"Exact plan returned by POST /v1/resolve."}},"additionalProperties":false,"type":"object","title":"QueryRequest","description":"Structured query execution request.\n\n═══════════════════════════════════════════════════════════\nPRIMARY PATH  —  Exact spec  (use after reading the schema)\n═══════════════════════════════════════════════════════════\nThe correct flow:\n  1. Call POST /v1/sources/register or POST /v1/sources/schema\n  2. LLM reads the returned schema (column names, roles, formulas)\n  3. LLM sends exact column names — Mojo validates and executes\n\nExample (top 5 customers by revenue):\n  {\n    \"source_name\": \"S0\",\n    \"metric_column\": \"measure_total\",\n    \"group_column\": \"dimension_label\",\n    \"aggregation\": \"sum\",\n    \"limit\": 5\n  }\n\nFor multi-hop joins:\n  {\n    \"source_name\": \"S0\",\n    \"metric_column\": \"measure_total\",\n    \"group_column\": \"dimension_label\",\n    \"join_path\": {\n      \"base_source\": \"S0\",\n      \"group_source\": \"S2\",\n      \"edges\": [\n        {\n          \"left_source\": \"S0\",\n          \"right_source\": \"S1\",\n          \"left_key\": \"k01_left\",\n          \"right_key\": \"k01_right\"\n        },\n        {\n          \"left_source\": \"S1\",\n          \"right_source\": \"S2\",\n          \"left_key\": \"k12_left\",\n          \"right_key\": \"k12_right\"\n        }\n      ]\n    },\n    \"aggregation\": \"sum\"\n  }\n\n═══════════════════════════════════════════════════════════\nFALLBACK PATH  —  Hint spec  (when schema is not yet known)\n═══════════════════════════════════════════════════════════\nThe engine resolves source and columns from structural role hints.\nUse this ONLY for exploratory queries. Always migrate to exact spec\nonce you have the schema — it is faster and never ambiguous.\n\nExample:\n  {\n    \"metric\": {\"role\": \"derived_measure\", \"hint\": \"total value\"},\n    \"group_by\": [\"segment\"],\n    \"aggregation\": \"sum\",\n    \"limit\": 5\n  }"},"JoinPathSpec":{"properties":{"base_source":{"type":"string","title":"Base Source","description":"Source that owns the metric column and anchors the path."},"group_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Source","description":"Final source expected to provide the group column, if different from base_source."},"edges":{"items":{"$ref":"#/components/schemas/JoinEdgeSpec"},"type":"array","title":"Edges","description":"Ordered join edges from base_source toward the dimension source."},"max_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Hops","description":"Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).","default":4},"min_path_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Path Confidence","description":"Minimum acceptable composed confidence across the full join path.","default":0},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Reject if more than one viable path exists with insufficient score separation.","default":true},"reject_on_fanout":{"type":"boolean","title":"Reject On Fanout","description":"Reject if estimated path fanout exceeds safe execution thresholds.","default":true}},"additionalProperties":false,"type":"object","required":["base_source"],"title":"JoinPathSpec","description":"Explicit multi-hop join contract replacing single-hop join fields."},"JoinEdgeSpec":{"properties":{"left_source":{"type":"string","title":"Left Source","description":"Source on the left side of the join edge."},"right_source":{"type":"string","title":"Right Source","description":"Source on the right side of the join edge."},"left_key":{"type":"string","title":"Left Key","description":"Exact join key column in left_source."},"right_key":{"type":"string","title":"Right Key","description":"Exact join key column in right_source."},"join_type":{"type":"string","title":"Join Type","description":"Join type. Initial implementation supports inner.","default":"inner"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","description":"Minimum acceptable confidence for this hop.","default":0},"expected_cardinality":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Expected Cardinality","description":"Optional expected cardinality such as one_to_many, many_to_one, or many_to_many."},"allow_many_to_many":{"type":"boolean","title":"Allow Many To Many","description":"If false, planner/executor must reject many_to_many fanout on this hop.","default":false}},"additionalProperties":false,"type":"object","required":["left_source","right_source","left_key","right_key"],"title":"JoinEdgeSpec","description":"One explicit edge in a multi-hop join path."},"DataSource":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this source (e.g., 'sales', 'orders')"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source."},"source_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Id","description":"Registered source ID; fastest path and avoids re-uploading data."},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"Inline JSON records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str","description":"Raw JSON array/object text (nested auto-flattened)"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"HTTP URL — format auto-detected"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64","description":"Excel .xlsx file, base64-encoded"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64","description":"Parquet file, base64-encoded"},"connection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection","description":"Connector config dict — see DataSource docstring for all types"},"table":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Table","description":"Legacy field — use connection instead"}},"type":"object","required":["name"],"title":"DataSource","description":"A data source to map. Every format normalizes to list[dict] internally.\n\nInline (no external dependency):\n  `records`    — JSON array of objects (fastest)\n  `csv`        — raw CSV text\n  `json_str`   — raw JSON array/object text (nested JSON is auto-flattened)\n  `url`        — HTTP(S) URL; format auto-detected from Content-Type / extension\n\nBinary files (base64-encoded for API transport):\n  `excel_b64`  — Excel .xlsx file, base64-encoded\n  `parquet_b64`— Parquet file, base64-encoded\n\nConnector config (routes through ConnectorRegistry):\n  `connection` — dict with `type` + connector-specific keys:\n    {\"type\": \"sql\",        \"connection_string\": \"postgresql+asyncpg://...\",\n     \"query\": \"SELECT ...\"}\n    {\"type\": \"sql\",        \"connection_string\": \"sqlite+aiosqlite:///db.sqlite\", \"query\": \"...\"}\n    {\"type\": \"rest_api\",   \"url\": \"https://...\", \"data_path\": \"data.items\"}\n    {\"type\": \"s3\",         \"bucket\": \"my-bucket\", \"key\": \"data/sales.parquet\"}\n    {\"type\": \"gcs\",        \"bucket\": \"my-bucket\", \"blob\": \"data/orders.csv\"}\n    {\"type\": \"azure_blob\", \"connection_string\": \"DefaultEndpointsProtocol=...\",\n                           \"container\": \"data\", \"blob\": \"sales.parquet\"}"},"MetricSpec":{"properties":{"role":{"type":"string","title":"Role","description":"Structural role. One of: base_measure, category, component, derived_measure, identifier, metric, ratio, text, time, unit_measure. derived_measure = computed aggregate (revenue, total value). base_measure = count/quantity. unit_measure = price/rate. ratio = percentage/margin. metric = best numeric column.","default":"derived_measure"},"hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Hint","description":"Optional weak signal — a word from the user's question. Used only as a tiebreaker when multiple columns share the same role. Never the primary signal. Examples: 'revenue', 'quantity', 'price'."}},"type":"object","title":"MetricSpec","description":"Structural role target. The LLM selects based on what the user wants.\n\nUse 'derived_measure' for revenue, spend, total value — the computed aggregate.\nUse 'base_measure' for counts, quantities, discrete amounts.\nUse 'unit_measure' for prices, rates, per-unit values.\nUse 'ratio' for percentages, margins, fill rates.\nUse 'metric' to let the engine pick the best numeric column."},"ConstraintSpec":{"properties":{"requires_derived":{"type":"boolean","title":"Requires Derived","description":"Reject if metric column is not a derived_measure (formula-proven).","default":false},"no_cross_source":{"type":"boolean","title":"No Cross Source","description":"Reject if query requires a cross-source join.","default":false},"min_column_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Column Confidence","description":"Reject if column_confidence component < this value.","default":0},"max_join_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Join Hops","description":"Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).","default":4}},"type":"object","title":"ConstraintSpec"},"ResolvedPlan-Input":{"properties":{"source_name":{"type":"string","title":"Source Name"},"metric_column":{"type":"string","title":"Metric Column"},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column"},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}]},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"schema_revision":{"type":"string","title":"Schema Revision"}},"additionalProperties":false,"type":"object","required":["source_name","metric_column","schema_revision"],"title":"ResolvedPlan"},"QueryBatchResponse":{"properties":{"results":{"items":{"$ref":"#/components/schemas/QueryBatchItemResponse"},"type":"array","title":"Results"},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"}},"additionalProperties":false,"type":"object","title":"QueryBatchResponse"},"QueryBatchItemResponse":{"properties":{"key":{"type":"string","title":"Key"},"data":{"anyOf":[{"$ref":"#/components/schemas/QueryResponse"},{"type":"null"}]},"metadata":{"anyOf":[{"$ref":"#/components/schemas/QueryExecutionMetadata"},{"type":"null"}]},"error":{"anyOf":[{"$ref":"#/components/schemas/QueryBatchError"},{"type":"null"}]}},"additionalProperties":false,"type":"object","required":["key"],"title":"QueryBatchItemResponse"},"QueryResponse":{"properties":{"query_id":{"type":"string","title":"Query Id"},"result":{"title":"Result"},"result_type":{"type":"string","title":"Result Type"},"confidence":{"type":"number","title":"Confidence"},"plan":{"items":{"type":"string"},"type":"array","title":"Plan"},"resolved_column":{"type":"string","title":"Resolved Column"},"resolved_role":{"type":"string","title":"Resolved Role"},"resolved_source":{"type":"string","title":"Resolved Source"},"row_count":{"type":"integer","title":"Row Count"},"candidates":{"items":{"$ref":"#/components/schemas/CandidateColumn"},"type":"array","title":"Candidates"},"source_scores":{"additionalProperties":{"type":"number"},"type":"object","title":"Source Scores"},"ambiguous":{"type":"boolean","title":"Ambiguous"},"exact_spec":{"type":"boolean","title":"Exact Spec"},"explanation":{"items":{"type":"string"},"type":"array","title":"Explanation","default":[]},"latency_ms":{"type":"number","title":"Latency Ms"},"decision_path":{"type":"string","title":"Decision Path"},"plan_hash":{"type":"string","title":"Plan Hash"},"schema_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Schema Revision"},"validated":{"type":"boolean","title":"Validated"},"deterministic_scope":{"type":"string","title":"Deterministic Scope"},"confidence_source":{"type":"string","title":"Confidence Source"},"clarification_required":{"type":"boolean","title":"Clarification Required","default":false},"rejection_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rejection Reason"},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"source_set":{"items":{"type":"string"},"type":"array","title":"Source Set","default":[]},"join_path":{"items":{"type":"object"},"type":"array","title":"Join Path","default":[]},"planner_mode":{"type":"string","title":"Planner Mode","default":"planner_hint"}},"type":"object","required":["query_id","result","result_type","confidence","plan","resolved_column","resolved_role","resolved_source","row_count","candidates","source_scores","ambiguous","exact_spec","latency_ms","decision_path","plan_hash","validated","deterministic_scope","confidence_source"],"title":"QueryResponse"},"CandidateColumn":{"properties":{"source":{"type":"string","title":"Source"},"column":{"type":"string","title":"Column"},"role":{"type":"string","title":"Role"},"magnitude":{"type":"string","title":"Magnitude"},"formula":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Formula"},"confidence":{"type":"number","title":"Confidence"},"score_components":{"additionalProperties":{"type":"number"},"type":"object","title":"Score Components"},"notes":{"items":{"type":"string"},"type":"array","title":"Notes"}},"type":"object","required":["source","column","role","magnitude","formula","confidence"],"title":"CandidateColumn"},"QueryExecutionMetadata":{"properties":{"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"latency_ms":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Latency Ms"},"tokens_in":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Tokens In"},"tokens_out":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Tokens Out"},"cost_usd":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cost Usd"},"cache_hit":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Cache Hit"}},"additionalProperties":false,"type":"object","title":"QueryExecutionMetadata"},"QueryBatchError":{"properties":{"code":{"type":"string","title":"Code"},"message":{"type":"string","title":"Message"},"details":{"type":"object","title":"Details"}},"additionalProperties":false,"type":"object","required":["code","message"],"title":"QueryBatchError"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/query/batch":{"post":{"tags":["Semantic Query"],"summary":"Execute multiple governed exact queries in one request","operationId":"query_batch_v1_query_batch_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryBatchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/QueryBatchResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/query/sql-report`

## POST /v1/query/sql-report

> Execute a constrained read-only SQL report over authorized datasets

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"SQLReportRequest":{"properties":{"sources":{"items":{"$ref":"#/components/schemas/SQLReportSource"},"type":"array","minItems":1,"title":"Sources"},"sql":{"type":"string","minLength":1,"title":"Sql"},"max_rows":{"anyOf":[{"type":"integer","maximum":1000,"minimum":1},{"type":"null"}],"title":"Max Rows"}},"additionalProperties":false,"type":"object","required":["sources","sql"],"title":"SQLReportRequest"},"SQLReportSource":{"properties":{"dataset_id":{"type":"string","minLength":1,"title":"Dataset Id"},"alias":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Alias"}},"additionalProperties":false,"type":"object","required":["dataset_id"],"title":"SQLReportSource"},"SQLReportResponse":{"properties":{"columns":{"items":{"type":"string"},"type":"array","title":"Columns"},"rows":{"items":{"type":"object"},"type":"array","title":"Rows"},"row_count":{"type":"integer","title":"Row Count"},"truncated":{"type":"boolean","title":"Truncated","default":false},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"latency_ms":{"type":"number","title":"Latency Ms"}},"additionalProperties":false,"type":"object","required":["row_count","latency_ms"],"title":"SQLReportResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/query/sql-report":{"post":{"tags":["Semantic Query"],"summary":"Execute a constrained read-only SQL report over authorized datasets","operationId":"query_sql_report_v1_query_sql_report_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SQLReportRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SQLReportResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/verify`

## Validate a structured query plan before execution

> \*\*LLM calls this after reading /v1/sources/schema.\*\*\
> \
> Submit the exact source + column names chosen by the LLM. The engine verifies:\
> \- Source exists in registry\
> \- metric\_column exists and is numeric\
> \- aggregation is valid for the column's role\
> \- group\_column exists (if given)\
> \- join path exists with sufficient confidence (if join\_source\_name given)\
> \
> Returns \`valid: true\` + resolved names on success, or \`valid: false\` + errors + suggestions on failure. \*\*Call /v1/execute (or /v1/query with exact-spec) only after verify returns valid.\*\*

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"VerifyRequest":{"properties":{"source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Name","description":"Exact source name from schema"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source. When provided, verification is scoped to that one registered dataset."},"metric_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Metric Column","description":"Exact column name to aggregate"},"aggregation":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Aggregation","description":"sum | avg | count | max | min"},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column","description":"Exact column name for group-by"},"join_source_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Join Source Name","description":"Second source name for join"},"join_columns":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Join Columns","description":"[local_col, remote_col] — join key pair. Omit to auto-detect."},"min_join_confidence":{"type":"number","title":"Min Join Confidence","description":"Reject join paths below this confidence threshold. Default 0.85 — only statistically solid joins are accepted. Lower to 0.50 to allow weaker joins at your own risk.","default":0.85},"mode":{"type":"string","title":"Mode","description":"strict — reject invalid plans with no suggestions (enterprise enforcement). assist — reject invalid plans AND return corrective suggestions (default, LLM-friendly).","default":"assist"},"resolved_plan":{"anyOf":[{"$ref":"#/components/schemas/ResolvedPlan-Input"},{"type":"null"}],"description":"Exact plan returned by POST /v1/resolve."}},"type":"object","title":"VerifyRequest","description":"LLM-produced execution plan. All names are EXACT (from schema endpoint).\nMojo checks: source exists, columns exist, aggregation is valid for the\ncolumn role, and join keys have sufficient confidence."},"ResolvedPlan-Input":{"properties":{"source_name":{"type":"string","title":"Source Name"},"metric_column":{"type":"string","title":"Metric Column"},"aggregation":{"type":"string","title":"Aggregation","description":"sum | avg | count | max | min","default":"sum"},"group_column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Column"},"join_path":{"anyOf":[{"$ref":"#/components/schemas/JoinPathSpec"},{"type":"null"}]},"filter":{"anyOf":[{"$ref":"#/components/schemas/FilterSpec"},{"type":"null"}]},"limit":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Limit"},"order":{"type":"string","title":"Order","description":"desc | asc","default":"desc"},"constraints":{"$ref":"#/components/schemas/ConstraintSpec"},"schema_revision":{"type":"string","title":"Schema Revision"}},"additionalProperties":false,"type":"object","required":["source_name","metric_column","schema_revision"],"title":"ResolvedPlan"},"JoinPathSpec":{"properties":{"base_source":{"type":"string","title":"Base Source","description":"Source that owns the metric column and anchors the path."},"group_source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Group Source","description":"Final source expected to provide the group column, if different from base_source."},"edges":{"items":{"$ref":"#/components/schemas/JoinEdgeSpec"},"type":"array","title":"Edges","description":"Ordered join edges from base_source toward the dimension source."},"max_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Hops","description":"Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).","default":4},"min_path_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Path Confidence","description":"Minimum acceptable composed confidence across the full join path.","default":0},"reject_on_ambiguity":{"type":"boolean","title":"Reject On Ambiguity","description":"Reject if more than one viable path exists with insufficient score separation.","default":true},"reject_on_fanout":{"type":"boolean","title":"Reject On Fanout","description":"Reject if estimated path fanout exceeds safe execution thresholds.","default":true}},"additionalProperties":false,"type":"object","required":["base_source"],"title":"JoinPathSpec","description":"Explicit multi-hop join contract replacing single-hop join fields."},"JoinEdgeSpec":{"properties":{"left_source":{"type":"string","title":"Left Source","description":"Source on the left side of the join edge."},"right_source":{"type":"string","title":"Right Source","description":"Source on the right side of the join edge."},"left_key":{"type":"string","title":"Left Key","description":"Exact join key column in left_source."},"right_key":{"type":"string","title":"Right Key","description":"Exact join key column in right_source."},"join_type":{"type":"string","title":"Join Type","description":"Join type. Initial implementation supports inner.","default":"inner"},"min_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Confidence","description":"Minimum acceptable confidence for this hop.","default":0},"expected_cardinality":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Expected Cardinality","description":"Optional expected cardinality such as one_to_many, many_to_one, or many_to_many."},"allow_many_to_many":{"type":"boolean","title":"Allow Many To Many","description":"If false, planner/executor must reject many_to_many fanout on this hop.","default":false}},"additionalProperties":false,"type":"object","required":["left_source","right_source","left_key","right_key"],"title":"JoinEdgeSpec","description":"One explicit edge in a multi-hop join path."},"FilterSpec":{"properties":{"time_filter":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Time Filter","description":"Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year."},"conditions":{"items":{"$ref":"#/components/schemas/FilterConditionSpec"},"type":"array","title":"Conditions","description":"Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null."}},"type":"object","title":"FilterSpec","description":"Time or value filter."},"FilterConditionSpec":{"properties":{"column":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Column","description":"Exact source column name for this filter when schema is known."},"dimension_hint":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dimension Hint","description":"Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters."},"op":{"type":"string","enum":["eq","in","gt","gte","lt","lte","is_null","is_not_null"],"title":"Op","description":"Deterministic filter operator.","default":"eq"},"value":{"anyOf":[{},{"type":"null"}],"title":"Value","description":"Scalar comparison value for eq/gt/gte/lt/lte."},"values":{"anyOf":[{"items":{},"type":"array"},{"type":"null"}],"title":"Values","description":"List comparison values for in."}},"additionalProperties":false,"type":"object","title":"FilterConditionSpec"},"ConstraintSpec":{"properties":{"requires_derived":{"type":"boolean","title":"Requires Derived","description":"Reject if metric column is not a derived_measure (formula-proven).","default":false},"no_cross_source":{"type":"boolean","title":"No Cross Source","description":"Reject if query requires a cross-source join.","default":false},"min_column_confidence":{"type":"number","maximum":1,"minimum":0,"title":"Min Column Confidence","description":"Reject if column_confidence component < this value.","default":0},"max_join_hops":{"type":"integer","maximum":6,"minimum":1,"title":"Max Join Hops","description":"Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).","default":4}},"type":"object","title":"ConstraintSpec"},"VerifyResponse":{"properties":{"valid":{"type":"boolean","title":"Valid"},"errors":{"items":{"type":"string"},"type":"array","title":"Errors"},"suggestions":{"items":{"type":"string"},"type":"array","title":"Suggestions"},"resolved":{"additionalProperties":{"type":"string"},"type":"object","title":"Resolved"},"valid_dimensions":{"items":{"type":"string"},"type":"array","title":"Valid Dimensions","default":[]},"valid_measures":{"items":{"type":"string"},"type":"array","title":"Valid Measures","default":[]},"source_behavior":{"type":"string","title":"Source Behavior","default":""},"latency_ms":{"type":"number","title":"Latency Ms"},"verified":{"type":"boolean","title":"Verified","default":false},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id"},"schema_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Schema Revision"},"plan_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Plan Hash"},"verification_mode":{"type":"string","title":"Verification Mode","default":"assist"},"rejection_reason":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rejection Reason"}},"type":"object","required":["valid","errors","suggestions","resolved","latency_ms"],"title":"VerifyResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/verify":{"post":{"tags":["Semantic Query","Semantic Query"],"summary":"Validate a structured query plan before execution","description":"**LLM calls this after reading /v1/sources/schema.**\n\nSubmit the exact source + column names chosen by the LLM. The engine verifies:\n- Source exists in registry\n- metric_column exists and is numeric\n- aggregation is valid for the column's role\n- group_column exists (if given)\n- join path exists with sufficient confidence (if join_source_name given)\n\nReturns `valid: true` + resolved names on success, or `valid: false` + errors + suggestions on failure. **Call /v1/execute (or /v1/query with exact-spec) only after verify returns valid.**","operationId":"verify_plan_v1_verify_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VerifyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/VerifyResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Simulation

### `POST /v1/simulate`

## Run a simulation

> Execute a Monte Carlo simulation and receive a structured decision envelope. Use \`mode: 'auto'\` for minimal setup or \`mode: 'expert'\` for full control.\
> \
> \*\*Performance\*\*: p50 < 15ms server-side (Mojo worker pool, async persistence).\
> \
> \*\*Quota\*\*: Each successful call consumes 1 simulation from your monthly quota. Returns HTTP 429 when quota or rate limit is exceeded.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"DecisionEnvelope":{"properties":{"run_id":{"type":"string","format":"uuid","title":"Run Id"},"status":{"type":"string","title":"Status","default":"completed"},"engine_version":{"type":"string","title":"Engine Version"},"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"rationale":{"type":"string","title":"Rationale"},"metrics":{"$ref":"#/components/schemas/MetricsSummary"},"percentiles":{"$ref":"#/components/schemas/PercentileSummary"},"scenarios_run":{"type":"integer","title":"Scenarios Run"},"execution_ms":{"type":"integer","title":"Execution Ms"},"metadata":{"$ref":"#/components/schemas/RunMetadata"},"simulation_model":{"type":"string","title":"Simulation Model","description":"Which simulation algorithm was used. Possible values: monte_carlo | qmc_sobol | lhs | bootstrap | scenario | sensitivity | mcmc | decision_tree | time_series | compare | importance_sampling","default":"monte_carlo"},"engine_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Engine Type","description":"Engine that ran the simulation (e.g. 'mojo-native-expr', 'lhs', 'mcmc')"},"simulation_class":{"type":"string","title":"Simulation Class","description":"High-level simulation contract class. Examples: predictive, scenario_analysis, sensitivity_analysis, decision_tree.","default":"predictive"},"model_revision":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Revision","description":"Stable engine or model revision used to generate this result."},"assumptions_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Assumptions Hash","description":"Stable fingerprint of the validated simulation assumptions executed by the engine."},"validated_inputs":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Validated Inputs","description":"Normalized summary of the validated request inputs used for execution. Includes mode, runs, variable counts, and model selection."},"confidence_interval":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Confidence Interval","description":"Primary outcome confidence interval derived from the simulated distribution."},"request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Id","description":"Correlation identifier propagated from the API request."},"scenario_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Scenario Analysis","description":"Populated for simulation_model='scenario': expected_value, best_case, scenarios list"},"sensitivity_analysis":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Sensitivity Analysis","description":"Populated for simulation_model='sensitivity': tornado_chart, first_order_sobol, variable_importance"},"bootstrap_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Bootstrap Result","description":"Populated for simulation_model='bootstrap': statistic, observed_value, CI, bias, SE"},"mcmc_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Mcmc Result","description":"Populated for simulation_model='mcmc': posterior summaries, R-hat, acceptance_rate"},"importance_sampling_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Importance Sampling Result","description":"Populated for simulation_model='importance_sampling'. Contains: tail_direction, target_threshold, tail_probability, tail_probability_se, cvar_tail, weighted_mean, weighted_std, theta (tilt parameter), tilt_variable, effective_sample_size, nominal_sample_size, variance_reduction_factor, naive_tail_count."},"scenario_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Scenario Ranking"},"sensitivity_ranking":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Sensitivity Ranking"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score"},"score_breakdown":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Score Breakdown"},"created_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Created At"},"decision_tree_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Decision Tree Result","description":"Populated for simulation_model='decision_tree': n_paths, expected_value, paths[]"},"time_series_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Time Series Result","description":"Populated for simulation_model='time_series'. Contains: model, granularity, dt_years, initial_value, n_steps, fan_chart (per-horizon p5/p25/p50/p75/p95), terminal distribution, max_drawdown_pct, and optional sample_paths for visualization."},"formatted_result":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Formatted Result","description":"Human-readable formatted output values with units. Populated when output_unit_specs or unit_spec is provided. Contains: mean_formatted, p5_formatted, p95_formatted, unit, unit_type, etc."},"unit_context":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Unit Context","description":"Unit metadata for all variables and outputs. Contains per-variable unit type, code, precision, and display scale. Use this to reconstruct formatted values client-side."},"unit_warnings":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Unit Warnings","description":"Non-fatal unit validation warnings (e.g. negative currency, out-of-range probability). Simulation still ran — these are advisory only."},"charts":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Charts","description":"Pre-computed Vega-Lite compatible chart specs for instant rendering. Populated when include_charts=true in the request or automatically for sensitivity/time_series engine types. Keys: 'histogram', 'cdf', 'tornado', 'fan_chart', 'scatter'. Each value is a complete Vega-Lite spec that can be passed to vega-embed."},"histogram_data":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Histogram Data","description":"Pre-computed histogram bins (50 bins) for the primary output distribution."},"decision_plan":{"anyOf":[{"$ref":"#/components/schemas/DecisionPlan"},{"type":"null"}],"description":"Structured decision summary. Always populated by /v1/simulate and /v1/recommend. Contains: recommended_action, confidence, expected_value, risk (p5/p95/PoL), all ranked options, rationale, and integrity hashes."},"request_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Request Hash","description":"SHA-256 fingerprint of the INPUT payload (variables, distributions, objective function, seed). Cryptographic proof of what data was used to make this decision. Computed at submission time before simulation runs. Format: hex string, 64 chars."},"result_hash":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Result Hash","description":"SHA-256 fingerprint of this decision OUTPUT (64-char hex). Covers: run_id, request_hash (input binding), recommended_action, confidence, rationale, metrics, percentiles, scenarios_run, engine_version, simulation_model. Binds the decision to both its inputs AND outputs. Use to verify the decision has not been tampered with. Also returned as X-Decision-Hash response header."}},"type":"object","required":["run_id","engine_version","recommended_action","confidence","rationale","metrics","percentiles","scenarios_run","execution_ms","metadata"],"title":"DecisionEnvelope","description":"Full decision output returned by /v1/simulate, /v1/recommend, and /v1/score."},"MetricsSummary":{"properties":{"expected_value":{"type":"number","title":"Expected Value"},"median":{"type":"number","title":"Median"},"std_deviation":{"type":"number","title":"Std Deviation"},"variance":{"type":"number","title":"Variance"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95"},"cvar_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cvar 95"}},"type":"object","required":["expected_value","median","std_deviation","variance","probability_of_loss"],"title":"MetricsSummary"},"PercentileSummary":{"properties":{"p5":{"type":"number","title":"P5"},"p10":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P10"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p90":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P90"},"p95":{"type":"number","title":"P95"},"p99":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P99"}},"type":"object","required":["p5","p25","p50","p75","p95"],"title":"PercentileSummary"},"RunMetadata":{"properties":{"mode":{"type":"string","title":"Mode"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"billing_units":{"type":"integer","title":"Billing Units"},"engine_version":{"type":"string","title":"Engine Version"}},"type":"object","required":["mode","billing_units","engine_version"],"title":"RunMetadata"},"DecisionPlan":{"properties":{"recommended_action":{"type":"string","title":"Recommended Action"},"confidence":{"type":"number","maximum":1,"minimum":0,"title":"Confidence"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"options":{"items":{"$ref":"#/components/schemas/DecisionOption"},"type":"array","title":"Options","description":"All alternatives ranked by expected value. Single-element for simulate, multi for recommend."},"rationale":{"type":"string","title":"Rationale"},"integrity":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Integrity","description":"Cryptographic proof of inputs/outputs: {request_hash, result_hash}."},"calibration":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Calibration","description":"Human-readable calibration summary, e.g. '12 outcomes | bias=-8.3% (over-optimistic) | hit_rate=75%'. Null until MIN_SAMPLES (5) outcomes are recorded for this org."}},"type":"object","required":["recommended_action","confidence","expected_value","risk","rationale"],"title":"DecisionPlan","description":"Structured, LLM-readable summary of the decision output.\n\nThis is the headline object — it surfaces all decision-critical fields\nin a compact, consistent shape regardless of simulation model used.\nPopulate ``options`` with all ranked alternatives when using /v1/recommend."},"RiskProfile":{"properties":{"p5":{"type":"number","title":"P5","description":"5th-percentile outcome (downside risk floor)"},"p95":{"type":"number","title":"P95","description":"95th-percentile outcome (upside ceiling)"},"probability_of_loss":{"type":"number","maximum":1,"minimum":0,"title":"Probability Of Loss","description":"P(outcome < 0)"},"var_95":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Var 95","description":"Value-at-Risk at 95% confidence"}},"type":"object","required":["p5","p95","probability_of_loss"],"title":"RiskProfile","description":"Quantified downside and upside for a single outcome distribution."},"DecisionOption":{"properties":{"name":{"type":"string","title":"Name"},"rank":{"type":"integer","minimum":1,"title":"Rank"},"expected_value":{"type":"number","title":"Expected Value"},"risk":{"$ref":"#/components/schemas/RiskProfile"},"score":{"anyOf":[{"type":"number","maximum":1,"minimum":0},{"type":"null"}],"title":"Score","description":"Composite score (0–1)"}},"type":"object","required":["name","rank","expected_value","risk"],"title":"DecisionOption","description":"One named alternative in a multi-option decision comparison."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/simulate":{"post":{"tags":["Simulation"],"summary":"Run a simulation","description":"Execute a Monte Carlo simulation and receive a structured decision envelope. Use `mode: 'auto'` for minimal setup or `mode: 'expert'` for full control.\n\n**Performance**: p50 < 15ms server-side (Mojo worker pool, async persistence).\n\n**Quota**: Each successful call consumes 1 simulation from your monthly quota. Returns HTTP 429 when quota or rate limit is exceeded.","operationId":"simulate_v1_simulate_post","requestBody":{"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Payload","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DecisionEnvelope"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/simulate/templates`

## List simulation templates for all industries

> Returns all available domain-specific simulation templates. Requires API key authentication. Use the template's \`id\` with \`GET /v1/simulate/templates/{id}\` to get a ready-to-run payload.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/simulate/templates":{"get":{"tags":["Simulation"],"summary":"List simulation templates for all industries","description":"Returns all available domain-specific simulation templates. Requires API key authentication. Use the template's `id` with `GET /v1/simulate/templates/{id}` to get a ready-to-run payload.","operationId":"list_simulation_templates_v1_simulate_templates_get","parameters":[{"name":"domain","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Domain"}},{"name":"industry","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Industry"}},{"name":"tag","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tag"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":25,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/simulate/templates/{template_id}`

## GET /v1/simulate/templates/{template\_id}

> Get a simulation template with ready-to-run payload

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/simulate/templates/{template_id}":{"get":{"tags":["Simulation"],"summary":"Get a simulation template with ready-to-run payload","operationId":"get_simulation_template_v1_simulate_templates__template_id__get","parameters":[{"name":"template_id","in":"path","required":true,"schema":{"type":"string","title":"Template Id"}},{"name":"runs","in":"query","required":false,"schema":{"type":"integer","default":50000,"title":"Runs"}},{"name":"seed","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/templates/{template_id}/run`

## Run a simulation template directly

> Run a simulation template by ID without constructing the full payload. Optionally override \`runs\` and \`seed\`. Returns simulation results immediately.\
> \
> Use \`GET /v1/simulate/templates\` to list all available templates.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/templates/{template_id}/run":{"post":{"tags":["Simulation"],"summary":"Run a simulation template directly","description":"Run a simulation template by ID without constructing the full payload. Optionally override `runs` and `seed`. Returns simulation results immediately.\n\nUse `GET /v1/simulate/templates` to list all available templates.","operationId":"run_simulation_template_v1_templates__template_id__run_post","parameters":[{"name":"template_id","in":"path","required":true,"schema":{"type":"string","title":"Template Id"}},{"name":"runs","in":"query","required":false,"schema":{"type":"integer","default":10000,"title":"Runs"}},{"name":"seed","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"}},{"name":"engine","in":"query","required":false,"schema":{"type":"string","default":"monte_carlo","title":"Engine"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Source Registry

### `POST /v1/sources/register`

## Register a data source — profile, index, detect joins to all existing sources

> \*\*One-time registration per data source.\*\*\
> \
> \- Full column scan (handles sparse/late-appearing data)\
> \- Mojo detects A×B≈C formulas within the source\
> \- Mojo detects join keys to every already-registered source\
> \- Result cached in memory (hot) + persisted to disk (survives restarts)\
> \
> After registration, use \`POST /v1/query\` with \`sources: \[]\` to query all registered sources, or pass \`source\_ids\` to target specific ones.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"apps__api_server__routers__sources__RegisterRequest":{"properties":{"source":{"$ref":"#/components/schemas/DataSource"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description","description":"Optional human description"}},"type":"object","required":["source"],"title":"RegisterRequest"},"DataSource":{"properties":{"name":{"type":"string","title":"Name","description":"Label for this source (e.g., 'sales', 'orders')"},"dataset_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Dataset Id","description":"Public dataset ID alias for a registered source."},"source_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source Id","description":"Registered source ID; fastest path and avoids re-uploading data."},"records":{"anyOf":[{"items":{"type":"object"},"type":"array"},{"type":"null"}],"title":"Records","description":"Inline JSON records"},"csv":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Csv","description":"Raw CSV text"},"json_str":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Json Str","description":"Raw JSON array/object text (nested auto-flattened)"},"url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Url","description":"HTTP URL — format auto-detected"},"excel_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Excel B64","description":"Excel .xlsx file, base64-encoded"},"parquet_b64":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parquet B64","description":"Parquet file, base64-encoded"},"connection":{"anyOf":[{"type":"object"},{"type":"null"}],"title":"Connection","description":"Connector config dict — see DataSource docstring for all types"},"table":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Table","description":"Legacy field — use connection instead"}},"type":"object","required":["name"],"title":"DataSource","description":"A data source to map. Every format normalizes to list[dict] internally.\n\nInline (no external dependency):\n  `records`    — JSON array of objects (fastest)\n  `csv`        — raw CSV text\n  `json_str`   — raw JSON array/object text (nested JSON is auto-flattened)\n  `url`        — HTTP(S) URL; format auto-detected from Content-Type / extension\n\nBinary files (base64-encoded for API transport):\n  `excel_b64`  — Excel .xlsx file, base64-encoded\n  `parquet_b64`— Parquet file, base64-encoded\n\nConnector config (routes through ConnectorRegistry):\n  `connection` — dict with `type` + connector-specific keys:\n    {\"type\": \"sql\",        \"connection_string\": \"postgresql+asyncpg://...\",\n     \"query\": \"SELECT ...\"}\n    {\"type\": \"sql\",        \"connection_string\": \"sqlite+aiosqlite:///db.sqlite\", \"query\": \"...\"}\n    {\"type\": \"rest_api\",   \"url\": \"https://...\", \"data_path\": \"data.items\"}\n    {\"type\": \"s3\",         \"bucket\": \"my-bucket\", \"key\": \"data/sales.parquet\"}\n    {\"type\": \"gcs\",        \"bucket\": \"my-bucket\", \"blob\": \"data/orders.csv\"}\n    {\"type\": \"azure_blob\", \"connection_string\": \"DefaultEndpointsProtocol=...\",\n                           \"container\": \"data\", \"blob\": \"sales.parquet\"}"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/sources/register":{"post":{"tags":["Source Registry"],"summary":"Register a data source — profile, index, detect joins to all existing sources","description":"**One-time registration per data source.**\n\n- Full column scan (handles sparse/late-appearing data)\n- Mojo detects A×B≈C formulas within the source\n- Mojo detects join keys to every already-registered source\n- Result cached in memory (hot) + persisted to disk (survives restarts)\n\nAfter registration, use `POST /v1/query` with `sources: []` to query all registered sources, or pass `source_ids` to target specific ones.","operationId":"register_source_v1_sources_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/apps__api_server__routers__sources__RegisterRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Register Source V1 Sources Register Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/sources`

## GET /v1/sources

> List all registered sources for this org

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/sources":{"get":{"tags":["Source Registry"],"summary":"List all registered sources for this org","operationId":"list_sources_v1_sources_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response List Sources V1 Sources Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/sources/graph`

## GET /v1/sources/graph

> Connection graph — all detected join paths between registered sources

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}}},"paths":{"/v1/sources/graph":{"get":{"tags":["Source Registry"],"summary":"Connection graph — all detected join paths between registered sources","operationId":"get_graph_v1_sources_graph_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Graph V1 Sources Graph Get"}}}}}}}}}
```

### `GET /v1/sources/{source_id}`

## GET /v1/sources/{source\_id}

> Get schema for a registered source

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/sources/{source_id}":{"get":{"tags":["Source Registry"],"summary":"Get schema for a registered source","operationId":"get_source_v1_sources__source_id__get","parameters":[{"name":"source_id","in":"path","required":true,"schema":{"type":"string","title":"Source Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Get Source V1 Sources  Source Id  Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/sources/{source_id}`

## DELETE /v1/sources/{source\_id}

> Remove a registered source

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/sources/{source_id}":{"delete":{"tags":["Source Registry"],"summary":"Remove a registered source","operationId":"delete_source_v1_sources__source_id__delete","parameters":[{"name":"source_id","in":"path","required":true,"schema":{"type":"string","title":"Source Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Delete Source V1 Sources  Source Id  Delete"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Streaming

### `POST /v1/simulate/stream`

## Streaming simulation via Server-Sent Events

> Run a simulation and receive progressive results via \*\*Server-Sent Events\*\*.\
> \
> The connection stays open and emits events as the Mojo engine computes:\
> \- \*\*\`progress\`\*\* events every \`checkpoint\_every\` runs (default: 1000)\
> &#x20; Each carries Welford online statistics: \`mean\`, \`std\`, \`min\`, \`max\`,\
> &#x20; \`probability\_of\_loss\`, \`runs\_completed\`, \`progress\` (0–1).\
> \- \*\*\`final\`\*\* event when complete — contains the full \`DecisionEnvelope\`\
> &#x20; identical to what \`/v1/simulate\` returns.\
> \
> \### Example (curl)\
> \`\`\`bash\
> curl -N -X POST /v1/simulate/stream \\\
> &#x20; -H "Authorization: Bearer sk-..." \\\
> &#x20; -H "Content-Type: application/json" \\\
> &#x20; -d '{"mode":"expert","runs":100000,"variables":\[...]}'\
> \`\`\`\
> \
> \### Example (JavaScript EventSource)\
> \`\`\`javascript\
> const es = new EventSource('/v1/simulate/stream?token=sk-...');\
> es.addEventListener('progress', e => console.log(JSON.parse(e.data)));\
> es.addEventListener('final', e => {\
> &#x20; console.log(JSON.parse(e.data).result);\
> &#x20; es.close();\
> });\
> \`\`\`\
> \
> \### Query parameters\
> \- \`checkpoint\_every\` — emit a progress event every N runs (default: 1000, min: 100)

````json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/simulate/stream":{"post":{"tags":["Streaming"],"summary":"Streaming simulation via Server-Sent Events","description":"Run a simulation and receive progressive results via **Server-Sent Events**.\n\nThe connection stays open and emits events as the Mojo engine computes:\n- **`progress`** events every `checkpoint_every` runs (default: 1000)\n  Each carries Welford online statistics: `mean`, `std`, `min`, `max`,\n  `probability_of_loss`, `runs_completed`, `progress` (0–1).\n- **`final`** event when complete — contains the full `DecisionEnvelope`\n  identical to what `/v1/simulate` returns.\n\n### Example (curl)\n```bash\ncurl -N -X POST /v1/simulate/stream \\\n  -H \"Authorization: Bearer sk-...\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"mode\":\"expert\",\"runs\":100000,\"variables\":[...]}'\n```\n\n### Example (JavaScript EventSource)\n```javascript\nconst es = new EventSource('/v1/simulate/stream?token=sk-...');\nes.addEventListener('progress', e => console.log(JSON.parse(e.data)));\nes.addEventListener('final', e => {\n  console.log(JSON.parse(e.data).result);\n  es.close();\n});\n```\n\n### Query parameters\n- `checkpoint_every` — emit a progress event every N runs (default: 1000, min: 100)","operationId":"simulate_stream_v1_simulate_stream_post","parameters":[{"name":"checkpoint_every","in":"query","required":false,"schema":{"type":"integer","default":1000,"title":"Checkpoint Every"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}},"title":"Payload"}}}},"responses":{"200":{"description":"SSE stream of progress events + final DecisionEnvelope","content":{"text/event-stream":{}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
````

## System

### `GET /v1/health`

## GET /v1/health

> Health check

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/health":{"get":{"tags":["System"],"summary":"Health check","operationId":"health_v1_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HealthResponse"}}}}}}}},"components":{"schemas":{"HealthResponse":{"properties":{"status":{"type":"string","title":"Status"},"timestamp":{"type":"string","format":"date-time","title":"Timestamp"}},"type":"object","required":["status","timestamp"],"title":"HealthResponse"}}}}
```

### `GET /v1/version`

## GET /v1/version

> API and engine version

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/version":{"get":{"tags":["System"],"summary":"API and engine version","operationId":"version_v1_version_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/VersionResponse"}}}}}}}},"components":{"schemas":{"VersionResponse":{"properties":{"api_version":{"type":"string","title":"Api Version"},"engine_version":{"type":"string","title":"Engine Version"},"environment":{"type":"string","title":"Environment"}},"type":"object","required":["api_version","engine_version","environment"],"title":"VersionResponse"}}}}
```

### `GET /v1/meta/contract`

## GET /v1/meta/contract

> Machine-readable Codna contract

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"paths":{"/v1/meta/contract":{"get":{"tags":["System"],"summary":"Machine-readable Codna contract","operationId":"contract_v1_meta_contract_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/PlatformContractResponse"}}}}}}}},"components":{"schemas":{"PlatformContractResponse":{"properties":{"contract_version":{"type":"string","title":"Contract Version"},"brand":{"type":"string","title":"Brand"},"api_base_url":{"type":"string","title":"Api Base Url"},"mcp_endpoint":{"type":"string","title":"Mcp Endpoint"},"mcp_tools_endpoint":{"type":"string","title":"Mcp Tools Endpoint"},"auth_scheme":{"type":"string","title":"Auth Scheme"},"api_key_prefixes":{"$ref":"#/components/schemas/ApiKeyPrefixesResponse"},"compatibility":{"$ref":"#/components/schemas/CompatibilityResponse"},"defaults":{"$ref":"#/components/schemas/DefaultsResponse"},"primary_data_query_contract":{"type":"object","title":"Primary Data Query Contract"},"integrations":{"items":{"$ref":"#/components/schemas/IntegrationResponse"},"type":"array","title":"Integrations"}},"type":"object","required":["contract_version","brand","api_base_url","mcp_endpoint","mcp_tools_endpoint","auth_scheme","api_key_prefixes","compatibility","defaults","primary_data_query_contract"],"title":"PlatformContractResponse"},"ApiKeyPrefixesResponse":{"properties":{"live":{"type":"string","title":"Live"},"test":{"type":"string","title":"Test"}},"type":"object","required":["live","test"],"title":"ApiKeyPrefixesResponse"},"CompatibilityResponse":{"properties":{"legacy_headers":{"items":{"type":"string"},"type":"array","title":"Legacy Headers"},"legacy_env_vars":{"items":{"type":"string"},"type":"array","title":"Legacy Env Vars"},"legacy_domains":{"items":{"type":"string"},"type":"array","title":"Legacy Domains"},"deprecation_window_days":{"type":"integer","title":"Deprecation Window Days"}},"type":"object","required":["legacy_headers","legacy_env_vars","legacy_domains","deprecation_window_days"],"title":"CompatibilityResponse"},"DefaultsResponse":{"properties":{"read_only_default":{"type":"boolean","title":"Read Only Default"},"write_confirmation_required":{"type":"boolean","title":"Write Confirmation Required"},"plan_limits":{"additionalProperties":{"type":"object"},"type":"object","title":"Plan Limits"}},"type":"object","required":["read_only_default","write_confirmation_required","plan_limits"],"title":"DefaultsResponse"},"IntegrationResponse":{"properties":{"name":{"type":"string","title":"Name"},"description":{"type":"string","title":"Description"},"icon":{"type":"string","title":"Icon"},"capabilities":{"items":{"type":"string"},"type":"array","title":"Capabilities"},"auth_scheme":{"type":"string","title":"Auth Scheme"},"required_scopes":{"items":{"type":"string"},"type":"array","title":"Required Scopes"},"read_only_default":{"type":"boolean","title":"Read Only Default"},"write_actions":{"items":{"type":"string"},"type":"array","title":"Write Actions"},"admin_controls":{"items":{"type":"string"},"type":"array","title":"Admin Controls"},"docs_url":{"type":"string","title":"Docs Url"},"privacy_url":{"type":"string","title":"Privacy Url"},"terms_url":{"type":"string","title":"Terms Url"},"support_url":{"type":"string","title":"Support Url"},"regions":{"items":{"type":"string"},"type":"array","title":"Regions"},"status":{"type":"string","title":"Status"}},"type":"object","required":["name","description","icon","capabilities","auth_scheme","required_scopes","read_only_default","docs_url","privacy_url","terms_url","support_url","status"],"title":"IntegrationResponse"}}}}
```

## Team

### `GET /v1/team`

## List team members

> List all active users in the authenticated org.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"MemberInfo":{"properties":{"user_id":{"type":"string","title":"User Id"},"name":{"type":"string","title":"Name"},"email":{"type":"string","title":"Email"},"role":{"type":"string","title":"Role"},"status":{"type":"string","title":"Status"},"last_active":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Active"}},"type":"object","required":["user_id","name","email","role","status","last_active"],"title":"MemberInfo"},"TeamListResponse":{"properties":{"members":{"items":{"$ref":"#/components/schemas/MemberInfo"},"type":"array","title":"Members"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["members","total","page","limit","pages"],"title":"TeamListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/team":{"get":{"tags":["Team"],"summary":"List team members","description":"List all active users in the authenticated org.","operationId":"list_team_v1_team_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","minimum":1},{"type":"null"}],"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"anyOf":[{"type":"array","items":{"$ref":"#/components/schemas/MemberInfo"}},{"$ref":"#/components/schemas/TeamListResponse"}],"title":"Response List Team V1 Team Get"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/team/invite`

## Invite a team member

> Send an invitation email to a new team member (stub — email not implemented).

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"InviteRequest":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"role":{"type":"string","title":"Role","default":"member"}},"type":"object","required":["email"],"title":"InviteRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/team/invite":{"post":{"tags":["Team"],"summary":"Invite a team member","description":"Send an invitation email to a new team member (stub — email not implemented).","operationId":"invite_member_v1_team_invite_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InviteRequest"}}},"required":true},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Invite Member V1 Team Invite Post"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `PATCH /v1/team/{user_id}/role`

## Update a team member's role

> Change a team member's role.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RoleUpdateRequest":{"properties":{"role":{"type":"string","title":"Role"}},"type":"object","required":["role"],"title":"RoleUpdateRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/team/{user_id}/role":{"patch":{"tags":["Team"],"summary":"Update a team member's role","description":"Change a team member's role.","operationId":"update_member_role_v1_team__user_id__role_patch","parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RoleUpdateRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Update Member Role V1 Team  User Id  Role Patch"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/team/{user_id}`

## Remove a team member

> Remove a user from the org.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/team/{user_id}":{"delete":{"tags":["Team"],"summary":"Remove a team member","description":"Remove a user from the org.","operationId":"remove_member_v1_team__user_id__delete","parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"User Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/audit-logs`

## Paginated audit log from DB

> Return paginated audit log for the authenticated org from the audit\_events table.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"AuditLogResponse":{"properties":{"entries":{"items":{"$ref":"#/components/schemas/AuditLogEntry"},"type":"array","title":"Entries"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["entries","total","page","limit","pages"],"title":"AuditLogResponse"},"AuditLogEntry":{"properties":{"id":{"type":"string","title":"Id"},"timestamp":{"type":"string","format":"date-time","title":"Timestamp"},"actor_email":{"type":"string","title":"Actor Email"},"action":{"type":"string","title":"Action"},"resource_type":{"type":"string","title":"Resource Type"},"resource_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Resource Id"},"ip_address":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Ip Address"},"result":{"type":"string","title":"Result"}},"type":"object","required":["id","timestamp","actor_email","action","resource_type","resource_id","ip_address","result"],"title":"AuditLogEntry"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/audit-logs":{"get":{"tags":["Team"],"summary":"Paginated audit log from DB","description":"Return paginated audit log for the authenticated org from the audit_events table.","operationId":"get_audit_logs_v1_audit_logs_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"default":25,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AuditLogResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## Triggers

### `POST /v1/triggers`

## POST /v1/triggers

> Register a trigger

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"RegisterTriggerRequest":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"condition":{"$ref":"#/components/schemas/TriggerCondition"},"simulation_template":{"type":"object","title":"Simulation Template","description":"SimulateRequest-compatible payload to run when trigger fires."},"webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Webhook Url","description":"HTTPS endpoint to POST notification results to."},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url","description":"When set and auto_execute=true, the full DecisionPlan is POSTed here as an actionable execution payload (same format as POST /v1/decisions/{id}/execute)."},"auto_execute":{"type":"boolean","title":"Auto Execute","description":"If true, automatically dispatch the decision to execution_webhook_url after every successful trigger fire.","default":false},"description":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Description"}},"type":"object","required":["name","condition","simulation_template"],"title":"RegisterTriggerRequest"},"TriggerCondition":{"properties":{"source_id":{"type":"string","title":"Source Id"},"metric_hint":{"type":"string","title":"Metric Hint"},"threshold":{"type":"number","title":"Threshold"},"direction":{"type":"string","enum":["above","below","change"],"title":"Direction"},"aggregation":{"type":"string","enum":["sum","avg","max","min","count"],"title":"Aggregation","default":"sum"}},"type":"object","required":["source_id","metric_hint","threshold","direction"],"title":"TriggerCondition"},"TriggerSummary":{"properties":{"trigger_id":{"type":"string","title":"Trigger Id"},"org_id":{"type":"string","title":"Org Id"},"name":{"type":"string","title":"Name"},"status":{"type":"string","enum":["active","paused"],"title":"Status"},"condition":{"$ref":"#/components/schemas/TriggerCondition"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Webhook Url"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"auto_execute":{"type":"boolean","title":"Auto Execute","default":false},"created_at":{"type":"string","format":"date-time","title":"Created At"},"last_checked_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Checked At"},"last_fired_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Fired At"},"last_result_summary":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last Result Summary"}},"type":"object","required":["trigger_id","org_id","name","status","condition","description","webhook_url","created_at","last_checked_at","last_fired_at","last_result_summary"],"title":"TriggerSummary"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/triggers":{"post":{"tags":["Triggers"],"summary":"Register a trigger","operationId":"register_trigger_v1_triggers_post","requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterTriggerRequest"}}}},"responses":{"201":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TriggerSummary"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/triggers`

## GET /v1/triggers

> List all triggers

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"TriggerListResponse":{"properties":{"triggers":{"items":{"$ref":"#/components/schemas/TriggerSummary"},"type":"array","title":"Triggers"},"count":{"type":"integer","title":"Count"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"}},"type":"object","required":["triggers","count","total","page","limit","pages"],"title":"TriggerListResponse"},"TriggerSummary":{"properties":{"trigger_id":{"type":"string","title":"Trigger Id"},"org_id":{"type":"string","title":"Org Id"},"name":{"type":"string","title":"Name"},"status":{"type":"string","enum":["active","paused"],"title":"Status"},"condition":{"$ref":"#/components/schemas/TriggerCondition"},"description":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Description"},"webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Webhook Url"},"execution_webhook_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Webhook Url"},"auto_execute":{"type":"boolean","title":"Auto Execute","default":false},"created_at":{"type":"string","format":"date-time","title":"Created At"},"last_checked_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Checked At"},"last_fired_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Last Fired At"},"last_result_summary":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Last Result Summary"}},"type":"object","required":["trigger_id","org_id","name","status","condition","description","webhook_url","created_at","last_checked_at","last_fired_at","last_result_summary"],"title":"TriggerSummary"},"TriggerCondition":{"properties":{"source_id":{"type":"string","title":"Source Id"},"metric_hint":{"type":"string","title":"Metric Hint"},"threshold":{"type":"number","title":"Threshold"},"direction":{"type":"string","enum":["above","below","change"],"title":"Direction"},"aggregation":{"type":"string","enum":["sum","avg","max","min","count"],"title":"Aggregation","default":"sum"}},"type":"object","required":["source_id","metric_hint","threshold","direction"],"title":"TriggerCondition"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/triggers":{"get":{"tags":["Triggers"],"summary":"List all triggers","operationId":"list_triggers_v1_triggers_get","parameters":[{"name":"status","in":"query","required":false,"schema":{"type":"string","default":"all","title":"Status"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"anyOf":[{"type":"integer","maximum":200,"minimum":1},{"type":"null"}],"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/TriggerListResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/triggers/{trigger_id}/fire`

## Fire a trigger

> Evaluate the trigger condition and run the simulation template if met (or forced).

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"FireTriggerRequest":{"properties":{"force":{"type":"boolean","title":"Force","description":"Run simulation even if condition is not currently met.","default":false}},"type":"object","title":"FireTriggerRequest"},"FireTriggerResponse":{"properties":{"trigger_id":{"type":"string","title":"Trigger Id"},"condition_met":{"type":"boolean","title":"Condition Met"},"fired":{"type":"boolean","title":"Fired"},"simulation_run_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Simulation Run Id"},"recommended_action":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Recommended Action"},"expected_value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Expected Value"},"confidence":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Confidence"},"fired_at":{"anyOf":[{"type":"string","format":"date-time"},{"type":"null"}],"title":"Fired At"},"execution_status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Execution Status"},"message":{"type":"string","title":"Message"}},"type":"object","required":["trigger_id","condition_met","fired","simulation_run_id","recommended_action","expected_value","confidence","fired_at","message"],"title":"FireTriggerResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/triggers/{trigger_id}/fire":{"post":{"tags":["Triggers"],"summary":"Fire a trigger","description":"Evaluate the trigger condition and run the simulation template if met (or forced).","operationId":"fire_trigger_v1_triggers__trigger_id__fire_post","parameters":[{"name":"trigger_id","in":"path","required":true,"schema":{"type":"string","title":"Trigger Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FireTriggerRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/FireTriggerResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `PATCH /v1/triggers/{trigger_id}/pause`

## PATCH /v1/triggers/{trigger\_id}/pause

> Pause or resume a trigger

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/triggers/{trigger_id}/pause":{"patch":{"tags":["Triggers"],"summary":"Pause or resume a trigger","operationId":"pause_trigger_v1_triggers__trigger_id__pause_patch","parameters":[{"name":"trigger_id","in":"path","required":true,"schema":{"type":"string","title":"Trigger Id"}},{"name":"paused","in":"query","required":false,"schema":{"type":"boolean","default":true,"title":"Paused"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Pause Trigger V1 Triggers  Trigger Id  Pause Patch"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/triggers/{trigger_id}`

## DELETE /v1/triggers/{trigger\_id}

> Delete a trigger

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/triggers/{trigger_id}":{"delete":{"tags":["Triggers"],"summary":"Delete a trigger","operationId":"delete_trigger_v1_triggers__trigger_id__delete","parameters":[{"name":"trigger_id","in":"path","required":true,"schema":{"type":"string","title":"Trigger Id"}}],"responses":{"204":{"description":"Successful Response"},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## What-If Analysis

### `POST /v1/simulate/what-if`

## What-if parametric sweep

> Vary one variable parameter across a range and see how outcomes change. All steps run in parallel via Mojo worker pool. Returns a sweep with mean, percentiles, and probability of loss at each step. Automatically computes sensitivity direction and elasticity.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"WhatIfRequest":{"properties":{"request":{"oneOf":[{"$ref":"#/components/schemas/SimulateRequestAuto"},{"$ref":"#/components/schemas/SimulateRequestExpert"}],"title":"Request","description":"Base simulation request","discriminator":{"propertyName":"mode","mapping":{"auto":"#/components/schemas/SimulateRequestAuto","expert":"#/components/schemas/SimulateRequestExpert"}}},"variable":{"type":"string","title":"Variable","description":"Variable name to sweep"},"param":{"type":"string","title":"Param","description":"Which parameter to vary: mean, std, low, high, mode, value","default":"mean"},"range_pct":{"type":"number","title":"Range Pct","description":"Sweep range as fraction of base value (e.g. 0.30 = ±30%)","default":0.3},"n_steps":{"type":"integer","maximum":51,"minimum":3,"title":"N Steps","description":"Number of steps (odd number recommended for symmetric sweep)","default":11},"runs_per_step":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs Per Step","description":"Monte Carlo runs per step. Lower for faster response.","default":5000}},"type":"object","required":["request","variable"],"title":"WhatIfRequest","description":"Inline what-if request (no stored run needed)."},"SimulateRequestAuto":{"properties":{"mode":{"const":"auto","title":"Mode"},"scenario":{"$ref":"#/components/schemas/AutoScenario"},"runs":{"type":"integer","maximum":100000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]}},"type":"object","required":["mode","scenario"],"title":"SimulateRequestAuto","description":"Auto-mode simulation request — minimal setup, engine infers distributions."},"AutoScenario":{"properties":{"name":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Name"},"variables":{"additionalProperties":{"$ref":"#/components/schemas/AutoVariable"},"type":"object","maxProperties":50,"minProperties":1,"title":"Variables"},"objective":{"$ref":"#/components/schemas/ObjectiveType"}},"type":"object","required":["variables","objective"],"title":"AutoScenario"},"AutoVariable":{"properties":{"low":{"type":"number","title":"Low","description":"Lower bound / pessimistic value"},"high":{"type":"number","title":"High","description":"Upper bound / optimistic value"},"description":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Description"}},"type":"object","required":["low","high"],"title":"AutoVariable"},"ObjectiveType":{"type":"string","enum":["maximize_net_value","maximize_revenue","minimize_cost","minimize_risk","maximize_score"],"title":"ObjectiveType"},"SimulationModel":{"type":"string","enum":["monte_carlo","qmc_sobol","lhs","bootstrap","scenario","sensitivity","mcmc","decision_tree","time_series","compare","importance_sampling"],"title":"SimulationModel","description":"Which simulation algorithm to use. ALL run natively in Mojo — zero Python bottlenecks."},"BootstrapConfig":{"properties":{"historical_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Historical Data"},"statistic":{"type":"string","title":"Statistic","description":"Statistic to compute on each resample. One of: mean, median, std, variance, sum, min, max, sharpe, percentile_5, percentile_25, percentile_75, percentile_95, range, cv","default":"mean"},"confidence_level":{"type":"number","maximum":1,"minimum":0,"title":"Confidence Level","default":0.95}},"type":"object","required":["historical_data"],"title":"BootstrapConfig","description":"Config for engine_type='bootstrap' — non-parametric resampling."},"ScenarioConfig":{"properties":{"scenarios":{"items":{"$ref":"#/components/schemas/ScenarioItem"},"type":"array","maxItems":50,"minItems":1,"title":"Scenarios"}},"type":"object","required":["scenarios"],"title":"ScenarioConfig","description":"Config for engine_type='scenario' — discrete weighted scenarios."},"ScenarioItem":{"properties":{"name":{"type":"string","maxLength":200,"title":"Name"},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability"},"variables":{"additionalProperties":{"type":"number"},"type":"object","title":"Variables"},"objective_function":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Objective Function"}},"type":"object","required":["name","probability"],"title":"ScenarioItem","description":"A single named scenario for discrete scenario analysis."},"SensitivityConfig":{"properties":{"method":{"type":"string","title":"Method","description":"tornado | sobol | both","default":"both"}},"type":"object","title":"SensitivityConfig","description":"Config for engine_type='sensitivity' — sensitivity analysis."},"SimulateRequestExpert":{"properties":{"mode":{"const":"expert","title":"Mode"},"simulation":{"$ref":"#/components/schemas/ExpertSimulation"},"runs":{"type":"integer","maximum":1000000,"minimum":100,"title":"Runs","default":10000},"seed":{"anyOf":[{"type":"integer","minimum":0},{"type":"null"}],"title":"Seed"},"simulation_model":{"allOf":[{"$ref":"#/components/schemas/SimulationModel"}],"description":"Simulation algorithm. All run natively in Mojo.","default":"monte_carlo"},"bootstrap_config":{"anyOf":[{"$ref":"#/components/schemas/BootstrapConfig"},{"type":"null"}]},"scenario_config":{"anyOf":[{"$ref":"#/components/schemas/ScenarioConfig"},{"type":"null"}]},"mcmc_config":{"anyOf":[{"$ref":"#/components/schemas/MCMCConfig"},{"type":"null"}]},"sensitivity_config":{"anyOf":[{"$ref":"#/components/schemas/SensitivityConfig"},{"type":"null"}]},"importance_sampling_config":{"anyOf":[{"$ref":"#/components/schemas/ImportanceSamplingConfig"},{"type":"null"}],"description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events. Required when simulation_model='importance_sampling'. Provides unbiased tail probability and CVaR estimates with 100–10,000× fewer samples than brute-force MC."},"decision_tree_config":{"anyOf":[{"$ref":"#/components/schemas/DecisionTreeConfig"},{"type":"null"}],"description":"Config for engine_type='decision_tree' — multi-layered branching decisions."},"time_series_config":{"anyOf":[{"$ref":"#/components/schemas/TimeSeriesConfig"},{"type":"null"}],"description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation. Models: GBM (stocks/crypto), OU (rates/spreads), arithmetic, compound, custom. Granularities: ms, s, min, h, day, week, month, quarter, year."},"include_charts":{"type":"boolean","title":"Include Charts","description":"Include pre-computed Vega-Lite chart specs in the response. When true, adds 'charts' dict with histogram, CDF, tornado (if sensitivity), fan_chart (if time_series). Ready to pass to vega-embed for instant rendering. Adds ~5ms to response time.","default":false},"include_histogram":{"type":"boolean","title":"Include Histogram","description":"Include pre-computed 50-bin histogram data (lighter than full chart spec). Adds 'histogram_data' to response. Useful for quick distribution preview.","default":false}},"type":"object","required":["mode","simulation"],"title":"SimulateRequestExpert","description":"Expert-mode simulation request — full distribution and objective control."},"ExpertSimulation":{"properties":{"variables":{"items":{"$ref":"#/components/schemas/VariableSpec"},"type":"array","minItems":1,"title":"Variables"},"correlations":{"items":{"$ref":"#/components/schemas/CorrelationSpec"},"type":"array","title":"Correlations"},"objective_function":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Objective Function","description":"Expression evaluated each scenario. Supports all math functions. Multi-output: separate with | pipe character. Example: 'revenue - cost | (revenue - cost) / revenue * 100 | min(cash_flow, 0)'"},"scoring":{"$ref":"#/components/schemas/ScoringWeights"},"domain":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain","description":"Industry/domain hint: finance, medical, manufacturing, aerospace, defense, etc."},"domain_template":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Template","description":"Name of predefined domain template used (for reference)"},"output_labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Labels","description":"Labels for multi-output objectives (matches | separator count)"},"output_units":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Output Units","description":"Physical/currency units for each output. E.g. ['USD', '%', 'years']"},"output_unit_specs":{"anyOf":[{"items":{"$ref":"#/components/schemas/UnitSpec"},"type":"array"},{"type":"null"}],"title":"Output Unit Specs","description":"Full UnitSpec per output objective (matches | separator count). Enables formatted_result in the response with currency symbols, compact notation ($1.2M), scientific notation (1.23e-9 Pa), etc. Example: [{'type':'currency','code':'USD','format':'compact'}, {'type':'percentage'}]"}},"type":"object","required":["variables"],"title":"ExpertSimulation","description":"Universal simulation specification. No restrictions on domain, variable count,\nor expression complexity. Works for any industry and data type.\n\nobjective_function — complete function reference:\n  Arithmetic:   +, -, *, /, ^ (power), % (mod)\n  Standard:     sqrt(x), exp(x), ln(x), log(x), log10(x), log2(x), log1p(x),\n                expm1(x), abs(x), floor(x), ceil(x), round(x)\n  Min/Max:      min(a,b), max(a,b), clip(v,lo,hi)\n  Conditional:  if(cond>0, then_val, else_val)\n  Trigonometry: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x)\n                atan2(y,x), sinh(x), cosh(x), tanh(x)\n  Special:      erf(x), erfc(x), gamma(x), lgamma(x), sign(x), hypot(a,b)\n  Statistical:  norm_cdf(x), norm_pdf(x), norm_ppf(p),\n                t_cdf(x, df), chi2_cdf(x, df), logistic(x), logit(x)\n  Combinatorics: factorial(n), comb(n,k), perm(n,k)\n  Sequences:    fibonacci(n), fib(n), fib_ratio(n) = F(n)/F(n-1)\n  Financial:    npv(rate,cf0,cf1,...), pmt(rate,n,pv), fv(rate,n,pmt,pv),\n                pv(rate,n,pmt), annuity(rate,n), duration(rate,n)\n  Constants:    c (speed of light), G (gravity), g (9.81 m/s²),\n                kB (Boltzmann), NA (Avogadro), R (gas), pi, e, phi\n  Multi-output: separate objectives with | e.g. \"net_profit | risk_score | irr\"\n  Variables:    any variable name from the variables list as a symbol\n\nExamples:\n  \"revenue - cost\"\n  \"max(0, sales * margin - fixed_cost)\"\n  \"npv(0.1, -capex, cf1, cf2, cf3, cf4, cf5)\"\n  \"norm_cdf((mu - threshold) / sigma)\"\n  \"mass * g * height\"            # kinetic/potential energy\n  \"fibonacci(growth_stage)\"      # Fibonacci growth model\n  \"revenue - cost | revenue / cost | norm_cdf(revenue - target)\"  # multi-output"},"VariableSpec":{"properties":{"name":{"type":"string","maxLength":500,"minLength":1,"title":"Name"},"distribution":{"$ref":"#/components/schemas/DistributionType"},"params":{"$ref":"#/components/schemas/DistributionParams"},"unit":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Unit","description":"Short-hand unit string: 'USD', 'BTC', '%', 'bps', 'days', 'Pa', etc."},"unit_spec":{"anyOf":[{"$ref":"#/components/schemas/UnitSpec"},{"type":"null"}],"description":"Full unit specification with type, code, precision, scale, format, sim_scale. Supersedes 'unit' if both provided. Enables preprocessing (date→epoch, crypto satoshi→BTC), range validation, and formatted output."},"description":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Description"},"domain_hint":{"anyOf":[{"type":"string","maxLength":200},{"type":"null"}],"title":"Domain Hint","description":"Optional domain hint e.g. 'time_to_failure', 'patient_recovery_days', 'material_yield_strength'"},"labels":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Labels","description":"For categorical/discrete: human-readable labels for each outcome index"}},"type":"object","required":["name","distribution","params"],"title":"VariableSpec","description":"A single simulation variable. No domain restrictions — works for any\nphysical, financial, clinical, operational, or scientific measurement."},"DistributionType":{"type":"string","enum":["normal","uniform","triangular","lognormal","fixed","discrete","categorical","beta","exponential","weibull","gamma","pert","bernoulli","poisson","student_t","cauchy","laplace","pareto","gumbel","rayleigh","arcsine","logistic","halfnormal","vonmises","neg_binomial","hypergeometric","negative_binomial"],"title":"DistributionType","description":"Universal distribution library — no restrictions on domain or data type.\nApplicable to any industry: finance, medical, manufacturing, aerospace,\ndefense, energy, hospitality, insurance, pharma, supply chain, and more."},"DistributionParams":{"properties":{"mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mean"},"std":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Std"},"low":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Low"},"high":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"High"},"mode":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Mode"},"value":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Value"},"alpha":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Alpha"},"beta":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Beta"},"rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Rate"},"lambda":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Lambda"},"shape":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Shape"},"scale":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Scale"},"likely":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Likely"},"gamma":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Gamma"},"p":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"P"},"values":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Values"},"probabilities":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Probabilities"}},"additionalProperties":true,"type":"object","title":"DistributionParams"},"UnitSpec":{"properties":{"type":{"type":"string","title":"Type","description":"Unit category: currency | crypto | date | duration | percentage | bps | scientific | si | count | probability | custom | raw","default":"raw"},"code":{"type":"string","maxLength":50,"title":"Code","description":"Unit identifier: ISO 4217 currency, crypto ticker, SI symbol, etc.","default":""},"precision":{"anyOf":[{"type":"integer","maximum":18,"minimum":0},{"type":"null"}],"title":"Precision","description":"Display decimal places. None = auto-inferred from type/code."},"scale":{"type":"number","title":"Scale","description":"Multiply raw simulation output by this for display (e.g. 100 for percentage).","default":1},"format":{"type":"string","title":"Format","description":"Display format: standard | compact ($1.2M) | scientific (1.23e-9)","default":"standard"},"base_unit":{"type":"string","maxLength":50,"title":"Base Unit","description":"Sub-unit label (informational). E.g. 'satoshi' for BTC, 'wei' for ETH.","default":""},"sim_scale":{"type":"number","title":"Sim Scale","description":"Divide input params by this before simulation. E.g. sim_scale=1e8 if BTC inputs are in satoshis, converts to whole BTC for Mojo.","default":1}},"additionalProperties":true,"type":"object","title":"UnitSpec","description":"Universal unit specification — supports any numeric domain.\n\nShort-hand strings also accepted anywhere a UnitSpec is expected:\n  \"USD\"        → currency/USD (2 decimal places)\n  \"BTC\"        → crypto/BTC (8 decimal places, satoshi-aware)\n  \"ETH\"        → crypto/ETH (18 decimals, wei-aware)\n  \"%\"          → percentage (scale × 100 for display)\n  \"bps\"        → basis points (scale × 10,000 for display)\n  \"days\"       → duration in days\n  \"Pa\" / \"kg\"  → SI unit (scientific notation for tiny/huge values)\n  \"probability\" → strictly [0,1] validated\n  \"count\"      → non-negative integer-like\n\nFull dict form:\n  {\n    \"type\": \"currency\",      # unit category\n    \"code\": \"USD\",           # unit identifier\n    \"precision\": 2,          # display decimal places (None = auto)\n    \"scale\": 1.0,            # multiply raw value for display (e.g. 100 for 0→1 % → 0→100%)\n    \"format\": \"compact\",     # standard | compact | scientific\n    \"base_unit\": \"satoshi\",  # sub-unit label (informational)\n    \"sim_scale\": 1.0         # divide input by this before simulation\n  }"},"CorrelationSpec":{"properties":{"variables":{"items":{"type":"string"},"type":"array","maxItems":2,"minItems":2,"title":"Variables"},"coefficient":{"type":"number","maximum":1,"minimum":-1,"title":"Coefficient"}},"type":"object","required":["variables","coefficient"],"title":"CorrelationSpec"},"ScoringWeights":{"properties":{"expected_value":{"type":"number","maximum":1,"minimum":0,"title":"Expected Value","default":0.6},"downside_risk":{"type":"number","maximum":1,"minimum":0,"title":"Downside Risk","default":0.4}},"type":"object","title":"ScoringWeights"},"MCMCConfig":{"properties":{"observed_data":{"items":{"type":"number"},"type":"array","maxItems":100000,"minItems":2,"title":"Observed Data"},"parameter_priors":{"type":"object","title":"Parameter Priors","description":"Dict of param_name → {distribution, params}. Auto-inferred from data if empty. Example: {'mean': {'distribution': 'normal', 'params': {'mean': 500000, 'std': 100000}}}"},"likelihood":{"type":"string","title":"Likelihood","description":"Likelihood model: normal | lognormal | poisson","default":"normal"},"chains":{"type":"integer","maximum":16,"minimum":1,"title":"Chains","default":4},"burn_in":{"type":"integer","maximum":50000,"minimum":100,"title":"Burn In","default":1000}},"type":"object","required":["observed_data"],"title":"MCMCConfig","description":"Config for engine_type='mcmc' — Metropolis-Hastings Bayesian MCMC."},"ImportanceSamplingConfig":{"properties":{"target_threshold":{"type":"number","title":"Target Threshold","description":"The rare event level. E.g. -500000 for a $500k loss, or 2.5 for an extreme gain."},"tail_direction":{"type":"string","title":"Tail Direction","description":"'lower' for loss events (outcome < threshold), 'upper' for extreme gains (outcome > threshold).","default":"lower"},"tilt_variable":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tilt Variable","description":"Name of the normal-distributed variable to apply exponential tilting to. Auto-detects the highest-variance normal variable if omitted."},"tilt_sigma":{"type":"number","title":"Tilt Sigma","description":"Override the tilt parameter θ directly (0 = auto-compute from threshold). Advanced use only.","default":0}},"type":"object","required":["target_threshold"],"title":"ImportanceSamplingConfig","description":"Config for engine_type='importance_sampling' — exponential tilting for rare tail events.\n\nUse when you need accurate estimates of very low-probability events\n(e.g. 1-in-10,000 loss scenarios) without running millions of MC trials.\n\nThe engine shifts sampling mass toward the target tail using exponential tilting\n(θ optimal tilt), then corrects back with likelihood ratio weights.\nReports: tail_probability, tail_probability_se, cvar_tail, ESS, variance_reduction_factor."},"DecisionTreeConfig":{"properties":{"nodes":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"minItems":1,"title":"Nodes","description":"Root nodes of the decision tree. Multiple roots = parallel independent decisions."},"max_depth":{"type":"integer","maximum":20,"minimum":1,"title":"Max Depth","description":"Maximum allowed tree depth","default":10}},"type":"object","required":["nodes"],"title":"DecisionTreeConfig","description":"Config for engine_type='decision_tree' — multi-layered decisions with branches.\n\nExample (2-level tree):\n  nodes: [\n    {\n      id: \"launch_decision\", type: \"decision\", name: \"Launch Product?\",\n      branches: [\n        {\n          id: \"launch_yes\", type: \"chance\", name: \"Launch\", probability: 1.0,\n          branches: [\n            { id: \"accept\", type: \"terminal\", name: \"Market Accepts\",\n              probability: 0.7, objective_function: \"revenue - launch_cost\" },\n            { id: \"reject\", type: \"terminal\", name: \"Market Rejects\",\n              probability: 0.3, variables: {\"revenue\": 0},\n              objective_function: \"-launch_cost\" }\n          ]\n        }\n      ]\n    }\n  ]"},"DecisionNode":{"properties":{"id":{"type":"string","maxLength":200,"minLength":1,"title":"Id"},"type":{"type":"string","title":"Type","description":"Node type: decision | chance | terminal","default":"terminal"},"name":{"type":"string","maxLength":500,"title":"Name","default":""},"probability":{"type":"number","maximum":1,"minimum":0,"title":"Probability","description":"Branch probability (for chance nodes). All siblings should sum to 1.0.","default":1},"condition":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Condition","description":"Optional expression condition for this branch to be active"},"variables":{"type":"object","title":"Variables","description":"Variable overrides for this branch. Scalar value → treated as fixed distribution. Dict → full VariableSpec override {distribution, params}."},"objective_function":{"anyOf":[{"type":"string","maxLength":1000},{"type":"null"}],"title":"Objective Function","description":"Expression override for this node. Inherits top-level if not set."},"branches":{"items":{"$ref":"#/components/schemas/DecisionNode"},"type":"array","maxItems":50,"title":"Branches","description":"Child branches. Empty = terminal node."}},"type":"object","required":["id"],"title":"DecisionNode","description":"A node in a multi-layered decision tree.\n\nNode types:\n  decision  — represents a controllable choice (e.g. \"Launch\" vs \"Don't Launch\")\n  chance    — represents an uncertain outcome with a probability (e.g. \"Market Accepts\")\n  terminal  — leaf node; variables + objective_function evaluated here\n\nEach node can override any parent variable with a new distribution or scalar.\nVariable overrides cascade top-down: child inherits parent, then applies its own."},"TimeSeriesConfig":{"properties":{"model":{"type":"string","title":"Model","description":"Path model: gbm | ou | arithmetic | compound | custom","default":"gbm"},"initial_value":{"type":"number","title":"Initial Value","description":"Starting value of the process (e.g. current stock price, balance, etc.)"},"horizons":{"items":{"type":"integer"},"type":"array","maxItems":100,"minItems":1,"title":"Horizons","description":"Time steps at which to record distributions. E.g. [1,3,6,12] for 1/3/6/12 months.","default":[1,3,6,12]},"granularity":{"type":"string","title":"Granularity","description":"Time unit per step. One of: ms, s, min, h, day, week, month, quarter, year. All drift/vol parameters assumed annualized unless granularity='custom'.","default":"month"},"drift":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Drift","description":"Annualized drift / expected return. Float shorthand or StochasticParam for uncertain drift. GBM: annual log-return. OU: not used (use long_run_mean). Compound: annual return.","default":0},"volatility":{"anyOf":[{"$ref":"#/components/schemas/StochasticParam"},{"type":"number"}],"title":"Volatility","description":"Annualized volatility (σ). Float or StochasticParam.","default":0.2},"autocorrelation":{"type":"number","maximum":0.99,"minimum":-0.99,"title":"Autocorrelation","description":"AR(1) autocorrelation coefficient for innovations (0 = i.i.d., >0 = trending, <0 = mean-reverting noise)","default":0},"long_run_mean":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Run Mean","description":"OU model: long-run mean (μ∞). Defaults to initial_value."},"mean_reversion_speed":{"type":"number","minimum":0,"title":"Mean Reversion Speed","description":"OU model: speed of mean reversion (θ). Higher = faster pull to mean.","default":0.5},"path_expression":{"anyOf":[{"type":"string","maxLength":500},{"type":"null"}],"title":"Path Expression","description":"Custom model: Python expression for next step value. Variables: value, t, dt, drift, vol, z, initial. Example: 'value * exp((drift - 0.5*vol**2)*dt + vol*dt**0.5*z)'"},"fan_chart_percentiles":{"items":{"type":"integer"},"type":"array","maxItems":20,"minItems":1,"title":"Fan Chart Percentiles","description":"Percentile levels to include in the fan chart output at each horizon.","default":[5,10,25,50,75,90,95]},"output_paths":{"type":"boolean","title":"Output Paths","description":"Include sample path data in response (for fan chart visualization). Adds ~50 paths.","default":false},"n_sample_paths":{"type":"integer","maximum":500,"minimum":1,"title":"N Sample Paths","description":"Number of sample paths to include when output_paths=True.","default":50}},"type":"object","required":["initial_value"],"title":"TimeSeriesConfig","description":"Config for engine_type='time_series' — multi-horizon stochastic path simulation.\n\nSupported models:\n  gbm        — Geometric Brownian Motion\n  ou         — Ornstein-Uhlenbeck mean-reversion\n  arithmetic — Arithmetic Brownian Motion\n  compound   — Compound return\n  custom     — Expression-driven path\n\nGranularities: ms, s, min, h, day, week, month, quarter, year"},"StochasticParam":{"properties":{"type":{"type":"string","title":"Type","description":"fixed | normal | uniform | lognormal","default":"fixed"},"value":{"type":"number","title":"Value","description":"Fixed value (for type='fixed')","default":0},"mean":{"type":"number","title":"Mean","description":"Mean (for type='normal' or 'lognormal')","default":0},"std":{"type":"number","title":"Std","description":"Std dev (for type='normal' or 'lognormal')","default":0},"low":{"type":"number","title":"Low","description":"Lower bound (for type='uniform')","default":0},"high":{"type":"number","title":"High","description":"Upper bound (for type='uniform')","default":0}},"type":"object","title":"StochasticParam","description":"A simulation parameter that is itself stochastic (drawn fresh for each path).\nUse for uncertain drift, volatility, or any time-series parameter."},"WhatIfResponse":{"properties":{"variable":{"type":"string","title":"Variable"},"n_steps":{"type":"integer","title":"N Steps"},"range_low":{"type":"number","title":"Range Low"},"range_high":{"type":"number","title":"Range High"},"param_changed":{"type":"string","title":"Param Changed"},"steps":{"items":{"$ref":"#/components/schemas/WhatIfStep"},"type":"array","title":"Steps"},"increasing_direction":{"type":"string","title":"Increasing Direction"},"sensitivity_label":{"type":"string","title":"Sensitivity Label"},"elasticity":{"type":"number","title":"Elasticity"}},"type":"object","required":["variable","n_steps","range_low","range_high","param_changed","steps","increasing_direction","sensitivity_label","elasticity"],"title":"WhatIfResponse","description":"Full what-if sweep result."},"WhatIfStep":{"properties":{"step":{"type":"integer","title":"Step"},"value":{"type":"number","title":"Value"},"label":{"type":"string","title":"Label"},"mean":{"type":"number","title":"Mean"},"std":{"type":"number","title":"Std"},"p5":{"type":"number","title":"P5"},"p25":{"type":"number","title":"P25"},"p50":{"type":"number","title":"P50"},"p75":{"type":"number","title":"P75"},"p95":{"type":"number","title":"P95"},"probability_of_loss":{"type":"number","title":"Probability Of Loss"},"score":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Score"}},"type":"object","required":["step","value","label","mean","std","p5","p25","p50","p75","p95","probability_of_loss"],"title":"WhatIfStep","description":"A single point in the what-if sweep."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/simulate/what-if":{"post":{"tags":["What-If Analysis"],"summary":"What-if parametric sweep","description":"Vary one variable parameter across a range and see how outcomes change. All steps run in parallel via Mojo worker pool. Returns a sweep with mean, percentiles, and probability of loss at each step. Automatically computes sensitivity direction and elasticity.","operationId":"what_if_inline_v1_simulate_what_if_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WhatIfRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/WhatIfResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## credits

### `POST /v1/credits/refresh`

## Issue a new execution credit batch for a local runtime device

> Called automatically by the local runtime daemon when its credit pool drops below 10%.  Returns the number of credits granted and the expiry timestamp.  Denied (HTTP 429) when the org's monthly quota is exhausted.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"CreditRefreshRequest":{"properties":{"device_id":{"type":"string","title":"Device Id"},"billing_period":{"type":"string","title":"Billing Period"},"credits_used":{"type":"integer","title":"Credits Used","default":0}},"type":"object","required":["device_id","billing_period"],"title":"CreditRefreshRequest"},"CreditRefreshResponse":{"properties":{"credits_granted":{"type":"integer","title":"Credits Granted"},"credits_issued_this_month":{"type":"integer","title":"Credits Issued This Month"},"monthly_limit":{"type":"integer","title":"Monthly Limit"},"monthly_remaining":{"type":"integer","title":"Monthly Remaining"},"billing_period":{"type":"string","title":"Billing Period"},"expires_at":{"type":"number","title":"Expires At"},"refresh_after":{"type":"number","title":"Refresh After"},"server_time":{"type":"number","title":"Server Time"}},"type":"object","required":["credits_granted","credits_issued_this_month","monthly_limit","monthly_remaining","billing_period","expires_at","refresh_after","server_time"],"title":"CreditRefreshResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/credits/refresh":{"post":{"tags":["credits"],"summary":"Issue a new execution credit batch for a local runtime device","description":"Called automatically by the local runtime daemon when its credit pool drops below 10%.  Returns the number of credits granted and the expiry timestamp.  Denied (HTTP 429) when the org's monthly quota is exhausted.","operationId":"refresh_credits_v1_credits_refresh_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditRefreshRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditRefreshResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## devices

### `POST /v1/device/register`

## Register a device and receive a signed license token

> Called by \`algenta login\`. Registers the calling machine under the API key, checks the plan's device limit, and returns a signed JWT device license stored locally by the SDK. Re-registering the same device (same device\_id) refreshes the license.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"apps__api_server__routers__devices__RegisterRequest":{"properties":{"device":{"$ref":"#/components/schemas/DeviceInfo"}},"type":"object","required":["device"],"title":"RegisterRequest"},"DeviceInfo":{"properties":{"device_id":{"type":"string","maxLength":64,"minLength":16,"title":"Device Id"},"platform":{"type":"string","maxLength":50,"title":"Platform","default":""},"platform_version":{"type":"string","maxLength":50,"title":"Platform Version","default":""},"hostname_hash":{"type":"string","maxLength":64,"title":"Hostname Hash","default":""},"sdk_version":{"type":"string","maxLength":128,"title":"Sdk Version","default":""}},"type":"object","required":["device_id"],"title":"DeviceInfo"},"RegisterResponse":{"properties":{"license_token":{"type":"string","title":"License Token"},"device_id":{"type":"string","title":"Device Id"},"plan":{"type":"string","title":"Plan"},"device_limit":{"type":"integer","title":"Device Limit"},"device_count":{"type":"integer","title":"Device Count"},"api_key_prefix":{"type":"string","title":"Api Key Prefix"},"message":{"type":"string","title":"Message"},"credits_granted":{"type":"integer","title":"Credits Granted","default":0},"credits_expires_at":{"type":"number","title":"Credits Expires At","default":0},"credits_billing_period":{"type":"string","title":"Credits Billing Period","default":""},"server_time":{"type":"number","title":"Server Time","default":0}},"type":"object","required":["license_token","device_id","plan","device_limit","device_count","api_key_prefix","message"],"title":"RegisterResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/device/register":{"post":{"tags":["devices"],"summary":"Register a device and receive a signed license token","description":"Called by `algenta login`. Registers the calling machine under the API key, checks the plan's device limit, and returns a signed JWT device license stored locally by the SDK. Re-registering the same device (same device_id) refreshes the license.","operationId":"device_register_v1_device_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/apps__api_server__routers__devices__RegisterRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/RegisterResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `POST /v1/device/heartbeat`

## POST /v1/device/heartbeat

> 24-hour device heartbeat — updates last\_seen and returns device count

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HeartbeatRequest":{"properties":{"device_id":{"type":"string","maxLength":64,"minLength":16,"title":"Device Id"},"usage":{"type":"object","title":"Usage"}},"type":"object","required":["device_id"],"title":"HeartbeatRequest"},"HeartbeatResponse":{"properties":{"device_id":{"type":"string","title":"Device Id"},"plan":{"type":"string","title":"Plan"},"device_limit":{"type":"integer","title":"Device Limit"},"device_count":{"type":"integer","title":"Device Count"},"status":{"type":"string","title":"Status"},"message":{"type":"string","title":"Message"},"server_time":{"type":"number","title":"Server Time","default":0}},"type":"object","required":["device_id","plan","device_limit","device_count","status","message"],"title":"HeartbeatResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/device/heartbeat":{"post":{"tags":["devices"],"summary":"24-hour device heartbeat — updates last_seen and returns device count","operationId":"device_heartbeat_v1_device_heartbeat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HeartbeatRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HeartbeatResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `GET /v1/device/list`

## GET /v1/device/list

> List all registered devices for this org

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"DeviceListResponse":{"properties":{"devices":{"items":{"type":"object"},"type":"array","title":"Devices"},"device_count":{"type":"integer","title":"Device Count"},"total":{"type":"integer","title":"Total"},"page":{"type":"integer","title":"Page"},"limit":{"type":"integer","title":"Limit"},"pages":{"type":"integer","title":"Pages"},"device_limit":{"type":"integer","title":"Device Limit"},"plan":{"type":"string","title":"Plan"}},"type":"object","required":["devices","device_count","total","page","limit","pages","device_limit","plan"],"title":"DeviceListResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/device/list":{"get":{"tags":["devices"],"summary":"List all registered devices for this org","operationId":"device_list_v1_device_list_get","parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":200,"minimum":1,"default":25,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceListResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

### `DELETE /v1/device/{registration_id}`

## Revoke a registered device

> Frees up one device slot. The device will lose access on next license refresh.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/device/{registration_id}":{"delete":{"tags":["devices"],"summary":"Revoke a registered device","description":"Frees up one device slot. The device will lose access on next license refresh.","operationId":"device_revoke_v1_device__registration_id__delete","parameters":[{"name":"registration_id","in":"path","required":true,"schema":{"type":"string","format":"uuid","title":"Registration Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"type":"object","title":"Response Device Revoke V1 Device  Registration Id  Delete"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```

## metering

### `POST /v1/metering`

## Ingest local runtime execution analytics

> Called by the local runtime daemon to flush buffered execution events. Analytics only — quota enforcement is handled by the credit bucket. Events are structured-logged for the analytics pipeline.

```json
{"openapi":"3.1.0","info":{"title":"Algenta API","version":"1.0.0"},"servers":[{"url":"https://api.algenta.ai","description":"Algenta API"}],"security":[{"BearerAuth":[]}],"components":{"securitySchemes":{"BearerAuth":{"type":"http","scheme":"bearer","bearerFormat":"APIKey","description":"Canonical v1 authentication. Use Authorization: Bearer <api_key>."}},"schemas":{"MeteringBatchRequest":{"properties":{"device_id":{"type":"string","maxLength":64,"minLength":1,"title":"Device Id"},"events":{"items":{"$ref":"#/components/schemas/MeteringEvent"},"type":"array","title":"Events"}},"type":"object","required":["device_id"],"title":"MeteringBatchRequest"},"MeteringEvent":{"properties":{"event_type":{"type":"string","title":"Event Type","default":""},"module":{"type":"string","title":"Module","default":""},"function":{"type":"string","title":"Function","default":""},"engine_used":{"type":"string","title":"Engine Used","default":""},"latency_ms":{"type":"number","title":"Latency Ms","default":0},"success":{"type":"boolean","title":"Success","default":true},"timestamp":{"type":"number","title":"Timestamp","default":0},"request_id":{"type":"string","title":"Request Id","default":""}},"type":"object","title":"MeteringEvent"},"MeteringBatchResponse":{"properties":{"accepted":{"type":"integer","title":"Accepted"},"billing_period":{"type":"string","title":"Billing Period"}},"type":"object","required":["accepted","billing_period"],"title":"MeteringBatchResponse"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}},"paths":{"/v1/metering":{"post":{"tags":["metering"],"summary":"Ingest local runtime execution analytics","description":"Called by the local runtime daemon to flush buffered execution events. Analytics only — quota enforcement is handled by the credit bucket. Events are structured-logged for the analytics pipeline.","operationId":"ingest_metering_events_v1_metering_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeteringBatchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeteringBatchResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}}}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.algenta.ai/http-api/explorer.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
