Skip to content

Golden Age Hub - Development Guide

Welcome to the development portal for Golden Age Hub. This guide coordinates our coding practices, testing workflows, security standards, and git branching protocols. Following these procedures keeps our platform HIPAA-compliant, stable, and ready for deployment to U.S.-sovereign infrastructure.

Table of Contents

  1. Getting Started
  2. Development Environment
  3. Code Style
  4. Git Workflow
  5. Testing
  6. CI/CD Pipeline
  7. Backend Development
  8. Frontend Development
  9. Security & Compliance
  10. Deployment

Getting Started

Prerequisites

  • Python 3.10+
  • Node.js 18+ (for frontend only)
  • Docker & Docker Compose
  • PostgreSQL 14+

Quick Start

# Clone the repository
git clone https://github.com/goldenage-hub/goldenage-hub.git
cd goldenage-hub

# Set up environment variables
cp .env.example .env
# Edit .env with your configuration

# Start services
docker-compose up -d

# Install dependencies
cd backend && uv sync --no-dev
cd backend
uv sync --no-dev

# Run database migrations
uv run alembic upgrade head

# Start the development server
uv run uvicorn backend.main:app --reload

MVP Focus Areas

  • Core Features: Fall detection, wandering alerts, and caregiver notifications
  • Offline First: Mobile app works without internet connection
  • Data Integrity: Append-only ledger for all care events
  • US Compliance: HIPAA-aligned security and data handling
  • Personalized ML: Federated learning for personalized models
  • ML Ops: ZenML for model training and deployment

Development Environment

Backend Setup

  1. Python Environment

  2. uv for dependency management

  3. Python 3.10+
  4. FastAPI framework
  5. SQLAlchemy ORM
  6. Alembic for migrations

  7. Database

  8. PostgreSQL 15+ (specifically TimescaleDB pg17 container) for primary data store.

  9. TimescaleDB time-series hypertables with automatic compression for event telemetry.
  10. Redis for message queuing, rate-limiting, and sequence gap caching.

  11. Services

  12. PostgreSQL/TimescaleDB for data persistence.
  13. Redis-first queuing with Celery worker pipeline processing.
  14. S3-compatible object storage (American Cloud A2) for WORM-compliant cold event archiving.
  15. Open Policy Agent (OPA) policy engine for alert routing/throttling.
  16. Real-time notification WebSocket server integrated with the gateway.

Frontend Setup (MVP)

  1. Framework

  2. React 18 with TypeScript

  3. Vite as build tool
  4. Tailwind CSS for styling
  5. PWA support for offline functionality

  6. State Management

  7. React Context for global state
  8. React Query for server state
  9. Simple form handling with React Hook Form

Code Style

Python (Backend)

  • Follow PEP 8 with 100 character line length
  • Google-style docstrings for all public methods
  • Type hints for all function signatures
  • Use f-strings for string formatting
  • Format with black and sort imports with isort
# Example model
class Patient(Base):
    """Patient data model.

    Attributes:
        id: Unique identifier for the patient
        first_name: Patient's first name
        last_name: Patient's last name
        date_of_birth: Patient's date of birth (YYYY-MM-DD)
    """
    __tablename__ = 'patients'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid4)
    first_name = Column(String(100), nullable=False)
    last_name = Column(String(100), nullable=False)
    date_of_birth = Column(Date, nullable=False)
    created_at = Column(DateTime, server_default=func.now())

TypeScript (Frontend)

  • 2 space indentation
  • Single quotes for strings
  • Semicolons required
  • TypeScript strict mode
  • Functional components with hooks
// Example component
interface AlertProps {
  type: "fall" | "wandering";
  timestamp: string;
  patientName: string;
  onAcknowledge: () => void;
}

export const AlertCard: React.FC<AlertProps> = ({
  type,
  timestamp,
  patientName,
  onAcknowledge,
}) => {
  const alertType = type === "fall" ? "Fall Detected" : "Wandering Alert";

  return (
    <div className="border-l-4 border-red-500 bg-white p-4 shadow">
      <div className="flex justify-between">
        <div>
          <h3 className="font-bold">{alertType}</h3>
          <p className="text-sm text-gray-600">
            {format(new Date(timestamp), "MMM d, yyyy h:mm a")}
          </p>
          <p className="mt-1">{patientName}</p>
        </div>
        <button
          onClick={onAcknowledge}
          className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600"
        >
          Acknowledge
        </button>
      </div>
    </div>
  );
};

Git Workflow

