> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting Guide

> Version: 1.0.0 Last Updated: 2025-01-27 Status: Stable Target Audience: Developers

**Version:** 1.0.0\
**Last Updated:** 2025-01-27\
**Status:** Stable\
**Target Audience:** Developers

Troubleshooting common development issues in the Encore Health OS Platform.

***

## Quick Reference

| Issue Category      | Common Symptoms                        | Quick Fix                            |
| ------------------- | -------------------------------------- | ------------------------------------ |
| Build Errors        | `npm install` fails, TypeScript errors | Check Node version, clear cache      |
| Supabase Connection | "Invalid Supabase URL", CORS errors    | Verify `.env.local` variables        |
| Authentication      | Login fails, session not persisting    | Check auth configuration             |
| TypeScript Errors   | Type mismatches, missing types         | Regenerate Supabase types            |
| Performance         | Slow builds, large bundle size         | Check lazy loading, optimize imports |
| Mobile Issues       | Layout breaks, touch targets too small | Verify responsive breakpoints        |

**For detailed solutions, see sections below.**

***

## Diagnostic Workflow

When encountering an issue, follow this workflow:

1. **Check Error Message** - Read the full error message and stack trace
2. **Verify Environment** - Ensure `.env.local` is configured correctly
3. **Check Dependencies** - Run `npm install` to ensure packages are up to date
4. **Clear Cache** - Clear build-cache and restart dev server
5. **Check Documentation** - Review relevant guides (see Related Documentation)
6. **Search Codebase** - Look for similar patterns or error handling
7. **Check Logs** - Review browser console and terminal output

***

## Build & Dependency Issues

### npm install Fails

#### Symptoms

* `npm ERR!` messages during installation
* Package resolution errors
* Permission denied errors

#### Solutions

1. **Clear npm cache:**
   ```bash theme={null}
   npm cache clean --force
   rm -rf node_modules package-lock.json
   npm install
   ```

2. **Check Node version:**
   ```bash theme={null}
   node --version  # Should be 18.x or 20.x
   ```

3. **Use correct package manager:**
   ```bash theme={null}
   # If using npm
   npm install

   # If using pnpm
   pnpm install
   ```

4. **Check for conflicting packages:**
   ```bash theme={null}
   npm ls  # Check for dependency conflicts
   ```

### TypeScript Build Errors

#### Symptoms

* `TS2307: Cannot find module` errors
* Type mismatches
* Missing type definitions

#### Solutions

1. **Regenerate Supabase types:**
   ```bash theme={null}
   npx supabase gen types typescript --project-id {project-ref} > src/integrations/supabase/types.ts
   ```

2. **Restart TypeScript server:**
   * VS Code: `Cmd/Ctrl + Shift + P` → "TypeScript: Restart TS Server"
   * Or reload VS Code window

3. **Check import paths:**
   ```typescript theme={null}
   // ✅ CORRECT: Use @/ alias
   import { Button } from '@/shared/ui/button';

   // ❌ WRONG: Relative paths
   import { Button } from '../../../shared/ui/button';
   ```

4. **Verify tsconfig.json:**
   * Check `paths` configuration for `@/` alias
   * Ensure `include` contains all source files

### Vite Build Errors

#### Symptoms

* Build fails with module resolution errors
* "Cannot find module" in production build
* Chunk loading errors

#### Solutions

1. **Clear Vite cache:**
   ```bash theme={null}
   rm -rf node_modules/.vite
   npm run dev
   ```

2. **Check for dynamic imports:**
   ```typescript theme={null}
   // ✅ CORRECT: Use React.lazy for routes
   const Dashboard = lazy(() => import('./Dashboard'));

   // ❌ WRONG: Direct imports for routes
   import Dashboard from './Dashboard';
   ```

3. **Verify environment variables:**
   * All `VITE_` prefixed variables must be set
   * Check `.env.local` exists and is properly formatted

***

## TypeScript Errors

### Missing Type Definitions

#### Symptoms

* `TS2307: Cannot find module '@/...'`
* `TS2339: Property '...' does not exist on type`

#### Solutions

1. **Regenerate Supabase types:**
   ```bash theme={null}
   npx supabase gen types typescript --project-id {project-ref} > src/integrations/supabase/types.ts
   ```

2. **Install missing type packages:**
   ```bash theme={null}
   npm install --save-dev @types/{package-name}
   ```

3. **Check tsconfig.json paths:**
   ```json theme={null}
   {
     "compilerOptions": {
       "paths": {
         "@/*": ["./src/*"]
       }
     }
   }
   ```

### Type Mismatches

#### Symptoms

