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¶
- Getting Started
- Development Environment
- Code Style
- Git Workflow
- Testing
- CI/CD Pipeline
- Backend Development
- Frontend Development
- Security & Compliance
- 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¶
-
Python Environment
-
uv for dependency management
- Python 3.10+
- FastAPI framework
- SQLAlchemy ORM
-
Alembic for migrations
-
Database
-
PostgreSQL 15+ (specifically TimescaleDB pg17 container) for primary data store.
- TimescaleDB time-series hypertables with automatic compression for event telemetry.
-
Redis for message queuing, rate-limiting, and sequence gap caching.
-
Services
- PostgreSQL/TimescaleDB for data persistence.
- Redis-first queuing with Celery worker pipeline processing.
- S3-compatible object storage (American Cloud A2) for WORM-compliant cold event archiving.
- Open Policy Agent (OPA) policy engine for alert routing/throttling.
- Real-time notification WebSocket server integrated with the gateway.
Frontend Setup (MVP)¶
-
Framework
-
React 18 with TypeScript
- Vite as build tool
- Tailwind CSS for styling
-
PWA support for offline functionality
-
State Management
- React Context for global state
- React Query for server state
- 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
blackand sort imports withisort
# 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 featuresfix/- Bug fixeshotfix/- Critical production fixesdocs/- Documentation updatesrefactor/- Code improvements without new featureschore/- Maintenance tasks
Commit Message Format¶
Types (MVP Focus):
feat: New MVP feature (e.g., fall detection, alerts)fix: Bug fix for MVP functionalitydocs: Documentation updatesrefactor: Code improvements without behavior changestest: Adding or fixing testschore: 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
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¶
- Always use
uv runfor command execution - Start PostgreSQL before running tests
- Run HIPAA compliance validation locally before pushing
- Monitor coverage reports to maintain 80% minimum
- Review security scan results regularly
API Development¶
Adding New Endpoints¶
- Create a new router in
backend/api/v1/routers/ - Add tests in
tests/api/v1/ - Update OpenAPI documentation
- 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¶
- Set up a PostgreSQL database
- Configure environment variables
- Run database migrations
- 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¶
- Install ZenML and required dependencies:
- Initialize ZenML repository:
- Create a ZenML stack for local development:
Federated Learning Workflow¶
-
Meta-Model Training:
-
Train initial models on aggregated, anonymized data
-
Deploy meta-models to edge devices
-
Local Training Pipeline:
-
Data preprocessing and feature engineering
- Model fine-tuning with local data
-
Evaluation and validation
-
Federated Updates:
- Secure aggregation of model updates
- Differential privacy guarantees
- 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¶
-
Edge Deployment:
-
Convert models to TFLite for edge devices
- Optimize for low-latency inference
-
Implement model versioning
-
Monitoring:
- Track model performance metrics
- Monitor for data drift
- 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¶
- Check if PostgreSQL is running
- Verify credentials in
.env - Check port conflicts
Frontend Build Failures¶
- Clear node modules and reinstall
- Check for version conflicts
- Verify environment variables
API Errors¶
- Check server logs
- Verify request format
- Check authentication headers
Debugging¶
- Use VS Code debug configurations
- Set breakpoints in code
- Check application logs
- Use Postman for API testing
Documentation¶
Updating Documentation¶
- Update relevant
.mdfiles - Update API documentation
- Update inline code documentation
- 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.