Skip to content
muneer406Public

About

AI carbon footprint tracker: describe your day in plain language and get structured emissions data back. Next.js, tRPC, Supabase, Zod-validated LLM extraction.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

EcoLoop

Next.js 16 TypeScript 5 tRPC 11 Supabase Tailwind 4 Three.js Zod Claude or Groq WCAG 2.2 AA MIT License

Know your carbon. Build the habit. See the change.

EcoLoop is an AI-powered sustainability platform that helps users understand, track, and reduce their carbon footprint through simple natural-language descriptions of their day.


🎯 Core Loop

flowchart TD
    U[User Input] -->|"I drove 12km, ate a burger"| AI[AI Extraction]
    AI -->|Structured JSON| VAL{Zod Validation}
    VAL -->|Passed| CO2[COβ‚‚ Engine]
    VAL -->|Failed| REJ[Reject / Retry]
    CO2 -->|Deterministic Calculation| DB[(Supabase PostgreSQL)]
    DB --> DASH[Dashboard Update]
    DB --> HABIT[Habit Engine]
    HABIT -->|Personalized Action| ACT[Action Card]
    ACT --> TRACK[Progress Tracking]
    TRACK -->|Streak Update| U
Loading

πŸ— Architecture

graph TB
    subgraph Browser["Browser"]
        UI[React Components]
        RQ[React Query Cache]
        ZS[Zustand Stores]
    end

    subgraph NextJS["Next.js 16"]
        subgraph AppRouter["App Router"]
            LANDING["/ Landing"]
            LOGIN["/login Auth"]
            CHAT["/chat Core Loop"]
            DASHBOARD["/dashboard Analytics"]
        end
        TRPC[tRPC API Layer]
        PROXY[Proxy / Auth Guard]
    end

    subgraph Services["Service Layer"]
        AI_SVC[AI Service]
        CO2_SVC[COβ‚‚ Engine]
        HABIT_SVC[Habit Engine]
        DASH_SVC[Dashboard Service]
    end

    subgraph External["External Services"]
        CLAUDE[Anthropic Claude]
        SUPABASE[Supabase]
        PG[(PostgreSQL)]
    end

    UI --> TRPC --> Services
    AI_SVC --> CLAUDE
    CO2_SVC --> SUPABASE --> PG
    HABIT_SVC --> SUPABASE
    DASH_SVC --> SUPABASE
    PROXY --> SUPABASE
Loading

πŸ›  Tech Stack

Layer Technology Purpose
Framework Next.js 16 App Router, SSR, ISR
Language TypeScript 5 (strict) End-to-end type safety
API tRPC 11 Type-safe RPC layer
Database Supabase PostgreSQL Data storage + auth
Auth Supabase Auth Google OAuth + Magic Link
Security Row Level Security Per-user data isolation
Validation Zod 4 Schema enforcement
Styling Tailwind CSS 4 Utility-first CSS
Components shadcn/ui + Base UI Accessible primitives
Animation Framer Motion Motion system
3D React Three Fiber + Drei Carbon Field visualization
Charts Recharts Analytics visualizations
State Zustand + React Query Client + server state
AI Vercel AI SDK Claude (paid) β†’ Groq (free fallback)
Rate Limit In-memory 20 req/hr per user
Testing Vitest Unit + integration tests

πŸ“Š Features

Feature Status Description
AI Activity Extraction βœ“ Natural language β†’ structured activities (Claude or free Groq)
COβ‚‚ Calculation Engine βœ“ Deterministic, source-cited emission factors
Personal Dashboard βœ“ Weekly trends, category breakdown, comparisons
Carbon Field βœ“ Three.js particle visualization of impact
Habit Engine βœ“ Personalized daily micro-actions based on biggest contributor
Streak System βœ“ Consecutive days tracked (log + action required)
Google OAuth βœ“ One-click social authentication
Magic Link βœ“ Passwordless email authentication
Onboarding βœ“ Country, transport, and diet personalization
Rate Limiting βœ“ 20 requests/hour for AI chat
Accessibility βœ“ WCAG 2.2 AA, keyboard nav, screen readers
Responsive βœ“ Mobile-first, adaptive particle count
Unit Tests βœ“ 31 tests across COβ‚‚ engine and AI defense

