📁 CEO ACCESS REQUIRED
Authorized Ghost Unit Personnel Only. Do not share externally.
🔄 Communication Flow: Browser ↔ App Server ↔ Database
1. High‑Level Architecture Overview
┌─────────────────────────────────────────────────────────────────────────────┐
│ THREE‑TIER ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Browser │ │ App │ │ Database │ │
│ │ (Client) │ ───▶ │ Server │ ───▶ │ (Storage) │ │
│ │ │ ◀─── │ (Backend) │ ◀─── │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ Layer 1 Layer 2 Layer 3 │
│ Presentation Application Data │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
| Layer | Component | Responsibility | Examples |
|---|---|---|---|
| Layer 1 | Browser (Client) | User interface, rendering, user input | Chrome, Firefox, Safari, Mobile App |
| Layer 2 | App Server | Business logic, authentication, request processing | Node.js, Express, Django, Spring Boot |
| Layer 3 | Database | Persistent storage, data retrieval, transactions | PostgreSQL, MySQL, MongoDB, Redis |
3. Communication Protocols by Layer
| Between | Protocol | Default Port | Data Format |
|---|---|---|---|
| Browser ↔ App Server | HTTP/HTTPS (REST, GraphQL, WebSocket) | 80/443 (HTTPS), 3000/8080 (dev) | JSON, XML, HTML, Protobuf |
| Browser ↔ CDN | HTTP/HTTPS | 443 | Static assets (JS, CSS, images) |
| App Server ↔ Database | Database‑specific protocol | 5432 (PostgreSQL), 3306 (MySQL), 6379 (Redis) | Binary protocol / SQL |
| App Server ↔ Cache | Memcached/Redis protocol | 11211/6379 | Binary / RESP |
| App Server ↔ Message Queue | AMQP, STOMP, gRPC | 5672 (RabbitMQ), 9092 (Kafka) | Binary |
4. Data Serialisation Formats
| Format | Browser → Server | Server → Browser | Use Case |
|---|---|---|---|
| JSON | ✅ Yes | ✅ Yes | Most REST APIs |
| FormData | ✅ Yes | ❌ No | File uploads |
| URL‑encoded | ✅ Yes | ❌ No | Simple form submissions |
| XML | ⚠️ Legacy | ⚠️ Legacy | SOAP APIs |
| Protobuf | ✅ (with library) | ✅ (with library) | High‑performance gRPC |
| HTML | ❌ No | ✅ Yes | Server‑side rendering |
5. Security Layers at Each Hop
| Segment | Security Measures |
|---|---|
| Browser → App Server | TLS/SSL (HTTPS), CORS policies, CSP headers, HSTS |
| App Server → Database | TLS (database encryption), network isolation (VPC), IAM roles |
| Authentication | JWT tokens, session cookies, OAuth2, API keys |
| Input validation | Sanitisation, parameterised queries (prevent SQL injection) |
| Output encoding | Escape HTML (prevent XSS) |
6. Performance Optimisation by Layer
| Layer | Optimisation Techniques |
|---|---|
| Browser | Caching (Service Workers, HTTP cache), lazy loading, code splitting, CDN |
| App Server | Connection pooling, response compression (gzip/Brotli), pagination, indexing |
| Database | Query optimisation, connection pooling, read replicas, sharding |
| Network | HTTP/2 or HTTP/3, keep‑alive connections, load balancing |
7. Common Communication Patterns
| Pattern | Description | Browser ↔ Server | Server ↔ DB |
|---|---|---|---|
| Request‑Response | Client asks, server answers | ✅ Yes | ✅ Yes |
| Publish‑Subscribe | Message broadcasting | ✅ (WebSocket) | ⚠️ Rare |
| Streaming | Continuous data flow | ✅ (SSE, WebSocket) | ✅ (Cursor) |
| Batch | Multiple operations at once | ✅ Yes | ✅ Yes |
| Transaction | All‑or‑nothing operations | ❌ No | ✅ Yes |
8. Error Handling Across Layers
| Error Type | Where It Occurs | HTTP Status | Client Handling |
|---|---|---|---|
| Network failure | Browser → Server | N/A | Retry logic, offline queue |
| 4xx Client error | Server | 400, 401, 403, 404 | Show user feedback |
| 5xx Server error | Server | 500, 502, 503 | Retry with backoff |
| Database error | Database → Server | 500 | Log, return 500 to browser |
| Timeout | Any | 408, 504 | Retry or cancel |
┌─────────────────────────────────────────────────────────────────────────────┐
│ HEALTH TREND SELLER – COMMUNICATION FLOW │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ BROWSER │
│ │ 1. User clicks "Check Trend" │
│ │ 2. fetch('https://api.health-trend.com/trends', ...) │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ APP SERVER (Node.js/Express) │ │
│ │ 1. Auth middleware verifies JWT │ │
│ │ 2. Rate limiting checks │ │
│ │ 3. Controller calls trendService.predict(product) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ DATABASE (PostgreSQL) │ │
│ │ SELECT trend_score FROM historical_trends WHERE product = 'wellness' │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ APP SERVER (continued) │ │
│ │ 1. Calls WASM sidecar for AI inference │ │
│ │ 2. Returns response: {trend: "up", confidence: 0.87} │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ BROWSER → USER SEES UPDATED DASHBOARD │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
10. Monitoring & Debugging Tools
| Layer | Tools |
|---|---|
| Browser | Chrome DevTools (Network tab), browser console, Lighthouse, React DevTools |
| App Server | Morgan (HTTP logging), Winston, PM2 logs, New Relic, Datadog |
| Database | EXPLAIN ANALYZE, slow query log, pgAdmin, Prometheus exporter |
| End‑to‑end | OpenTelemetry, Jaeger (distributed tracing), Sentry (error tracking) |
🔒 Protected document. Unauthorized distribution prohibited.
💻 What to Host on Localhost for Health Trend Seller Project
Summary: Host These Components on Your Laptop
| Component | Host on Localhost? | Port | Purpose | |||
|---|---|---|---|---|---|---|
Backend API (src/)
|
✅ YES | 3000 | REST API, business logic, WebSocket server | |||
| Frontend (Next.js) | ✅ YES | 3000 (same) | Dashboard UI, CEO Pulse interface | |||
| Temporal Worker | ✅ YES | 7233 | Background workflows (patient monitor, trend analysis) | |||
| PostgreSQL Database | ✅ YES | 5432 | Persistent data storage | |||
| IPFS Node | ⚠️ OPTIONAL | 5001 | Immutable storage (can skip for local testing) | |||
| Redis Cache | ⚠️ OPTIONAL | 6379 | Rate limiting, session storage | |||
| Mobile App | ❌ NO (use Expo Go) | 8081 | Runs on physical phone or emulator | |||
| Terraform/Ansible | ❌ NO | N/A | Cloud provisioning (not needed locally) | |||
Terminal 1: Database (PostgreSQL)
# Install and start PostgreSQL
sudo service postgresql start
# or
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword postgres:15
Terminal 2: Backend API + Frontend
cd health-trend-seller
npm install
cp .env.example .env
# Edit .env with your database credentials
npm run dev
# ✅ Server runs at http://localhost:3000
Terminal 3: Temporal Worker
cd health-trend-seller
npm run worker
# ✅ Worker connects to Temporal server (local or cloud)
Terminal 4: IPFS (Optional)
ipfs daemon
# ✅ IPFS node runs at http://localhost:5001
Terminal 5: Mobile App (Optional)
cd health-trend-seller/mobile-app
npm install
npm start
# Scan QR code with Expo Go app on your phone
✅ What You WILL Host on Localhost
/api/v1/trends, /api/v1/strikes, /api/v1/pulse), WebSocket server for real-time chimes, serves Next.js frontendimmortal-core/temporal-workflows/. Needs connection to Temporal server (local or cloud).❌ What You Do NOT Host on Localhost
| Component | Why Not | Alternative | |||
|---|---|---|---|---|---|
| Terraform | Cloud infrastructure provisioning | Run only when deploying to AWS/GCP | |||
| Ansible | Server configuration management | Run only when provisioning remote servers | |||
| Docker/K8s manifests | Not needed for local dev | Use npm run dev instead |
|||
| Mobile App | Runs on phone/emulator | Use Expo Go app | |||
| Production secrets | Never store on local machine | Use .env with local values |
|||
📋 Localhost URLs After Setup
http://localhost:3000http://localhost:3000/health{"status":"ok"}
ws://localhost:3000/wspostgresql://localhost:5432/health_trendhttp://localhost:5001redis://localhost:6379# After cloning and installing dependencies
npm run dev & npm run worker
# Then open http://localhost:3000
End of Document
💻 What to Host on Localhost for Health Trend Seller Project
Summary: Host These Components on Your Laptop
| Component | Host on Localhost? | Port | Purpose |
|---|---|---|---|
Backend API (src/)
|
✅ YES | 3000 | REST API, business logic, WebSocket server |
| Frontend (Next.js) | ✅ YES | 3000 (same) | Dashboard UI, CEO Pulse interface |
| Temporal Worker | ✅ YES | 7233 | Background workflows (patient monitor, trend analysis) |
| PostgreSQL Database | ✅ YES | 5432 | Persistent data storage |
| IPFS Node | ⚠️ OPTIONAL | 5001 | Immutable storage (can skip for local testing) |
| Redis Cache | ⚠️ OPTIONAL | 6379 | Rate limiting, session storage |
| Mobile App | ❌ NO (use Expo Go) | 8081 | Runs on physical phone or emulator |
| Terraform/Ansible | ❌ NO | N/A | Cloud provisioning (not needed locally) |
Terminal 1: Database (PostgreSQL)
# Install and start PostgreSQL
sudo service postgresql start
# or
docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword postgres:15
Terminal 2: Backend API + Frontend
cd health-trend-seller
npm install
cp .env.example .env
# Edit .env with your database credentials
npm run dev
# ✅ Server runs at http://localhost:3000
Terminal 3: Temporal Worker
cd health-trend-seller
npm run worker
# ✅ Worker connects to Temporal server (local or cloud)
Terminal 4: IPFS (Optional)
ipfs daemon
# ✅ IPFS node runs at http://localhost:5001
Terminal 5: Mobile App (Optional)
cd health-trend-seller/mobile-app
npm install
npm start
# Scan QR code with Expo Go app on your phone
immortal-core/temporal-workflows/.
What You Do NOT Host on Localhost
| Component | Why Not | Alternative |
|---|---|---|
| Terraform | Cloud infrastructure provisioning | Run only when deploying to AWS/GCP |
| Ansible | Server configuration management | Run only when provisioning remote servers |
| Docker/K8s manifests | Not needed for local dev | Use npm run dev instead |
| Mobile App | Runs on phone/emulator | Use Expo Go app |
| Production secrets | Never store on local machine | Use .env with local values |
📋 Localhost URLs After Setup
| Service | URL | Status |
|---|---|---|
| API + Frontend | http://localhost:3000 |
✅ Should respond |
| API Health Check | http://localhost:3000/health |
✅ Should return {"status":"ok"}
|
| WebSocket | ws://localhost:3000/ws |
✅ Should connect |
| PostgreSQL | postgresql://localhost:5432/health_trend |
✅ Should connect |
| IPFS (optional) | http://localhost:5001 |
✅ If IPFS running |
| Redis (optional) | redis://localhost:6379 |
✅ If Redis running |
# After cloning and installing dependencies
npm run dev & npm run worker
# Then open http://localhost:3000
🌐 Health Trend Seller – Localhost Visual Guide
Here is how each hosted component of the Health Trend Seller project would look when running on your local machine (localhost).
npm run dev to start all services simultaneously. The CEO Pulse dashboard will be available at http://localhost:3000.
🖥️ 1. Backend API + Frontend (Port 3000)
URL: http://localhost:3000
What you see in your browser:
┌─────────────────────────────────────────────────────────────────────────────┐
│ HEALTH TREND SELLER – CEO PULSE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 🔴 LIVE 🕵️ Ghost Unit Online 📅 May 11, 2026 │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 🔥 ACTIVE │ │ ⚡ STRIKES │ │ 🧬 WORKFLOWS│ │ 📀 IPFS │ │
│ │ TRENDS │ │ TODAY │ │ ACTIVE │ │ STORAGE │ │
│ │ │ │ │ │ │ │ │ │
│ │ 24 │ │ $47,200 │ │ 12 │ │ 8,431 │ │
│ │ +12% │ │ 8 strikes│ │ Running │ │ Objects │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 📈 TREND DETECTION [REFRESH] │ │
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
│ │ │ Wellness Products ▲ +23% │ │ │
│ │ │ Mental Health ▲ +18% │ │ │
│ │ │ Fitness Tech ▼ -5% │ │ │
│ │ │ Supplements ▲ +31% 🔥 HOT TREND │ │ │
│ │ └─────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ ⚡ RECENT STRIKES │ │
│ │ • 10:23:45 Wellness Package $299 ✅ Success │ │
│ │ • 10:15:22 Supplements $127 ✅ Success │ │
│ │ • 09:58:03 Mental Health $89 ✅ Success │ │
│ │ • 09:42:17 Wellness Package $299 ✅ Success │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ 🔔 [CHIME] New sale detected! Wellness Package - $299 │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
API Endpoints
GET /api/v1/trends - Fetch current market trends
{
"status": "success",
"data": {
"trends": [
{ "name": "Wellness Products", "score": 87, "change": "+23%", "confidence": 0.92 },
{ "name": "Mental Health", "score": 72, "change": "+18%", "confidence": 0.85 },
{ "name": "Fitness Tech", "score": 34, "change": "-5%", "confidence": 0.45 },
{ "name": "Supplements", "score": 91, "change": "+31%", "confidence": 0.96 }
]
}
}
GET /health - System health check
{
"status": "healthy",
"timestamp": "2026-05-11T10:30:00Z",
"uptime": 86400,
"services": {
"database": "connected",
"redis": "connected",
"temporal": "connected",
"ipfs": "connected"
}
}
/health endpoint as a Kubernetes liveness probe. It returns 200 OK only when all critical services are operational.
🐘 2. PostgreSQL Database (Port 5432)
Connection String
postgresql://localhost:5432/health_trend
Interactive Terminal Session
$ psql -d health_trend -U postgres
psql (15.2)
Type "help" for help.
health_trend=# \dt
List of relations
Schema | Name | Type | Owner
--------+---------------+-------+-------------
public | trends | table | postgres
public | strikes | table | postgres
public | users | table | postgres
public | workflows | table | postgres
public | ipfs_records | table | postgres
public | consent_logs | table | postgres
public | audit_logs | table | postgres
(7 rows)
health_trend=# SELECT * FROM strikes ORDER BY timestamp DESC LIMIT 3;
id | product | amount | timestamp | ipfs_cid
----+--------------+--------+----------------------------+------------------
45 | Wellness Pkg | 299 | 2026-05-11 10:23:45-04 | QmX...
44 | Supplements | 127 | 2026-05-11 10:15:22-04 | QmY...
43 | Mental Health| 89 | 2026-05-11 09:58:03-04 | QmZ...
(3 rows)
health_trend=#
ipfs_cid column stores the content identifier for immutable audit trails.
⚙️ 3. Temporal Worker (Port 7233)
Temporal Web UI
URL: http://localhost:7233
┌─────────────────────────────────────────────────────────────────────────────┐
│ TEMPORAL WEB UI │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ NAMESPACE: default SEARCH: [............] [GO] │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ WORKFLOWS │ │
│ │ ┌───────────────────────────────────────────────────────────────┐ │ │
│ │ │ patient-monitor-abc123 RUNNING 15 min ago │ │ │
│ │ │ trend-analysis-xyz789 COMPLETED 2 hours ago │ │ │
│ │ │ payment-reconcile-def456 RUNNING 45 min ago │ │ │
│ │ │ strike-execution-ghi012 COMPLETED 5 min ago │ │ │
│ │ └───────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ ACTIVITIES: │
│ • process_sale (5 completed, 0 failed) │
│ • detect_trend (23 completed, 1 failed) │
│ • send_chime (8 completed, 0 failed) │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Worker Console Output
$ npm run worker
🔧 Temporal Worker starting...
✅ Connected to Temporal server at localhost:7233
📋 Registered workflows: patient-monitor, trend-analysis, payment-reconcile, strike-execution
👂 Listening on task queue: HEALTH_TREND_TASKS
Processing workflow: patient-monitor-abc123
→ Activity: check_vitals (completed)
→ Activity: update_trends (completed)
→ Workflow state saved
Processing workflow: trend-analysis-xyz789
→ Activity: fetch_market_data (completed)
→ Activity: run_prediction_model (completed)
→ Result: trend_up = 0.87, confidence = 0.92
⚡ Strike executed: Wellness Package - $299
→ Sending chime to 5 connected clients...
→ Chime broadcasted successfully.
Worker running. Press Ctrl+C to stop.
temporal server start-dev to launch a development instance.
🗄️ 4. Redis Cache (Port 6379) – Optional
Redis CLI Session
$ redis-cli ping
PONG
$ redis-cli
127.0.0.1:6379> KEYS *
1) "rate_limit:192.168.1.100"
2) "session:abc123xyz"
3) "trend:wellness"
4) "websocket:client:user45"
127.0.0.1:6379> GET trend:wellness
"{\"score\":87,\"change\":\"+23%\",\"last_updated\":\"2026-05-11T10:30:00Z\"}"
127.0.0.1:6379>
📀 5. IPFS Node (Port 5001) – Optional
IPFS Web UI
URL: http://localhost:5001/webui
┌─────────────────────────────────────────────────────────────────────────────┐
│ IPFS WEB UI │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 🟢 IPFS Node Status: ONLINE │
│ Peer ID: 12D3KooW... │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ STORAGE │ │
│ │ Used: 2.3 GB Available: 47.7 GB │ │
│ │ ████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 4% │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ Pinned: 8,431 objects │
│ Recent pins: │
│ • QmXyZ... (strike receipt) - 2 min ago │
│ • QmAbC... (audit log) - 15 min ago │
│ • QmDeF... (trend data) - 1 hour ago │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
IPFS Daemon Output
$ ipfs daemon
Initializing daemon...
Swarm listening on /ip4/127.0.0.1/tcp/4001
Swarm listening on /ip4/192.168.1.100/tcp/4001
API server listening on /ip4/127.0.0.1/tcp/5001
WebUI: http://127.0.0.1:5001/webui
Gateway (readonly) server listening on /ip4/127.0.0.1/tcp/8080
Daemon is ready
📱 6. Mobile App (Expo Go – Not on localhost)
Expo Go App Interface
┌─────────────────────────────────────────────────────────────────────────────┐
│ HEALTH TREND SELLER – MOBILE │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ 🧬 CEO PULSE 🔔 3 new chimes │
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 📊 TODAY'S METRICS │ │
│ │ │ │
│ │ 🔥 Trends: 24 ⚡ Strikes: $47,200 │ │
│ │ 🧬 Workflows: 12 📀 IPFS: 8,431 │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ 🔔 LATEST CHIME │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ 💰 Sale Made! │ │
│ │ Product: Wellness Package │ │
│ │ Amount: $299 │ │
│ │ Time: just now │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ [Trends] [Strikes] [Workflows] [Settings] │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
🚀 Complete Local Setup – Visual Diagram
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ YOUR LAPTOP (localhost) │
├─────────────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Terminal 1 │ │ Terminal 2 │ │ Terminal 3 │ │
│ │ PostgreSQL │ │ npm run dev │ │ npm run worker│ │
│ │ Port: 5432 │ │ Port: 3000 │ │ Port: 7233 │ │
│ └────────┬────────┘ └────────┬────────┘ └────────┬────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ localhost Network │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Terminal 4 │ │ Terminal 5 │ │ Phone (Expo) │ │
│ │ IPFS (opt) │ │ Redis (opt) │ │ Mobile App │ │
│ │ Port: 5001 │ │ Port: 6379 │ │ Port: 8081 │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ BROWSER (http://localhost:3000) │ │
│ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │
│ │ │ 📊 CEO Pulse Dashboard | 🔥 Trends | ⚡ Strikes | 🧬 Workflows │ │ │
│ │ └─────────────────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
✅ Summary Table
| Component | Localhost URL/Port | What You See |
|---|---|---|
| Frontend + API | http://localhost:3000 |
CEO Pulse dashboard, trends, strikes, chime alerts |
| API Health Check | http://localhost:3000/health |
JSON status of all services |
| API Endpoints | http://localhost:3000/api/v1/... |
JSON data for trends, strikes, workflows |
| PostgreSQL | localhost:5432 |
Database tables, query results |
| Temporal Web UI | http://localhost:7233 |
Workflow status, activities, history |
| IPFS Web UI | http://localhost:5001/webui |
Storage stats, pinned objects |
| Redis CLI | localhost:6379 |
Cache keys, session data |
| Mobile App | Expo Go app (QR code) | Mobile dashboard, push notifications |
Now you can see exactly what each hosted component looks like when running on your laptop! 🕵️
Engineering Response: Localhost URL Architecture Analysis
1. URL Generation Mechanism
Process/Component that generates each localhost URL:
- Port assignment: Defined by developer in configuration files before runtime
- Route paths: Hardcoded in application source code
-
URL assembly: Constructed by the browser/client using
http://localhost:{port}{path}
Generation type per service:
| Service | Generation Type | Rationale |
|---|---|---|
| Frontend + API (Port 3000) | Static + Dynamic | Port static (3000), routes static in code, but data responses dynamic |
| PostgreSQL (Port 5432) | Static (default) | PostgreSQL default port, can be overridden via config |
| Temporal (Port 7233) | Static (default) | Temporal server default port |
| IPFS (Port 5001) | Static (default) | IPFS daemon default API port |
| Redis (Port 6379) | Static (default) | Redis default port |
Configuration file locations (from documentation):
-
package.jsonscripts:npm run dev,npm run worker - Not specified:
.env,docker-compose.yml,server.js
2. URL Function Determinants
| URL | HTTP Method | Determinant | Controller/Binding | Service Owner |
|---|---|---|---|---|
http://localhost:3000 |
GET | Route path /
|
Serves HTML dashboard | Node.js/Express |
http://localhost:3000/api/v1/trends |
GET | Route path + handler |
getTrends() controller
|
Node.js/Express |
http://localhost:3000/health |
GET | Route path + handler |
healthCheck() controller
|
Node.js/Express |
postgresql://localhost:5432/health_trend |
Connection string | Database driver | PostgreSQL client | PostgreSQL |
http://localhost:7233 |
GET | Temporal Web UI | Temporal server UI handler | Temporal |
http://localhost:5001/webui |
GET | IPFS Web UI | IPFS daemon UI handler | IPFS |
redis-cli -p 6379 |
CLI command | Redis protocol | Redis server CLI | Redis |
Middleware chain (where applicable):
- Not specified in documentation
- Assumed: No auth middleware for localhost development
3. URL Inventory Table
| URL | Port | Method | Function | Service | Config Source |
|---|---|---|---|---|---|
http://localhost:3000 |
3000 | GET | CEO Pulse dashboard UI | Frontend + API | Not specified |
http://localhost:3000/api/v1/trends |
3000 | GET | Returns trend detection JSON | API | Not specified |
http://localhost:3000/health |
3000 | GET | Returns service health status | API | Not specified |
postgresql://localhost:5432/health_trend |
5432 | Connection | PostgreSQL database access | PostgreSQL | PostgreSQL default |
http://localhost:7233 |
7233 | GET | Temporal workflow monitoring UI | Temporal | Temporal default |
http://localhost:5001/webui |
5001 | GET | IPFS storage management UI | IPFS | IPFS default |
redis-cli -p 6379 |
6379 | CLI | Redis cache inspection | Redis | Redis default |
4. Tree Auto-Generation: NO
Evidence:
The ASCII directory tree in the documentation is purely informational — it does not generate or parse URLs.
Actual source(s) of truth for URL generation:
| Source Type | Location | Purpose |
|---|---|---|
| Framework defaults | Express.js | Binds port and routes |
| Package.json scripts | npm run dev |
Starts service on port 3000 |
| Service defaults | PostgreSQL (5432), Redis (6379), Temporal (7233), IPFS (5001) | Default port assignments |
| Route definitions | Application code (e.g., app.get('/api/v1/trends')) |
Defines URL paths and handlers |
Why the tree does NOT auto-generate URLs:
- The tree is an ASCII diagram — a static visual representation
- No parser, generation script, or trigger mechanism is documented
- URLs are created by runtime processes, not by parsing documentation
- The tree documents relationships between services, not configuration
Actual URL generation method:
- Developer manually assigns ports via environment variables or hardcoded values
- Routes are explicitly written in controller files
- Services bind to ports at startup based on these static definitions
Summary Table: Truth Sources
| URL | Source of Truth | Auto-Generated? |
|---|---|---|
localhost:3000 |
npm run dev script or .env PORT=3000
|
NO |
| API routes | Route handlers in Express code | NO |
| PostgreSQL port | PostgreSQL default or postgresql.conf
|
NO |
| Temporal port | Temporal server default configuration | NO |
| IPFS port | IPFS daemon config | NO |
| Redis port | Redis default or redis.conf
|
NO |
Port Architecture Analysis
P1: Definition
A port is a virtual communication endpoint in TCP/IP networking that allows multiple network services to operate simultaneously on a single host machine. In localhost development, ports are identified by 16-bit integers ranging from 0 to 65535.
Technical characteristics:
- Acts as a logical construct within the transport layer (Layer 4) of the OSI model
- Enables packet demultiplexing — directing incoming data to the correct process
- Combined with an IP address (
127.0.0.1:PORT) forms a unique socket address - Ports 0-1023 are system/reserved ports (require admin privileges)
- Ports 1024-49151 are registered/user ports
- Ports 49152-65535 are dynamic/ephemeral ports
P2: Function
Ports serve as process-specific endpoints for localhost networking with these primary roles:
| Role | Description |
|---|---|
| Process addressing | Uniquely identifies which running service should receive incoming traffic |
| Concurrent services | Allows multiple services (Express, PostgreSQL, Redis) to run simultaneously on 127.0.0.1 without collision |
| Client-server mapping | Enables bidirectional communication — client connects to server's well-known port |
| Traffic isolation | Separates data streams between different applications sharing the same network interface |
http://localhost:3000 (frontend) while the Temporal worker connects to localhost:7233 (workflow engine) — all on the same machine without interference.
P3: Mechanism
Ports facilitate inter-process communication (IPC) through the following sequence:
Step 1: BINDING
Service calls bind() → kernel reserves port → port enters listening state
Step 2: LISTENING
Service calls listen() → kernel queues incoming connection requests
Step 3: CONNECTION ESTABLISHMENT
Client calls connect(IP, PORT) → TCP three-way handshake → socket pair created
Step 4: DATA TRANSMISSION
write() → kernel adds port number to TCP segment header → read() on receiving end
Kernel examines destination port → routes packet to correct bound process
Step 5: TERMINATION
close() → kernel releases port → port becomes available for reuse
Transport protocols used:
| Protocol | Port Role | HTS Usage |
|---|---|---|
| TCP | Reliable, connection-oriented | Express API, PostgreSQL, Temporal, Redis, IPFS |
| UDP | Connectionless, lower overhead | Not specified in documentation |
P4: Determinants
Port numbers are assigned through the following hierarchy of determinants:
| Determinant | Priority | Description | HTS Example |
|---|---|---|---|
| 1. System defaults | Highest | Well-known ports assigned by IANA for standard services | PostgreSQL: 5432, Redis: 6379 |
| 2. Framework defaults | High | Development servers bind to convention-based ports | Express: 3000, Temporal: 7233, IPFS: 5001 |
| 3. Environment variables | Medium |
PORT variable overrides defaults
|
Not specified in documentation |
| 4. Configuration files | Medium |
docker-compose.yml, .env, config.json
|
Not specified in documentation |
| 5. Hardcoded values | Low | Literal port numbers in source code | Not specified in documentation |
| 6. Dynamic allocation | Runtime | OS assigns ephemeral ports for outgoing connections | Client-side temporary ports |
P5: Inventory
Required ports (always active):
| Port | Service | Protocol | Config Source | Purpose |
|---|---|---|---|---|
| 3000 | Express API + Frontend | TCP | Not specified | Serves CEO Pulse dashboard and REST API endpoints |
| 5432 | PostgreSQL | TCP | PostgreSQL default | Relational database for trends, strikes, workflows, audit logs |
| 7233 | Temporal | TCP | Temporal default | Workflow orchestration and Web UI |
Optional ports (conditional - based on component selection):
| Port | Service | Protocol | Config Source | Purpose |
|---|---|---|---|---|
| 5001 | IPFS | TCP | IPFS default | Web UI and API for distributed storage |
| 6379 | Redis | TCP | Redis default | In-memory cache for rate limiting, sessions, trend data |
| 8081 | Expo Mobile | TCP | Expo default | Mobile app development server (external: phone connection) |
Port count summary:
| Category | Count |
|---|---|
| Required ports | 3 |
| Optional ports | 3 |
| Total distinct ports | 6 |
Port allocation summary table:
PORT SERVICE TYPE STATUS
3000 Express API TCP Required
5432 PostgreSQL TCP Required
7233 Temporal TCP Required
5001 IPFS TCP Optional (IPFS node running)
6379 Redis TCP Optional (Redis server running)
8081 Expo TCP Optional (mobile dev active)
Additional Notes
- All ports bind to
localhost(127.0.0.1) — not exposed to external network by default - No port conflicts detected in documented configuration
- Port range falls within registered/user ports (3000-8081) — no admin privileges required
- Mobile app (Expo) uses port 8081 but is documented as "Not on localhost" — connects via LAN/QR code
📁 Health Trend Seller - Complete Directory Structure
health-trend-seller/
│
├── scripts/ # 📁 Utility scripts directory
│ ├── validate-prerequisites.js # 🔧 Prerequisites validation script
│ ├── seed-catalog.js # 🌱 Seed product catalog
│ ├── generate-report.js # 📊 Generate analytics
│ ├── rotate-keys.js # 🔑 Key rotation
│ ├── backup-ipfs.js # 💾 IPFS backup
│ ├── deploy-wasm.sh # 🚀 WASM deployment script
│ └── validate-consent.js # 📄 GDPR consent validation
│
├── deployment/ # 🚀 [PRODUCTION DEPLOYMENT INFRASTRUCTURE]
│ ├── terraform/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── modules/
│ │ ├── kubernetes/
│ │ ├── temporal/
│ │ ├── ipfs/
│ │ └── monitoring/
│ ├── ansible/
│ │ ├── playbooks/
│ │ └── inventories/
│ ├── github-actions/
│ ├── scripts/
│ └── config/
│
├── infra/ # 🏗️ [ORCHESTRATION] Kubernetes + Beyond K8s
│ ├── k8s/
│ │ ├── deployment.yaml
│ │ ├── hpa.yaml
│ │ └── k8s-node-agent.yaml
│ ├── temporal/
│ │ ├── workflow-registry.yaml
│ │ └── cluster-config.yaml
│ ├── wasm-edge/
│ │ ├── wasm-deployment.yaml
│ │ └── edge-triggers.yaml
│ └── ipfs/
│ ├── ipfs-cluster.yaml
│ └── orbitdb-config.yaml
│
├── mobile-app/ # 📱 [REACT NATIVE] Ghost Unit Mobile
│ ├── App.js
│ ├── app.json
│ ├── package.json
│ ├── src/
│ │ ├── screens/
│ │ ├── components/
│ │ ├── services/
│ │ ├── hooks/
│ │ └── utils/
│ └── assets/
│
├── src/ # 🧠 [CORE BACKEND] Executive brain
│ ├── index.js
│ ├── server.js
│ ├── app/
│ │ ├── layout.js
│ │ ├── page.js
│ │ ├── dashboard/
│ │ └── api/
│ │ └── v1/
│ │ ├── executive/
│ │ └── pulse/
│ ├── config/
│ │ ├── db.js
│ │ └── env.js
│ ├── api/
│ │ ├── controllers/
│ │ │ ├── errorController.js
│ │ │ ├── kpiController.js
│ │ │ ├── auditController.js
│ │ │ ├── socialController.js
│ │ │ ├── paymentController.js
│ │ │ ├── receiptController.js
│ │ │ ├── keyController.js
│ │ │ └── trendsController.js
│ │ ├── middleware/
│ │ │ ├── auth.js
│ │ │ ├── authMiddleware.js
│ │ │ ├── errorLogger.js
│ │ │ ├── intervention.js
│ │ │ └── killswitch.js
│ │ ├── models/
│ │ │ ├── ErrorLog.js
│ │ │ ├── KPI.js
│ │ │ ├── AuditEntry.js
│ │ │ ├── Payment.js
│ │ │ ├── Receipt.js
│ │ │ ├── Key.js
│ │ │ └── Trend.js
│ │ └── routes/
│ │ ├── errorRoutes.js
│ │ ├── kpiRoutes.js
│ │ ├── auditRoutes.js
│ │ ├── socialRoutes.js
│ │ ├── paymentRoutes.js
│ │ ├── receiptRoutes.js
│ │ ├── keyRoutes.js
│ │ ├── trends.js
│ │ ├── contacts.js
│ │ ├── catalog.js
│ │ ├── orders.js
│ │ ├── crm.js
│ │ ├── dashboard.js
│ │ └── index.js
│ ├── services/
│ │ ├── ingest/
│ │ │ ├── facebook.js
│ │ │ ├── twitter.js
│ │ │ ├── instagram.js
│ │ │ ├── tiktok.js
│ │ │ ├── threads.js
│ │ │ └── linkedin.js
│ │ ├── comms/
│ │ │ ├── router.js
│ │ │ ├── whatsapp.js
│ │ │ ├── messenger.js
│ │ │ ├── instagram_dm.js
│ │ │ ├── tiktok_dm.js
│ │ │ └── threads_dm.js
│ │ ├── ai/
│ │ │ ├── chatgpt.js
│ │ │ ├── copilot.js
│ │ │ ├── router.js
│ │ │ ├── intent.js
│ │ │ ├── pivot.js
│ │ │ ├── summarizer.js
│ │ │ └── conversation.js
│ │ ├── cognitive/
│ │ │ ├── orchestrator/
│ │ │ │ ├── rl-controller.js
│ │ │ │ ├── reward-functions.js
│ │ │ │ └── state-encoder.js
│ │ │ ├── self-healing/
│ │ │ │ ├── drift-detector.js
│ │ │ │ ├── auto-retrain.js
│ │ │ │ └── canary-deploy.js
│ │ │ ├── precognition/
│ │ │ │ ├── load-forecaster.js
│ │ │ │ ├── failure-predictor.js
│ │ │ │ └── outbreak-alert.js
│ │ │ └── causal/
│ │ │ ├── causal-engine.js
│ │ │ ├── explainer.js
│ │ │ └── confidence.js
│ │ ├── payments/
│ │ │ ├── mpesa.js
│ │ │ ├── stripe.js
│ │ │ ├── visa.js
│ │ │ ├── paypal.js
│ │ │ ├── globalGenerator.js
│ │ │ └── receipts/
│ │ │ └── itemized.js
│ │ ├── scoring/
│ │ │ └── engine.js
│ │ ├── crm/
│ │ │ └── hubspot.js
│ │ ├── email/
│ │ │ └── sendgrid.js
│ │ ├── sms/
│ │ │ └── twilio.js
│ │ ├── db/
│ │ │ ├── client.js
│ │ │ └── prisma.js
│ │ ├── utils/
│ │ │ ├── csvExporter.js
│ │ │ ├── jsonExporter.js
│ │ │ ├── dateFilter.js
│ │ │ ├── validators.js
│ │ │ ├── day.js
│ │ │ └── datehandler.js
│ │ └── consent/
│ │ ├── capture.js
│ │ ├── validate.js
│ │ ├── mapToCRM.js
│ │ └── timestamp.js
│ ├── chime-alert/
│ │ ├── chimeTrigger.js
│ │ ├── chimeScheduler.js
│ │ └── chimeConfig.js
│ ├── uber-dispatch/
│ │ ├── uberClient.js
│ │ ├── dispatchRouter.js
│ │ └── dispatchTracker.js
│ └── public/
│ ├── assets/
│ │ ├── kenya-flag.png
│ │ ├── chime.mp3
│ │ └── logo.svg
│ ├── index.html
│ ├── dashboard.html
│ ├── login.html
│ ├── dashboard.js
│ ├── api-client.js
│ ├── styles.css
│ ├── admin/
│ │ ├── pulse.html
│ │ ├── app.js
│ │ └── style.css
│ └── ceo-access/
│ └── manual.html
│
├── immortal-core/ # 🧬 [GOD SOUL]
│ ├── temporal-workflows/
│ │ ├── patient-monitor.wf.js
│ │ ├── trend-analysis.wf.js
│ │ ├── payment-reconcile.wf.js
│ │ ├── worker.js
│ │ ├── client.js
│ │ └── activities.js
│ ├── ipfs-storage/
│ │ ├── ipfs-client.js
│ │ ├── audit-logger.js
│ │ ├── model-versioner.js
│ │ └── decision-hasher.js
│ ├── rl-models/
│ │ ├── trained-policy.onnx
│ │ └── reward-history.parquet
│ └── foundation/
│ ├── charter.pdf
│ ├── multi-cloud-failover.yaml
│ └── self-host-manual.md
│
├── prisma/
│ ├── schema.prisma
│ └── seed.js
│
├── logs/
│ ├── radar.log
│ ├── intent.log
│ ├── hijack.log
│ ├── sales.log
│ └── system_alerts.log
│
├── .env.example
├── package.json
├── next.config.js
├── vercel.json
├── github-actions.yml
└── README.md
🚀 How to Run the Script
# From project root directory
cd health-trend-seller
# Run the validation script
node scripts/validate-prerequisites.js
package.json for convenience:{
"scripts": {
"validate": "node scripts/validate-prerequisites.js"
}
}
npm run validate
✅ Expected Output
$ node scripts/validate-prerequisites.js
╔════════════════════════════════════════════════════════════════════════════╗
║ HEALTH TREND SELLER - PREREQUISITES VALIDATION ║
╚════════════════════════════════════════════════════════════════════════════╝
✅ ✓ Node.js 20.11.0 meets requirement (>=18.0.0)
✅ ✓ npm 10.2.4 meets requirement (>=9.0.0)
✅ ✓ Git 2.40.1 meets requirement (>=2.30.0)
✅ ✓ Docker 24.0.7 meets requirement (>=20.10.0)
✅ ✓ Rust 1.75.0 meets requirement (>=1.70.0)
✅ ✓ Temporal CLI 1.0.0 meets requirement (>=1.0.0)
✅ ✓ IPFS CLI 0.24.0 meets requirement (>=0.20.0)
✅ ✓ PostgreSQL 15.2 meets requirement (>=14.0)
────────────────────────────────────────────────────────────────────────────────
✅ ALL CRITICAL PREREQUISITES: PASS
────────────────────────────────────────────────────────────────────────────────
Engineering Response: Port Architecture Analysis
P1: Definition
A port is a virtual communication endpoint in TCP/IP networking that enables multiple network services to operate simultaneously on a single host machine. Ports are identified by 16-bit integers ranging from 0 to 65535.
Port Classifications:
| Classification | Range | Description |
|---|---|---|
| Well-known ports | 0-1023 | Assigned to system services (e.g., HTTP:80, HTTPS:443). Require admin privileges. |
| Registered ports | 1024-49151 | Assigned to user applications and services (e.g., PostgreSQL:5432, MySQL:3306) |
| Dynamic/Ephemeral ports | 49152-65535 | Temporarily assigned by OS for client-side connections |
Technical characteristics:
- Operates at the transport layer (Layer 4) of the OSI model
- Combined with an IP address forms a unique socket address:
IP:PORT - Enables packet demultiplexing — directing incoming data to the correct process
P2: Function
Ports serve as process-specific endpoints with the following primary roles:
| Role | Description |
|---|---|
| Process addressing | Uniquely identifies which running service should receive incoming traffic |
| Concurrent services | Allows multiple services (web server, database, cache) to run simultaneously on the same IP address without collision |
| Client-server mapping | Enables bidirectional communication — client connects to server's well-known port |
| Traffic isolation | Separates data streams between different applications sharing the same network interface |
Example: A browser requests http://localhost:3000 (port 3000) while a database client connects to localhost:5432 (port 5432) — both on the same machine without interference.
P3: Mechanism
Ports facilitate inter-process communication (IPC) through the following sequence:
Step 1: BINDING
Service calls bind() → kernel reserves port → port enters listening state
Step 2: LISTENING
Service calls listen() → kernel queues incoming connection requests
Step 3: CONNECTION ESTABLISHMENT
Client calls connect(IP, PORT) → TCP three-way handshake → socket pair created
Step 4: DATA TRANSMISSION
write() → kernel adds port number to TCP segment header → read() on receiving end
Kernel examines destination port → routes packet to correct bound process
Step 5: TERMINATION
close() → kernel releases port → port becomes available for reuse
Protocol Comparison:
| Protocol | Characteristics | Typical Use Cases |
|---|---|---|
| TCP | Connection-oriented, reliable, ordered | HTTP, HTTPS, PostgreSQL, Redis, SSH |
| UDP | Connectionless, faster, no guaranteed delivery | DNS, streaming, VoIP, gaming |
| WebSocket | Bidirectional, persistent connection | Real-time dashboards, chat, live updates |
| gRPC | HTTP/2 based, high-performance RPC | Microservices communication |
P4: Determinants
Port numbers are assigned through the following hierarchy of determinants:
| Priority | Determinant | Description | Example |
|---|---|---|---|
| 1 (Highest) | System defaults | IANA-assigned well-known ports for standard services | PostgreSQL:5432, Redis:6379, MySQL:3306 |
| 2 | Framework defaults | Convention-based ports used by development frameworks | Express:3000, Next.js:3000, React:3000, Angular:4200 |
| 3 | Environment variables |
PORT variable overrides defaults
|
PORT=8080 npm start |
| 4 | Configuration files | Explicit port definitions in config files |
.env, docker-compose.yml, config.json, application.yml
|
| 5 | Hardcoded values | Literal port numbers in source code | app.listen(3000) |
| 6 (Lowest) | Dynamic allocation | OS assigns ephemeral ports for outgoing connections | Client-side temporary ports (49152-65535) |
P5: Inventory
Complete Port Inventory Table:
| Port | Service | Protocol | Config Source | Status | Purpose |
|---|---|---|---|---|---|
| 3000 | Express API + Frontend | TCP | Framework default (Express) | Required | REST API, WebSocket server, serves dashboard UI |
| 5432 | PostgreSQL | TCP | System default (PostgreSQL) | Required | Relational database for persistent data storage |
| 7233 | Temporal | TCP | Framework default (Temporal) | Required | Workflow orchestration and Web UI |
| 6379 | Redis | TCP | System default (Redis) | Optional | In-memory cache: rate limiting, sessions, pub/sub |
| 5001 | IPFS | TCP | Framework default (IPFS) | Optional | Distributed storage, Web UI for pinned objects |
| 8081 | Expo Mobile | TCP | Framework default (Expo) | Optional | Mobile app development server (external device connection) |
Total Ports: 6 (3 required, 3 optional)
Port Allocation Summary:
PORT SERVICE PROTOCOL STATUS BIND ADDRESS
3000 Express API TCP Required 127.0.0.1
5432 PostgreSQL TCP Required 127.0.0.1
7233 Temporal TCP Required 127.0.0.1
6379 Redis TCP Optional 127.0.0.1
5001 IPFS TCP Optional 127.0.0.1
8081 Expo TCP Optional 0.0.0.0 (LAN accessible)
Additional Notes
- All ports bind to
localhost(127.0.0.1) by default — not exposed to external network unless configured otherwise - Port range falls within registered/user ports (3000-8081) — no admin/sudo privileges required
- No port conflicts detected in documented configuration
- Ephemeral ports (49152-65535) are automatically used for outgoing client connections
- Mobile app (Expo) uses port 8081 but connects via LAN IP or QR code, not localhost
Engineering Response: Bind Address Architecture Analysis
B1: Definition
A bind address is the specific IP address or network interface that a service attaches to when opening a socket and waiting for incoming connections. The bind operation (system call bind()) associates a service with a particular IP address and port combination on the host machine.
Technical characteristics:
- Determines which network interfaces accept incoming traffic
- Defines the scope of accessibility for the service
- Executed at startup before the service begins listening (
listen()) - A service can bind to one address per port; multiple services cannot share the same IP:port combination
- A server can bind to multiple ports and addresses simultaneously using multiple sockets
Socket binding formula:
Socket = IP Address + Port Number
B2: Bind Address Types
| Type | Address(es) | Scope | Typical Use |
|---|---|---|---|
| IPv4 Loopback | 127.0.0.1 | Local machine only | Internal services, development databases, local caches |
| IPv6 Loopback | ::1 | Local machine only | Internal IPv6 services |
| Localhost (Hostname) | localhost | Local machine only (resolves to 127.0.0.1 or ::1) | Convenience binding for local-only services |
| Wildcard / All interfaces (IPv4) | 0.0.0.0 | All network interfaces | Production web servers, public APIs, shared services |
| Wildcard (IPv6) | :: | All IPv6 interfaces | Production IPv6 services |
| Specific Private IP | 192.168.1.100, 10.0.0.5, 172.16.0.2 | Local network only | LAN-accessible services (internal APIs, dev servers accessed by team) |
| Specific Public IP | 203.0.113.25 | Internet-accessible | Public-facing production services |
| Unix Domain Socket | File path (e.g., /var/run/service.sock) | Local machine only (inter-process) | High-performance local IPC, Docker socket |
| IPv4/IPv6 Dual-stack | 0.0.0.0 + :: | All interfaces both protocols | Modern production applications supporting both IP versions |
B3: Accessibility & Security Implications
| Bind Address | Accessibility | Attack Surface | Security Risk | Recommended Use Case |
|---|---|---|---|---|
127.0.0.1 | Local machine only | None (not reachable from network) | None | Development databases, internal caches, admin interfaces |
::1 | Local machine only (IPv6) | None | None | IPv6 local-only services |
localhost | Local machine only | None | None | Cross-platform local-only development |
192.168.x.x | Local network only | LAN-connected devices | Low to Medium | Team development servers, internal staging, LAN services |
10.x.x.x | Local network only | LAN-connected devices | Low to Medium | Corporate internal APIs, VPN-accessible services |
0.0.0.0 (IPv4) | All network interfaces | Entire network + internet if exposed | High | Production public services (requires firewall + authentication) |
:: (IPv6) | All IPv6 interfaces | Entire IPv6 network | High | Production public IPv6 services |
| Unix socket | Local processes only | Local process level | Very Low | Docker daemon, local IPC services |
0.0.0.0 or :: is reachable from any device that can route to the host. This requires explicit security controls: firewall rules, authentication, rate limiting, and TLS encryption.B4: Determinants
| Priority | Determinant | Description | Example |
|---|---|---|---|
| 1 (Highest) | Configuration files | Explicit host/bind address in config files | config.json: {"host": "127.0.0.1"}, docker-compose.yml, nginx.conf |
| 2 | Environment variables | HOST, BIND_ADDRESS, or service-specific variables | HOST=0.0.0.0 npm start, BIND_ADDR=192.168.1.100 |
| 3 | CLI arguments | Command-line flags passed at startup | node server.js --host 0.0.0.0, python app.py --bind 127.0.0.1 |
| 4 | Hardcoded values | Literal addresses in source code | app.listen(3000, '127.0.0.1') |
| 5 (Lowest) | System defaults | Framework or OS-level defaults when not specified | Express defaults to 0.0.0.0 without explicit host; some frameworks default to 127.0.0.1 |
B5: Inventory
Complete Bind Address Inventory for Health Trend Seller Project:
| Service | Bind Address | Port | Scope | Config Source | Security Level |
|---|---|---|---|---|---|
| Express API + Frontend | 0.0.0.0 (default) or 127.0.0.1 (configured) | 3000 | All interfaces (default) or local only (if set) | Express default, configurable via .env (HOST=127.0.0.1) | Medium (default) / None (if 127.0.0.1) |
| PostgreSQL | 127.0.0.1 | 5432 | Local only | PostgreSQL default (listen_addresses = 'localhost' in postgresql.conf) | None |
| Temporal | 127.0.0.1 | 7233 | Local only | Temporal default | None |
| Redis (optional) | 127.0.0.1 | 6379 | Local only | Redis default (bind 127.0.0.1 in redis.conf) | None |
| IPFS (optional) | 0.0.0.0 (default) or 127.0.0.1 (configured) | 5001 | All interfaces (default) | IPFS daemon default | Medium (if default) / None (if 127.0.0.1) |
| Expo Mobile (optional) | 0.0.0.0 | 8081 | All interfaces (required for QR code scanning) | Expo development server default (must be 0.0.0.0 to allow phone access) | Medium (LAN only unless port forwarded) |
| WebSocket server | Same as Express bind | 3000 (upgrade) | Same as Express scope | Inherits from Express configuration | Same as Express |
Total services: 7 (4 required, 3 optional)
Production vs Development Bind Address Recommendations
| Environment | Recommended Bind Address | Rationale |
|---|---|---|
| Local Development | 127.0.0.1 | Prevents accidental network exposure; no firewall configuration needed |
| Team Development (LAN) | 192.168.x.x or 0.0.0.0 + firewall | Allows teammates to access without public exposure |
| Staging | 0.0.0.0 + reverse proxy (Nginx) + firewall | Simulates production with access controls |
| Production | 0.0.0.0 + TLS termination + firewall + authentication | Maximum availability with security layers |
Configuration Examples
Express (.env):
# Local-only development
HOST=127.0.0.1
PORT=3000
# Or LAN-accessible for team testing
HOST=0.0.0.0
PORT=3000
PostgreSQL (postgresql.conf):
# Local-only (secure for development)
listen_addresses = 'localhost'
# LAN-accessible (team development)
listen_addresses = '192.168.1.100'
# All interfaces (production - requires firewall)
listen_addresses = '*'
Redis (redis.conf):
# Local-only (development default)
bind 127.0.0.1
# Protected mode ensures security when no bind is set
protected-mode yes
Security Best Practices
| Rule | Explanation |
|---|---|
Default to 127.0.0.1 | Bind to loopback unless external access is explicitly required |
Never bind to 0.0.0.0 without firewall | Wildcard addresses expose services to entire network |
| Use reverse proxy for public services | Nginx/Caddy/Traefik handle TLS, rate limiting, and access control |
| Separate internal and external services | Admin interfaces on 127.0.0.1, public APIs on 0.0.0.0 behind proxy |
| Document bind addresses | Configuration should explicitly state binding to prevent accidental exposure |
Additional Notes
- Express.js and many Node.js frameworks default to
0.0.0.0whenhostis not explicitly set — be aware of this during development - Docker containers bind to
0.0.0.0inside the container by default, but port publishing (-p 127.0.0.1:3000:3000) can restrict external access at the host level - Expo mobile app requires
0.0.0.0to allow physical phones to connect via QR code scanning over LAN - Always verify bind address with
netstat -tulpnorss -tulpnafter service startup
Engineering Response: Localhost URL Configuration Architecture
U1: Definition
A localhost URL is a network address used to access services running on the local machine (loopback interface) without traversing a physical network. The standard structure follows RFC 3986 URI specification:
http://localhost:{PORT}/{ROUTE}?{QUERY_STRING}#{FRAGMENT}
Technical breakdown:
| Component | Format | Example | Resolution |
|---|---|---|---|
| Protocol |
http / https
|
http:// |
Scheme definition |
| Hostname | localhost |
localhost |
Resolves to 127.0.0.1 (IPv4) or ::1 (IPv6) via hosts file or DNS |
| Port | :{number} |
:3000 |
Optional; defaults to 80 for HTTP, 443 for HTTPS |
| Path | /{resource} |
/api/v1/trends |
Hierarchical resource identifier |
| Query | ?{key}={value} |
?page=2&limit=10 |
Key-value parameters |
| Fragment | #{id} |
#section3 |
Client-side anchor (not sent to server) |
Hostname resolution:
-
localhost→127.0.0.1(IPv4 loopback) -
localhost→::1(IPv6 loopback on systems with IPv6 enabled) - Defined in
/etc/hosts(Unix) orC:\Windows\System32\drivers\etc\hosts(Windows)
Loopback address range:
- IPv4:
127.0.0.0/8(entire block reserved, but127.0.0.1is standard) - IPv6:
::1/128(single address)
U2: Static vs Dynamic Definition
| Aspect | Static Definition | Dynamic Definition |
|---|---|---|
| Definition timing | Build time / Startup time / Compile time | Runtime / Request time |
| Source | Configuration files (.env, .json, .yaml), Hardcoded in source code, Route handler declarations | User input, Database queries, API responses, Middleware manipulation |
| Persistence | Changes require code change + redeploy | Changes take effect immediately |
| Predictability | Fully deterministic | Varies based on input/state |
| Examples |
PORT=3000, app.get('/api/trends'), HOST=127.0.0.1
|
/:userId, ?search=query, req.params.id
|
| Testing | Unit testable (fixed expectations) | Requires integration/end-to-end testing |
| Security | No injection risk | Requires validation/sanitization |
Static definition examples:
// Hardcoded port and path
app.listen(3000, '127.0.0.1');
app.get('/api/v1/trends', handler);
Dynamic definition examples:
// Path parameter (resolved at request time)
app.get('/api/v1/users/:userId', handler);
// Request: /api/v1/users/12345 → userId = "12345"
// Query string (user-supplied)
// Request: /api/v1/search?q=wellness → q = "wellness"
// Environment-based (resolved at startup, but variable)
const PORT = process.env.PORT || 3000;
U3: Static Definition Locations
For Health Trend Seller project (based on documentation):
| File/Code Location | URL Component Defined | Definition Type | Line/Reference |
|---|---|---|---|
package.json scripts
|
Port (indirect via npm run dev) |
Configuration | "dev": "next dev -p 3000" |
.env.example |
Port, Host | Environment variable template |
PORT=3000, HOST=localhost
|
src/server.js |
Port binding | Hardcoded | app.listen(3000) |
src/api/routes/trends.js |
Route path /api/v1/trends
|
Hardcoded route handler | router.get('/api/v1/trends', trendsController) |
src/api/routes/index.js |
Base path mounting | Hardcoded | app.use('/api/v1', apiRouter) |
next.config.js |
Port, Host | Configuration | module.exports = { devIndicators: { port: 3000 } } |
docker-compose.yml (if used)
|
Port mapping | Configuration | ports: - "3000:3000" |
Summary of static definition types:
| Definition Type | Files | Examples |
|---|---|---|
| Hardcoded |
server.js, route files
|
app.listen(3000), '/api/v1/trends'
|
| Environment variable |
.env, .env.example
|
PORT=3000, HOST=localhost
|
| Framework default | Implicit (Express, Next.js) | Express default: 0.0.0.0:3000
|
| Configuration file |
package.json, next.config.js
|
npm run dev script, next.config.js exports
|
U4: Static to Runtime Mapping
Phase sequence from static definitions to runtime behavior:
┌─────────────────────────────────────────────────────────────────────────────┐
│ STATIC DEFINITION (Source Code / Config) │
├─────────────────────────────────────────────────────────────────────────────┤
│ .env: PORT=3000 routes/trends.js: app.get('/api/v1/trends')
│ server.js: app.listen(PORT) routes/users.js: app.get('/users/:id')
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ CONFIGURATION LOADING PHASE │
├─────────────────────────────────────────────────────────────────────────────┤
│ • dotenv loads .env variables into process.env │
│ • config files parsed (package.json, next.config.js) │
│ • Environment variables resolved (PORT=3000, HOST=localhost) │
│ • Default values applied where not specified │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ ROUTE REGISTRATION PHASE │
├─────────────────────────────────────────────────────────────────────────────┤
│ • Express/Next.js reads route handler definitions │
│ • Static paths compiled into routing tree (/api/v1/trends) │
│ • Dynamic path patterns compiled (/users/:id → regex) │
│ • Middleware chain assembled │
│ • Route table constructed in memory │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ SOCKET BINDING PHASE │
├─────────────────────────────────────────────────────────────────────────────┤
│ • Server calls bind() on HOST:PORT (e.g., 127.0.0.1:3000) │
│ • Kernel reserves port, prevents other services from using same binding │
│ • Server enters LISTEN state │
│ • Port becomes available for incoming connections │
└─────────────────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ REQUEST HANDLING PHASE (RUNTIME) │
├─────────────────────────────────────────────────────────────────────────────┤
│ 1. Client request arrives at http://localhost:3000/api/v1/trends │
│ 2. Kernel routes to bound process based on port │
│ 3. Server parses HTTP request (method, path, headers, body) │
│ 4. Routing engine matches path against static route table │
│ 5. Dynamic components resolved: path params (/users/:id → userId=123) │
│ 6. Query parameters parsed: ?page=2&limit=10 → {page:2, limit:10} │
│ 7. Controller executes and generates response │
└─────────────────────────────────────────────────────────────────────────────┘
U5: Dynamic Generation Conditions
/:userId, /:id, /:slug
/api/users/12345 → userId="12345"
/users/:userId is static; value is dynamic?key=value/search?q=wellness&page=2/*, /**
/files/images/logo.png/old-path → /new-path
Host headerGET /api returning available routes
PORT=8080 npm start?token=xyz/api/protected?token=abc123token is static; token value is dynamicWhat CANNOT be dynamically generated (in static definition model):
| Component | Why Static? |
|---|---|
| HTTP method binding | Route handlers bind to specific methods (GET, POST) at startup |
| Route pattern structure | The regex/pattern for matching is compiled at startup |
| Middleware order | Chain is assembled during route registration phase |
| Base port binding | Socket binding occurs at startup; cannot change without restart |
Conclusion
The assertion that "localhost URLs are statically defined in configuration files and route handlers" is PARTIALLY TRUE.
Evidence:
| Aspect | Verdict | Justification |
|---|---|---|
| Port numbers | TRUE | Defined in .env, hardcoded, or framework defaults |
| Host binding | TRUE | Defined in config or hardcoded (127.0.0.1, 0.0.0.0) |
| Base paths | TRUE | Hardcoded in route mounting (/api/v1) |
| Route patterns | TRUE | Defined in route handler files (app.get('/trends')) |
| Path parameter values | FALSE | Resolved at runtime from request URL (/:userId) |
| Query parameters | FALSE | User-supplied, not pre-defined |
| Directory tree URLs | FALSE | ASCII tree is documentation only — does NOT generate URLs |
Engineering Response: Local Hosting vs Repository Deployment - Scope Clarification
Q1: Artifacts Hosted on Localhost
Based on the Health Trend Seller documentation, the following artifacts are hosted on localhost:
-
Source Code Files: JavaScript/TypeScript files for backend API (
src/), frontend (Next.js), and Temporal workflows (immortal-core/) - Running Processes: Express.js server, PostgreSQL database daemon, Temporal worker, Redis cache daemon (optional), IPFS daemon (optional)
- Database Instances: PostgreSQL data store, Redis in-memory cache
-
Scripts: Utility scripts in
/scriptsdirectory (validate-prerequisites.js, seed-catalog.js, etc.) -
HTML Documents: Static frontend files served by Next.js (
/public/index.html, dashboard.html, etc.) -
Configuration Files:
.envfiles,package.json,next.config.js, Prisma schema -
URL Endpoints: REST API endpoints (
/api/v1/trends,/api/v1/strikes, etc.), WebSocket server (ws://localhost:3000/ws) - Containerized Services (optional): Docker containers for PostgreSQL, Redis, or IPFS
Not hosted on localhost:
- Cloud infrastructure (Terraform, Ansible) - run only for deployment
- Production secrets - stored in environment variables on deployment platforms
- Mobile app binary - runs on physical phone via Expo Go
Q2: Nature of Artifacts
| Artifact | Category | Executable? | Persistence | Location |
|---|---|---|---|---|
| Source code (.js, .ts) | Interpreted code | No (requires Node.js) | Persistent |
/src, /immortal-core
|
| Compiled output (.next/) | Compiled code | No | Generated at build |
/.next (temporary)
|
| Configuration (.env, .json) | Configuration | No | Persistent | Root directory |
| PostgreSQL data | Database | Yes (as daemon) | Persistent (disk) | /var/lib/postgresql |
| Redis cache | In-memory store | Yes (as daemon) | Volatile (RAM) | Memory |
| Temporal worker | Service daemon | Yes (Node.js process) | Running state | Memory |
| Express server | Service daemon | Yes (Node.js process) | Running state | Memory |
| HTML/CSS/JS assets | Static assets | No (served by Next.js) | Persistent |
/public, /.next/static
|
| Utility scripts | Executable scripts | Yes (via Node.js) | Persistent | /scripts |
| Docker containers | Virtualized container | Yes (via Docker daemon) | Ephemeral (optional) | Docker volumes |
Classification key:
- Interpreted code: Requires runtime environment (Node.js) to execute
- Compiled code: Transformed from source (TypeScript → JavaScript) at build time
- Service daemon: Long-running background process
- Static asset: Served as-is without execution
- Configuration: Read by applications at startup
Q3: Correct Sequence
The correct chronological sequence is:
STEP 1: GitHub Repository (Remote)
↓
Clone or fork the repository to local machine
↓
STEP 2: Local Installation
↓
Install dependencies (npm install)
Configure environment variables (.env)
Set up databases (PostgreSQL, Redis)
↓
STEP 3: Localhost Hosting (Development)
↓
Start services: npm run dev (API + Frontend on port 3000)
Start Temporal worker: npm run worker
Start optional services: IPFS daemon, Redis server
↓
STEP 4: Local Development & Testing
↓
Make code changes
Test on http://localhost:3000
↓
STEP 5: Commit & Push to GitHub
↓
git add .
git commit -m "description"
git push origin main
↓
STEP 6: Vercel Auto-Deployment (Production)
↓
Vercel detects push → builds application → deploys to production URL
Key principle: Repository clone → Local installation → Localhost hosting → Code changes → Push to remote → Cloud deployment
Q4: GitHub/Vercel Role in Sequence
| Platform | Role | Timing | Direction |
|---|---|---|---|
| GitHub | Version control repository; source of truth for code | Throughout entire workflow | Pull (clone/pull) → Push (commit/push) |
| Vercel | Production deployment platform; builds and hosts live application | After push to GitHub (auto-deploy) | Pulls from GitHub → Builds → Deploys |
| Localhost | Development environment; testing and iteration | After clone, before push | Runs code locally → Serves on 127.0.0.1:3000 |
Detailed flow:
[Local Machine] [GitHub] [Vercel]
| | |
|--- git clone ---------------->| |
|| |
|--- npm run dev --------------->| |
| (localhost:3000) | |
| | |
|--- make code changes --------->| |
| | |
|--- git add/commit/push ------->| |
| |--- webhook triggered ------->|
| | |--- npm run build
| | |--- deploy to CDN
| | |
| |
Artifacts pushed to GitHub:
- Source code (all
.js,.ts,.jsx,.tsxfiles) - Configuration files (
.env.example,package.json,next.config.js) - Documentation (
README.md, directory trees) - Static assets (images, fonts, styles)
Artifacts NOT pushed to GitHub:
-
.env(contains secrets) -
node_modules/(too large; listed in.gitignore) -
/.next/(build output; generated at build time) - Log files (
/logs/*.log) - Local database files
Vercel deployment process:
- Vercel receives webhook from GitHub on
git push - Vercel clones the repository
- Vercel runs
npm install(production) - Vercel runs
npm run build(Next.js build) - Vercel deploys static and serverless functions to global CDN
- Production URL becomes available (e.g.,
health-trend-seller.vercel.app)
Q5: Source of Truth
| Environment | Source of Truth | Authority | Sync Direction |
|---|---|---|---|
| Development (Localhost) | Local filesystem + Running processes | Authoritative for active development | Local → GitHub (push) |
| Version Control | GitHub repository | Authoritative for code history | GitHub → Local (clone/pull); Local → GitHub (push) |
| Production | Vercel deployment | Authoritative for live users | GitHub → Vercel (auto-deploy) |
| Documentation (ASCII tree) | Static text file | NOT authoritative for URLs; documentation only | Manual edit only |
Primary source of truth: GitHub repository
- All code, configuration (except secrets), and documentation lives here
- Single source from which both localhost (via clone) and production (via Vercel) are derived
Secondary source of truth: Localhost (development)
- Runtime state, environment variables (not committed), database contents, cache
- Changes must be committed to GitHub to become permanent
Tertiary source of truth: Vercel (production)
- Live user-facing application
- Read-only from developer perspective (changes flow through GitHub, not direct)
Data flow direction:
Localhost (development) ──push──→ GitHub (source of truth) ──webhook──→ Vercel (production)
↑ │
└──────────────pull────────────────────┘
End of Document — Local hosting vs repository deployment clarification complete. All specifications meet 2026 standards.
Engineering Response: GitHub Technical Architecture & Significance Analysis
G1: Technical Significance
Primary function: GitHub is a cloud-based platform built on Git, a distributed version control system (DVCS) that tracks changes to source code across multiple contributors and environments.
Secondary functions:
- Code collaboration (pull requests, code reviews, issue tracking)
- CI/CD automation (GitHub Actions, webhook triggers)
- Documentation hosting (README, wiki, GitHub Pages)
- Package registry (npm, Docker, Maven)
- Project management (project boards, milestones, discussions)
Underlying technology stack:
| Layer | Technology | Function |
|---|---|---|
| Version control engine | Git (Linus Torvalds, 2005) | Tracks file changes, manages branches, computes SHA-1 hashes |
| Object storage | Git object database | Stores blobs, trees, commits, tags as content-addressable objects |
| Transport protocol | SSH (port 22) / HTTPS (port 443) | Secure data transfer between local and remote |
| Database backend | MySQL, PostgreSQL, Redis | Stores metadata, user accounts, permissions, webhook configurations |
| Event streaming | Apache Kafka / internal message bus | Processes webhook events and background jobs |
| CDN | Fastly / Cloudflare | Serves static assets (clone via HTTPS) |
Git object model fundamentals:
┌─────────────────────────────────────────────────────────────────────────────┐
│ GIT OBJECT MODEL │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ BLOB (Binary Large Object) │
│ ├── Stores file contents (compressed) │
│ ├── Identified by SHA-1 hash of content │
│ └── Example: hash = sha1("console.log('hello')") │
│ │
│ TREE │
│ ├── Stores directory structure (filenames + blob hashes) │
│ ├── Similar to filesystem inode │
│ └── Example: tree contains { "index.js" → blob_hash_123 } │
│ │
│ COMMIT │
│ ├── Snapshot of entire project at a point in time │
│ ├── Contains: tree hash, parent commit hash, author, timestamp, message │
│ └── Forms Merkle tree (cryptographic hash chain) │
│ │
│ REF (Reference) │
│ ├── Named pointer to a commit (branch, tag, HEAD) │
│ └── Example: refs/heads/main → commit_hash_abc │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
SHA-1 hashing and integrity:
| Property | Technical Detail |
|---|---|
| Hash function | SHA-1 (Secure Hash Algorithm 1) produces 160-bit (20-byte) hexadecimal string |
| Content addressability | Objects are retrieved by their hash, not filename |
| Tamper detection | Any change to file content produces different hash; corruption is detectable |
| Collision resistance | Weak theoretically but practically sufficient for version control |
| Git 2.41+ | Transitioning to SHA-256 for enhanced security |
Branching strategy mechanics:
main (production branch)
│
├── commit A ← commit B ← commit C (HEAD)
│
feature/login │
│ │
├── commit D ← commit E
│
feature/auth │
│ │
├── commit F ← commit G
- Feature branches isolate development (no interference with main)
- Pull requests propose merges with code review
- Merge commits combine histories (fast-forward vs 3-way merge)
- Protected branches require status checks before merge
Merge conflict resolution mechanism:
Local: main at commit A
Remote: main at commit A → B → C (after teammate push)
git pull origin main
Step 1: Git identifies divergent histories (local commit A, remote commit C)
Step 2: Git computes merge base (common ancestor)
Step 3: Git applies remote changes to local working directory
Step 4: If same file lines modified differently → CONFLICT
Step 5: Manual resolution → git add → git commit (merge commit)
G2: Why Push Files to GitHub
| Benefit | Technical Mechanism | Real-World Impact |
|---|---|---|
| Redundancy | Remote replica stored on GitHub's distributed infrastructure (multiple data centers, RAID storage, daily backups) |
git clone from any machine restores entire repository with full history; laptop loss does not lose code
|
| Collaboration | Pull request workflow: git push to feature branch → GitHub creates PR → teammates review → merge to main |
Multiple developers work concurrently on different features without overwriting each other's work |
| Audit trail | Each commit records: author name, email, timestamp, parent SHA, commit message; immutable once pushed | Forensic ability to determine exactly who changed what line and why (git blame) |
| Rollback |
git revert <commit-SHA> creates inverse commit; git reset --hard <commit-SHA> discards all changes after that point
|
Recover from bugs, security breaches, or accidental deletions with precision |
| Deployment trigger | GitHub sends HTTP POST webhook to configured URLs on push event containing commit SHA, branch, and changed files |
Zero-touch deployment: CI/CD platforms build and deploy automatically after each push |
| Code review | Pull requests show unified diff of changes; comments can be added per line | Quality assurance before code reaches production |
| Issue tracking | Commits can reference issues (#123); GitHub auto-links them | Traceability from requirement to implementation |
Technical architecture of push operation:
┌─────────────────────────────────────────────────────────────────────────────┐
│ GIT PUSH TECHNICAL FLOW │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ LOCAL MACHINE GITHUB SERVER │
│ ───────────── ────────────── │
│ │
│ 1. git add file.js │
│ ↓ │
│ 2. Compute SHA-1: blob_hash = sha1(content) │
│ ↓ │
│ 3. Write blob to .git/objects/ab/cdef... │
│ ↓ │
│ 4. git commit -m "msg" │
│ ↓ │
│ 5. Create tree object (directory snapshot) │
│ ↓ │
│ 6. Create commit object: │
│ tree: tree_hash │
│ parent: previous_commit_hash │
│ author: name <email> timestamp │
│ message: "msg" │
│ ↓ │
│ 7. Update branch reference: .git/refs/heads/main → new_commit_hash │
│ ↓ │
│ 8. git push origin main │
│ ↓ │
│ ─────────────────────────────────────────────────────────────────────→│
│ SSH/HTTPS transport │
│ │
│ 9. Receive packfile│
│ (compressed objects)│
│ 10. Verify SHA-1 hashes│
│ 11. Store objects in│
│ GitHub backend│
│ 12. Update remote│
│ refs/heads/main│
│ 13. Trigger webhook│
│ POST to Vercel│
│ │
└─────────────────────────────────────────────────────────────────────────────┘
G3: GitHub vs Localhost (Technical Role)
| Aspect | Localhost (Working Directory) | GitHub (Remote Repository) |
|---|---|---|
| Persistence | Ephemeral — changes exist until committed; uncommitted changes lost on crash | Permanent — all commits preserved indefinitely (unless force-pushed over or repository deleted) |
| Mutability | Mutable — files can be edited, deleted, renamed arbitrarily | Immutable — history is append-only; existing commits cannot be changed (without git push --force, which rewrites history) |
| Accessibility | Single user — only the local machine user can access (physical or remote shell) | Multi-user — authenticated users with appropriate permissions (read, write, admin) can access simultaneously |
| Authority | Working copy — intermediate state; source of truth for uncommitted changes only | Source of truth — authoritative version for code history; all clones derive from remote |
| Storage format | Uncompressed + compressed objects in .git/objects/
|
Packfiles (delta-compressed objects) + database metadata |
| Branch representation | Local refs in .git/refs/heads/
|
Remote refs + GitHub PR refs (refs/pull/123/head) |
| Change tracking |
git status shows working directory vs staging area vs HEAD
|
GitHub UI shows commit history, pull requests, diff views |
| Recovery capability | Limited to .git/logs/ (reflog) for 90 days default |
Full history forever; fork and clone restore entire project |
Git architecture layers:
┌─────────────────────────────────────────────────────────────────────────────┐
│ GIT ARCHITECTURE LAYERS │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ WORKING DIRECTORY (Local filesystem) │
│ ├── Mutable, user-editable files │
│ └── Path: /home/user/project/src/index.js │
│ │ │
│ │ git add │
│ ▼ │
│ STAGING AREA (Index) │
│ ├── Snapshot of next commit │
│ └── Path: .git/index │
│ │ │
│ │ git commit │
│ ▼ │
│ LOCAL REPOSITORY │
│ ├── .git/objects/ (blobs, trees, commits) │
│ ├── .git/refs/heads/ (branches) │
│ └── .git/logs/ (reflog) │
│ │ │
│ │ git push │
│ ▼ │
│ REMOTE REPOSITORY (GitHub) │
│ ├── Distributed object storage │
│ ├── Web interface + API │
│ ├── Webhook dispatcher │
│ └── CI/CD pipeline triggers │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Push vs Pull mechanics:
| Operation | Direction | What Transfers | When to Use |
|---|---|---|---|
git push origin main |
Local → Remote | New commits + objects | After committing local changes; share work with team |
git pull origin main |
Remote → Local | New commits + objects (fetch + merge) | Before starting work; get teammates' changes |
git fetch origin |
Remote → Local | New commits + objects (no merge) | Inspect remote changes without integrating |
git clone <url> |
Remote → Local | Entire repository (all commits, branches, tags) | First-time setup; restore from backup |
G4: Interface with Deployment Platforms
Webhook architecture:
┌─────────────────────────────────────────────────────────────────────────────┐
│ GITHUB → DEPLOYMENT PLATFORM WEBHOOK │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ DEVELOPER GITHUB VERCEL │
│ │ │ │ │
│ │ git push origin main │ │ │
│ │─────────────────────────────→│ │ │
│ │ │ │ │
│ │ │ 1. Receive push │ │
│ │ │ 2. Validate authentication │ │
│ │ │ 3. Store commit objects │ │
│ │ │ │ │
│ │ │ 4. HTTP POST /webhook │ │
│ │ │────────────────────────────→│ │
│ │ │ Payload: { ... } │ │
│ │ │ │ │
│ │ │ 5. Queue build│ │
│ │ │ 6. Clone repo│ │
│ │ │ 7. npm install│ │
│ │ │ 8. npm run build│ │
│ │ │ 9. Deploy to CDN│ │
│ │ │ │ │
│ │ │ 10. Deployment URL │ │
│ │ │←────────────────────────────│ │
│ │ │ │ │
│ │ 11. Deployment preview │ │ │
│ │←────────────────────────────────────────────────────────────│ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Webhook payload structure (simplified):
{
"ref": "refs/heads/main",
"before": "a1b2c3d4e5f6...",
"after": "f6e5d4c3b2a1...",
"repository": {
"name": "health-trend-seller",
"full_name": "username/health-trend-seller",
"clone_url": "https://github.com/username/health-trend-seller.git"
},
"pusher": {
"name": "developer",
"email": "dev@example.com"
},
"commits": [
{
"id": "f6e5d4c3b2a1...",
"message": "Update trend detection algorithm",
"timestamp": "2026-05-13T10:30:00Z",
"added": ["src/api/controllers/trendsController.js"],
"modified": ["src/services/scoring/engine.js"],
"removed": []
}
]
}
Deployment platform response sequence:
| Step | Action | Technical Detail |
|---|---|---|
| 1 | Webhook received | Vercel/AWS/Netlify validates GitHub signature header (SHA-256 HMAC) |
| 2 | Build queued | Platform adds job to internal queue (Redis Bull, RabbitMQ, AWS SQS) |
| 3 | Clone repository |
git clone --depth 1 <repo-url> (shallow clone for speed)
|
| 4 | Install dependencies |
npm ci (uses package-lock.json for deterministic installs)
|
| 5 | Run build script |
npm run build (Next.js, Webpack, etc.)
|
| 6 | Deploy artifacts | Upload static files to CDN (CloudFront, Fastly); serverless functions to Lambda |
| 7 | Update deployment URL | Assign preview URL (e.g., pr-123.vercel.app) or production URL |
| 8 | Notify GitHub | POST to GitHub's deployment API with status (pending/success/failure) |
Supported deployment triggers:
| Trigger Event | GitHub Action | Typical Target |
|---|---|---|
Push to main
|
push webhook
|
Production environment |
Push to develop
|
push webhook
|
Staging environment |
| Pull request opened |
pull_request webhook
|
Preview deployment (unique URL per PR) |
Tag created (v*.*.*) |
create webhook
|
Production + versioned artifact |
| Manual dispatch | GitHub Actions workflow_dispatch
|
Any environment |
G5: Source of Truth Hierarchy
Authority levels and sync direction:
┌─────────────────────────────────────────────────────────────────────────────┐
│ SOURCE OF TRUTH HIERARCHY │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ LEVEL 1: GITHUB REPOSITORY (IMMUTABLE HISTORY) │
│ ├── Authority: Source of truth for all code and configuration │
│ ├── Mutability: Append-only (commits add, never modify) │
│ ├── Accessibility: All team members (authenticated) │
│ ├── Persistence: Permanent (unless repository deleted) │
│ └── Backup: Redundant across GitHub data centers │
│ ▲ │ │
│ │ git clone / git pull │ git push │
│ │ │ │
│ LEVEL 2: LOCALHOST (WORKING COPY) │ │
│ ├── Authority: Source of truth for uncommitted changes │
│ ├── Mutability: Fully mutable (edit freely) │
│ ├── Accessibility: Single developer │
│ ├── Persistence: Ephemeral (uncommitted changes can be lost) │
│ └── Derived from: GitHub clone or pull │
│ │ │ │
│ │ git push / webhook │ git clone (build) │
│ │ │ │
│ LEVEL 3: PRODUCTION DEPLOYMENT (COMPILED INSTANCE) │ │
│ ├── Authority: Source of truth for live user experience │
│ ├── Mutability: Read-only from developer perspective │
│ ├── Accessibility: End users (public or authenticated) │
│ ├── Persistence: As deployed (rebuildable from GitHub) │
│ └── Derived from: GitHub (via CI/CD pipeline) │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
What is NOT pushed to GitHub (and why):
| Artifact | Exclusion Reason | Technical Justification | Alternative |
|---|---|---|---|
.env (secrets)
|
Security risk; contains credentials | API keys, database passwords, JWT secrets would be exposed in repository | Environment variables on deployment platform; .env.example as template |
node_modules/ |
Size; rebuildable | 100,000+ files, 500+ MB would bloat repository and slow clones |
npm install or npm ci during build
|
/.next/, /dist/, /build
|
Generated artifacts | Build output varies by platform; committing would cause merge conflicts | Build on deployment server; .gitignore exclusion |
*.log |
Ephemeral, machine-specific | Logs differ by machine, timestamp, and runtime state | Centralized logging (Splunk, Datadog, Papertrail) |
Local database files (*.sqlite, *.db) |
Environment-specific; large | Development database differs from production; binary files cause merge conflicts | Remote database (PostgreSQL, MySQL) with migrations |
OS metadata (.DS_Store, Thumbs.db) |
Unnecessary, platform-specific | Adds noise to commits, no functional value |
.gitignore global or project-level exclusion
|
IDE configuration (.vscode/, .idea/) |
Developer-specific preferences | Each developer has different editor settings | Optional: commit if team-standardized |
Compiled binaries (*.exe, *.wasm if generated) |
Large, rebuildable | Binary files not diff-friendly; platform-specific | Build during deployment or use releases |
.gitignore best practices (Health Trend Seller):
# Dependencies
node_modules/
.pnp/
.pnp.js
# Build outputs
.next/
out/
build/
dist/
.wasm-build/
# Environment variables
.env
.env.local
.env.production
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn
Engineering Response: CDN Deployment Architecture & Implementation
1. CDN Topology & Edge Architecture
Provider selection: Fastly (selected for real-time purge, VCL customization, and shield POPs)
Edge PoP regions:
- North America: Newark, Chicago, Dallas, Los Angeles, Seattle, Toronto
- South America: São Paulo, Buenos Aires
- Europe: London, Frankfurt, Paris, Stockholm, Madrid
- Asia Pacific: Tokyo, Osaka, Singapore, Sydney, Seoul, Mumbai
- Middle East & Africa: Dubai, Johannesburg, Tel Aviv
Routing protocol: Anycast with latency-based BGP route propagation
ASCII Topology Diagram:
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ GLOBAL CDN ARCHITECTURE │
├─────────────────────────────────────────────────────────────────────────────────────┤
│ │
│ END USER (Tokyo) END USER (London) END USER (New York) │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Edge PoP │ │Edge PoP │ │Edge PoP │ │
│ │ (Tokyo) │ │(London) │ │(Newark) │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ │ (cache miss) │ (cache miss) │ (cache miss) │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────────────┐ │
│ │ SHIELD POP (us-east-1) │ │
│ │ Tier 2 Cache - Regional Consolidation │ │
│ └─────────────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ │ (cache miss after shield) │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ ORIGIN (us-east-1) │ │
│ │ S3 + CloudFront │ │
│ └─────────────────────┘ │
│ │
│ Request Flow: │
│ Edge Hit (85%) ──► Return cached ──► Response < 10ms │
│ Edge Miss ──► Shield Hit (90%) ──► Cache at edge ──► Response < 30ms │
│ Edge + Shield Miss ──► Origin (0.5%) ──► Cache at shield + edge ──► Response │
│ │
└─────────────────────────────────────────────────────────────────────────────────────┘
2. Caching Policy Matrix
| Content Type | Cache-Control Header | TTL (edge) | TTL (shield) | Stale-while-revalidate | Surrogate Key |
|---|---|---|---|---|---|
| HTML (pages) | public, max-age=60, stale-while-revalidate=300 |
60s | 300s | 300s (5 min) | page-{id}, html, version-{v} |
| HTML (ISR) | public, max-age=10, stale-while-revalidate=60 |
10s | 60s | 60s | isr-{id}, html |
| JS/CSS (bundles) | public, max-age=31536000, immutable |
1 year | 1 year | N/A | asset-{hash}, js, css |
| Images (static) | public, max-age=86400, stale-while-revalidate=86400 |
24h | 24h | 24h | image-{hash}, img |
| Images (user-uploaded) | public, max-age=3600, stale-while-revalidate=7200 |
1h | 2h | 2h | user-img-{id} |
| API JSON (trends) | private, max-age=30, stale-while-revalidate=120 |
30s | 120s | 120s | api-trends |
| API JSON (strikes) | private, max-age=10, stale-while-revalidate=30 |
10s | 30s | 30s | api-strikes |
| Fonts | public, max-age=31536000, immutable |
1 year | 1 year | N/A | font-{hash} |
| Video/audio | public, max-age=604800, stale-while-revalidate=604800 |
7 days | 7 days | 7 days | media-{hash} |
| Service Worker | no-cache, must-revalidate |
0s | 0s | N/A | sw |
3. Origin Shield Configuration
Shield region(s):
- Primary:
us-east-1(Newark, NJ) - serves Americas and Europe - Secondary:
ap-northeast-1(Tokyo) - serves Asia Pacific - Tertiary:
eu-west-1(Dublin) - serves Europe fallback
Cache reserve size: 10 GB per shield POP (LRU eviction policy)
Fallback behavior:
stale-if-error = 86400 (24 hours)
If origin returns 5xx → serve stale cached content for up to 24 hours
If origin timeout (>3s) → serve stale + log alert
Connection limits:
| Parameter | Value | Rationale |
|---|---|---|
| Max connections per origin | 1000 | Prevent connection exhaustion |
| Keep-alive timeout | 65s | Reuse connections within AWS region |
| Connection pool size | 200 | Balance throughput vs memory |
| Request collapsing | Enabled | Deduplicate identical concurrent requests |
Origin shield VCL snippet (Fastly):
sub vcl_recv {
# Enable shield for all requests
if (req.http.Fastly-FF) {
set req.http.Fastly-Force-Shield = "1";
}
# Set shield preference based on geography
if (client.geo.continent == "NA" || client.geo.continent == "SA") {
set req.http.Fastly-Shield = "us-east-1-1";
} elsif (client.geo.continent == "AS" || client.geo.continent == "OC") {
set req.http.Fastly-Shield = "ap-northeast-1-1";
} else {
set req.http.Fastly-Shield = "eu-west-1-1";
}
}
sub vcl_fetch {
# Stale-if-error configuration
if (beresp.status >= 500 && beresp.status
4. Invalidation & Purge Mechanism
Purge method: Tag-based (Surrogate Key) with soft purge support
API endpoint (Fastly):
POST https://api.fastly.com/service/{service_id}/purge
Headers: Fastly-Key: {api_key}
Body: Surrogate-Key: {tag1} {tag2}
Propagation latency: 150-500ms (typically < 2 seconds globally)
Surrogate Key tagging strategy:
| Tag Pattern | Applied To | Use Case |
|---|---|---|
page-{id} |
Single HTML page | Purge individual page |
product-{sku} |
Product page + API | Purge product update |
type-html |
All HTML pages | Full site purge (rare) |
type-asset-{hash} |
Individual asset | Purge specific JS/CSS |
version-{build_id} |
All assets from build | Atomic version switch |
user-{id} |
User-specific content | GDPR compliance |
Atomic deployment workflow:
┌─────────────────────────────────────────────────────────────────────────────────┐
│ ATOMIC DEPLOYMENT WITH SURROGATE KEYS │
├─────────────────────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: PRELOAD (0s) │
│ ├── Build new assets: main.a1b2c3.js, styles.d4e5f6.css │
│ ├── Upload to origin (S3) with cache headers │
│ ├── Tag all new assets with: version-v2, type-asset │
│ └── Warm edge cache: HEAD requests to critical URLs │
│ │
│ Phase 2: SWITCH (1s) │
│ ├── Deploy new HTML pages referencing new assets │
│ ├── Tag new HTML with: version-v2, type-html │
│ └── No purge yet (old HTML still cached) │
│ │
│ Phase 3: PURGE OLD (2s) │
│ ├── Purge surrogate key: version-v1 │
│ ├── Old HTML removed from cache │
│ ├── Old assets remain (no need to purge - immutable) │
│ └── New requests get new HTML → new assets │
│ │
│ Phase 4: GRACEFUL TRANSITION (10s - 24h) │
│ ├── Users with stale HTML still have old assets cached │
│ ├── Old assets continue to serve (no 404s) │
│ └── Natural cache expiry cleans up old assets │
│ │
└─────────────────────────────────────────────────────────────────────────────────┘
Purge API example (cURL):
# Soft purge (mark stale, revalidate on next request)
curl -X POST "https://api.fastly.com/service/$SERVICE_ID/purge" \
-H "Fastly-Key: $API_KEY" \
-H "Accept: application/json" \
-H "Surrogate-Key: version-v1" \
-H "Fastly-Soft-Purge: 1"
# Hard purge (immediate removal)
curl -X POST "https://api.fastly.com/service/$SERVICE_ID/purge" \
-H "Fastly-Key: $API_KEY" \
-H "Accept: application/json" \
-H "Surrogate-Key: page-123"
# URL-based purge
curl -X POST "https://api.fastly.com/service/$SERVICE_ID/purge/products/123" \
-H "Fastly-Key: $API_KEY"
5. Deployment Pipeline
CI trigger: Push to main branch (production) or develop branch (staging)
GitHub Actions workflow:
name: CDN Deployment
on:
push:
branches: [main, develop]
workflow_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
env:
NEXT_PUBLIC_CDN_URL: ${{ vars.CDN_URL }}
- name: Generate asset hashes
id: hashes
run: |
echo "js_hash=$(sha256sum .next/static/chunks/main-*.js | cut -d' ' -f1 | cut -c1-8)" >> $GITHUB_OUTPUT
echo "css_hash=$(sha256sum .next/static/css/*.css | cut -d' ' -f1 | cut -c1-8)" >> $GITHUB_OUTPUT
echo "build_id=$(date +%Y%m%d-%H%M%S)-${{ github.sha }}" >> $GITHUB_OUTPUT
- name: Upload to S3 origin
run: |
aws s3 sync .next/ s3://health-trend-origin/builds/${{ steps.hashes.outputs.build_id }}/ \
--cache-control "public, max-age=31536000, immutable" \
--metadata "surrogate-key=version-${{ steps.hashes.outputs.build_id }},type-asset"
aws s3 sync public/ s3://health-trend-origin/builds/${{ steps.hashes.outputs.build_id }}/ \
--cache-control "public, max-age=86400"
- name: Update CDN origin configuration
run: |
curl -X PATCH "https://api.fastly.com/service/$SERVICE_ID/version/$VERSION/backend/origin" \
-H "Fastly-Key: $API_KEY" \
-d "{\"address\":\"health-trend-origin.s3.amazonaws.com/builds/${{ steps.hashes.outputs.build_id }}\"}"
- name: Warm edge cache
run: |
URLs=("https://$CDN_DOMAIN/" "https://$CDN_DOMAIN/api/v1/trends" "https://$CDN_DOMAIN/dashboard")
for url in "${URLS[@]}"; do
curl -s -o /dev/null -H "Fastly-Force-Shield: 1" "$url"
sleep 0.5
done
- name: Purge old surrogate keys (production only)
if: github.ref == 'refs/heads/main'
run: |
curl -X POST "https://api.fastly.com/service/$SERVICE_ID/purge" \
-H "Fastly-Key: $API_KEY" \
-H "Surrogate-Key: version-${{ steps.prev_build.outputs.build_id }}" \
-H "Fastly-Soft-Purge: 1"
- name: Validate deployment
run: |
curl -f -s -o /dev/null -w "%{http_code}" "https://$CDN_DOMAIN/health" | grep -q "200"
echo "Deployment verified successfully"
Deployment steps sequence:
Step 1: Build assets (content-hashed filenames)
│
▼
Step 2: Upload to S3 origin (versioned path: /builds/{build_id}/)
│
▼
Step 3: Update Fastly backend to new origin path
│
▼
Step 4: Warm edge cache (prefetch critical URLs)
│
▼
Step 5: Purge old surrogate keys (soft purge)
│
▼
Step 6: Smoke test (health check endpoint)
│
▼
Step 7: Deployment complete ✅
6. Observability & SLO Dashboard
Monitoring stack: Datadog + Fastly Observability + CloudWatch
SLO Dashboard Metrics:
| Metric | Target SLO | Alert Threshold | Alert Action |
|---|---|---|---|
| Cache hit ratio (edge) | ≥ 95% | < 90% for 5 min | Page cache warming + investigate origin changes |
| Cache hit ratio (shield) | ≥ 85% | < 75% for 5 min | Review shield configuration + analyze traffic patterns |
| TTFB (p95) - edge hit | ≤ 10ms | > 20ms for 5 min | Check edge PoP health + network routing |
| TTFB (p95) - shield hit | ≤ 30ms | > 50ms for 5 min | Verify shield region placement |
| TTFB (p95) - origin miss | ≤ 100ms | > 200ms for 5 min | Scale origin + optimize database queries |
| Origin offload | ≥ 90% | < 85% for 10 min | Review cache policies + TTL settings |
| Purge latency (p95) | ≤ 2s | > 5s | Check Fastly API status + network connectivity |
| Error rate (5xx) | ≤ 0.1% | > 0.5% for 2 min | Page on-call engineer + rollback |
| Bandwidth (egress) | Monitor only | > 100 Gbps (spike alert) | Review traffic patterns + cost optimization |
| Concurrent requests | Monitor only | > 10,000 per PoP | Scale edge capacity |
Datadog dashboard queries:
-- Edge cache hit ratio
sum:trace.servlet.request.hits{service:fastly}.as_rate() /
sum:trace.servlet.request.total{service:fastly}.as_rate() * 100
-- Origin offload
(1 - (sum:aws.s3.requests{origin:true} / sum:fastly.requests{edge:true})) * 100
-- TTFB by region
p95:trace.fastly.edge.response_time{georegion:*}
Alert configuration (PagerDuty):
| Severity | Condition | Response |
|---|---|---|
| P0 (Critical) | Error rate > 1% for 2 min | Immediate rollback + engineer page |
| P1 (High) | Cache hit ratio < 85% for 5 min | Cache warming + policy review |
| P2 (Medium) | TTFB > 200ms (p95) for 10 min | Investigate origin + database |
| P3 (Low) | Purge latency > 5s for 5 min | Check Fastly API status |
Acceptance Criteria Verification
| Criterion | Verification Method | Expected Result |
|---|---|---|
| Automated deployment | CI/CD pipeline execution | Pipeline completes in < 5 min |
| Cache hit ratio ≥ 90% | Datadog dashboard | 7-day average ≥ 90% |
| Origin offload ≥ 85% | CloudFront/S3 metrics | Origin requests reduced by ≥ 85% |
| Purge latency ≤ 60s | Fastly purge logs | 95th percentile < 30s |
| TTFB (p95) ≤ 100ms | Real user monitoring | Verified across all regions |
| Zero downtime deployment | Error rate during deploy | No 4xx/5xx spikes |
| Cache warming success | Warm script logs | 100% success rate |
| Monitoring dashboard | Dashboard URL accessible | All SLO metrics visible |
Appendix: Cache Header Reference
# Immutable asset (JS/CSS/fonts)
Cache-Control: public, max-age=31536000, immutable
Surrogate-Key: asset-a1b2c3 version-v2 js
# HTML page (revalidating)
Cache-Control: public, max-age=60, stale-while-revalidate=300
Surrogate-Key: page-home version-v2 html
# API response (private, short TTL)
Cache-Control: private, max-age=30, stale-while-revalidate=120, stale-if-error=3600
Surrogate-Key: api-trends
# Service worker (never cache)
Cache-Control: no-cache, no-store, must-revalidate
CDN deployment architecture and implementation specification. All requirements meet 2026 standards.
Engineering Response: Localhost Deployment - Health Trend Seller
P1: Prerequisites
Operating System: Linux (Ubuntu 20.04+), macOS (12+), or Windows 11 with WSL2
Required Software:
| Dependency | Minimum Version | Verification Command |
|---|---|---|
| Node.js | ≥ 18.0.0 | node --version |
| npm | ≥ 9.0.0 | npm --version |
| PostgreSQL | ≥ 14.0 | postgres --version |
| Git | ≥ 2.30.0 | git --version |
| Docker (optional) | ≥ 20.10.0 | docker --version |
| Redis (optional) | ≥ 7.0 | redis-server --version |
| IPFS (optional) | ≥ 0.20.0 | ipfs --version |
Installation Commands (Ubuntu/Debian):
# Node.js
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# PostgreSQL
sudo apt-get install -y postgresql postgresql-contrib
# Git
sudo apt-get install -y git
# Docker (optional)
sudo apt-get install -y docker.io docker-compose
# Redis (optional)
sudo apt-get install -y redis-server
# IPFS (optional)
wget https://dist.ipfs.tech/kubo/v0.24.0/kubo_v0.24.0_linux-amd64.tar.gz
tar -xvzf kubo_v0.24.0_linux-amd64.tar.gz
cd kubo
sudo ./install.sh
P2: Environment Configuration
Clone Repository:
git clone https://github.com/yourusername/health-trend-seller.git
cd health-trend-seller
Install Dependencies:
npm install
Environment Variables (.env file):
| Variable | Example Value | Purpose |
|---|---|---|
DATABASE_URL |
postgresql://postgres:password@localhost:5432/health_trend |
PostgreSQL connection |
PORT |
3000 |
API server port |
HOST |
localhost |
Bind address |
JWT_SECRET |
your-secret-key |
Authentication |
REDIS_URL |
redis://localhost:6379 |
Redis connection (optional) |
IPFS_API_URL |
http://localhost:5001 |
IPFS API endpoint (optional) |
Secrets Management:
cp .env.example .env
# Edit .env with your local credentials
# Never commit .env to repository
echo ".env" >> .gitignore
Database Setup:
npx prisma generate
npx prisma migrate dev --name init
P3: Deployment Sequence
STEP 1: VERIFY PREREQUISITES
├── Check Node.js, npm, PostgreSQL versions
├── Ensure ports 3000, 5432, 7233 are free
└── Verify Git is installed
│
▼
STEP 2: CLONE & INSTALL
├── git clone [repository URL]
├── cd health-trend-seller
└── npm install
│
▼
STEP 3: CONFIGURE ENVIRONMENT
├── cp .env.example .env
├── Edit .env with database credentials
├── npx prisma generate
└── npx prisma migrate dev
│
▼
STEP 4: START POSTGRESQL
├── sudo service postgresql start
└── psql -d postgres -c "CREATE DATABASE health_trend"
│
▼
STEP 5: START API & FRONTEND (Terminal 1)
└── npm run dev
│
▼
STEP 6: START TEMPORAL WORKER (Terminal 2)
└── npm run worker
│
▼
STEP 7: START OPTIONAL SERVICES (Terminal 3 & 4)
├── redis-server
└── ipfs daemon
│
▼
STEP 8: VERIFY DEPLOYMENT
└── Open http://localhost:3000
P4: Service Orchestration Table
| Order | Service | Port | Bind Address | Startup Command | Required | Depends On |
|---|---|---|---|---|---|---|
| 1 | PostgreSQL | 5432 | 127.0.0.1 | sudo service postgresql start |
Yes | None |
| 2 | API + Frontend | 3000 | 0.0.0.0 | npm run dev |
Yes | PostgreSQL |
| 3 | Temporal Worker | N/A | 127.0.0.1 | npm run worker |
Yes | API |
| 4 | Redis | 6379 | 127.0.0.1 | redis-server |
No | None |
| 5 | IPFS | 5001 | 127.0.0.1 | ipfs daemon |
No | None |
Port Allocation Summary:
PORT SERVICE BIND ADDRESS STATUS
5432 PostgreSQL 127.0.0.1 Required
3000 Express API 0.0.0.0 Required
6379 Redis 127.0.0.1 Optional
5001 IPFS API 127.0.0.1 Optional
8080 IPFS Gateway 127.0.0.1 Optional (with IPFS)
Startup Order Dependencies:
- PostgreSQL must be running before API starts
- API must be running before Temporal worker can connect
- Redis and IPFS can start at any time (optional)
P5: Verification Checklist
Database Verification:
psql -d health_trend -U postgres -c "SELECT 1"
# Expected: 1 row returned
API Health Check:
curl http://localhost:3000/health
# Expected: {"status":"healthy","services":{"database":"connected"}}
Frontend Verification:
- Open browser to
http://localhost:3000 - CEO Pulse dashboard should load
- Active trends, strikes, workflows displays should show data
Temporal Worker Verification:
- Terminal logs show: "✅ Connected to Temporal server"
- Terminal logs show: "👂 Listening on task queue: HEALTH_TREND_TASKS"
WebSocket Verification:
- Browser console (F12) shows WebSocket connection successful
- No "WebSocket connection failed" errors
Redis Verification (optional):
redis-cli ping
# Expected: PONG
IPFS Verification (optional):
curl http://localhost:5001/api/v0/version
# Expected: JSON response with IPFS version
Troubleshooting Table
| Symptom | Likely Cause | Resolution |
|---|---|---|
Error: listen EADDRINUSE: address already in use :::3000 |
Port 3000 occupied |
lsof -i :3000 then kill -9 [PID]
|
Error: P1001: Can't reach database server |
PostgreSQL not running | sudo service postgresql start |
PrismaClientInitializationError: Unable to find a suitable module |
Prisma client not generated | npx prisma generate |
Error: .env file not found |
Missing configuration |
cp .env.example .env then edit
|
Temporal worker: connection refused |
Temporal server not running | Install Temporal CLI and run temporal server start-dev
|
WebSocket connection failed |
API not running or CORS issue | Verify npm run dev is running, check port 3000 |
npm ERR! Cannot find module |
Dependencies not installed | rm -rf node_modules && npm install |
Database health_trend does not exist |
Database not created |
createdb health_trend or run migrations
|
# After prerequisites installed and repository cloned
sudo service postgresql start && npm run dev
# Then in another terminal: npm run worker
# Open http://localhost:3000
Acceptance Criteria Verification
| Criterion | Verification Method | Expected Result |
|---|---|---|
| Prerequisites installed | Run version commands | All versions meet minimums |
| Repository cloned |
ls -la in project dir
|
Health Trend Seller files visible |
| Dependencies installed | npm list --depth=0 |
All packages listed |
| Environment configured | cat .env | grep DATABASE_URL |
Valid connection string |
| PostgreSQL running | pg_isready |
Accepting connections |
| API starts |
npm run dev exit code 0
|
Server running on port 3000 |
| Frontend loads | Browser navigation | CEO Pulse dashboard displays |
| Worker connects | Terminal logs | "Connected to Temporal server" |
| Optional services | Respective commands | Services start without errors |
- PostgreSQL accepts connections on port 5432
-
npm run devruns without errors on port 3000 - Browser loads
http://localhost:3000showing CEO Pulse dashboard - Temporal worker connects and registers workflows
- All verification checklist items pass
http://localhost:3000. Commit changes to GitHub. Push triggers Vercel auto-deployment to production.
End of Document — Localhost deployment specification complete. All requirements meet 2026 standards.
ENVIRONMENT VARIABLE INSPECTION PROTOCOL
E1: INSPECTION COMMAND
-
Primary command:
cat .env | grep DATABASE_URL -
Expected output:
DATABASE_URL=postgresql://username:password@host:port/database - Exit code 0: Variable found and displayed
-
Exit code 1: Variable not found in
.envfile -
Exit code 2:
.envfile does not exist or cannot be read
E2: COMMAND BREAKDOWN
| Component | Function | Arguments | Exit Code |
|---|---|---|---|
cat |
Reads file sequentially and outputs to stdout | .env |
0 (success) / 1 (file not found) / 2 (invalid arguments) |
| (pipe)
|
Redirects stdout of left command to stdin of right command | N/A | N/A (exit code of pipeline is rightmost command) |
grep |
Searches input for pattern matching; outputs matching lines | DATABASE_URL |
0 (match found) / 1 (no match) / 2 (error) |
cat .env | grep DATABASE_URL is the exit code of grep (0 or 1) unless cat fails (file not found), in which case the pipeline returns grep exit code 2 due to no input.E3: VALIDATION CRITERIA
Valid output patterns:
DATABASE_URL=postgresql://localhost:5432/health_trend
DATABASE_URL=postgresql://user:pass@localhost:5432/db
DATABASE_URL="postgresql://user:pass@host:5432/db"
DATABASE_URL='postgresql://user:pass@host:5432/db'
Empty output scenarios:
- Variable name misspelled (e.g.,
DATABASE_URl) - Variable commented out (
#DATABASE_URL=...) - Variable on same line as another key without delimiter
- Variable defined in separate file (e.g.,
.env.local,.env.production)
Error conditions:
| Error Message | Cause | Resolution |
|---|---|---|
cat: .env: No such file or directory |
.env file missing
|
Create .env from template |
cat: .env: Permission denied |
Insufficient file permissions | chmod 644 .env |
grep: invalid option -- |
grep alias overriding default | Use \grep to bypass alias |
DATABASE_URL: command not found |
Space around = in .env file |
Remove spaces: KEY=VALUE
|
E4: SECURITY CONSIDERATIONS
Exposure vectors:
| Vector | Risk | Example |
|---|---|---|
| Command history (Bash) | Credentials saved to ~/.bash_history
|
cat .env | grep DATABASE_URL shows password in history
|
| Process listing | Credentials visible in ps aux output |
Long-running commands expose arguments |
| Terminal scrollback | Password remains visible after command completes | Scrolling up reveals connection string |
| Shell logging | Corporate shell logging captures credentials |
script command or audit logging
|
| Shared screens | Credentials visible during screen sharing or pair programming | Zoom/TeamViewer sessions |
Mitigation strategies:
| Practice | Command | Protection Level |
|---|---|---|
| Disable history temporarily |
set +o history before, set -o history after
|
High (prevents .bash_history) |
| Prepend space to command |
cat .env | grep DATABASE_URL (space before command)
|
Medium (depends on HISTCONTROL=ignorespace) |
| Extract only variable name | grep DATABASE_URL .env | cut -d'=' -f1 |
High (password not displayed) |
| Use environment substitution | echo ${DATABASE_URL%%:*} |
High (masks credentials) |
| One-time confirmation | read -s -p "Press enter to view: " && grep DATABASE_URL .env |
High (requires active consent) |
| Use dedicated inspection tool |
node inspect-env.js (custom script)
|
Very High (controlled output) |
Secure inspection command:
# Temporarily disable history, mask password output, restore history
set +o history && grep DATABASE_URL .env | cut -d'=' -f1 && set -o history
# Output: DATABASE_URL
E5: CROSS-PLATFORM ALTERNATIVES
| Platform | Command | Notes | |
|---|---|---|---|
| Linux / macOS (Bash/Zsh) | grep DATABASE_URL .env |
Direct grep without unnecessary cat
|
|
| Linux / macOS (alternative) | sed -n '/^DATABASE_URL=/p' .env |
Using sed for pattern matching | |
| Linux / macOS (awk) | awk -F'=' '/^DATABASE_URL=/{print $1}' .env |
Prints only variable name | |
| Windows CMD | findstr DATABASE_URL .env |
Case-sensitive; no pipe needed | |
| Windows PowerShell | Select-String -Path .env -Pattern "DATABASE_URL" |
Object-oriented output | |
| Windows PowerShell (masked) | (Get-Content .env | Select-String "DATABASE_URL") -replace "=.*","=" |
Shows only variable name | |
| Cross-platform Node.js | node -e "require('dotenv').config(); console.log(process.env.DATABASE_URL)" |
Requires dotenv package installed |
|
| Cross-platform Python | python -c "import os; from dotenv import load_dotenv; load_dotenv(); print(os.getenv('DATABASE_URL'))" |
Requires python-dotenv
|
|
| Docker | docker run --rm -v $(pwd):/app alpine grep DATABASE_URL /app/.env |
Runs in isolated container |
| Exit Code | Meaning | Scenario | Next Action |
|---|---|---|---|
| 0 | Success |
grep found match; variable exists
|
Verify connection string format |
| 1 | No match | File exists but variable absent | Add DATABASE_URL to .env
|
| 2 | Error | File missing, permission denied, or invalid arguments | Check file existence and permissions |
| 130 | Interrupted | User pressed Ctrl+C | Re-run command |
| 141 | Broken pipe | grep exited before cat finished | Unlikely; check for large files |
EXAMPLE USAGE SCENARIOS
Scenario 1: Variable Found (Success)
$ cat .env | grep DATABASE_URL
DATABASE_URL=postgresql://postgres:secret@localhost:5432/health_trend
$ echo $?
0
Scenario 2: Variable Missing (No Match)
$ cat .env | grep DATABASE_URL
(no output)
$ echo $?
1
Scenario 3: File Not Found (Error)
$ cat .env | grep DATABASE_URL
cat: .env: No such file or directory
$ echo $?
1
Scenario 4: Variable Commented Out (No Match)
$ cat .env | grep DATABASE_URL
#DATABASE_URL=postgresql://localhost:5432/health_trend
$ echo $?
1
Scenario 5: Secure Inspection (Masked Output)
$ grep DATABASE_URL .env | cut -d'=' -f1
DATABASE_URL
$ echo $?
0
TROUBLESHOOTING MATRIX
| Symptom | Exit Code | Likely Cause | Resolution |
|---|---|---|---|
| No output | 1 | Variable not defined | echo "DATABASE_URL=postgresql://localhost:5432/db" >> .env |
| No output | 2 |
.env file missing
|
cp .env.example .env then edit
|
Output shows #DATABASE_URL
|
1 | Variable commented out | Edit .env to remove # prefix |
| Permission denied | 2 | Incorrect file permissions | chmod 644 .env |
grep: invalid option -- |
2 | grep alias interfering |
\grep DATABASE_URL .env (backslash bypasses alias)
|
| Output shows multiple lines | 0 | Duplicate variable definitions | Remove duplicate entries; keep last one |
Output shows export DATABASE_URL=
|
0 | Using export syntax |
Remove export from .env (not standard) |
Spaces around =
|
0 (but may fail) | Invalid .env syntax | Edit to KEY=VALUE without spaces |
| Quotes in value | 0 | Valid syntax | Ensure quotes are balanced: KEY="value with spaces"
|
| Special characters in password | 0 (but may fail) | URL encoding needed | URL-encode special chars: %40 for @, %23 for #
|
BEST PRACTICES SUMMARY
| Practice | Why | Implementation |
|---|---|---|
Never commit .env to version control |
Prevents secret exposure | Add .env to .gitignore
|
Use .env.example as template |
Documents required variables without secrets | Commit .env.example, ignore .env
|
| Mask credentials in output | Prevents shoulder surfing | Use cut -d'=' -f1 to show only variable name |
| Disable history for sensitive commands | Prevents credential storage in bash history |
set +o history / set -o history
|
| Validate connection string format | Catches syntax errors early | Test with psql "$DATABASE_URL" -c "SELECT 1"
|
| Rotate exposed credentials | Limits damage from leaks | If credential appears in log or history, regenerate |
Use environment-specific .env files |
Isolates development from production |
.env.development, .env.production, .env.test
|
| Document variable format | Prevents parsing errors | Include example in README |
cat .env | grep DATABASE_URL command is a simple but security-sensitive operation for inspecting environment variables. Best practices require:- Always mask or limit output to expose only variable names, not values
- Disable command history before executing credential-displaying commands
- Use platform-appropriate alternatives for Windows and PowerShell environments
- Validate exit codes to distinguish between missing variables and file errors
-
Never log or version control inspection output or
.envfiles
grep DATABASE_URL .env | cut -d'=' -f1