* `TS2322: Type 'X' is not assignable to type 'Y'`
* Generic type errors

#### Solutions

1. **Check component prop types:**
   ```typescript theme={null}
   // Verify prop types match
   interface ComponentProps {
     value: string;  // Not number!
   }
   ```

2. **Use type assertions carefully:**
   ```typescript theme={null}
   // ✅ CORRECT: Type guard
   if (typeof value === 'string') {
     // value is string here
   }

   // ⚠️ Use sparingly: Type assertion
   const value = data as string;
   ```

3. **Check Supabase query return types:**
   ```typescript theme={null}
   const { data, error } = await supabase
     .from('table_name')
     .select('*')
     .single();

   // data is typed based on Database types
   ```

***

## Supabase Connection Issues

### "Invalid Supabase URL" Error

#### Symptoms

* Connection fails on app load
* "Invalid Supabase URL" error message

#### Solutions

1. **Verify `.env.local` exists:**
   ```bash theme={null}
   cat .env.local
   # Should contain:
   # VITE_SUPABASE_URL=https://{project-ref}.supabase.co
   # VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
   ```

2. **Check URL format:**
   ```bash theme={null}
   # ✅ CORRECT
   VITE_SUPABASE_URL=https://abcdefghijklmnop.supabase.co

   # ❌ WRONG
   VITE_SUPABASE_URL=https://abcdefghijklmnop.supabase.co/  # Trailing slash
   VITE_SUPABASE_URL=http://abcdefghijklmnop.supabase.co    # HTTP not HTTPS
   ```

3. **Restart dev server:**
   ```bash theme={null}
   # Stop server (Ctrl+C)
   npm run dev
   ```

### CORS Errors

#### Symptoms

* `CORS policy: No 'Access-Control-Allow-Origin' header`
* Requests blocked by browser

#### Solutions

1. **Verify Supabase project URL:**
   * Check `VITE_SUPABASE_URL` matches your Supabase project
   * Ensure project is active in Supabase Dashboard

2. **Check Supabase CORS settings:**
   * Supabase Dashboard → Settings → API
   * Verify allowed origins include your domain

3. **For edge functions:**
   ```typescript theme={null}
   // Ensure CORS headers in edge functions
   const corsHeaders = {
     'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
   };
   ```

### "Missing required environment variables" Error

#### Symptoms

* App fails to start
* Error about missing Supabase variables

#### Solutions

1. **Check `.env.local` file:**
   ```bash theme={null}
   # File should exist at project root
   ls -la .env.local
   ```

2. **Verify variable names:**
   ```bash theme={null}
   # ✅ CORRECT: VITE_ prefix for client variables
   VITE_SUPABASE_URL=...
   VITE_SUPABASE_PUBLISHABLE_KEY=...

   # ❌ WRONG: Missing VITE_ prefix
   SUPABASE_URL=...
   ```

3. **Copy from `.env.example`:**
   ```bash theme={null}
   cp .env.example .env.local
   # Then fill in your values
   ```

4. **Restart dev server after changes**

***

### Supabase: Remote migration versions not found

#### Symptoms

* `supabase db push` fails with `Remote migration versions not found in local migrations directory`
* CI or deployment jobs fail while reconciling migration history

#### Root Cause

Remote migration history contains versions that do not exist in local `supabase/migrations/` files.

#### Resolution Steps

1. **Inspect remote history:**
   ```bash theme={null}
   supabase link --project-ref <project-ref>
   supabase migration list
   ```
2. **Compare with local files:**
   ```powershell theme={null}
   Get-ChildItem "supabase/migrations/*.sql" | Select-Object Name | Sort-Object Name
   ```
3. **Reconcile each missing version:**
   * Preferred: recreate the missing migration SQL file with the exact remote version and commit it
   * If no-op: add a placeholder migration file documenting why it is empty
4. **Re-run sync:**
   ```bash theme={null}
   supabase db push
   ```

#### Prevention

* Always create migration files first (`supabase migration new ...`)
* Commit migration files before applying to remote
* Avoid direct schema changes in Supabase Dashboard without corresponding migration files

***

## Authentication Problems

### Login Fails

#### Symptoms

* Login button does nothing
* Error message on login attempt
* Redirects back to login page

#### Solutions

1. **Check Supabase auth configuration:**
   ```typescript theme={null}
   // Verify client configuration
   export const supabase = createClient(
     SUPABASE_URL,
     SUPABASE_PUBLISHABLE_KEY,
     {
       auth: {
         storage: localStorage,
         persistSession: true,
         autoRefreshToken: true,
       }
     }
   );
   ```

2. **Check email/password format:**
   * Email must be valid format
   * Password must meet Supabase requirements (min 6 characters)

