---
title: "Platform Intelligence API"
description: "Public endpoint aggregating real-time platform statistics for the AINative Intelligence Dashboard, including agent events, lake analytics, and ads performance"
canonical: "https://docs.ainative.studio/docs/api/platform-intelligence"
last-updated: "2026-10-13T21:42:35.442Z"
---

# Platform Intelligence API

Source: https://docs.ainative.studio/docs/api/platform-intelligence

> Public endpoint aggregating real-time platform statistics for the AINative Intelligence Dashboard, including agent events, lake analytics, and ads performance

# Platform Intelligence API

Public endpoint that aggregates real-time platform statistics for the AINative Intelligence Dashboard at `ainative.studio/intelligence`. No authentication required.

---

## Table of Contents

- [Endpoints](#endpoints)
- [Response Schema](#response-schema)
- [Data Sources](#data-sources)
- [How the Dashboard Consumes This](#how-the-dashboard-consumes-this)

---

## Endpoints

### GET /api/v1/public/platform/intelligence

Full platform intelligence response with stats, agent events, data lake analytics, and ads performance.

**Auth:** None (public endpoint)

**Route registration:** Mounted via the public router at prefix `/platform`, defined in `app.api.routers.public`.

**Example request:**

```bash
curl https://api.ainative.studio/api/v1/public/platform/intelligence
```

**Example response:**

```json
{
  "stats": {
    "uptime_pct": 99.97,
    "requests_total": 642000,
    "agents_active": 14,
    "models_served": 8,
    "memory_queries_today": 312,
    "tasks_completed_today": 47,
    "tokens_processed_today": 1580000,
    "improvement_loops": 89,
    "last_updated": "2026-06-01T14:30:00+00:00",
    "latency_p99_ms": 245.50
  },
  "agent_events": [
    {
      "id": "machine-dev-mac",
      "agent": "Dev Mac",
      "role": "Machine",
      "action": "12 agents online",
      "target": "45 improvement loops",
      "timestamp": "2m ago",
      "status": "running"
    },
    {
      "id": "agent-sage",
      "agent": "Sage",
      "role": "Backend",
      "action": "merged PR #3450",
      "target": "",
      "timestamp": "15m ago",
      "status": "completed"
    }
  ],
  "lake": {
    "agent_runs_30d": 1240,
    "agent_success_rate_pct": 94.2,
    "api_requests_30d": 580000,
    "total_credits_30d": 12450.75,
    "loop_quality": {
      "overall_success_rate_pct": 91.5,
      "improving": true,
      "trend": [
        {"date": "2026-05-25", "success_rate": 89.0, "total_runs": 42}
      ],
      "source": "lake"
    },
    "packages": {
      "total_downloads": 52000,
      "top_packages": [
        {"name": "zerodb-mcp", "ecosystem": "pypi", "downloads": 18500}
      ],
      "source": "lake"
    },
    "business": {
      "mrr_trend_7d": [
        {"date": "2026-05-31", "amount_usd": 125.00}
      ],
      "stripe_events_7d": 34,
      "emails_delivered_7d": 210,
      "open_pipeline_value": 15000.00,
      "open_deals_count": 3,
      "commerce_revenue_7d": 450.00,
      "source": "lake"
    },
    "rlhf_quality_score_7d": 0.8234,
    "regional_economy": {
      "unemployment_rate": 4.2,
      "fred_series_count": 6,
      "federal_awards_ytd": 125000.00,
      "federal_awards_count": 8,
      "edd_total_employment": 132000.0,
      "source": "lake"
    },
    "source": "lake"
  },
  "ads": {
    "total_spend": 0,
    "total_clicks": 1420,
    "total_impressions": 0,
    "total_conversions": 3,
    "avg_cpc": 0,
    "ctr": 0,
    "campaigns_active": 4,
    "top_keyword": "platform activity",
    "top_keyword_conversions": 3,
    "source": "db_proxy"
  },
  "ok": true
}
```

---

### GET /api/v1/public/platform/intelligence/summary

Lightweight aggregate summary optimized for fast polling.

**Auth:** None

```bash
curl https://api.ainative.studio/api/v1/public/platform/intelligence/summary
```

**Response fields:**

| Field | Type | Description |
|-------|------|-------------|
| `agent_runs_today` | int | Agent tasks completed today (from lake) |
| `agent_runs_week` | int | Agent tasks completed this week |
| `api_calls_today` | int | API requests today |
| `billing_revenue_week` | float | Credits consumed this week |
| `top_packages_downloads` | int | Total package downloads (30d) |
| `generated_at` | string | ISO timestamp |
| `source` | string | `"lake"`, `"lake_empty"`, or `"unavailable"` |

---

### GET /api/v1/public/platform/intelligence/packages

npm and PyPI download statistics from the data lake.

**Auth:** None

**Query parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `days` | int | 30 | Days to aggregate (1-90) |

```bash
curl "https://api.ainative.studio/api/v1/public/platform/intelligence/packages?days=30"
```

**Response fields:**

| Field | Type | Description |
|-------|------|-------------|
| `total_downloads` | int | Sum of all package downloads |
| `packages` | list | Sorted by downloads desc: `{name, ecosystem, downloads}` |
| `days` | int | Aggregation window |
| `generated_at` | string | ISO timestamp |
| `source` | string | `"lake"`, `"lake_empty"`, or `"unavailable"` |

---

## Response Schema

### PlatformIntelligenceResponse (top level)

| Field | Type | Description |
|-------|------|-------------|
| `stats` | PlatformIntelligenceStats | Core platform metrics |
| `agent_events` | list[AgentEvent] | Recent agent activity feed (up to 20 events) |
| `lake` | LakeAnalytics or null | Historical analytics from MinIO data lake |
| `ads` | AdsStats or null | Google Ads campaign performance proxy |
| `ok` | bool | Always `true` on success |

### PlatformIntelligenceStats

| Field | Type | Source | Description |
|-------|------|--------|-------------|
| `uptime_pct` | float | `mcp_request_logs` (primary), `kong_usage_metrics` (secondary) | 7-day uptime derived from 5xx error rate. Fallback: 99.97 |
| `requests_total` | int | `mcp_request_logs` | Total API requests (all time) |
| `agents_active` | int | `agent_heartbeat_executions` + `agent_deployments` + `peer_swarm_heartbeat` | Count of active agents across all sources |
| `models_served` | int | `/api/v1/models` endpoint | Number of AI models available |
| `memory_queries_today` | int | `mcp_request_logs` (endpoint LIKE `%/memory/%`) | ZeroMemory API calls today |
| `tasks_completed_today` | int | `agent_run_log` + `swarm_tasks` + `peer_swarm_heartbeat` | Completed agent tasks today |
| `tokens_processed_today` | int | `platform/llm_token_usage` lake partition (primary), credits x 1000 (fallback) | LLM tokens processed today |
| `improvement_loops` | int | `agent_run_log` + `agent_traces` + `peer_swarm_heartbeat` + `mcp_request_logs` | Memory consolidation, reflection, and decay operations |
| `last_updated` | string | computed | ISO timestamp of when stats were generated |
| `latency_p99_ms` | float or null | `mcp_request_logs` (7-day p99 percentile) | p99 API latency in milliseconds |

### AgentEvent

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique event identifier (prefixed: `agent-`, `machine-`, `cloud-`, `hb-`) |
| `agent` | string | Friendly agent name (e.g., "Cody", "Sage", "Aurora") |
| `role` | string | Agent role (e.g., "Orchestrator", "Backend", "QA") |
| `action` | string | What the agent did |
| `target` | string | Target of the action (may be empty) |
| `timestamp` | string | Human-readable relative time (e.g., "5m ago", "2h ago") |
| `status` | string | `"completed"`, `"running"`, or `"queued"` |

### LakeAnalytics

| Field | Type | Description |
|-------|------|-------------|
| `agent_runs_30d` | int | Total agent runs in the last 30 days |
| `agent_success_rate_pct` | float | Agent success rate over 30 days |
| `api_requests_30d` | int | Total API requests over 30 days |
| `total_credits_30d` | float | Total credits consumed over 30 days |
| `loop_quality` | LoopQualityTrend | Recursive improvement loop quality trend (14d) |
| `packages` | PackageStats | npm + PyPI download stats (30d) |
| `business` | BusinessSignals or null | Revenue, pipeline, and email delivery signals |
| `rlhf_quality_score_7d` | float or null | Average RLHF reward score (7d) |
| `regional_economy` | RegionalEconomicSignals or null | Santa Cruz County open-data signals |
| `source` | string | `"lake"`, `"lake_empty"`, or `"unavailable"` |

### BusinessSignals

| Field | Type | Description |
|-------|------|-------------|
| `mrr_trend_7d` | list | Daily revenue trend: `{date, amount_usd}` |
| `stripe_events_7d` | int | Total Stripe webhook events in 7 days |
| `emails_delivered_7d` | int | Emails successfully delivered |
| `open_pipeline_value` | float | Sum of open deal values (ZeroPipeline) |
| `open_deals_count` | int | Number of open deals |
| `commerce_revenue_7d` | float | ZeroCommerce order revenue |
| `source` | string | `"lake"` or `"unavailable"` |

### RegionalEconomicSignals

| Field | Type | Description |
|-------|------|-------------|
| `unemployment_rate` | float or null | Latest FRED CACRUZ0URN series value |
| `fred_series_count` | int | Distinct FRED economic series in the lake |
| `federal_awards_ytd` | float | USAspending total federal award amount YTD |
| `federal_awards_count` | int | Number of federal awards |
| `edd_total_employment` | float or null | Latest QCEW all-industry employment |
| `source` | string | `"lake"` or `"unavailable"` |

### AdsStats

| Field | Type | Description |
|-------|------|-------------|
| `total_spend` | float | Ad spend (0 when Google Ads API unavailable) |
| `total_clicks` | int | Proxied from today's API request count |
| `total_impressions` | int | 0 when unavailable |
| `total_conversions` | int | New user signups today (excluding test/trial accounts) |
| `avg_cpc` | float | Average cost per click |
| `ctr` | float | Click-through rate |
| `campaigns_active` | int | Active campaign count |
| `top_keyword` | string | Top performing keyword |
| `top_keyword_conversions` | int | Conversions for top keyword |
| `source` | string | `"db_proxy"`, `"ads_report"`, or `"unavailable"` |

---

## Data Sources

The intelligence endpoint aggregates data from multiple database tables and external services. Each data source is queried independently with its own error handling, so a failure in one source does not block the others.

### Database Tables

| Table | Data Pulled | Used For |
|-------|-------------|----------|
| `mcp_request_logs` | Total request count, credits consumed, memory query count, uptime (5xx rate), p99 latency, improvement loop endpoints | `requests_total`, `memory_queries_today`, `uptime_pct`, `latency_p99_ms`, `improvement_loops` |
| `agent_run_log` | Per-agent latest activity, task completion count, improvement summaries | `tasks_completed_today`, `agent_events`, `improvement_loops` |
| `peer_swarm_heartbeat` | Active agent count and improvement loops from peer machines (10-min staleness window) | `agents_active`, `improvement_loops`, machine-level events |
| `agent_heartbeat_executions` | Distinct agents with successful runs in last 2 hours | `agents_active`, heartbeat events |
| `agent_deployments` | Running Agent Cloud deployments | `agents_active` (cloud) |
| `agent_traces` | Recent Agent Cloud operations, memory/reflect/consolidate traces | Cloud agent events, `improvement_loops` |
| `swarm_tasks` | Completed swarm tasks today | `tasks_completed_today` |
| `kong_usage_metrics` | Error rate, p99 latency (secondary source, rarely populated) | `uptime_pct` fallback |
| `users` | New signups today | `ads.total_conversions` |

### MinIO Data Lake (Parquet partitions)

| Partition | Data | Used For |
|-----------|------|----------|
| `agent_run_log` | 30-day agent run history | `lake.agent_runs_30d`, `lake.agent_success_rate_pct` |
| `mcp_request_logs` | 30-day API request history | `lake.api_requests_30d`, `lake.total_credits_30d` |
| `package_stats` | npm + PyPI download counts | `lake.packages` |
| `rlhf_signals` | RLHF reward scores | `lake.rlhf_quality_score_7d` |
| `stripe_events` | Stripe webhook events | `lake.business.mrr_trend_7d`, `lake.business.stripe_events_7d` |
| `external/email` | Email delivery events | `lake.business.emails_delivered_7d` |
| `business/crm/deals` | ZeroPipeline deal data | `lake.business.open_pipeline_value` |
| `business/commerce/orders` | ZeroCommerce orders | `lake.business.commerce_revenue_7d` |
| `external/scc/fred_indicators` | FRED economic indicators | `lake.regional_economy.unemployment_rate` |
| `external/scc/federal_awards` | USAspending awards | `lake.regional_economy.federal_awards_ytd` |
| `external/scc/edd_labor` | EDD QCEW labor data | `lake.regional_economy.edd_total_employment` |
| `platform/llm_token_usage` | Daily LLM token counts | `stats.tokens_processed_today` |

### External HTTP Calls

| Service | Purpose |
|---------|---------|
| `GET /api/v1/models` (self) | Count available AI models for `stats.models_served` |
| GitHub API (`api.github.com`) | Fallback agent events from recent PRs across AINative-Studio repos (used when all DB event sources are empty) |

---

## How the Dashboard Consumes This

The Intelligence Dashboard at `ainative.studio/intelligence` is a Next.js page in the frontend application.

### Polling behavior

The page fetches `GET /api/v1/public/platform/intelligence` on load and refreshes on a regular interval. No authentication is needed since the endpoint is mounted under the public router.

### Agent roster

The endpoint maintains a known agent roster that maps agent IDs to friendly names and roles:

| Agent ID | Display Name | Role |
|----------|-------------|------|
| `main` | Cody | Orchestrator |
| `sage` | Sage | Backend |
| `aurora` | Aurora | QA |
| `nova` | Nova | Security |
| `atlas` | Atlas | Infra |
| `lyra` | Lyra | Frontend |
| `luma` | Luma | Documentation |
| `helios` | Helios | Performance |
| `vega` | Vega | Analytics |
| `pr-review-bot` | PR Bot | Code Review |
| `sales-agent` | Sales | Sales |
| `vp-marketing` | Marketing | Marketing |
| `scout` | Scout | Intelligence |

Agents that have no recent `agent_run_log` entries are shown with status `"queued"` and action `"idle -- awaiting task"`.

### Event priority

Agent events are assembled from multiple sources in priority order:

1. **Heartbeat executions** (`agent_heartbeat_executions`) -- real cron execution results with success/fail status
2. **Peer swarm events** (`peer_swarm_heartbeat` + `agent_run_log`) -- per-agent activity cards plus machine-level summaries
3. **Run log events** (`agent_run_log`) -- individual task completions
4. **Agent Cloud events** (`agent_traces`) -- cloud-deployed agent operations
5. **GitHub PR fallback** -- recent pull requests across AINative-Studio repos, used when all DB sources are empty

The combined list is truncated to 20 events.

### Staleness handling

- `peer_swarm_heartbeat` entries older than 600 seconds (configurable via `PEER_HEARTBEAT_MAX_AGE_SECS`) are ignored.
- `agent_heartbeat_executions` uses a 2-hour window.
- `agent_run_log` and `agent_traces` use 6-12 hour windows depending on the query.
- When no heartbeat data is available, `agents_active` falls back to the count of configured agents (currently 11).

### Uptime calculation

Uptime is derived from `mcp_request_logs` over a 7-day window:

```
uptime_pct = 100.0 - (100.0 * count(status_code >= 500) / count(*))
```

Values outside the range [90, 100] are discarded and the system falls back to `kong_usage_metrics` or a static fallback of 99.97%.

### Lake data availability

The `lake` field is `null` when the MinIO data lake has no exported data. Each sub-section (`loop_quality`, `packages`, `business`, `regional_economy`) has its own `source` field indicating whether real lake data was available or not. The top-level `lake.source` is `"lake"` if any sub-source has data, `"lake_empty"` if all partitions are empty, and the entire field is omitted if the lake query module fails to import.
