Your Complete Guide to AI-Powered Development
- Getting Started
- Platform Overview
- Development Environment
- Creating Your First Service
- Working with AI Assistance
- Testing and Quality
- Deployment and Operations
- Monitoring and Debugging
- Best Practices
- Resources and Support
As a developer on the Three Horizons AI Platform, you have access to cutting-edge AI-powered development tools that will dramatically improve your productivity and code quality. This guide will walk you through everything you need to know.
- Account Setup: GitHub, Azure, and Developer Hub access
- Environment: VS Code with Copilot installed
- Authentication: CLI tools configured
- Training: Complete onboarding modules
- First App: Deploy your hello-world service
graph LR
A[Onboarding] --> B[Local Setup]
B --> C[First Service]
C --> D[AI Integration]
D --> E[Production Deploy]
E --> F[Monitoring]
F --> G[Optimization]
style A fill:#99ccff
style D fill:#ff9999
style E fill:#99ff99
| Layer | Purpose | Tools |
|---|---|---|
| Development | Code creation and testing | VS Code, Copilot, DevBox |
| Integration | Build and quality checks | GitHub Actions, SonarQube |
| Deployment | Progressive rollout | GitOps, Flagger, ArgoCD |
| Runtime | Container orchestration | Kubernetes, Istio |
| Monitoring | Observability | Prometheus, Grafana, Jaeger |
| AI Services | Intelligence layer | Azure AI, Copilot Agent |
- Developer Hub: Your central portal for all platform services
- GitHub Copilot: AI pair programmer for code generation
- DevBox: Cloud-powered development environments
- Golden Paths: Pre-configured templates for common patterns
- Agentic DevOps: Autonomous CI/CD pipelines
#!/bin/bash
# developer-setup.sh - Run this first!
echo "π Setting up your Three Horizons development environment"
# Check prerequisites
check_requirement() {
if ! command -v $1 &> /dev/null; then
echo "β $1 is not installed. Please install it first."
exit 1
fi
echo "β
$1 is installed"
}
echo "π Checking requirements..."
check_requirement git
check_requirement docker
check_requirement kubectl
check_requirement code
# Configure Git
echo "π§ Configuring Git..."
git config --global init.defaultBranch main
git config --global pull.rebase false
# Install VS Code extensions
echo "π» Installing VS Code extensions..."
extensions=(
"GitHub.copilot"
"GitHub.copilot-chat"
"ms-vscode-remote.remote-containers"
"ms-kubernetes-tools.vscode-kubernetes-tools"
"redhat.vscode-yaml"
"hashicorp.terraform"
)
for ext in "${extensions[@]}"; do
code --install-extension "$ext"
done
# Authenticate with services
echo "π Setting up authentication..."
# GitHub
if ! gh auth status &> /dev/null; then
echo "π Please authenticate with GitHub:"
gh auth login
fi
# Azure
if ! az account show &> /dev/null; then
echo "βοΈ Please authenticate with Azure:"
az login
fi
# Set up local Kubernetes context
echo "βΈοΈ Configuring Kubernetes..."
ENVIRONMENT=${ENVIRONMENT:-dev}
az aks get-credentials \
--resource-group "rg-threehorizons-${ENVIRONMENT}-compute" \
--name "aks-threehorizons-${ENVIRONMENT}" \
--overwrite-existing
# Clone essential repos
echo "π₯ Cloning platform repositories..."
mkdir -p ~/threehorizons
cd ~/threehorizons
repos=(
"platform-documentation"
"application-templates"
"demo-apps"
)
for repo in "${repos[@]}"; do
if [ ! -d "$repo" ]; then
gh repo clone "threehorizons-ai/$repo"
fi
done
# Create workspace settings
echo "βοΈ Creating workspace settings..."
cat > ~/threehorizons/.vscode/settings.json << 'EOF'
{
"github.copilot.enable": {
"*": true
},
"editor.formatOnSave": true,
"editor.rulers": [80, 120],
"files.trimTrailingWhitespace": true,
"go.lintTool": "golangci-lint",
"python.linting.enabled": true,
"typescript.preferences.quoteStyle": "single"
}
EOF
echo "β
Setup complete! Open VS Code in ~/threehorizons to start developing."
echo ""
echo "π Next steps:"
echo "1. Visit the Developer Hub: https://devhub.threehorizons.ai"
echo "2. Create your first service using templates"
echo "3. Enable GitHub Copilot in VS Code"
echo ""
echo "Happy coding! π"# .devbox/config.yaml
name: my-devbox
spec:
# Performance tier
size: large # 8 vCPU, 32GB RAM
# Pre-installed tools
features:
- docker-in-docker
- kubernetes-tools
- cloud-sdks
- ai-ml-tools
# Your customizations
dotfiles:
repository: https://github.com/YOUR_USERNAME/dotfiles
# Startup commands
postCreate: |
# Personal setup
echo "alias k=kubectl" >> ~/.bashrc
echo "alias g=git" >> ~/.bashrc
# Project setup
gh repo clone threehorizons-ai/my-service ~/workspace/my-service
cd ~/workspace/my-service
npm installTo create your DevBox:
# Create DevBox
curl -X POST https://devhub.threehorizons.ai/api/devbox \
-H "Authorization: Bearer $DEVHUB_TOKEN" \
-H "Content-Type: application/json" \
-d @.devbox/config.yaml
# Connect to DevBox
devbox connect my-devbox// .vscode/settings.json - Optimized for Three Horizons development
{
// GitHub Copilot
"github.copilot.enable": {
"*": true,
"yaml": true,
"plaintext": true,
"markdown": true
},
"github.copilot.advanced": {
"length": "medium",
"temperature": 0.7,
"top_p": 0.95,
"stops": {
"python": ["\n\n\n"],
"javascript": ["\n\n\n"],
"typescript": ["\n\n\n"],
"go": ["\n\n\n"]
}
},
// Language-specific
"go.formatTool": "goimports",
"go.lintOnSave": "workspace",
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// Three Horizons specific
"threehorizons.developerHub.url": "https://devhub.threehorizons.ai",
"threehorizons.ai.model": "gpt-4",
"threehorizons.telemetry.enabled": true,
// Productivity
"editor.suggestSelection": "first",
"editor.snippetSuggestions": "top",
"editor.tabCompletion": "on",
"terminal.integrated.enableMultiLinePasteWarning": false,
// Security
"git.enableSmartCommit": true,
"git.confirmSync": false,
"gitlens.advanced.messages": {
"suppressCommitHasNoPreviousCommitWarning": true
}
}Navigate to Developer Hub and follow these steps:
// Example: Creating a microservice
const steps = {
1: "Click 'Create Component' in Developer Hub",
2: "Select 'Microservice Template'",
3: "Fill in service details",
4: "Choose your tech stack",
5: "Review and create"
};# template-inputs.yaml
apiVersion: scaffolder.backstage.io/v1beta3
kind: Template
metadata:
name: microservice-template
title: Microservice
description: Create a production-ready microservice
spec:
owner: platform-team
type: service
parameters:
- title: Service Details
properties:
name:
title: Name
type: string
description: Unique name for your service
pattern: '^[a-z0-9-]+$'
maxLength: 63
description:
title: Description
type: string
owner:
title: Team
type: string
ui:field: OwnerPicker
- title: Technology
properties:
language:
title: Programming Language
type: string
enum:
- go
- nodejs
- python
- java
default: go
database:
title: Database
type: string
enum:
- postgresql
- mysql
- mongodb
- none
default: postgresql
- title: Features
properties:
features:
title: Enable Features
type: array
items:
type: string
enum:
- api
- grpc
- messaging
- caching
- authentication
default:
- api
- authentication# Your service will have this structure:
my-service/
βββ .github/
β βββ workflows/
β βββ ci.yml # Automated CI pipeline
β βββ security.yml # Security scanning
β βββ deploy.yml # GitOps deployment
βββ src/
β βββ main.go # Application entry point
β βββ handlers/ # HTTP/gRPC handlers
β βββ services/ # Business logic
β βββ models/ # Data models
βββ tests/
β βββ unit/ # Unit tests
β βββ integration/ # Integration tests
β βββ e2e/ # End-to-end tests
βββ k8s/
β βββ base/ # Base Kubernetes manifests
β βββ overlays/ # Environment-specific configs
βββ docs/
β βββ README.md # Service documentation
β βββ API.md # API documentation
β βββ ARCHITECTURE.md # Architecture decisions
βββ Dockerfile # Multi-stage container build
βββ Makefile # Common development tasks
βββ .gitignore # Git ignore rules
βββ catalog-info.yaml # Developer Hub metadata// src/handlers/hello.go - Your first endpoint
package handlers
import (
"encoding/json"
"net/http"
"github.com/threehorizons/my-service/pkg/telemetry"
"go.opentelemetry.io/otel/attribute"
)
// HelloHandler returns a personalized greeting
// GitHub Copilot will help you complete this!
func HelloHandler(w http.ResponseWriter, r *http.Request) {
ctx, span := telemetry.Tracer.Start(r.Context(), "HelloHandler")
defer span.End()
// Extract name from query params
name := r.URL.Query().Get("name")
if name == "" {
name = "World"
}
// Add telemetry
span.SetAttributes(attribute.String("user.name", name))
// Create response
response := map[string]interface{}{
"message": fmt.Sprintf("Hello, %s! Welcome to Three Horizons.", name),
"timestamp": time.Now().UTC(),
"version": os.Getenv("VERSION"),
}
// Return JSON response
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}// copilot-examples.ts
// 1. Clear comments help Copilot understand intent
// Function to validate email addresses using regex
export function validateEmail(email: string): boolean {
// Copilot will suggest the regex pattern
}
// 2. Use descriptive function names
// Calculate the compound annual growth rate between two values over n years
export function calculateCAGR(initialValue: number, finalValue: number, years: number): number {
// Copilot will provide the formula
}
// 3. Provide examples in comments
// Parse CSV data into objects
// Example input: "name,age,city\nJohn,30,NYC\nJane,25,LA"
// Example output: [{name: "John", age: 30, city: "NYC"}, ...]
export function parseCSV(csvData: string): any[] {
// Copilot will implement the parser
}
// 4. Leverage Copilot for tests
describe('UserService', () => {
// Test that createUser validates required fields
it('should validate required fields when creating a user', async () => {
// Copilot will generate comprehensive test cases
});
});# .github/copilot-review.yml
name: AI Code Review Settings
review:
# What Copilot should focus on
focus_areas:
- security
- performance
- best_practices
- documentation
# Custom instructions
instructions: |
- Follow Three Horizons coding standards
- Ensure proper error handling
- Check for security vulnerabilities
- Verify test coverage
- Validate API contracts
# Severity levels
severity_threshold: medium
# Auto-fix simple issues
auto_fix:
enabled: true
types:
- formatting
- imports
- simple_refactoring# Example Copilot Chat commands in VS Code
# Explain code
/explain What does this function do?
# Generate tests
/tests Generate unit tests for the UserService class
# Fix issues
/fix This function is throwing a null pointer exception
# Optimize code
/optimize Make this query more efficient
# Security review
/security Check this code for vulnerabilities
# Documentation
/doc Generate API documentation for this endpoint// debugging-with-ai.ts
// When you encounter an error, Copilot can help debug
export class DebugExample {
async processOrder(orderId: string) {
try {
// Your code here
const order = await this.getOrder(orderId);
const result = await this.validateOrder(order);
return result;
} catch (error) {
// Ask Copilot: "Why might this error occur and how to fix it?"
// Copilot will analyze the code and suggest solutions
console.error('Order processing failed:', error);
// Copilot suggestion: Add specific error handling
if (error.code === 'ORDER_NOT_FOUND') {
throw new NotFoundError(`Order ${orderId} not found`);
} else if (error.code === 'VALIDATION_FAILED') {
throw new ValidationError('Order validation failed', error.details);
}
// Log to monitoring system
this.logger.error('Unexpected error in processOrder', {
orderId,
error: error.message,
stack: error.stack
});
throw error;
}
}
}// tests/unit/service_test.go
package tests
import (
"testing"
"github.com/stretchr/testify/assert"
)
// Ask Copilot to generate test cases
func TestUserService(t *testing.T) {
// Test case: Create user with valid data
t.Run("CreateUser_ValidData_Success", func(t *testing.T) {
// Copilot will generate the test implementation
service := NewUserService()
user := &User{
Name: "John Doe",
Email: "john@example.com",
}
result, err := service.CreateUser(user)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.NotEmpty(t, result.ID)
assert.Equal(t, user.Name, result.Name)
})
// Copilot will suggest additional test cases:
// - Invalid email format
// - Duplicate email
// - Missing required fields
// - Database connection failure
}# .sonarqube.yml
sonar.projectKey=threehorizons:my-service
sonar.organization=threehorizons
# Quality Gates
sonar.qualitygate.wait=true
# Coverage requirements
sonar.coverage.minimumPct=80
sonar.coverage.exclusions=**/*_test.go,**/mocks/**
# Code quality rules
sonar.go.coverage.reportPaths=coverage.out
sonar.python.coverage.reportPaths=coverage.xml
sonar.javascript.lcov.reportPaths=coverage/lcov.info
# Security hotspots
sonar.security.hotspots.maxIssues=0
# Custom rules for Three Horizons
sonar.custom.rules=file://quality-rules.xml# .github/workflows/test.yml
name: Comprehensive Testing
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
test-type: [unit, integration, e2e, security, performance]
steps:
- uses: actions/checkout@v4
- name: Setup test environment
uses: ./.github/actions/setup-tests
- name: Run ${{ matrix.test-type }} tests
run: |
case "${{ matrix.test-type }}" in
unit)
make test-unit
;;
integration)
make test-integration
;;
e2e)
make test-e2e
;;
security)
make test-security
;;
performance)
make test-performance
;;
esac
- name: AI Test Analysis
if: always()
uses: threehorizons/ai-test-analyzer@v1
with:
test-results: ./test-results
coverage-report: ./coverage
- name: Upload results
uses: actions/upload-artifact@v4
with:
name: test-results-${{ matrix.test-type }}
path: test-results/// tests/performance/load-test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate } from 'k6/metrics';
// Custom metric
const errorRate = new Rate('errors');
export const options = {
stages: [
{ duration: '2m', target: 100 }, // Ramp up
{ duration: '5m', target: 100 }, // Stay at 100 users
{ duration: '2m', target: 0 }, // Ramp down
],
thresholds: {
'http_req_duration': ['p(95)<500'], // 95% of requests under 500ms
'errors': ['rate<0.1'], // Error rate under 10%
},
};
export default function () {
const response = http.get('https://api.threehorizons.ai/v1/users');
// Check response
const success = check(response, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
errorRate.add(!success);
sleep(1);
}# k8s/base/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-service
labels:
app: my-service
version: v1
spec:
replicas: 3
selector:
matchLabels:
app: my-service
template:
metadata:
labels:
app: my-service
version: v1
annotations:
# Prometheus scraping
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
# Istio sidecar
sidecar.istio.io/inject: "true"
spec:
serviceAccountName: my-service
containers:
- name: my-service
image: acrthreehorizons.azurecr.io/my-service:latest
ports:
- containerPort: 8080
name: http
- containerPort: 8081
name: grpc
env:
- name: ENVIRONMENT
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: VERSION
value: "{{ .Values.version }}"
- name: AI_ENABLED
value: "true"
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
securityContext:
runAsNonRoot: true
runAsUser: 1000
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL# k8s/overlays/production/canary.yaml
apiVersion: flagger.app/v1beta1
kind: Canary
metadata:
name: my-service
namespace: production
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: my-service
progressDeadlineSeconds: 300
service:
port: 8080
targetPort: 8080
gateways:
- public-gateway
hosts:
- my-service.threehorizons.ai
analysis:
interval: 30s
threshold: 5
maxWeight: 50
stepWeight: 10
metrics:
- name: request-success-rate
thresholdRange:
min: 99
interval: 1m
- name: request-duration
thresholdRange:
max: 500
interval: 30s
webhooks:
- name: ai-analysis
type: pre-rollout
url: http://deployment-agent:8080/analyze
- name: load-test
type: rollout
url: http://flagger-loadtester:8080/# Makefile - Common deployment tasks
# Variables
SERVICE_NAME := my-service
REGISTRY := acrthreehorizons.azurecr.io
VERSION := $(shell git describe --tags --always --dirty)
# Development deployment
.PHONY: deploy-dev
deploy-dev:
@echo "π Deploying to development..."
kubectl apply -k k8s/overlays/dev
kubectl rollout status deployment/$(SERVICE_NAME) -n dev
# Staging deployment
.PHONY: deploy-staging
deploy-staging: test
@echo "π Deploying to staging..."
kubectl apply -k k8s/overlays/staging
kubectl rollout status deployment/$(SERVICE_NAME) -n staging
@echo "π§ͺ Running smoke tests..."
./scripts/smoke-tests.sh staging
# Production deployment (GitOps)
.PHONY: deploy-prod
deploy-prod:
@echo "π Creating production deployment PR..."
./scripts/promote-to-prod.sh $(VERSION)
# Rollback
.PHONY: rollback
rollback:
@echo "π Rolling back deployment..."
kubectl rollout undo deployment/$(SERVICE_NAME) -n $(NAMESPACE)
kubectl rollout status deployment/$(SERVICE_NAME) -n $(NAMESPACE)
# View logs
.PHONY: logs
logs:
kubectl logs -f deployment/$(SERVICE_NAME) -n $(NAMESPACE) --tail=100
# Port forward for local debugging
.PHONY: port-forward
port-forward:
kubectl port-forward deployment/$(SERVICE_NAME) 8080:8080 -n $(NAMESPACE)// pkg/telemetry/telemetry.go
package telemetry
import (
"context"
"fmt"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/prometheus"
"go.opentelemetry.io/otel/exporters/jaeger"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
Tracer trace.Tracer
Meter metric.Meter
// Common metrics
RequestCount metric.Int64Counter
RequestDuration metric.Float64Histogram
ErrorCount metric.Int64Counter
)
func Initialize(serviceName string) error {
// Initialize tracer
tracerProvider, err := initTracer(serviceName)
if err != nil {
return fmt.Errorf("failed to initialize tracer: %w", err)
}
otel.SetTracerProvider(tracerProvider)
Tracer = otel.Tracer(serviceName)
// Initialize metrics
meterProvider, err := initMetrics()
if err != nil {
return fmt.Errorf("failed to initialize metrics: %w", err)
}
otel.SetMeterProvider(meterProvider)
Meter = otel.Meter(serviceName)
// Create common metrics
RequestCount, _ = Meter.Int64Counter("requests_total",
metric.WithDescription("Total number of requests"))
RequestDuration, _ = Meter.Float64Histogram("request_duration_seconds",
metric.WithDescription("Request duration in seconds"))
ErrorCount, _ = Meter.Int64Counter("errors_total",
metric.WithDescription("Total number of errors"))
return nil
}
// Middleware for automatic instrumentation
func HTTPMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, span := Tracer.Start(r.Context(), r.URL.Path)
defer span.End()
start := time.Now()
wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(wrapped, r.WithContext(ctx))
duration := time.Since(start).Seconds()
// Record metrics
RequestCount.Add(ctx, 1,
metric.WithAttributes(
attribute.String("method", r.Method),
attribute.String("path", r.URL.Path),
attribute.Int("status", wrapped.statusCode),
))
RequestDuration.Record(ctx, duration,
metric.WithAttributes(
attribute.String("method", r.Method),
attribute.String("path", r.URL.Path),
))
if wrapped.statusCode >= 400 {
ErrorCount.Add(ctx, 1,
metric.WithAttributes(
attribute.Int("status", wrapped.statusCode),
))
}
})
}// grafana/dashboards/my-service.json
{
"dashboard": {
"title": "My Service Dashboard",
"panels": [
{
"title": "Request Rate",
"targets": [
{
"expr": "sum(rate(requests_total{service=\"my-service\"}[5m])) by (method)"
}
],
"type": "graph"
},
{
"title": "Error Rate",
"targets": [
{
"expr": "sum(rate(errors_total{service=\"my-service\"}[5m])) / sum(rate(requests_total{service=\"my-service\"}[5m]))"
}
],
"type": "singlestat",
"thresholds": "0.01,0.05",
"colors": ["green", "yellow", "red"]
},
{
"title": "P95 Latency",
"targets": [
{
"expr": "histogram_quantile(0.95, sum(rate(request_duration_seconds_bucket{service=\"my-service\"}[5m])) by (le))"
}
],
"type": "graph"
},
{
"title": "AI Assistance Metrics",
"targets": [
{
"expr": "sum(rate(ai_suggestions_accepted_total[5m])) / sum(rate(ai_suggestions_total[5m]))"
}
],
"type": "gauge",
"title": "AI Suggestion Acceptance Rate"
}
]
}
}#!/bin/bash
# scripts/debug-pod.sh
POD=$1
NAMESPACE=${2:-default}
echo "π Debugging pod: $POD in namespace: $NAMESPACE"
# Show pod details
echo "π Pod details:"
kubectl describe pod $POD -n $NAMESPACE
# Show recent logs
echo "π Recent logs:"
kubectl logs $POD -n $NAMESPACE --tail=50
# Check resource usage
echo "π Resource usage:"
kubectl top pod $POD -n $NAMESPACE
# Interactive debugging
echo "π§ Starting interactive debug session..."
echo "Available commands:"
echo " - logs: View real-time logs"
echo " - exec: Execute commands in pod"
echo " - port: Port forward to local"
echo " - events: Show pod events"
read -p "Select command: " cmd
case $cmd in
logs)
kubectl logs -f $POD -n $NAMESPACE
;;
exec)
kubectl exec -it $POD -n $NAMESPACE -- /bin/sh
;;
port)
read -p "Enter pod port: " pod_port
read -p "Enter local port: " local_port
kubectl port-forward $POD -n $NAMESPACE $local_port:$pod_port
;;
events)
kubectl get events -n $NAMESPACE --field-selector involvedObject.name=$POD
;;
esac// src/debugging/ai-debugger.ts
import { AIDebugger } from '@threehorizons/ai-debugger';
export class SmartDebugger {
private ai: AIDebugger;
constructor() {
this.ai = new AIDebugger({
apiKey: process.env.AI_API_KEY,
model: 'debug-assistant-v2'
});
}
async analyzeError(error: Error, context: any): Promise<DebugAnalysis> {
// Gather context
const debugContext = {
error: {
message: error.message,
stack: error.stack,
type: error.name
},
environment: process.env.NODE_ENV,
logs: await this.getRecentLogs(),
metrics: await this.getCurrentMetrics(),
context: context
};
// Get AI analysis
const analysis = await this.ai.analyze(debugContext);
return {
rootCause: analysis.rootCause,
suggestions: analysis.suggestions,
similarIssues: analysis.similarIssues,
fixCode: analysis.suggestedFix,
preventionTips: analysis.prevention
};
}
async suggestOptimization(performanceData: PerformanceData): Promise<Optimization[]> {
return await this.ai.optimizationSuggestions({
metrics: performanceData,
codeAnalysis: await this.analyzeCodeComplexity(),
dependencies: await this.analyzeDependencies()
});
}
}
// Usage
const debugger = new SmartDebugger();
app.use(async (err, req, res, next) => {
const analysis = await debugger.analyzeError(err, {
request: req.url,
method: req.method,
user: req.user
});
console.error('AI Debug Analysis:', analysis);
// In development, show detailed analysis
if (process.env.NODE_ENV === 'development') {
res.status(500).json({
error: err.message,
analysis: analysis
});
} else {
res.status(500).json({ error: 'Internal server error' });
}
});// standards/code-style.ts
/**
* Three Horizons Code Standards
*
* 1. Clear naming
* 2. Comprehensive error handling
* 3. Proper logging
* 4. Security by default
* 5. Performance awareness
*/
// β
Good: Clear, descriptive naming
export class UserAuthenticationService {
async authenticateUser(credentials: UserCredentials): Promise<AuthResult> {
// Implementation
}
}
// β Bad: Unclear naming
export class AuthSvc {
async auth(creds: any): Promise<any> {
// Implementation
}
}
// β
Good: Comprehensive error handling
export async function processPayment(payment: Payment): Promise<PaymentResult> {
try {
// Validate input
if (!payment.amount || payment.amount <= 0) {
throw new ValidationError('Invalid payment amount');
}
// Process payment
const result = await paymentGateway.process(payment);
// Log success
logger.info('Payment processed successfully', {
paymentId: result.id,
amount: payment.amount
});
return result;
} catch (error) {
// Log error with context
logger.error('Payment processing failed', {
error: error.message,
payment: payment.id,
stack: error.stack
});
// Rethrow with additional context
throw new PaymentError('Failed to process payment', { cause: error });
}
}
// β
Good: Security by default
export function createAPIKey(): string {
// Use cryptographically secure random
const key = crypto.randomBytes(32).toString('base64url');
// Hash for storage
const hashedKey = crypto
.createHash('sha256')
.update(key)
.digest('hex');
// Store only hash
database.save({ keyHash: hashedKey });
// Return key only once
return key;
}# .gitmessage - Commit message template
# <type>(<scope>): <subject>
#
# <body>
#
# <footer>
# Type: feat, fix, docs, style, refactor, test, chore
# Scope: component or file name
# Subject: imperative mood, don't capitalize, no period
# Example:
# feat(auth): add OAuth2 integration
#
# - Implemented Google OAuth2 provider
# - Added token refresh mechanism
# - Updated user model for OAuth data
#
# Closes #123# Service Documentation Template
## Overview
Brief description of what this service does and why it exists.
## Architecture
```mermaid
graph LR
A[Client] --> B[API Gateway]
B --> C[My Service]
C --> D[Database]
C --> E[Cache]Document all endpoints with examples.
POST /api/v1/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}List all environment variables and their purposes.
| Variable | Description | Default | Required |
|---|---|---|---|
| DATABASE_URL | PostgreSQL connection string | - | Yes |
| REDIS_URL | Redis connection string | localhost:6379 | No |
| LOG_LEVEL | Logging level | info | No |
Instructions for local development.
How to deploy this service.
Key metrics and where to find them.
Common issues and their solutions.
### 4. Security Checklist
```yaml
# security-checklist.yaml
security_requirements:
authentication:
- [ ] Use strong authentication (OAuth2/JWT)
- [ ] Implement proper session management
- [ ] Enable MFA for sensitive operations
authorization:
- [ ] Implement RBAC
- [ ] Follow principle of least privilege
- [ ] Validate all user inputs
data_protection:
- [ ] Encrypt sensitive data at rest
- [ ] Use TLS for all communications
- [ ] Implement proper key management
api_security:
- [ ] Rate limiting enabled
- [ ] Input validation on all endpoints
- [ ] CORS properly configured
dependencies:
- [ ] Regular dependency updates
- [ ] Security scanning in CI/CD
- [ ] No known vulnerabilities
monitoring:
- [ ] Security events logged
- [ ] Alerts for suspicious activity
- [ ] Regular security audits
-
Platform Documentation
-
AI Assistant Training
-
Technology Guides
-
Self-Service
# Search documentation devhub search "error handling" # Ask AI assistant devhub ai "How do I implement caching?" # View examples devhub examples list
-
Team Support
- Slack: #dev-support
- Office Hours: Tuesdays & Thursdays 2-4 PM
- Email: platform-support@threehorizons.ai
-
Emergency Support
- PagerDuty: platform-oncall
- Hotline: +1-555-PLATFORM
- Escalation: platform-leads@threehorizons.ai
# Development
make dev # Start local development
make test # Run all tests
make lint # Run linters
make build # Build application
# Deployment
make deploy-dev # Deploy to development
make deploy-staging # Deploy to staging
make promote-prod # Promote to production
# Debugging
make logs # View application logs
make debug # Start debug session
make port-forward # Forward ports locally
# Utilities
make clean # Clean build artifacts
make deps # Update dependencies
make security-scan # Run security scan
make perf-test # Run performance tests- Weekly Newsletter: Platform updates and tips
- Monthly Demos: New features and capabilities
- Quarterly Training: Deep dives into advanced topics
- Annual Conference: Three Horizons DevCon
-
Share Knowledge
- Write blog posts
- Create tutorials
- Share code snippets
-
Improve Platform
- Submit feature requests
- Report bugs
- Contribute to open source
-
Help Others
- Answer questions in Slack
- Mentor new developers
- Lead workshops
- Complete Onboarding: Finish all training modules
- Deploy First Service: Use the templates to create your service
- Explore AI Features: Try Copilot for complex tasks
- Join Community: Participate in Slack discussions
- Build Something Amazing: The platform is ready for you!
Welcome to Three Horizons! π
You're now equipped with everything needed to build amazing applications.