Branch Naming

  • feat/ - New features
  • fix/ - Bug fixes
  • hotfix/ - Critical production fixes
  • docs/ - Documentation updates
  • refactor/ - Code improvements without new features
  • chore/ - Maintenance tasks

Commit Message Format

<type>(<scope>): <subject>

[optional body]

[optional footer]

Types (MVP Focus):

  • feat: New MVP feature (e.g., fall detection, alerts)
  • fix: Bug fix for MVP functionality
  • docs: Documentation updates
  • refactor: Code improvements without behavior changes
  • test: Adding or fixing tests
  • chore: Build process or dependency updates

Example:

feat(alerts): implement fall detection notifications

- Added push notification for fall detection events
- Included patient name and location in alerts
- Added acknowledgment flow for caregivers

Part of MVP-123

Testing

Backend Tests

  • Unit Tests: Test core business logic
  • API Tests: Test FastAPI endpoints
  • Integration Tests: Test database interactions
  • Security Tests: Validate HIPAA compliance and security measures
  • Performance Tests: Database and application performance benchmarks
# Start services first
docker-compose up -d postgres

# Run all tests with isolated databases
cd backend
uv run pytest tests/ -v

# Run tests with coverage and parallel execution
uv run pytest tests/ -v -n 4 --cov=backend --cov-report=html

# Run performance tests
./run_performance_tests.sh

# Validate HIPAA compliance
uv run python validate_hipaa_compliance.py --root-dir backend

# Run specific test categories
uv run pytest tests/ -m unit          # Unit tests only
uv run pytest tests/ -m integration   # Integration tests only
uv run pytest tests/ -m security      # Security tests only
uv run pytest tests/ -m performance   # Performance tests only

Test Database Isolation

The test suite uses isolated PostgreSQL databases to ensure test reliability:

  • Each test session creates a unique database
  • Automatic cleanup after tests complete
  • No interference between test runs
  • HIPAA-compliant synthetic test data

Frontend Tests (MVP)

  • Unit Tests: Test components and hooks
  • Integration Tests: Test user flows
# Run unit tests
npm test

# Run tests in watch mode
npm test -- --watch

CI/CD Pipeline

Overview

Golden Age Hub uses a comprehensive CI/CD pipeline with GitHub Actions to ensure code quality, security, and HIPAA compliance.

Workflows

1. Isolated Testing (test-isolated.yml)

  • Purpose: Main testing pipeline with PostgreSQL service containers
  • Features:
  • Isolated database testing (unique database per test session)
  • Parallel test execution (4 workers)
  • Coverage reporting (80% minimum required)
  • Performance benchmarking
  • HIPAA compliance validation
  • Security scanning (Safety, Bandit, pip-audit)

2. Security Scanning (security.yml)

  • Purpose: Comprehensive security and compliance validation
  • Features:
  • Daily security scans
  • CodeQL analysis
  • Semgrep static analysis
  • Container security scanning (Trivy)
  • HIPAA compliance scoring
  • Dependency vulnerability auditing

3. Legacy CI (ci.yml)

  • Purpose: Existing pipeline with shared database approach
  • Status: Being phased out in favor of isolated testing

Pipeline Performance

Metric Before After Improvement
Test Execution Sequential Parallel (-n 4) ~4x faster
Database Creation 15-20s 8-12s ~40% faster
Coverage Reporting Basic HTML + XML Enhanced visibility
Security Scanning Basic Comprehensive Industry-leading

Local Development

To test CI/CD locally:

# Run the same tests as CI/CD
docker-compose up -d postgres
cd backend
uv run pytest tests/ -v -n 4 --cov=backend --cov-report=html

# Run security scans
uv run safety check
uv run bandit -r backend/

# Validate HIPAA compliance
uv run python validate_hipaa_compliance.py --root-dir backend

# Run performance benchmarks
./run_performance_tests.sh

Troubleshooting

Tests fail with database connection errors:

# Check PostgreSQL status
docker-compose ps postgres

# Restart PostgreSQL
docker-compose restart postgres

# Wait for readiness
until pg_isready -h localhost -p 5432; do sleep 2; done

Security scans find issues: - Review the security reports in GitHub Actions artifacts - Fix high-severity issues first - Use uv run safety check locally to validate fixes

HIPAA compliance fails: - Check for hardcoded credentials or patient data patterns - Ensure encryption libraries are used appropriately - Validate audit logging implementation

Best Practices

  1. Always use uv run for command execution
  2. Start PostgreSQL before running tests
  3. Run HIPAA compliance validation locally before pushing
  4. Monitor coverage reports to maintain 80% minimum
  5. Review security scan results regularly

API Development