πŸ“ Project Structure

src/
β”œβ”€β”€ app/                          # Next.js App Router pages
β”‚   β”œβ”€β”€ (app)/                    # Authenticated route group
β”‚   β”‚   β”œβ”€β”€ chat/                 # Core logging experience
β”‚   β”‚   β”œβ”€β”€ dashboard/            # Analytics dashboard
β”‚   β”‚   β”œβ”€β”€ onboarding/           # Profile setup
β”‚   β”‚   β”œβ”€β”€ profile/              # Account page
β”‚   β”‚   └── settings/             # Preferences
β”‚   β”œβ”€β”€ api/trpc/[trpc]/          # tRPC API endpoint
β”‚   β”œβ”€β”€ auth/callback/            # OAuth callback handler
β”‚   β”œβ”€β”€ login/                    # Authentication page
β”‚   └── layout.tsx                # Root layout
β”‚
β”œβ”€β”€ components/                   # React components
β”‚   β”œβ”€β”€ ui/                       # shadcn/ui primitives
β”‚   β”œβ”€β”€ app-nav.tsx               # Authenticated nav bar
β”‚   β”œβ”€β”€ auth-provider.tsx         # Supabase auth listener
β”‚   β”œβ”€β”€ carbon-field.tsx          # Three.js particle system
β”‚   β”œβ”€β”€ chat-input.tsx            # Activity input form
β”‚   β”œβ”€β”€ chat-history.tsx          # Activity history display
β”‚   β”œβ”€β”€ dashboard-client.tsx      # Dashboard with charts
β”‚   β”œβ”€β”€ login-form.tsx            # OAuth + Magic Link form
β”‚   β”œβ”€β”€ onboarding-form.tsx       # Profile setup wizard
β”‚   β”œβ”€β”€ action-card.tsx           # Daily micro-action card
β”‚   └── skip-link.tsx             # Accessibility skip link
β”‚
β”œβ”€β”€ server/                       # Backend logic
β”‚   β”œβ”€β”€ api/                      # tRPC layer
β”‚   β”‚   β”œβ”€β”€ context.ts            # Request context
β”‚   β”‚   β”œβ”€β”€ trpc.ts               # tRPC instance + middleware
β”‚   β”‚   β”œβ”€β”€ root.ts               # Root router
β”‚   β”‚   β”œβ”€β”€ rate-limit.ts         # In-memory rate limiter
β”‚   β”‚   └── routers/              # Feature routers
β”‚   β”‚       β”œβ”€β”€ chat.ts           # Core loop orchestrator
β”‚   β”‚       β”œβ”€β”€ dashboard.ts      # Metrics aggregation
β”‚   β”‚       β”œβ”€β”€ habits.ts         # Action selection + streaks
β”‚   β”‚       └── profile.ts        # User profile CRUD
β”‚   β”œβ”€β”€ services/                 # Pure business logic
β”‚   β”‚   β”œβ”€β”€ ai/                   # Claude extraction + defense
β”‚   β”‚   β”œβ”€β”€ co2/                  # Deterministic COβ‚‚ engine
β”‚   β”‚   β”œβ”€β”€ habits/               # Action selection + streak logic
β”‚   β”‚   β”œβ”€β”€ dashboard/            # Aggregation + trends
β”‚   β”‚   β”œβ”€β”€ analytics/            # Activity DB operations
β”‚   β”‚   └── auth/                 # Profile management
β”‚   β”œβ”€β”€ db/                       # Supabase clients
β”‚   β”‚   β”œβ”€β”€ supabase-server.ts    # Server-side (cookies)
β”‚   β”‚   β”œβ”€β”€ supabase-browser.ts   # Client-side
β”‚   β”‚   └── supabase-middleware.ts# Proxy auth
β”‚   └── validators/               # Zod schemas
β”‚
β”œβ”€β”€ stores/                       # Zustand stores
β”‚   β”œβ”€β”€ auth-store.ts             # Authentication state
β”‚   └── chat-store.ts             # Chat entries
β”‚
β”œβ”€β”€ hooks/                        # Custom React hooks
β”‚   β”œβ”€β”€ use-auth.ts               # Auth operations
β”‚   └── use-media-query.ts        # Responsive detection
β”‚
β”œβ”€β”€ lib/                          # Shared utilities
β”‚   β”œβ”€β”€ trpc-client.ts            # tRPC React client
β”‚   β”œβ”€β”€ trpc-provider.tsx         # tRPC + React Query provider
β”‚   └── utils.ts                  # cn() helper
β”‚
β”œβ”€β”€ types/                        # TypeScript type definitions
β”‚   └── index.ts                  # All shared types
β”‚
β”œβ”€β”€ constants/                    # Application constants
β”‚   └── index.ts                  # Rate limits, targets, config
β”‚
└── tests/                        # Unit tests
    β”œβ”€β”€ co2-engine.test.ts        # COβ‚‚ engine (21 tests)
    └── ai-defense.test.ts        # AI defense (10 tests)