3. **Verify user exists:**
   * Check Supabase Dashboard → Authentication → Users
   * Verify user is confirmed

4. **Check browser console:**
   * Look for error messages
   * Check Network tab for failed requests

### Session Not Persisting

#### Symptoms

* User logged out on page refresh
* Session lost after closing browser

#### Solutions

1. **Verify localStorage is enabled:**
   ```typescript theme={null}
   // Check browser settings
   // Some browsers block localStorage in private mode
   ```

2. **Check auth configuration:**
   ```typescript theme={null}
   auth: {
     storage: localStorage,  // ✅ Should be localStorage
     persistSession: true,   // ✅ Should be true
   }
   ```

3. **Clear browser storage:**
   * Open DevTools → Application → Storage
   * Clear localStorage and sessionStorage
   * Try logging in again

### "Unauthorized" Errors

#### Symptoms

* API calls return 401 Unauthorized
* RLS policies blocking access

#### Solutions

1. **Verify user is authenticated:**
   ```typescript theme={null}
   const { data: { user } } = await supabase.auth.getUser();
   if (!user) {
     // User not authenticated
   }
   ```

2. **Check RLS policies:**
   * Verify policies exist for the table
   * Check policy conditions match user context
   * See [Database Development Guide](./DATABASE_DEVELOPMENT_GUIDE.md) for RLS patterns

3. **Verify organization context:**
   ```typescript theme={null}
   // Ensure organization_id is set correctly
   const { data: { user } } = await supabase.auth.getUser();
   const orgId = user?.user_metadata?.organization_id;
   ```

***

## Performance Issues

### Slow Build Times

#### Symptoms

* `npm run build` takes > 5 minutes
* Dev server slow to start

#### Solutions

1. **Check bundle size:**
   ```bash theme={null}
   npm run build
   # Check output for large chunks
   ```

2. **Optimize imports:**
   ```typescript theme={null}
   // ✅ CORRECT: Tree-shakeable imports
   import { Button } from '@/shared/ui/button';

   // ❌ WRONG: Importing entire library
   import * as Icons from 'lucide-react';
   ```

3. **Use lazy loading:**
   ```typescript theme={null}
   // ✅ CORRECT: Lazy load routes
   const Dashboard = lazy(() => import('./Dashboard'));

   // ❌ WRONG: Direct imports
   import Dashboard from './Dashboard';
   ```

4. **Check for circular dependencies:**
   ```bash theme={null}
   npx madge --circular src/
   ```

### Large Bundle Size

#### Symptoms

* Initial bundle > 500KB
* Slow initial page load

#### Solutions

1. **Analyze bundle:**
   ```bash theme={null}
   npm run build
   # Review chunk sizes in output
   ```

2. **Use code splitting:**
   ```typescript theme={null}
   // Lazy load routes
   const Route = lazy(() => import('./Route'));
   ```

3. **Optimize images:**
   * Use WebP format
   * Implement lazy loading for images
   * Use appropriate image sizes

4. **Check for duplicate dependencies:**
   ```bash theme={null}
   npm ls | grep duplicate
   ```

### Slow Query Performance

#### Symptoms

* Queries take > 1 second
* UI feels sluggish

#### Solutions

1. **Check query optimization:**
   ```typescript theme={null}
   // ✅ CORRECT: Select only needed columns
   .select('id, name, email')

   // ❌ WRONG: Select all columns
   .select('*')
   ```

2. **Use indexes:**
   * Check Supabase Dashboard → Database → Indexes
   * Add indexes for frequently queried columns

3. **Implement pagination:**
   ```typescript theme={null}
   .select('*')
   .range(0, 49)  // First 50 records
   ```

4. **Use QueryClient caching:**
   ```typescript theme={null}
   const queryClient = new QueryClient({
     defaultOptions: {
       queries: {
         staleTime: 5 * 60 * 1000,  // 5 minutes
       },
     },
   });
   ```

***

## Mobile-Specific Issues

### Layout Breaks on Mobile

#### Symptoms

* Content overflows screen
* Horizontal scrolling
* Elements overlap

#### Solutions

1. **Use responsive utilities:**
   ```tsx theme={null}
   // ✅ CORRECT: Responsive classes
   <div className="grid grid-cols-1 md:grid-cols-2">

   // ❌ WRONG: Fixed width
   <div className="w-96">
   ```

2. **Use PageContainer:**
   ```tsx theme={null}
   // ✅ CORRECT: Consistent responsive padding
   <PageContainer spacing="md">

   // ❌ WRONG: Manual padding
   <div className="container mx-auto p-6">
   ```

