Skip to content

Latest commit

 

History

History
208 lines (160 loc) · 9.96 KB

DEVELOPMENT.md

File metadata and controls

208 lines (160 loc) · 9.96 KB

PACT — Developer Guide & Local Environment Setup

This document provides a comprehensive guide for developers contributing to the PACT codebase, including local development setup, database migrations, testing workflows, and environment configuration.

🌐 Live Production App: https://pact-os.vercel.app


1. Prerequisites

  • Node.js: v20.x or v22.x (LTS recommended)
  • Package Manager: npm (v10+)
  • Database: PostgreSQL 15+ (local instance or Supabase Cloud project)
  • Supabase CLI (optional, for local migration management): npm i -g supabase

2. Local Environment Setup

2.1 Clone and Install Dependencies

# 1. Clone repository fork
git clone https://github.com/<your-username>/Pact_OS.git
cd Pact_OS

# 2. Add upstream remote
git remote add upstream https://github.com/TheVicky1/Pact_OS.git

# 3. Install dependencies
npm install

Environment Variables Setup

PACT uses a .env.example reference template in the repository root so contributors can configure local environment variables without committing secrets. Follow these step-by-step instructions to set up your local environment:

  1. Copy .env.example to .env.local in the project root:
    # macOS / Linux / Git Bash / PowerShell
    cp .env.example .env.local
    
    # Windows Command Prompt
    copy .env.example .env.local
  2. Populate your Supabase & application keys in .env.local:
    • Retrieve NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY (or NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY) from your Supabase project dashboard under Project Settings -> API.
    • Note that the default template values in .env.example allow you to run the entire 56-suite offline test matrix (npm test) and explore the UI locally without live production credentials.
  3. Verify secret protection before committing:
    • .env.local is ignored by Git via .gitignore. Never commit actual keys to .env.example or version control, and run node scratch/secret-scan.mjs to verify zero leaked credentials.
Variable Description Required Example
NEXT_PUBLIC_SUPABASE_URL Supabase project API URL used by browser and server clients Yes https://xyz.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY Supabase public anonymous key for client-side auth & RLS queries Yes eyJhbGciOi...
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY Supabase publishable client key referenced in .env.example Yes your-supabase-publishable-key
SUPABASE_SERVICE_ROLE_KEY Server-only Supabase Service Role key for background cron sweeps Yes (Server) eyJhbGciOi...
CRON_SECRET Bearer secret token authorizing /api/cron/sweep-deadlines Yes (Cron) random_secure_hex_string
NEXT_PUBLIC_APP_URL Base public application URL for callbacks and links Yes http://localhost:3000
GOOGLE_CLIENT_ID Google Calendar OAuth 2.0 Client ID Optional xxx.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET Google Calendar OAuth 2.0 Client Secret Optional GOCSPX-xxx
GITHUB_CLIENT_ID GitHub OAuth / Proof-of-Work Integration Client ID Optional Ov23xxx
GITHUB_CLIENT_SECRET GitHub OAuth / Proof-of-Work Integration Client Secret Optional ghs_xxx
RESEND_API_KEY Resend API key for transactional email notifications Optional re_your_resend_api_key

3. Database Migrations

Database schemas and lifecycle triggers are managed through ordered SQL migrations in supabase/migrations/:

# To apply migrations against local or remote Supabase instance:
supabase db reset    # For local Supabase CLI
# OR execute migrations sequentially via Supabase SQL Editor / psql

