# Project export: Emmy

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: The home for your life’s story <3
- Devpost: https://devpost.com/software/emmy-hipa4n
- GitHub: https://github.com/tusharvaskarsharma/Emmy.git
- Demo: https://emmy-web-ochre.vercel.app/
- Video: https://www.youtube.com/embed/CGJNBCmuPK4?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 3 GitHub contributor(s) — tusharvaskarsharma (38 commits), akanksha312kumari (11 commits), railway-app[bot] (1 commits)

## Devpost submission (written by the team)

### Inspiration

My grandma, she was the strongest support of mine. If i stuck in a problem of my life, i look up in the sky and ask her “nani.. mai kya karu?” But she never replies! I wished i could hear her more, know what she would do in this situation, I wish she was there a lil longer! And then i thought, yes it’s not possible to have a person forever. But her words? Her principles? Her thought process? That’s a kind of data and data can be stored! So we decided to build something which can hear us talking, store it, analyze it, and answer based on that person’s principles and values. So that the next generations can feel as if the person is still there beside them, supporting them!!

### What it does

Emmy stays beside people, preserve their memories, stories, and voice, through conversations. And it creates a digital legacy. The loved ones can talk, feel the person they lost and revisit the memories anytime.

### How we built it

We built a real-time AI interviewer that asks meaningful questions, captures voice and stories, extracts structured memories, categorises them and stores them securely. The platform then generates an AI persona capable of answering future questions using those memories. Technologies we used include: Frontend: Next.js, React, Tailwind CSS Backend: FastAPI Database & Auth: Supabase (PostgreSQL + Authentication) Vector db: Pinecone AI: Gemini Live API, Groq LLM Voice: Real-time speech-to-text and text-to-speech Infrastructure: Railway (backend), Vercel (frontend)

### Accomplishments we're proud of

Built a working AI memory companion from scratch. Created smooth real-time voice conversations. Turned long conversations into organized memories.

### What we learned

We learned that emotion matters as much as intelligence in AI :)

### What's next

photo and video memories voice cloning mobile app

## README (from the GitHub repository)

# Emmy — AI-Powered Living Legacy Platform

> *An AI-powered living legacy system that preserves how a person thinks, speaks, and loves — so the people who matter most never lose them.*

**Hackathon:** OpenAI Hackathon (Devpost)
**Stack:** Gemini Live Audio · Groq persona generation · Next.js 14 · FastAPI · Supabase · Pinecone · librosa · CREPE Pitch Tracking · ElevenLabs Voice Clone · Acoustic Fingerprint Engine

---

## Table of Contents