3. **Check safe areas:**
   ```css theme={null}
   /* Add safe area insets for fixed elements */
   padding-bottom: calc(1rem + env(safe-area-inset-bottom));
   ```

4. **Test on actual devices:**
   * Use browser dev tools mobile emulation
   * Test on real iOS/Android devices

### Touch Targets Too Small

#### Symptoms

* Buttons hard to tap
* Links difficult to click

#### Solutions

1. **Use minimum touch target size:**
   ```tsx theme={null}
   // ✅ CORRECT: 44x44px minimum
   <button className="min-w-[44px] min-h-[44px]">

   // ❌ WRONG: Too small
   <button className="p-1">
   ```

2. **Add adequate padding:**
   ```tsx theme={null}
   <button className="px-4 py-3">  // Adequate padding
   ```

### Mobile Navigation Issues

#### Symptoms

* Bottom nav overlaps content
* Menu not opening
* Gestures not working

#### Solutions

1. **Add bottom padding for nav:**
   ```tsx theme={null}
   <div className="pb-20 md:pb-0">  // Account for bottom nav
   ```

2. **Check z-index:**
   ```tsx theme={null}
   <nav className="z-50">  // Nav should be above content
   ```

3. **Verify gesture handlers:**
   * Check `@/platform/gestures` imports
   * Verify gesture components are used correctly

***

## Cross-Browser Compatibility

### Safari-Specific Issues

#### Symptoms

* Layout breaks in Safari
* CSS not applying correctly

#### Solutions

1. **Check CSS vendor prefixes:**
   ```css theme={null}
   /* May need -webkit- prefix for Safari */
   -webkit-backdrop-filter: blur(10px);
   backdrop-filter: blur(10px);
   ```

2. **Verify safe area support:**
   ```css theme={null}
   /* Safari requires env() for safe areas */
   padding-bottom: env(safe-area-inset-bottom);
   ```

3. **Check localStorage support:**
   * Safari in private mode blocks localStorage
   * Check for localStorage availability

### Chrome-Specific Issues

#### Symptoms

* Service worker not updating
* Cache issues

#### Solutions

1. **Clear service worker:**
   * DevTools → Application → Service Workers
   * Click "Unregister"
   * Hard refresh (Ctrl+Shift+R)

2. **Clear cache:**
   * DevTools → Application → Clear storage
   * Clear site data

***

## Git & GitHub CLI Connectivity

### Verifying Git and GitHub CLI Setup

Use this checklist to verify Git and `gh` CLI are properly installed, authenticated, and connected to GitHub.

#### Git Verification

1. **Check Git installation:**

   ```bash theme={null}
   git --version  # Should show version 2.x or later
   ```

2. **Verify user identity (required for commits):**

   ```bash theme={null}
   git config --global user.name   # Should show your name
   git config --global user.email  # Should show your email
   ```

   If empty, set them:

   ```bash theme={null}
   git config --global user.name "Your Name"
   git config --global user.email "you@example.com"
   ```

3. **Verify repository connection:**

   ```bash theme={null}
   git remote -v  # Should show origin pointing to GitHub
   git fetch origin  # Should complete without authentication errors
   ```