Adding New Endpoints

  1. Create a new router in backend/api/v1/routers/
  2. Add tests in tests/api/v1/
  3. Update OpenAPI documentation
  4. Add request/response models

Versioning

  • API versioning is path-based: /api/v1/...
  • Breaking changes require a new version
  • Maintain backward compatibility for at least 6 months

Frontend Development

Component Structure

  • Page components for each view
  • Reusable UI components
  • Custom hooks for data fetching
  • Context for global state

Key Features

  • Offline-first data sync
  • Real-time event updates
  • Simple authentication flow
  • Responsive design for mobile

State Management

  • React Context for global state
  • React Query for server state
  • Local storage for offline data
  • Optimistic UI updates

Security & Compliance

For detailed security policies, encryption controls, HIPAA verification criteria, and threat models, please consult the Security Guide.

Deployment

Environment Setup

  1. Set up a PostgreSQL database
  2. Configure environment variables
  3. Run database migrations
  4. Start the FastAPI server

Docker

# Build the container
docker-compose build

# Start services
docker-compose up -d

# View logs
docker-compose logs -f

Production Checklist

  • Enable HTTPS
  • Configure backups
  • Set up monitoring
  • Enable logging
  • Configure alerts

Machine Learning Operations

ZenML Setup

  1. Install ZenML and required dependencies:
pip install zenml[all]
zenml integration install tensorflow pytorch
  1. Initialize ZenML repository:
zenml init
  1. Create a ZenML stack for local development:
zenml stack register local_stack -m local -o local -a local --set

Federated Learning Workflow

  1. Meta-Model Training:

  2. Train initial models on aggregated, anonymized data

  3. Deploy meta-models to edge devices

  4. Local Training Pipeline:

  5. Data preprocessing and feature engineering

  6. Model fine-tuning with local data
  7. Evaluation and validation

  8. Federated Updates:

  9. Secure aggregation of model updates
  10. Differential privacy guarantees
  11. Model versioning and rollback

ML Pipeline Example

from zenml import pipeline, step
from zenml.steps import Output, step

@step
def load_meta_model() -> tf.keras.Model:
    # Load the latest meta-model
    pass

@step
train_local_model(model: tf.keras.Model, data: pd.DataFrame) -> tf.keras.Model:
    # Fine-tune model on local data
    return model

@pipeline
def local_training_pipeline():
    # Define the pipeline
    model = load_meta_model()
    trained_model = train_local_model(model=model)
    # Add more steps as needed

Model Deployment

  1. Edge Deployment:

  2. Convert models to TFLite for edge devices

  3. Optimize for low-latency inference
  4. Implement model versioning

  5. Monitoring:

  6. Track model performance metrics
  7. Monitor for data drift
  8. Alert on model degradation

Backend Development

API Design

  • RESTful endpoints with JSON
  • Versioned API (v1)
  • JWT authentication
  • Rate limiting
  • Request validation with Pydantic

Core Endpoints (MVP)

POST   /v1/keys/register     # Device registration
POST   /v1/events/commit    # Submit events
GET    /v1/exports/evv      # Generate EVV export
GET    /v1/exports/rpm      # Generate RPM export
POST   /v1/roots/compute    # Compute Merkle root

Error Handling

  • Standard error responses
  • Meaningful HTTP status codes
  • Error codes for client handling
  • Request IDs for debugging

Data Validation

  • Pydantic models for all requests/responses
  • Input sanitization
  • Output serialization

Troubleshooting

Common Issues

Database Connection Issues

  1. Check if PostgreSQL is running
  2. Verify credentials in .env
  3. Check port conflicts

Frontend Build Failures

  1. Clear node modules and reinstall
  2. Check for version conflicts
  3. Verify environment variables

API Errors

  1. Check server logs
  2. Verify request format
  3. Check authentication headers

Debugging

  • Use VS Code debug configurations
  • Set breakpoints in code
  • Check application logs
  • Use Postman for API testing

Documentation

Updating Documentation

  1. Update relevant .md files
  2. Update API documentation
  3. Update inline code documentation
  4. Submit PR with changes

Documentation Standards

  • Use clear, concise language
  • Include code examples
  • Document all public APIs
  • Keep diagrams up to date

Next Steps

Once you are comfortable with the development workflow, explore the following guides to build and deploy:

  • Testing Guide: Learn how to run unit, integration, and performance tests locally or inside Docker containers.
  • CI/CD Pipeline: Understand the automated quality gates, linting checks, and security scans run on every PR.
  • Deployment Guide: See the production architecture specifications and Terraform scripts for deploying to U.S.-only environments.