Migration Overview

  1. 20260906000000_create_profiles_table.sql: User profile and timezone metadata.
  2. 20260907000000_create_core_domain_tables.sql: Goals, projects, tasks, and commitments.
  3. 20260907010000_task_lifecycle_engine.sql: Task transitions and audit triggers.
  4. 20260907020000_accountability_foundation.sql: Commitments and consequences.
  5. 20260907030000_commitment_assignment_engine.sql: Direct commitment assignment and role mapping.
  6. 20260907040000_consequence_activation_engine.sql: Consequence activation, masking, and triggers.
  7. 20260908000000_accountability_resolution_engine.sql: Penalty resolution, waivers, and referees.
  8. 20260908010000_accountability_hardening_and_edge_cases.sql: Immutability constraints and security.
  9. 20260909000000_create_calendar_events.sql: Calendar schedule and timeblocks.
  10. 20260910000000_create_finance_tables.sql: Integer-cents transactions and budgets.
  11. 20260911000000_deadline_sweeper_engine.sql: Automated task and commitment sweeper.
  12. 20260911010000_create_notifications_table.sql: In-app notification queue and channels.
  13. 20260911020000_google_calendar_sync.sql: Google Calendar token storage and sync logs.
  14. 20260911030000_external_proof_of_work.sql: GitHub, LeetCode, and Codeforces proof tables.
  15. 20260911040000_financial_discipline.sql: Budget alert triggers and recurrence rules.
  16. 20260911050000_user_onboarding.sql: Multi-step onboarding state machine.
  17. 20260911060000_production_hardening_and_cron_schedule.sql: pg_cron schedule definitions.
  18. 20260911070000_focus_sessions_engine.sql: Focus timer sessions and analytics.
  19. 20260911080000_habits_and_routines_engine.sql: Habits, routines, and streak calculation.
  20. 20260911090000_weekly_reviews_engine.sql: Weekly review rituals and draft state.
  21. 20260912000000_passkey_credentials.sql: WebAuthn/Passkey credential registration and challenges.
  22. 20260913000000_accountability_circles_and_pledges.sql: Multi-party circles and charity pledge escrow.
  23. 20260914000000_production_resilience_and_telemetry.sql: Sentry telemetry, circuit breakers, and rate limits.
  24. 20260915000000_daily_rituals_and_account_governance.sql: Daily rituals, data export, and deletion audit.
  25. 20260916000000_multi_device_sync_and_replication.sql: Sync changes, vector clocks, and devices.
  26. 20260917000000_discipline_intelligence_and_enterprise_sso.sql: Discipline insights, SSO providers, and audit logs.

4. Running the Development Server

npm run dev

Open http://localhost:3000 in your browser.


Troubleshooting Port Conflicts

If port 3000 is already in use, Next.js will automatically try another available port.

You can also specify a custom port:

PORT=3001 npm run dev

If you need to stop an existing process using port 3000, find the process ID with:

netstat -ano | findstr :3000

Then stop the process using:

taskkill /PID <PID> /F

5. Testing & Quality Assurance

PACT enforces a strict 56-suite automated test matrix verifying domain engines, math precision, security boundaries, and integration reliability. All tests execute completely offline using mock harnesses:

# 1. Run all 56 automated domain test suites
npm test
# (or: node scratch/run-tests.mjs)

# 2. Run a single targeted test suite
npm run test:file -- tests/habit-completion-service.test.ts

# 3. Run TypeScript strict typecheck
npx tsc --noEmit

# 4. Run ESLint code quality checks
npm run lint

# 5. Run zero-secret leak scanner
node scratch/secret-scan.mjs

# 6. Production build test
npm run build

6. Project Structure & Key Directories

src/
├── app/                  # Next.js App Router (pages, layouts, error boundaries)
│   ├── (auth)/           # Authentication pages & OAuth callbacks
│   ├── (dashboard)/app/  # Authenticated OS core modules
│   └── api/              # API Route Handlers (cron sweepers, data exports)
├── components/           # Shared glassmorphic UI components
├── features/             # Feature-specific components and UI logic
├── hooks/                # Custom React hooks (useUrlState, useSelection)
├── lib/                  # Pure domain engines, calculations, and services
│   ├── accountability/   # Commitment state machines & consequence execution
│   ├── analytics/        # Velocity scoring & completion rate math
│   ├── finance/          # Integer-cents arithmetic & budget evaluation
│   ├── focus/            # Deep work timer calculations & sound synthesis
│   ├── habits/           # Habit recurrence loops & streak engines
│   ├── integrations/     # External proof connectors (GitHub, LeetCode, Codeforces)
│   ├── notifications/    # Multi-channel notification dispatcher
│   ├── supabase/         # Server, client, and admin Supabase instances
│   ├── validations/      # Zod validation schemas for all mutations
│   └── weekly-review/    # Metric aggregation & weekly boundary calculations
└── types/                # TypeScript domain contracts

7. Development Best Practices

  1. Integer-Cents for Currency: Never use floating-point numbers for money. Always store and calculate financial values in integer cents (amount_cents).
    import { dollarsToCents, formatCentsToCurrency, sumCents } from '@/lib/money';
    
    const itemPriceCents = dollarsToCents(49.99); // 4999
    const taxCents = dollarsToCents(4.00);        // 400
    const totalCents = sumCents([itemPriceCents, taxCents]); // 5399
    
    console.log(formatCentsToCurrency(totalCents, 'USD')); // "$53.99"
  2. Server-Side Identity: Never trust user_id provided in client payloads. Always verify identity using supabase.auth.getUser().
  3. Zod Validation: Always validate Server Action inputs against strict Zod schemas before running business logic.
  4. Timezone Awareness: Always use lib/time.ts utilities for date operations to respect the user's configured profile timezone.
  5. Fail-Safe Third-Party Calls: External integration calls must always be wrapped in try/catch blocks that transition to RETRY_PENDING on failure rather than throwing unhandled exceptions.