4. **Windows line endings (recommended):**

   ```bash theme={null}
   git config --global core.autocrlf input
   ```

   See [Git / Line Endings (Windows)](#git--line-endings-windows) for details.

#### GitHub CLI (`gh`) Verification

1. **Check `gh` installation:**

   ```bash theme={null}
   gh --version  # Should show version 2.x or later
   ```

   If missing, install via: `winget install GitHub.cli`

2. **Verify authentication:**

   ```bash theme={null}
   gh auth status  # Should show logged in to github.com
   ```

   If not logged in, run: `gh auth login`

3. **Verify repository access:**

   ```bash theme={null}
   gh repo view  # Should show repository metadata
   gh api user   # Should return your user JSON
   ```

4. **Check token scopes (if using GitHub Projects):**

   ```bash theme={null}
   gh auth status  # Look for 'project' scope in output
   ```

   If missing, refresh with: `gh auth refresh -s project`

#### Authentication Alignment

Both Git and `gh` should use the same protocol (HTTPS or SSH):

* **HTTPS (recommended on Windows):** Git remote should be `https://github.com/...` and `gh auth status` should show "Git operations protocol: https"
* **SSH:** Git remote should be `git@github.com:...` and you should have SSH keys configured

If Git uses HTTPS but `gh` uses SSH (or vice versa), they may not share credentials. Align them:

* For HTTPS: Ensure Git Credential Manager is installed (`git credential-manager --version`)
* For SSH: Ensure `ssh -T git@github.com` succeeds

#### Common Issues

| Issue                                  | Solution                                                                                      |
| -------------------------------------- | --------------------------------------------------------------------------------------------- |
| `git: command not found`               | Install Git for Windows; restart terminal                                                     |
| `gh: command not found`                | Install GitHub CLI; restart terminal; verify PATH                                             |
| `Permission denied (publickey)`        | SSH key not loaded or not added to GitHub; or switch to HTTPS                                 |
| `HTTP 403` / `could not read Username` | Re-authenticate: `gh auth login` and/or clear stale credentials in Windows Credential Manager |
| Wrong GitHub user                      | `gh auth switch` (newer gh) or `gh auth logout` then `gh auth login`                          |

**Related:** See [GITHUB\_PROJECT\_SPEC\_TRACKING\_PLAN.md](./GITHUB_PROJECT_SPEC_TRACKING_PLAN.md) for GitHub Projects integration requirements.

***

## Git / Line Endings (Windows)

### Mass "changes" every time you reload the window

#### Symptoms

* After reloading the Cursor/VS Code window (or opening the project), Git shows hundreds of files as modified.
* `git status` or `git diff` shows "LF will be replaced by CRLF" (or similar) for many files.
* You did not edit those files; the only difference is line endings.

#### Cause

On Windows, Git can be configured to convert line endings to CRLF in the working copy while the repo stores LF. When the editor or Git "touches" files (e.g. on window reload), the mismatch makes every such file appear changed.

#### One-time fix (do this once)

1. **Tell Git to keep LF in the working copy** (in this repo):
   ```bash theme={null}
   git config core.autocrlf input
   ```
   With `input`, Git does not convert to CRLF on checkout, so files stay LF.

2. **Rewrite working copy to LF** so it matches the index (Biome is already set to `lineEnding: "lf"`):
   ```bash theme={null}
   npm run format
   ```
   This rewrites all formatted files to LF. After this, `git status` should show no (or far fewer) changes.

3. **Optional:** If you still see line-ending diffs in other files (e.g. outside Biome’s scope), refresh the index:
   ```bash theme={null}
   git add --renormalize .
   git status
   ```

#### Prevention

* The repo’s `.gitattributes` now uses `* text=auto eol=lf` so that all text files use LF on checkout, regardless of OS.
* Keep `core.autocrlf input` in this repo so Windows does not introduce CRLF again.

***

## Quick Reference Table

| Issue                            | Quick Fix                                              | Detailed Guide                                                 |
| -------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------- |
| Git/gh not connected             | `git fetch origin`, `gh auth status`                   | [Git & GitHub CLI Connectivity](#git--github-cli-connectivity) |
| Mass changes on reload (Windows) | `git config core.autocrlf input` then `npm run format` | [Git / Line Endings](#git--line-endings-windows)               |
| Build fails                      | `npm cache clean --force && npm install`               | [Build Issues](#build--dependency-issues)                      |
| TypeScript errors                | Restart TS server, regenerate types                    | [TypeScript Errors](#typescript-errors)                        |
| Supabase connection              | Check `.env.local` variables                           | [Supabase Issues](#supabase-connection-issues)                 |
| Auth not working                 | Verify auth config, check localStorage                 | [Authentication](#authentication-problems)                     |
| Slow performance                 | Check lazy loading, optimize queries                   | [Performance](#performance-issues)                             |
| Mobile layout breaks             | Use responsive classes, PageContainer                  | [Mobile Issues](#mobile-specific-issues)                       |
| Browser compatibility            | Check vendor prefixes, safe areas                      | [Cross-Browser](#cross-browser-compatibility)                  |

***

## Related Documentation

### Setup & Configuration

* [Environment Variables](./ENVIRONMENT_VARIABLES.md) - Environment variable configuration
* [Setup Quick Start](./SETUP_QUICK_START.md) - First-time developer setup
* [PWA Setup](./PWA_SETUP.md) - PWA configuration and troubleshooting

### Development Guides

* [Database Development Guide](./DATABASE_DEVELOPMENT_GUIDE.md) - Database and RLS troubleshooting
* [Performance Optimization Guide](./PERFORMANCE_OPTIMIZATION_GUIDE.md) - Performance debugging
* [Testing Setup and Run Guide](../testing/TESTING_SETUP_AND_RUN.md) - Test setup and debugging

### Standards

* [UI/UX Standards](./UI_UX_STANDARDS.md) - UI/UX troubleshooting
* [Spacing & UX Standards](./SPACING_AND_UX_STANDARDS.md) - Spacing issues
* [Constitution](../../constitution.md) - Core requirements and guardrails

***

**Maintained By:** Platform Foundation Team