1. [Executive Summary & The Hook](#1-executive-summary--the-hook)
   - [Project Name & Core Value Proposition](#11-project-name--core-value-proposition)
   - [Market Validity: Target User Personas](#12-market-validity-target-user-personas)
   - [Market Statistics & Why Now](#13-market-statistics--why-now)
2. [Comprehensive System Architecture](#2-comprehensive-system-architecture)
   - [Architecture Overview](#21-architecture-overview)
   - [Exact Tech Stack](#22-exact-tech-stack)
3. [Architectural Blueprint & File Structure](#3-architectural-blueprint--file-structure)
   - [Production-Grade Repository Structure](#31-production-grade-repository-structure)
   - [Key File Explanations](#32-key-file-explanations)
4. [Step-by-Step Building Process & Data Flow](#4-step-by-step-building-process--data-flow)
   - [Phase 1 — Data Collection & Ingestion: The Interview Session Pipeline](#phase-1--data-collection--ingestion-the-interview-session-pipeline)
   - [Phase 2 — Backend & AI Logic: The Family Conversation Pipeline](#phase-2--backend--ai-logic-the-family-conversation-pipeline)
   - [Phase 3 — Frontend Integration: Building the UI/UX](#phase-3--frontend-integration-building-the-uiux)
   - [GPT-5.6 & Codex Development Workflow](#41-gpt-56--codex-development-workflow)
5. [The Hackathon Winning Edge](#5-the-hackathon-winning-edge)
   - [What Makes This Win in a 3-Minute Demo](#51-what-makes-this-win-in-a-3-minute-demo)
   - [The 3-Minute Demo Script](#52-the-3-minute-demo-script)
6. [Personalised Voice Fingerprint Engine (Future Roadmap)](#6-personalised-voice-fingerprint-engine-future-roadmap)
   - [The Six Acoustic Dimensions Emmy Will Capture](#61-the-six-acoustic-dimensions-emmy-will-capture)
   - [The Technical Pipeline — End to End](#62-the-technical-pipeline--end-to-end)
   - [Step-by-Step Technical Detail](#63-step-by-step-technical-detail)
   - [The Three-Phase Voice Roadmap](#64-the-three-phase-voice-roadmap)
   - [New Files & Services Required for Voice](#65-new-files--services-required-for-voice)
   - [New Tech Stack Additions for Voice](#66-new-tech-stack-additions-for-voice)
   - [The Consent Architecture for Voice Cloning](#67-the-consent-architecture-for-voice-cloning)
7. [Deployment Instructions](#7-deployment-instructions)
8. [Mind Model Architecture](#8-mind-model-architecture)
9. [Cognitive Engine Architecture](#9-cognitive-engine-architecture)
10. [Autonomous Life Interview Engine](#10-autonomous-life-interview-engine)

---

## 1. Executive Summary & The Hook

### 1.1 Project Name & Core Value Proposition

**Emmy** is a consent-first, multimodal AI platform that transforms structured life-narrative sessions into a deeply personal, privately hosted "voice model" of a human being. Unlike a memorial website or a static recording, Emmy enables family members to have *new* conversations with a loved one's preserved memory — conversations grounded exclusively in what that person actually shared, recalled in their voice, reasoning style, and emotional cadence.

> **Core Value Proposition:** Emmy uses Gemini Live voice sessions, Groq-powered retrieval-grounded persona responses, and a consent-governed memory graph to let families continue meaningful conversations with the mind of someone they've lost — not a simulation, but a reflection.

**Critical ethical differentiator:** Emmy never fabricates. If a grandmother never shared a memory about a topic, her Emmy responds: *"I don't have a memory of that — I wish I did."* This boundary is technically enforced through RAG-only generation with a strict no-hallucination system prompt, making Emmy trustworthy rather than uncanny.

---

### 1.2 Market Validity: Target User Personas

#### Primary Persona — The Subject

**Demographics:**
- Age 55–80, often retired or semi-retired
- Has grandchildren or adult children who live remotely
- May have received an early-stage diagnosis (dementia, cancer)
- Moderate tech comfort — uses smartphone daily
- Deeply values being understood and remembered accurately

**Pain Points:**
- Fear that their stories, values, and personality will be forgotten
- No structured, dignified way to record their inner life
- Existing options (memoir writing, video diaries) feel like work
- Concerned about who controls their digital likeness after death
- Wants to give grandchildren something real, not a photo album

#### Secondary Persona — The Family Member

- Adult child, age 30–55, often geographically distant
- Has questions they never asked while they had the chance
- Wants to share a grandparent's wisdom with their own children
- Tech-savvy, emotionally motivated, high willingness to pay

#### Tertiary Persona — The Proactive Planner

- Age 35–55, any health status
- Has watched a parent die without documenting their story
- Motivated by not repeating that loss for their own children
- Uses tools like life insurance, wills — treats this as legacy infrastructure

---

### 1.3 Market Statistics & Why Now

| Metric | Value | Source |
|--------|-------|--------|
| People globally living with dementia | **55M+** (projected to triple by 2050) | WHO, 2023 |
| Global death care / end-of-life services market | **$110B** (growing 5.8% CAGR) | Industry reports |
| Adults who regret not asking a deceased parent more questions | **67%** | Pew, 2022 |

Three converging forces make this the right moment:

1. **Gemini Live** provides low-latency bidirectional audio over WebSockets, so a subject can have a natural spoken interview without exposing a long-lived provider key to the browser.
2. **Groq-hosted Llama 3.3 70B** produces retrieval-grounded persona responses and structured memory extraction on a configurable developer-tier model.
3. **Cultural moment** — post-COVID emphasis on digital legacy, combined with growing distrust of "AI ghost" companies that do this without consent, creates an opening for an ethical, subject-first competitor.

> **The competitive gap:** Existing players (HereAfter AI, StoryFile, Eternos) collect video recordings and build chatbots from transcripts. None use live audio AI for collection, none offer fine-tuned persona models, and none have a robust consent architecture. Emmy is not a better version of these products — it is a fundamentally different category.

---

## 2. Comprehensive System Architecture

### 2.1 Architecture Overview

Emmy is composed of seven principal layers:

- **Next.js 14 frontend** with real-time WebSocket connections for audio streaming
- **FastAPI backend** orchestrating the AI pipeline and business logic
- **Dual-database layer** — PostgreSQL via Supabase for structured data, Pinecone for vector embeddings
- **Multi-model AI layer** — Gemini Live for native session audio and Gemini embeddings; Groq Llama for persona generation, structured extraction, and audio transcription
- **Mind Model layer** — a consent-gated, evidence-linked cognitive model of values, reasoning, emotions, communication, and evolving life principles. It augments retrieval; it never substitutes unsupported traits for source memories.
- **Cognitive Engine layer** — an intent-aware, relationship- and time-sensitive answer-planning layer that creates a bounded evidence ledger before persona generation. It never stores or exposes chain-of-thought.
- **Autonomous Life Interview Engine** — a voluntary, coverage-aware long-horizon planner that identifies unexplored domains, recommends respectful follow-ups, tracks uncertainty, and keeps the subject in control.

FastAPI performs session processing, memory indexing, and persona updates 

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 180 recognized source files, 878 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- SQL (language) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Google Gemini (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 193)

```
.env.example
.gitignore
.vscode/settings.json
apps/api/.env.example
apps/api/app/__init__.py
apps/api/app/auth/dependencies.py
apps/api/app/auth/middleware.py
apps/api/app/auth/security.py
apps/api/app/config.py
apps/api/app/db/__init__.py
apps/api/app/db/client.py
apps/api/app/db/migrations/001_subjects.sql
apps/api/app/db/migrations/002_sessions.sql
apps/api/app/db/migrations/003_memories.sql
apps/api/app/db/migrations/004_echo_profiles.sql
apps/api/app/db/migrations/005_legacy_contacts.sql
apps/api/app/db/migrations/006_conversation_history.sql
apps/api/app/db/migrations/007_add_audio_and_time_period.sql
apps/api/app/db/migrations/008_finetune_jobs.sql
apps/api/app/db/migrations/010_multi_user_rls.sql
apps/api/app/db/migrations/011_provider_agnostic_persona_jobs.sql
apps/api/app/db/migrations/011_saas_resources.sql
apps/api/app/db/migrations/012_mind_model.sql
apps/api/app/db/migrations/013_cognitive_engine.sql
apps/api/app/db/migrations/014_autonomous_life_interview_engine.sql
apps/api/app/db/migrations/015_memories_realtime.sql
apps/api/app/db/migrations/016_semantic_memory_retrieval.sql
apps/api/app/db/migrations/017_mind_model_snapshots.sql
apps/api/app/db/migrations/018_profiles_data_api_grants.sql
apps/api/app/db/migrations/019_profile_username_system.sql
apps/api/app/db/migrations/020_family_groups.sql
apps/api/app/db/migrations/021_group_invitations.sql
apps/api/app/db/migrations/022_memory_retrieval_chunks.sql
apps/api/app/db/migrations/023_identity_profiles.sql
apps/api/app/db/migrations/024_rename_echo_to_emmy.sql
apps/api/app/db/migrations/025_rename_emmy_profile_constraint.sql
apps/api/app/db/migrations/026_index_emmy_profiles_user_id.sql
apps/api/app/db/migrations/027_identity_profile_schema_guard.sql
apps/api/app/db/repositories.py
apps/api/app/main.py
apps/api/app/models/__init__.py
apps/api/app/models/cognitive.py
apps/api/app/models/emmy.py
apps/api/app/models/finetune.py
apps/api/app/models/identity.py
apps/api/app/models/memory.py
apps/api/app/models/mind_model.py
apps/api/app/models/schema.py
apps/api/app/models/session.py
apps/api/app/models/subject.py
apps/api/app/routers/__init__.py
apps/api/app/routers/auth.py
apps/api/app/routers/emmy_conversation.py
apps/api/app/routers/emmy.py
apps/api/app/routers/finetune.py
apps/api/app/routers/groups.py
apps/api/app/routers/identity.py
apps/api/app/routers/memories.py
apps/api/app/routers/mind.py
apps/api/app/routers/profile.py
apps/api/app/routers/realtime.py
apps/api/app/routers/sessions.py
apps/api/app/services/__init__.py
apps/api/app/services/chat_service.py
apps/api/app/services/cognitive_engine.py
apps/api/app/services/embedding_service.py
apps/api/app/services/finetune_builder.py
apps/api/app/services/groq_service.py
apps/api/app/services/identity_service.py
apps/api/app/services/memory_chunking.py
apps/api/app/services/memory_extractor.py
apps/api/app/services/memory_storage_service.py
apps/api/app/services/mind_model_builder.py
apps/api/app/services/persona_service.py
apps/api/app/services/pinecone_service.py
apps/api/app/services/realtime_service.py
apps/api/app/services/retrieval_service.py
apps/api/app/services/session_audio_storage_service.py
apps/api/app/services/session_service.py
apps/api/app/services/transcription_service.py
apps/api/app/services/username_service.py
apps/api/app/workers/__init__.py
apps/api/app/workers/index_memory.py
apps/api/app/workers/process_session.py
apps/api/app/workers/retrain_persona.py
apps/api/app/workers/sync_consent.py
apps/api/pyproject.toml
apps/api/railway.toml
apps/api/tests/test_auth_dependencies.py
apps/api/tests/test_cognitive_engine.py
apps/api/tests/test_connections.py
apps/api/tests/test_consent_sync.py
apps/api/tests/test_cors.py
apps/api/tests/test_dashboard_summary.py
apps/api/tests/test_delete_all_memories.py
apps/api/tests/test_emmy_conversation_pipeline.py
apps/api/tests/test_emmy_conversation.py
apps/api/tests/test_family_groups.py
apps/api/tests/test_family_sharing_empty_states.py
apps/api/tests/test_gemini_live.py
apps/api/tests/test_identity_layer.py
apps/api/tests/test_memory_extractor.py
apps/api/tests/test_memory_index_row_normalization.py
apps/api/tests/test_memory_indexing.py
apps/api/tests/test_memory_retrieval_regression.py
apps/api/tests/test_memory_save.py
apps/api/tests/test_migration_idempotency.py
apps/api/tests/test_mind_model_builder.py
apps/api/tests/test_retrieval_policy.py
apps/api/tests/test_security.py
apps/api/tests/test_session_row_normalization.py
apps/api/tests/test_structured_memory_pipeline.py
apps/api/tests/test_username_system.py
apps/web/.env.example
apps/web/.eslintrc.js
apps/web/app/(auth)/callback/route.ts
apps/web/app/(auth)/forgot-password/page.tsx
apps/web/app/(auth)/login/page.tsx
apps/web/app/(auth)/onboarding/page.tsx
apps/web/app/(auth)/reset-password/page.tsx
[73 more files omitted for size]
```

### Dependencies

- apps/api/pyproject.toml: asyncpg@>=0.29.0, email-validator@>=2.0.0, fastapi@>=0.115,<1, gunicorn@>=21.2.0, httpx@>=0.27.0, httpx@>=0.27, pinecone@>=5.0, pinecone@>=5.0.0, pydantic-settings@>=2.4,<3, PyJWT@>=2.8.0, pytest@>=8.0, python-multipart@>=0.0.9, supabase@>=2.0, uvicorn[standard]@>=0.30,<1
- apps/web/package.json: @supabase/ssr@^0.5.2, @supabase/supabase-js@^2.49.4, @types/d3@^7.4.3, @types/d3-force@^3.0.10, @types/node@^20.17.0, @types/react@^18.3.12, @types/react-dom@^18.3.1, @vercel/analytics@^1.5.0, autoprefixer@^10.5.3, d3@^7.9.0, d3-force@^3.0.0, eslint@^8.57.1, eslint-config-next@^16.2.10, framer-motion@^12.42.2, lucide-react@^1.24.0, next@14.2.35, postcss@^8.5.19, react@^18.3.1, react-dom@^18.3.1, swr@^2.4.2, tailwindcss@^3.4.19, typescript@^5.6.3

### Recent commits (newest first)

- Document GPT-5.6 and Codex development workflow
- List accepted group members with archive sharing status
- Normalize UUIDs in identity profile responses
- Handle missing bearer sessions and auth validation outages
- Validate identity schema and handle new user profiles
- Add dashboard summary endpoint for session and memory totals
- Fix garbled Unicode characters in README
- Refactor application architecture and simplify implementation
- Improve memory retrieval fallback and structured extraction
- Harden Echo conversations with archive checks and fallbacks
- Improve session transcripts and consent-aware memory retrieval
- Add privacy settings endpoints and improve database error handling
- Harden migration checks for idempotent schema updates
- Add invitation workflow for family group membership
- Move group membership helper into private schema
- Add group sharing and secure username updates
- Remove Redis and Celery dependencies in favor of synchronous processing
- Harden OAuth callback error handling and cache control
- Configure production OAuth redirect URL
- Harden Supabase PKCE authentication flow

## Key source files (fetched from GitHub, selected and truncated for size)

### docs/family-groups.md

```markdown
# Family Groups

Family Groups let an Emmy owner grant their complete memory map to selected groups. Memories remain private unless the owner enables sharing for a specific group. Joining is invitation-only: no username lookup can add a member automatically.

## Security model

- Every invitation uses the recipient's canonical username, never their email address.
- `groups`, `group_members`, and `memory_permissions` have foreign keys, indexes, and row-level security policies in migration `020_family_groups.sql`.
- `group_invitations` in migration `021_group_invitations.sql` has a single pending invite per user/group, a seven-day expiry, recipient-only accept/decline policies, and an immutable transition trigger.
- A `group_members` row for a recipient can be inserted only after their invitation reaches `accepted`; pending, declined, and expired users have no shared-memory permission.
- A database trigger ensures a group can grant only its owner's memory map, and only the actual owner can hold the `owner` member role.
- The API checks authenticated membership for every group, shared-memory, shared-mind, and shared-chat request. The selected owner from the browser is only a selector, never authority.
- Emmy resolves the target owner before retrieval. It queries that owner's subject namespace only and scopes citations and Mind Model reads to that owner.

## Deployment

The API migration runner applies `apps/api/app/db/migrations/020_family_groups.sql` during backend startup. Deploy the API before using the new web UI, then deploy the web service. No worker, Redis, or Celery service is required.

## User flow

1. New accounts choose a 3–30 character lowercase username at signup. Existing users without a username are redirected to onboarding.
2. An owner creates a group, confirms an exact username search, and sends an invitation.
3. The recipient accepts or declines the invitation from **Invitations**. Pending invitations expire after seven days.
4. The owner turns on **Share my memory map** for that group. Only accepted members gain access.
5. Accepted members choose the owner's name under **Memory source** in Emmy. Switching source resets conversation history and uses only the selected, permitted owner context.

```

### docs/life-profile.md

```markdown
# Life Profile: identity facts separate from memories

Emmy now uses two deliberately separate sources of knowledge:

1. **Life Profile (`identity_profiles`)** for stable, user-maintained facts such as name, family, profession, date of birth, values, and favourites.
2. **Semantic memory** in PostgreSQL plus Pinecone for stories, conversations, events, feelings, and advice.

Identity facts are never embedded or written to Pinecone. This prevents a correct name, spouse, occupation, or birth place from depending on a similarity-search result.

## API

- `GET /identity` creates a sparse owner row when necessary and returns the complete Life Profile.
- `PUT /identity` updates only the submitted fields. Sending `null` clears an optional text field.
- `GET /identity/{owner_id}` is available only to the owner or an accepted member of a group whose memory sharing is enabled. A group member receives only fields included in the owner’s `privacy_settings.shared_fields` allow-list.

The web page is `/life-profile`. It provides sections for basic details, family, values/favourites, and optional contact/health details, plus a per-field group-sharing control. Contact and health fields are private by default.

## Conversation routing

`IdentityService.classify_question()` routes questions to one of four paths:

| Intent | Examples | Behaviour |
| --- | --- | --- |
| `identity` | “What is your name?”, “Who is your wife?”, “How old are you?” | Answers directly from `identity_profiles`; Pinecone is not queried. |
| `memory` | “What was your happiest memory?”, “What advice did you leave?” | Uses the existing consent-scoped RAG pipeline. |
| `mixed` | “What did your wife think when you became a doctor?” | Adds authorised Life Profile facts and retrieved semantic memories to the prompt. |
| `general` | Non-specific questions | Uses normal memory retrieval, with Life Profile context available to the prompt. |

Prompt order is always: Identity Context, Persona Context, Retrieved Memories, then the latest user question. The streaming compatibility chat service uses the same classifier and context builder.

## Security model

Migration `023_identity_profiles.sql` enables RLS and allows direct table access only to the owner. This prevents a group member from bypassing field privacy with `select *`.

The public `get_shared_identity_profile(uuid)` RPC is a deliberately constrained, authenticated `SECURITY DEFINER` function: it verifies the caller is the owner or an accepted member of a group with active memory sharing, then emits only the fields in `shared_fields`. It has a fixed empty search path and cannot be called by `anon` or `PUBLIC`.

The FastAPI routes independently perform the same group-membership check and field filtering; frontend code does not query `identity_profiles` directly.

## Operations

- The table and all policies/triggers/functions in migration 023 use idempotent DDL (`IF NOT EXISTS`, `DROP … IF EXISTS`, or `CREATE OR REPLACE`) so the API’s migration ru
[truncated — 212 more characters]
```

### package.json

```
{
  "name": "emmy",
  "private": true,
  "packageManager": "pnpm@10.13.1",
  "scripts": {
    "dev:web": "pnpm --dir apps/web dev",
    "build": "pnpm --dir apps/web build",
    "lint": "pnpm --dir apps/web lint"
  },
  "workspaces": ["apps/*", "packages/*"]
}

```

### packages/shared-types/package.json

```
{
  "name": "@emmy/shared-types",
  "version": "0.1.0",
  "private": true,
  "main": "./index.ts",
  "types": "./index.ts"
}

```

### apps/api/pyproject.toml

```
[project]
name = "emmy-api"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
  "fastapi>=0.115,<1",
  "uvicorn[standard]>=0.30,<1",
  "gunicorn>=21.2.0",
  "pydantic-settings>=2.4,<3",
  "asyncpg>=0.29.0",
  "PyJWT>=2.8.0",
  "httpx>=0.27.0",
  "pinecone>=5.0.0",
  "python-multipart>=0.0.9",
  "email-validator>=2.0.0"
]

[project.optional-dependencies]
live = [
  "supabase>=2.0",
  "pinecone>=5.0"
]
dev = ["pytest>=8.0", "httpx>=0.27"]

[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]


```

### apps/web/package.json

```
{
  "name": "emmy-web",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@vercel/analytics": "^1.5.0",
    "@supabase/ssr": "^0.5.2",
    "@supabase/supabase-js": "^2.49.4",
    "d3": "^7.9.0",
    "d3-force": "^3.0.0",
    "framer-motion": "^12.42.2",
    "lucide-react": "^1.24.0",
    "next": "14.2.35",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "swr": "^2.4.2"
  },
  "devDependencies": {
    "@types/d3": "^7.4.3",
    "@types/d3-force": "^3.0.10",
    "@types/node": "^20.17.0",
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "autoprefixer": "^10.5.3",
    "eslint": "^8.57.1",
    "eslint-config-next": "^16.2.10",
    "postcss": "^8.5.19",
    "tailwindcss": "^3.4.19",
    "typescript": "^5.6.3"
  }
}

```

### packages/shared-types/index.ts

```typescript
// Auto-generated types from FastAPI will go here
export {};

```

### apps/web/app/layout.tsx

```typescript
import type { Metadata } from "next";
import { Analytics } from "@vercel/analytics/next";
import { Inter, Instrument_Serif } from "next/font/google";
import "./globals.css";

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-geist-sans", // Keeping the CSS variable name the same so we don't have to update Tailwind config if it uses it
});

const instrumentSerif = Instrument_Serif({
  weight: "400",
  subsets: ["latin"],
  variable: "--font-instrument-serif",
});

export const metadata: Metadata = {
  title: "Emmy - Your Living Legacy",
  description: "AI-powered living legacy platform.",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={`${inter.variable} ${instrumentSerif.variable}`}>
        {children}
        <Analytics />
      </body>
    </html>
  );
}

```

### apps/web/app/page.tsx

```typescript
import Link from "next/link";
import { AppNav } from "../components/AppNav";

export default function Home() {
  return <main><AppNav /><section className="landing"><div><p className="eyebrow">A living legacy, built with consent</p><h1>Some stories deserve more than a recording.</h1><p className="lede">Emmy helps families preserve the voice, values, and memories of the people they love—without ever inventing a story.</p><div className="landing-actions"><Link className="button-link" href="/subject/session">Record a story</Link><Link className="text-link" href="/subject/dashboard">Open my legacy →</Link></div></div><div className="landing-orb"><div className="audio-orb ready"><span /></div><p>Every answer is grounded in a memory you shared.</p></div></section><section className="principles"><div><b>01</b><h2>Only true stories</h2><p>Emmy refuses to guess when a memory is not there.</p></div><div><b>02</b><h2>Consent stays with you</h2><p>Every memory is private, family, or legacy—by choice.</p></div><div><b>03</b><h2>Sources stay visible</h2><p>Every response points back to the memory behind it.</p></div></section></main>;
}

```

### apps/api/app/main.py

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from .config import get_settings

from .routers import sessions, memories, emmy, emmy_conversation, finetune, auth, realtime, mind, profile, groups, identity
from .db.client import db_client
from .auth.middleware import AuthMiddleware

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize DB or external connections here
    await db_client.connect()
    yield
    # Clean up here
    await db_client.disconnect()

app = FastAPI(title="Emmy API", version="0.1.0", lifespan=lifespan)
settings = get_settings()
cors_origins = settings.cors_origin_list

app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(AuthMiddleware)

@app.get("/health")
def health() -> dict:
    return {
        "ok": True,
        "mode": "live",
        "missing_live_integrations": settings.missing_live_integrations,
        # Origins are public configuration, not credentials.  Exposing the
        # effective parsed list makes a Railway configuration mistake directly
        # diagnosable without leaking any secret.
        "cors_origins": cors_origins,
    }

@app.get("/health/db")
async def health_db():
    if not db_client.pool:
        return {"ok": False, "status": "no pool initialized"}
    try:
        async with db_client.pool.acquire() as conn:
            await conn.execute("SELECT 1")
        return {"ok": True, "status": "connected"}
    except Exception as e:
        return {"ok": False, "status": str(e)}

@app.get("/health/providers")
def health_providers():
    """Reports provider configuration without disclosing credentials."""
    return {
        "ok": bool(settings.gemini_api_key and settings.groq_api_key),
        "gemini_live_model": settings.gemini_live_model,
        "groq_persona_model": settings.groq_persona_model,
    }

@app.get("/health/pinecone")
def health_pinecone():
    import os
    import httpx
    api_key = os.getenv("PINECONE_API_KEY", settings.pinecone_api_key)
    if not api_key:
        return {"ok": False, "status": "no api key"}
    return {"ok": True, "status": "pinecone api key configured"}

app.include_router(auth.router)
app.include_router(profile.router)
app.include_router(profile.privacy_router)
app.include_router(identity.router)
app.include_router(groups.router)
app.include_router(groups.shared_router)
# Backward-compatible account deletion endpoint; the canonical endpoint is /auth/account.
app.add_api_route("/account", auth.delete_account, methods=["DELETE"], status_code=204)
app.include_router(sessions.router)
app.include_router(memories.router)
app.include_router(emmy.router)
app.include_router(emmy_conversation.router)
app.include_router(finetune.router)
app.include_router(realtime.router)
app.include_router(mind.router)

# Wrap the complete application rather than adding CORS inside the middleware
# stack.  This ensures CORS headers are also present on error responses
# generated by FastAPI/Starlette (including an unexpected database exception),
# so browsers surface the real HTTP error instead of a misleading failed fetch.
app = CORSMiddleware(
    app=app,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    # Browser clients may add framework-specific request headers.  The origin
    # itself remains an exact allow-list match; allowing requested headers here
    # avoids failing a secure preflight solely because a harmless header changed.
    allow_headers=["*"],
    max_age=600,
)

```

[168 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]