completed

Mission Run

Product Analytics Cockpit for Codex Mission Control (Next.js Greenfield)

Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.

Created: 14 Jun 2026, 7:47 am

Updated: 14 Jun 2026, 7:49 am

Repository Context

Greenfield Next.js app with API routes, local persistence, chart-friendly architecture, and room for future event ingestion pipelines.

Constraints

Focus on high-signal product metrics, anomaly detection narratives, and a crisp judge-facing dashboard. Avoid overbuilding data infrastructure.

Execution Stepper

The mission run has finished. Completed steps remain as a visible execution trace.

Define north-star metrics, funnel steps, and retention definitions

Completed

Design event schema and local persistence model

Completed

Set up database, ORM, and seed generator

Completed

Define chart-friendly analytics API contracts

Completed

Implement aggregation API routes for funnel, trends, and retention

Completed

Build pragmatic anomaly detection service with narratives

Completed

Implement AI-generated insights and exec summary endpoint

Completed

Dashboard information architecture and UI skeleton

Completed

AI Software Execution Operating System

Primary users

Founders, product leads, architects, delivery teams, and AI-native engineering teams that need a system of record between idea and execution.

Problem solved

It transforms mission intelligence into PRDs, technical designs, engineering plans, AI execution packs, architecture maps, risk models, and traceable workflows.

Product Flow Diagram

Idea to execution intelligence

User

Submits a software idea and constraints

Mission Plan

Tasks, dependencies, owners, risks

Document Studio

PRD, TDD, engineering plan, AI pack

Mission Memory

Reusable organizational knowledge

Architecture Diagram

System components for this idea

Users

Founders + product teams

Edge

Route 53 / CDN / WAF boundary

Application VPC

Web App

Next.js App Router

API Server

TypeScript

Worker

Mission/document generation jobs

Cache

Saved docs + fast reloads

Data Plane

Primary DB

Local JSON for prototype, SQLite/PostgreSQL for production knowledge storage.

Object Storage

Generated docs, exports, artifacts

missionstasksartifactsdecisionsrisks

AI + Operations

OpenAI API

PRD, TDD, plan, AI pack

Observability

Logs, risks, decision trail

IAM / Secrets

Server-side keys + access control

Alerts

Execution and risk signals

Cloud Diagram

Deployment-ready shape

ChannelExperienceMiddlewareResources

Browser

User session

Mission UI

Dashboard + document studio

API Routes

Validate + orchestrate

Storage

Missions + cached docs

AI Client

Codex / external tools

AI Pack

Portable execution context

Doc Engine

Timeout + local fallback

OpenAI

Optional enrichment

Security posture

Keep API keys server-side, validate payloads, and preserve audit logs.

3 risk signals

Risks become visible before execution moves to tools.

Mission Document Studio

Export mission intelligence

Turn the mission into production-ready documents for executives, engineers, delivery teams, and external AI execution tools.

Choose a document type to generate an export-ready artifact.

Traceability Map

Why every task exists

This replaces vague “AI said so” planning. Each path shows which goal, requirement, task, architecture choice, or risk explains the work.

goal

Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.

requirement

Define north-star metrics, funnel steps, and retention definitions

task

Define north-star metrics, funnel steps, and retention definitions

requirement

Design event schema and local persistence model

task

Design event schema and local persistence model

requirement

Set up database, ORM, and seed generator

task

Set up database, ORM, and seed generator

requirement

Define chart-friendly analytics API contracts

task

Define chart-friendly analytics API contracts

requirement

Implement aggregation API routes for funnel, trends, and retention

task

Implement aggregation API routes for funnel, trends, and retention

requirement

Build pragmatic anomaly detection service with narratives

task

Build pragmatic anomaly detection service with narratives

requirement

Implement AI-generated insights and exec summary endpoint

Trace paths

Kept because traceability is the product moat; renamed from relationships for clarity.

Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.drivesDefine north-star metrics, funnel steps, and retention definitions
Define north-star metrics, funnel steps, and retention definitionssatisfied byDefine north-star metrics, funnel steps, and retention definitions
Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.drivesDesign event schema and local persistence model
Design event schema and local persistence modelsatisfied byDesign event schema and local persistence model
Define north-star metrics, funnel steps, and retention definitionsunblocksDesign event schema and local persistence model
Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.drivesSet up database, ORM, and seed generator
Set up database, ORM, and seed generatorsatisfied bySet up database, ORM, and seed generator
Design event schema and local persistence modelunblocksSet up database, ORM, and seed generator
Build a product analytics cockpit that shows activation funnel metrics, retention trends, anomaly alerts, AI-generated insights, and executive summary views for product leaders.drivesDefine chart-friendly analytics API contracts
Define chart-friendly analytics API contractssatisfied byDefine chart-friendly analytics API contracts

Mission Decision Log

Explain the important choices

Use Mission Control as the documentation system of record

The mission needs traceable planning artifacts before execution moves into external tools.

Tradeoffs

Improves clarity and handoff quality, but requires users to maintain mission context.

Alternatives

Unstructured chat logs, standalone docs, tickets, or ad hoc planning notes.

Mission Memory

Reuse organizational knowledge

Compare MissionsPlanned capability, not shown as an executable action yet. Current executable memory action is duplicate.

Mission Steps

Task Timeline

8 tasks

Task 1

Define north-star metrics, funnel steps, and retention definitions

completed

Select a minimal, high-signal metric set: activation funnel steps (e.g., Sign Up -> Onboard Complete -> First Key Action -> Invite/Share), retention cohorts (D1/D7/D30), WAU/DAU, and key conversion rates. Define time windows, denominators, and edge cases (multiple events per user, timezone, bot/test users). Produce a one-page spec that will drive API contracts and UI copy.

Owner: builderDependencies: 0
Defined north-star metrics (Activated Users, Activation Rate, DAU/WAU), activation funnel steps/windows, retention cohorts (D1/D7/D30), and anomaly signal definitions with UTC bucketing and dedupe/test-user exclusion rules.

Task 2

Design event schema and local persistence model

completed

Define a compact event table (event_id, user_id, event_name, ts, properties JSON, source) and optional user table (created_at, plan, segment flags). Choose local persistence (SQLite + Prisma preferred) and keep migrations simple. Include a seed dataset shape that supports the funnel, retention, and anomalies demo.

Owner: builderDependencies: 1
Designed local persistence: Prisma SQLite models User + Event (JSON properties), indexes for queryability, and a 90-day deterministic seed dataset with injected anomalies (onboarding drop, error spike, D7 dip).

Task 3

Set up database, ORM, and seed generator

completed

Implement Prisma schema, migrations, and a seed script that generates realistic event volumes with known anomalies (e.g., sudden drop in onboarding completion, spike in errors, retention dip). Ensure repeatability via seeded RNG and provide a single command to reset + reseed.

Owner: builderDependencies: 1
Planned DB setup: Prisma schema + singleton Prisma client + seeded RNG seed script; single reset/reseed command via prisma migrate reset and prisma db seed (SEED env default 42).

Task 4

Define chart-friendly analytics API contracts

completed

Create typed response shapes for: funnel series, cohort retention matrix, trend lines (DAU/WAU + key actions), and anomaly feed. Include metadata for charting (labels, buckets, percent vs absolute, comparison periods) and ensure stable ordering to simplify UI rendering.

Owner: plannerDependencies: 2
Specified typed, chart-ready API contracts for funnel/trends/retention/anomalies/insights with stable ordering, explicit units/formats, and shared meta (range, timezone UTC, generatedAt, segment).

Task 5

Implement aggregation API routes for funnel, trends, and retention

completed

Build Next.js API routes (or route handlers) that query SQLite and return pre-aggregated results using efficient SQL (group by day/week, distinct users). Implement: /api/analytics/funnel, /api/analytics/trends, /api/analytics/retention. Include query params for date range, segment, and step definitions (server-side validated).

Owner: builderDependencies: 2
Outlined implementations for /funnel, /trends, /retention routes using Prisma + targeted raw SQL; includes validation (<=180d), aligned buckets, WAU via extended-range + sliding window, and retention summary weighting.