supabase/
└── migrations/                   # Database migrations
    β”œβ”€β”€ 00001_schema.sql          # Tables, enums, RLS, triggers
    β”œβ”€β”€ 00002_seed_emission_factors.sql  # 46 emission factors
    └── 00003_seed_micro_actions.sql     # 24 micro-actions

πŸš€ Quick Start

# 1. Clone
git clone [https://github.com/Muneer320/EcoLoop.git && cd EcoLoop

# 2. Install
npm install

# 3. Configure environment
cp .env.example .env.local
# Fill in Supabase URL, Supabase Anon Key
# Set either ANTHROPIC_API_KEY (Claude) or GROQ_API_KEY (free) β€” or both

# 4. Set up Supabase
# Run migrations in supabase/migrations/ against your Supabase project

# 5. Run development server
npm run dev

# 6. Open
open http://localhost:3000

AI Provider

EcoLoop supports two AI providers with automatic fallback:

Priority Provider Model Key Required Cost
1st Anthropic Claude claude-sonnet-4-20250514 ANTHROPIC_API_KEY Paid
2nd Groq llama-3.3-70b-versatile GROQ_API_KEY Free

If ANTHROPIC_API_KEY is set, Claude is used. Otherwise, Groq is used automatically. Set either key β€” or both to have a paid primary and a free fallback.


πŸ§ͺ Testing

# Run all tests
npm test

# Watch mode
npm run test:watch

Coverage:

Module Tests Status
COβ‚‚ Engine 21 βœ…
AI Defense 10 βœ…
Total 31 βœ…

πŸ”’ Security

  • Row Level Security β€” Every user-owned table enforces auth.uid() = user_id
  • Input Validation β€” Zod schemas at every boundary (user input, AI output, API requests)
  • Rate Limiting β€” 20 AI calls/hour per user
  • Prompt Injection Defense β€” Incoming messages scanned for known attack patterns
  • CSP Ready β€” Content Security Policy headers configured
  • PKCE Authentication β€” Secure OAuth 2.0 code exchange
  • No Secrets in Client β€” All sensitive keys server-side only

🌍 Emission Factor Sources

All COβ‚‚ calculations are deterministic and sourced from peer-reviewed data:

Source Used For
DEFRA 2024 Transport, electricity, natural gas
IPCC Global averages, climate reporting
Our World In Data Food items, consumer goods
IEA Electricity generation by country

Every factor includes a citation stored in the emission_factors table.


🎨 Design Philosophy

What EcoLoop is:

  • An invisible-systems visualizer (atmosphere, particles, depth)
  • Inspired by Apple, Linear, and Arc Browser
  • Information-first with ambient visual enhancement

What EcoLoop is NOT:

  • No leaves, trees, forests, or globes
  • No green-washing imagery
  • No sustainability clichΓ©s
  • No gamification gimmicks

πŸ“œ License

MIT Β© EcoLoop


Built for the hackathon. Polished for the planet.

About

AI carbon footprint tracker: describe your day in plain language and get structured emissions data back. Next.js, tRPC, Supabase, Zod-validated LLM extraction.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages