Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion .cursor/rules/cursor-api.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,22 @@ Poll at most once per hour (data aggregated hourly).

### POST /teams/spend
Body: `{ page, pageSize }`
Returns `{ teamMemberSpend: [{ email, spendCents, fastPremiumRequests }], subscriptionCycleStart: number, totalPages }`
Returns (post-2026 shape):
```
{
teamMemberSpend: [{
userId, email, name, role, profilePictureUrl,
spendCents, // overage above plan (was cycle total in pre-2026 shape)
overallSpendCents, // cycle-to-date total (new field, post-2026)
fastPremiumRequests,
monthlyLimitDollars, hardLimitOverrideDollars,
effectivePerUserLimitDollars
}],
subscriptionCycleStart: number,
totalPages, totalMembers, limitedUsersCount, maxUserSpendCents
}
```
Note: the meaning of `spendCents` changed in 2026. Pre-2026 it was the cycle total; post-2026 it is the overage above the plan-included amount, and `overallSpendCents` holds the cycle total. `includedSpendCents` was removed from the response. `cursor-client.ts::normalizeMemberSpend` normalizes both shapes so downstream code can rely on `spendCents` = total and `includedSpendCents` = plan-covered. See GH issue #19.

### POST /teams/filtered-usage-events
Body: `{ email?, startDate?, endDate?, page, pageSize }`
Expand Down
8 changes: 5 additions & 3 deletions .cursor/rules/project-context.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ Cursor Enterprise APIs → Collector (src/lib/collector.ts) → SQLite (src/lib/
Dashboard (src/app/ pages)
```

Two CLI entry points:
- `npm run collect` — fetch data from Cursor APIs into SQLite
Three CLI entry points:
- `npm run collect` — fetch data from Cursor APIs into the database
- `npm run detect` — run anomaly detection + alerting on stored data
- `npm run reset` — clear database tables (per-table or all; see `--help`)

Single cron endpoint `POST /api/cron` does both: collect → detect → alert in one call.

Expand All @@ -52,6 +53,7 @@ Single cron endpoint `POST /api/cron` does both: collect → detect → alert in
| `src/lib/cursor-client.ts` | Cursor API client (Admin + Analytics), pagination, rate-limit retry |
| `src/lib/db.ts` | SQLite schema, all queries, dashboard stats, analytics, user stats |
| `src/lib/collector.ts` | Data collection pipeline (members, daily usage, spending, events, analytics, groups) |
| `src/lib/reset.ts` | Database reset orchestrator (per-table or full truncate) |
| `src/lib/anomaly/detector.ts` | Orchestrator — runs all 3 detection layers, deduplicates |
| `src/lib/anomaly/thresholds.ts` | Layer 1: static limits (spend, requests, tokens) |
| `src/lib/anomaly/zscore.ts` | Layer 2: statistical z-score on daily spend vs active team mean |
Expand Down Expand Up @@ -97,4 +99,4 @@ members, daily_usage, spending, usage_events, anomalies, incidents, config, coll

- API response shapes may not exactly match the live Cursor API. If real responses differ, update `src/lib/types.ts` and `src/lib/cursor-client.ts`.
- Trend detection can produce duplicate dedup keys (spend spike + cycle outlier both emit `trend:spend` for same user) — first one wins, second is silently dropped.
- CLI scripts (`npm run collect`, `npm run detect`) do NOT auto-load `.env` — use `source .env && export CURSOR_ADMIN_API_KEY` or run via the Next.js dev server cron endpoint instead.
- CLI scripts (`npm run collect`, `npm run detect`, `npm run reset`) load `.env` via `--env-file=.env` when run through npm scripts.
13 changes: 13 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,16 @@ AUTH_TRUST_HOST=true # required when behind a reverse prox
AUTH_URL= # public URL, e.g. https://your-app.fly.dev (auto-detected locally)

ELEVENLABS_API_KEY=

# Data storage (default: sqlite file at data/tracker.db)
# DATABASE_SOURCE=sqlite
# DATABASE_PATH=data/tracker.db

# Postgres (optional — start with: npm run postgres:up)
# DATABASE_SOURCE=postgres
# POSTGRES_USER=tracker
# POSTGRES_PASSWORD=change-me
# POSTGRES_DB=cursor_tracker
# POSTGRES_HOST=localhost
# POSTGRES_PORT=5433
# POSTGRES_URL= # optional full override instead of the vars above
36 changes: 36 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Run next",
"runtimeExecutable": "next",
"cwd": "${workspaceFolder}",
"args": []
},
{
"type": "node",
"request": "launch",
"name": "Debug: npm run collect",
"runtimeExecutable": "npx",
"runtimeArgs": ["tsx", "--env-file=.env", "src/lib/cli/collect.ts"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**", "**/node_modules/**"]
},
{
"type": "node",
"request": "launch",
"name": "Debug: npm run detect",
"runtimeExecutable": "npx",
"runtimeArgs": ["tsx", "--env-file=.env", "src/lib/cli/detect.ts"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"skipFiles": ["<node_internals>/**", "**/node_modules/**"]
}
]
}
65 changes: 56 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,52 @@ This runs the stored data through all three detection layers and sends alerts fo

> `npm run collect` only fetches data. `npm run detect` only runs detection. The cron endpoint (`POST /api/cron`) does both in one call.

### Reset stored data (optional)

To wipe collected data from the local database — for a fresh start or after testing — use the reset CLI. It deletes rows from selected tables (schema is preserved). Works with SQLite (default) and Postgres (`DATABASE_SOURCE=postgres`).

```bash
npm run reset -- --list # show all resettable tables
npm run reset -- --all # wipe every table (confirmation prompt)
npm run reset -- usage_events # wipe one or more tables
npm run reset -- --all --yes # skip confirmation (scripts/CI)
npm run reset:postgres -- --all # same, against Postgres
```

Clearing `metadata` or `config` also removes billing-cycle anchors, alert dedup state, and detection thresholds. After a reset, run `npm run collect` to repopulate from the Cursor API.

### Postgres storage (optional)

By default data is stored in a local SQLite file at `data/tracker.db`. For Postgres — with decimal-safe spend columns — set `DATABASE_SOURCE=postgres`.

**Start Postgres in Docker** (no local Postgres install required; uses port **5433** to avoid conflicting with a system Postgres on 5432):

```bash
npm run postgres:up
```

Add to `.env` (copy the Postgres block from `.env.example` and set your password):

```env
DATABASE_SOURCE=postgres
POSTGRES_USER=your_user
POSTGRES_PASSWORD=your_password
POSTGRES_DB=cursor_tracker
POSTGRES_HOST=localhost
POSTGRES_PORT=5433
```

Docker Compose and npm scripts read these values from `.env`. You can set `POSTGRES_URL` instead if you prefer a single connection string.

Then collect and run the dashboard against Postgres:

```bash
npm run collect:postgres # or npm run collect after updating .env
npm run dev:postgres # or npm run dev after updating .env
```

Schema is created automatically on first connect. For a full Docker stack (app + Postgres), use `docker compose -f docker-compose.full.yml up`.

### 6. Set up recurring collection

Trigger the cron endpoint hourly (via crontab, GitHub Actions, or any scheduler):
Expand Down Expand Up @@ -468,15 +514,15 @@ When both are set, either match grants access. When neither is set, any Google a

## Tech Stack

| Component | Technology |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Framework | [![Next.js](https://img.shields.io/badge/Next.js-000?logo=nextdotjs&logoColor=white)](https://github.com/vercel/next.js) App Router |
| Language | [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://github.com/microsoft/TypeScript) strict mode |
| Database | [![SQLite](https://img.shields.io/badge/SQLite-003B57?logo=sqlite&logoColor=white)](https://github.com/WiseLibs/better-sqlite3) via better-sqlite3 (swappable) |
| Charts | [![Recharts](https://img.shields.io/badge/Recharts-22B5BF?logo=recharts&logoColor=white)](https://github.com/recharts/recharts) |
| Styling | [![Tailwind CSS](https://img.shields.io/badge/Tailwind_CSS-06B6D4?logo=tailwindcss&logoColor=white)](https://github.com/tailwindlabs/tailwindcss) |
| Testing | [![Vitest](https://img.shields.io/badge/Vitest-6E9F18?logo=vitest&logoColor=white)](https://github.com/vitest-dev/vitest) |
| Deployment | [![Docker](https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white)](https://github.com/docker) multi-stage build |
| Component | Technology |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Framework | [![Next.js](https://img.shields.io/badge/Next.js-000?logo=nextdotjs&logoColor=white)](https://github.com/vercel/next.js) App Router |
| Language | [![TypeScript](https://img.shields.io/badge/TypeScript-3178C6?logo=typescript&logoColor=white)](https://github.com/microsoft/TypeScript) strict mode |
| Database | SQLite (default) or PostgreSQL via `DATABASE_SOURCE`; SQLite uses [better-sqlite3](https://github.com/WiseLibs/better-sqlite3), Postgres uses [pg](https://github.com/brianc/node-postgres) |
| Charts | [![Recharts](https://img.shields.io/badge/Recharts-22B5BF?logo=recharts&logoColor=white)](https://github.com/recharts/recharts) |
| Styling | [![Tailwind CSS](https://img.shields.io/badge/Tailwind_CSS-06B6D4?logo=tailwindcss&logoColor=white)](https://github.com/tailwindlabs/tailwindcss) |
| Testing | [![Vitest](https://img.shields.io/badge/Vitest-6E9F18?logo=vitest&logoColor=white)](https://github.com/vitest-dev/vitest) |
| Deployment | [![Docker](https://img.shields.io/badge/Docker-2496ED?logo=docker&logoColor=white)](https://github.com/docker) multi-stage build |

---

Expand All @@ -486,6 +532,7 @@ When both are set, either match grants access. When neither is set, any Google a
npm run dev # Start dev server
npm run collect # Manual data collection
npm run detect # Manual anomaly detection + alerting
npm run reset # Clear database tables (see --help)
npm run typecheck # Type checking
npm test # Run tests
npm run lint # Lint + format check
Expand Down
41 changes: 41 additions & 0 deletions docker-compose.full.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Full stack: tracker app + Postgres (set DATABASE_SOURCE=postgres in .env)
services:
tracker:
build: .
ports:
- "3000:3000"
volumes:
- tracker-data:/app/data
env_file:
- .env
environment:
DATABASE_SOURCE: ${DATABASE_SOURCE:-postgres}
POSTGRES_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/"]
interval: 30s
timeout: 10s
retries: 3

postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
restart: unless-stopped

volumes:
tracker-data:
postgres-data:
21 changes: 21 additions & 0 deletions docker-compose.postgres.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
services:
postgres:
image: postgres:16-alpine
container_name: cursor-tracker-postgres
ports:
- "5433:5432"
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 10
restart: unless-stopped

volumes:
postgres-data:
2 changes: 1 addition & 1 deletion next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { NextConfig } from "next";

const nextConfig: NextConfig = {
output: "standalone",
serverExternalPackages: ["better-sqlite3"],
serverExternalPackages: ["better-sqlite3", "pg", "synckit"],
};

export default nextConfig;
Loading