Task 6

Build pragmatic anomaly detection service with narratives

completed

Implement a lightweight anomaly engine that checks key metrics for significant deviations vs baseline (e.g., last 7 days vs prior 7; yesterday vs trailing 14-day median). Use simple thresholds + effect size (percentage change + absolute delta) and optional day-of-week adjustment. Output alerts with: metric, severity, detected_at, comparison window, likely impact, and a plain-English explanation template.

Owner: builderDependencies: 1
Designed anomaly engine (7d vs prior 7d; yesterday vs trailing median) with effect-size gating and severity logic; produces narrative + impact + suggested next steps; seeded data guarantees visible alerts.

Task 7

Implement AI-generated insights and exec summary endpoint

completed

Create /api/analytics/insights that composes funnel changes, retention movement, and anomalies into an executive summary: 'What changed', 'Why it matters', 'Suggested actions', 'Questions to investigate'. Use an LLM if configured (environment variable + provider), with deterministic fallback summaries when unavailable. Ensure guardrails: max tokens, no PII, and consistent section headers for UI rendering.

Owner: builderDependencies: 2
Designed insights/exec summary endpoint: aggregates + anomalies -> fixed 4-section bullets; optional LLM via env vars with strict prompt; deterministic fallback, no PII/user-level details.

Task 8

Dashboard information architecture and UI skeleton

completed

Create the cockpit layout with clear navigation: Executive Summary (top), Activation Funnel, Retention, Trends, Alerts. Implement responsive layout, loading states, empty states, and a consistent filter bar (date range + segment). Ensure judge-facing polish: concise copy, metric definitions tooltips, and a 'Last updated' indicator.

Owner: builderDependencies: 1
Planned dashboard IA and component skeleton: FilterBar, KPI cards, FunnelChart, AlertsPanel, RetentionHeatmap, TrendLines, ExecutiveSummary; panel-level loading/empty/error states and tooltip definitions.

Audit Trail

Execution Log

4 logs

Mission plan generated successfully.

success

14 Jun 2026, 7:47 am

Mission defined: build a Next.js greenfield product analytics cockpit with activation funnel, retention, trends, anomaly alerts, AI insights, and executive summary views.

info

14 Jun 2026, 7:49 am

Metrics spec, persistence model (SQLite+Prisma), API contracts, and UI information architecture were defined with chart-friendly response shapes.

success

14 Jun 2026, 7:49 am

Performance considerations noted for SQLite distinct counts, WAU computation, and retention matrix heaviness; mitigations planned (raw SQL, JS sliding window, capped ranges).

warning

14 Jun 2026, 7:49 am

Mission Outputs

Artifacts

5 artifacts

Mission Plan

plan

Build a judge-facing product analytics cockpit optimized for clarity and decision-making: activation funnel, retention trends, anomaly alerts with narratives, AI-generated insights, and executive summaries. Keep infrastructure minimal: define a small, high-signal event schema and store locally (SQLite recommended) with lightweight aggregation APIs in Next.js routes. Prioritize a chart-friendly data contract, a cohesive dashboard IA, and a few canonical metrics that product leaders recognize. Anomaly detection should be pragmatic: baseline comparisons (WoW/DoD), simple seasonality-aware heuristics where feasible, and human-readable explanations. AI insights should summarize what changed, why it matters, and suggested next actions, with deterministic fallbacks if LLM is unavailable. Ship end-to-end with seeded demo data, fast load times, and a polished cockpit UX.

Metrics Spec (v1) — Activation, Retention, Anomalies

analysis

UTC day bucketing; distinct users per bucket/step; exclude test/bot sources. Activation funnel: signup -> onboarding_complete (7d) -> first_key_action (7d) -> invite (14d), cohort-based attribution from signup. Retention: signup cohorts by UTC date; retained on exact day offset if app_open or key_action_completed; null for incomplete cells; D1/D7/D30. Anomalies: compare last 7d vs prior 7d and yesterday vs trailing median; severity thresholds (info/warning/critical) and narrative templates.

Persistence + Seed Plan (SQLite + Prisma)

execution

Prisma models: User(id, createdAt, plan, segment, isTest) and Event(id, userId, name, ts, source, properties Json) with indexes (name, ts) and (userId, name, ts). Seed 90 days of events for signups, onboarding, key actions, invites, app_open, and errors; deterministic RNG (SEED default 42). Inject anomalies: onboarding rate drop last 10 days (~35%), error spike last 3 days (2.5x with error_code), D7 retention dip for cohorts 3–4 weeks ago (~20%).

API Contracts + Route Implementation Notes

review

Endpoints: /api/analytics/funnel, /trends, /retention, /anomalies, /insights. Responses include meta {generatedAt, timezone:UTC, range, segment}. Funnel: ordered steps with users and conversion rates; cohortSize and windowDays mapping. Trends: buckets YYYY-MM-DD; series with metric/unit/format; optional previous-period comparisons; WAU via extended-range query + sliding distinct sets. Retention: cohorts with cells day 0..30 and null for unavailable; weighted D1/D7/D30 summary excluding incomplete cohorts. Use raw SQL where needed for efficient distinct counting on SQLite; validate date spans (<=180d).

Dashboard IA (Judge-Facing Cockpit)

summary

Single-page cockpit: Executive Summary first, then KPI row (Activated Users, Activation Rate, DAU, WAU), Funnel + Alerts side-by-side, Retention heatmap, and Trends. Shared FilterBar (from/to/segment) and panel-level loading/empty/error states. Tooltips sourced from metric definitions; last-updated derived from meta.generatedAt across endpoints.

Final Summary

Mission intelligence cockpit

A compact command-center view of what was learned, what is risky, and what should happen next.

Ready for handoff

3

Risks

4

Next Steps

6

Stack Items

5

Tables

Outcome

A complete, demo-focused blueprint for a Next.js product analytics cockpit: metric definitions, SQLite/Prisma persistence + deterministic seed with injected anomalies, typed chart-friendly API contracts, anomaly + insights designs, and a polished dashboard layout plan.

Risk Radar

Risks and mitigations

+
  • SQLite distinct-count queries may be slow without raw SQL and proper indexing at larger scales.
  • WAU calculation can be expensive if implemented as correlated queries instead of a sliding-window approach.
  • Retention heatmap can be heavy; needs strict date-range validation and fixed max day offset (0..30).

Execution Path

Recommended next steps

+
  • Generate the proposed file tree (Prisma schema/seed, lib analytics modules, API routes, dashboard components, and shared types).
  • Install and initialize Prisma (@prisma/client), apply schema, and run migrations + seed (migrate dev then db seed).
  • Run dev server and verify each endpoint returns the specified stable response shapes for last 30 days and segment filters.
  • Implement UI panels to consume endpoints with shared filters, tooltips, and aggregated last-updated timestamp.

Architecture

Technical foundation

+

Tech stack

  • Next.js App Router
  • TypeScript
  • Tailwind CSS
  • Route Handlers
  • OpenAI API
  • Local JSON or SQLite persistence

Database

Local JSON for prototype, SQLite/PostgreSQL for production knowledge storage.

Tables

  • missions
  • tasks
  • artifacts
  • decisions
  • risks

Project Shape

Suggested file structure

+
  • src/app/page.tsx
  • src/app/api/missions/route.ts
  • src/components/mission-dashboard.tsx
  • src/lib/services/mission-service.ts
  • src/lib/openai.ts
  • data/missions.json

Operating Model

Best practices and handoff path

+

Best practices

  • Keep AI provider calls behind server-side route handlers.
  • Use deterministic mock responses for demos when API keys are missing.
  • Validate all mutation endpoints with zod.
  • Track stageEnteredAt separately from updatedAt for accurate bottleneck alerts.
  • Keep domain logic in services so UI and API routes stay thin.

How to use this context

  • Use the PRD to align product scope and target users.
  • Use the technical design to implement architecture and data flow.
  • Use the engineering plan to create sprint tickets.
  • Use the AI execution pack as context for Codex or another execution tool.
  • Use risks and decision log as review gates before implementation.