Appearance
Cloudflare Migration Plan V2
Executive Summary
Full migration from Bun/SQLite to Cloudflare Workers platform using parallel subagent execution on a single feature branch (cloudflare-sandbox-refactor). Timeline: 8-10 weeks with aggressive parallelization and automated service deployment via cloudflare-manager skill.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Parallel Execution Strategy │
├─────────────────────────────────────────────────────────────┤
│ Stage 1: Foundation (Week 1) │
│ ├─ [Agent: typescript-type-system-specialist] │
│ ├─ [Agent: file-creator] │
│ └─ [Skill: cloudflare-manager] → Infrastructure Setup │
├─────────────────────────────────────────────────────────────┤
│ Stage 2: Parallel Core Development (Weeks 2-4) │
│ ├─ Track A: Database Layer [Agent: dependency-analyzer] │
│ ├─ Track B: Worker Services [Agent: swift-macos-expert] │
│ ├─ Track C: Frontend Adapt [Agent: react-to-web-components]│
│ └─ Track D: Testing Suite [Agent: playwright-test-architect]│
├─────────────────────────────────────────────────────────────┤
│ Stage 3: Integration & Optimization (Weeks 5-6) │
│ ├─ [Agent: qa-gate-validator] │
│ └─ [Agent: test-runner] │
├─────────────────────────────────────────────────────────────┤
│ Stage 4: Deployment & Cutover (Weeks 7-8) │
│ ├─ [Agent: git-workflow-manager] │
│ └─ [Skill: cloudflare-manager] → Production Deploy │
└─────────────────────────────────────────────────────────────┘Stage 1: Foundation & Infrastructure (Week 1)
1.1 Project Structure Setup
Subagents: file-creator, typescript-type-system-specialistCan Run In Parallel: YES - All foundation tasks
bash
# Parallel Task Set 1A - Directory Structure
packages/
├── cloudflare-shared/ # Shared utilities, types, adapters
├── cloudflare-workers/ # All Worker implementations
│ ├── auth-worker/
│ ├── task-worker/
│ ├── github-worker/
│ ├── agent-worker/
│ ├── api-gateway/
│ └── websocket-worker/
├── cloudflare-durable/ # Durable Object classes
└── cloudflare-migrations/ # D1 migration scripts1.2 Cloudflare Infrastructure Deployment
Skill: cloudflare-managerExecution: Immediate, parallel with structure setup
bash
# AUTOMATED DEPLOYMENT via cloudflare-manager skill
# This will be executed by the skill to create ALL required services
# Phase 1: Storage Infrastructure
- D1 Database: monotask-production
- KV Namespaces: sessions, cache, rate-limits, feature-flags, api-keys
- R2 Buckets: evidence-storage, screenshots, agent-artifacts
- Queues: task-processing, agent-execution, github-sync
# Phase 2: Worker Skeleton Deployment
- Deploy placeholder workers for all services
- Configure routes and bindings
- Set up environment variables
# Phase 3: Durable Objects Registration
- WebSocketRoom for real-time updates
- TaskCoordinator for state machine
- QueueManager for job processing
- SandboxLifecycle for container management1.3 DatabaseAdapter Interface Implementation
Subagent: typescript-type-system-specialistDependencies: None Parallel: YES
typescript
// Key deliverable: Dual-mode database adapter
interface DatabaseAdapter {
query<T>(sql: string, params?: any[]): Promise<T[]>;
execute(sql: string, params?: any[]): Promise<void>;
transaction<T>(fn: () => Promise<T>): Promise<T>;
batch(operations: Operation[]): Promise<void>;
}Stage 2: Parallel Core Development (Weeks 2-4)
Track A: Database Layer Conversion
Lead Agent: dependency-analyzerSupport Agents: typescript-type-system-specialist, test-runnerDependencies: DatabaseAdapter interface from Stage 1 Can Run In Parallel: YES with Tracks B, C, D
Tasks (All Async Conversion):
typescript
// Repositories to convert (15+ total)
- TaskRepository → TaskRepositoryAsync
- ProjectRepository → ProjectRepositoryAsync
- AgentRepository → AgentRepositoryAsync
- ValidationRepository → ValidationRepositoryAsync
- GitHubRepository → GitHubRepositoryAsync
- [... all other repositories]
// Migration Scripts
- SQLite → D1 schema conversion
- Event sourcing implementation
- Materialized view creation
- Index optimizationTrack B: Worker Services Implementation
Lead Agent: azure-devops-specialistSupport Agents: typescript-type-system-specialist, context-fetcherDependencies: DatabaseAdapter from Stage 1 Can Run In Parallel: YES with Tracks A, C, D
Worker Implementation Matrix:
| Worker | Priority | Dependencies | Subagent |
|---|---|---|---|
| auth-worker | P0 | KV, D1 | typescript-type-system-specialist |
| api-gateway | P0 | All workers | azure-devops-specialist |
| task-worker | P1 | D1, DurableObjects | task-orchestrator |
| github-worker | P1 | D1, Queues | git-workflow-manager |
| agent-worker | P2 | D1, Queues, R2 | prompt-engineer |
| websocket-worker | P2 | DurableObjects | typescript-type-system-specialist |
Track C: Frontend Adaptation
Lead Agent: react-developerSupport Agents: typescript-react-test-writer, ui-redesign-specialistDependencies: API contract from Track B (can mock initially) Can Run In Parallel: YES with Tracks A, B, D
Frontend Tasks:
javascript
// Conversion Tasks
1. API endpoint migration to Worker URLs
2. WebSocket client for Durable Objects
3. Sandbox management UI components
4. Authentication flow updates
5. Real-time update handlers
6. Error boundary updates
7. Performance optimizationsTrack D: Comprehensive Testing Suite
Lead Agent: playwright-test-architectSupport Agents: qa-gate-validator, test-runnerDependencies: None (can create tests in parallel) Can Run In Parallel: YES with Tracks A, B, C
Test Coverage Requirements:
typescript
// Unit Tests (Vitest)
- DatabaseAdapter implementations
- Repository async methods
- Worker request handlers
- Durable Object state machines
// Integration Tests
- D1 database operations
- KV/R2 storage operations
- Queue processing
- Worker-to-worker communication
// E2E Tests (Playwright)
- Complete task lifecycle
- GitHub integration flow
- Real-time updates
- Sandbox executionStage 3: Integration & Queue Implementation (Weeks 5-6)
3.1 Queue & Background Processing
Lead Agent: task-orchestratorDependencies: Workers from Track B Parallel Execution: Within queue types
typescript
// Queue Implementations
interface QueueConfig {
taskProcessing: {
handler: TaskQueueHandler;
maxBatchSize: 100;
maxRetries: 3;
};
agentExecution: {
handler: AgentQueueHandler;
maxBatchSize: 10;
maxRetries: 5;
};
githubSync: {
handler: GitHubSyncHandler;
maxBatchSize: 50;
maxRetries: 3;
};
}3.2 Sandbox Integration
Lead Agent: azure-devops-specialistSupport Agent: qa-gate-validatorDependencies: Agent Worker, Queue system
typescript
// Sandbox Lifecycle Management
class SandboxLifecycle extends DurableObject {
async provision(spec: SandboxSpec): Promise<Container>;
async execute(code: string, timeout: number): Promise<Result>;
async cleanup(): Promise<void>;
async monitor(): Promise<Metrics>;
}Stage 4: Testing & Validation (Weeks 6-7)
Parallel Testing Strategy
Orchestrator: qa-gate-validatorExecution: All test suites run in parallel
bash
# Parallel Test Execution Plan
├─ Performance Testing [Agent: test-runner]
│ ├─ Load testing (k6)
│ ├─ Latency benchmarks
│ └─ Cold start analysis
├─ Security Testing [Agent: qa-gate-validator]
│ ├─ JWT validation
│ ├─ Rate limiting
│ └─ CORS verification
├─ Integration Testing [Agent: playwright-test-architect]
│ ├─ End-to-end workflows
│ ├─ Cross-worker communication
│ └─ Database consistency
└─ Regression Testing [Agent: typescript-react-test-writer]
├─ API compatibility
├─ Frontend functionality
└─ State managementStage 5: Deployment & Migration (Weeks 7-8)
5.1 Staged Rollout Plan
Lead Agent: git-workflow-managerSupport: cloudflare-manager skill
yaml
# Deployment Phases
phase1_shadow:
duration: 48 hours
traffic: 0%
mode: dual-write
rollback: immediate
phase2_canary:
duration: 72 hours
traffic: 10%
mode: dual-write
rollback: dns-switch
phase3_rollout:
duration: 5 days
traffic: 50%
mode: read-cloudflare-write-both
rollback: traffic-split
phase4_cutover:
duration: permanent
traffic: 100%
mode: cloudflare-only
rollback: data-export5.2 Data Migration Strategy
Agent: task-orchestratorParallel Execution: By data type
sql
-- Parallel Migration Streams
Stream 1: Core Data (tasks, projects, users)
Stream 2: Transactional Data (validations, executions)
Stream 3: Binary Data (screenshots, artifacts)
Stream 4: Metrics & Logs (events, analytics)Dependency Graph & Critical Path
Subagent Deployment Strategy
Continuous Agent Deployment
typescript
type AgentDeployment = {
stage: number;
agents: {
primary: string;
support: string[];
parallel: boolean;
}[];
};
const deploymentPlan: AgentDeployment[] = [
{
stage: 1,
agents: [
{
primary: "file-creator",
support: ["typescript-type-system-specialist"],
parallel: true,
},
],
},
{
stage: 2,
agents: [
{
primary: "dependency-analyzer",
support: ["test-runner"],
parallel: true,
},
{
primary: "azure-devops-specialist",
support: ["context-fetcher"],
parallel: true,
},
{
primary: "react-to-web-components-converter",
support: ["ui-redesign-specialist"],
parallel: true,
},
{
primary: "playwright-test-architect",
support: ["qa-gate-validator"],
parallel: true,
},
],
},
];Cloudflare Manager Skill Integration
Automated Service Generation
The cloudflare-manager skill will be invoked at two critical points:
Initial Infrastructure Setup (Week 1)
bash
# Invoke cloudflare-manager skill for complete infrastructure setup
Skill: cloudflare-manager
Task: "Create complete Cloudflare infrastructure for MonoTask migration"
Config: {
databases: ["monotask-production"],
kvNamespaces: ["sessions", "cache", "rate-limits", "feature-flags", "api-keys"],
r2Buckets: ["evidence-storage", "screenshots", "agent-artifacts"],
queues: ["task-processing", "agent-execution", "github-sync"],
workers: ["auth", "task", "github", "agent", "api-gateway", "websocket"],
durableObjects: ["WebSocketRoom", "TaskCoordinator", "QueueManager", "SandboxLifecycle"],
pages: ["monotask-frontend"],
environment: "production"
}Production Deployment (Week 8)
bash
# Invoke cloudflare-manager skill for production deployment
Skill: cloudflare-manager
Task: "Deploy all services to Cloudflare production"
Config: {
deployWorkers: true,
configureDNS: true,
setupRoutes: true,
enableAnalytics: true,
configureRateLimiting: true,
setupFailover: true
}Success Metrics & KPIs
Performance Targets
| Metric | Current (Bun/SQLite) | Target (Cloudflare) | Measurement |
|---|---|---|---|
| API p95 Latency | 150ms | <100ms | Cloudflare Analytics |
| DB Query p95 | 20ms | <10ms | D1 Metrics |
| WebSocket Broadcast | 100ms | <50ms | Custom Metrics |
| Cold Start | N/A | <50ms | Worker Analytics |
| Availability | 99.5% | 99.9% | Uptime Monitoring |
Cost Targets
yaml
monthly_budget:
infrastructure: $25
breakdown:
workers: $5
d1_database: $5
kv_storage: $5
r2_storage: $5
durable_objects: $5
cost_optimization:
- KV caching for D1 reads
- Request coalescing
- Edge caching
- Batch operationsRisk Mitigation Matrix
| Risk | Probability | Impact | Mitigation | Owner |
|---|---|---|---|---|
| D1 Performance Issues | Medium | High | Dual-write mode, KV caching | Track A |
| Worker Cold Starts | High | Medium | Keep-alive pings, bundling | Track B |
| Migration Data Loss | Low | Critical | Incremental backup, validation | Track A |
| API Breaking Changes | Medium | High | Versioned endpoints, deprecation | Track B |
| Cost Overrun | Low | Medium | Usage monitoring, alerts | All |
Rollback Procedures
Component-Level Rollback
typescript
interface RollbackStrategy {
trigger: "error-rate" | "latency" | "manual";
threshold: number;
procedure: "dns-switch" | "traffic-split" | "dual-write-disable";
duration: number; // minutes to complete rollback
}
const rollbackPlan: Record<string, RollbackStrategy> = {
api: {
trigger: "error-rate",
threshold: 5,
procedure: "dns-switch",
duration: 5,
},
database: {
trigger: "latency",
threshold: 100,
procedure: "dual-write-disable",
duration: 10,
},
frontend: {
trigger: "manual",
threshold: 0,
procedure: "traffic-split",
duration: 2,
},
};Communication & Coordination
Daily Sync Points
yaml
morning_sync:
time: "09:00 UTC"
duration: 15min
topics:
- Parallel task progress
- Blocker identification
- API contract changes
- Test results
evening_checkpoint:
time: "17:00 UTC"
duration: 10min
topics:
- Completed tasks
- Next day priorities
- Risk updatesWeekly Milestones
- Monday: Deploy to staging
- Wednesday: Integration testing
- Friday: Performance review & go/no-go decision
Next Immediate Actions
Hour 1-2: Setup
- ✅ Ensure on
cloudflare-sandbox-refactorbranch - ✅ Configure Cloudflare API credentials in
.env - ✅ Invoke
cloudflare-managerskill for infrastructure setup
Hour 3-8: Foundation (Parallel Execution)
bash
# Launch all Stage 1 agents in parallel
Task 1: file-creator → Create directory structure
Task 2: typescript-type-system-specialist → DatabaseAdapter interface
Task 3: cloudflare-manager → Deploy infrastructure
Task 4: dependency-analyzer → Map repository dependenciesDay 2: Begin Core Development
bash
# Launch all Stage 2 track agents in parallel
Track A: dependency-analyzer → Async repository conversion
Track B: azure-devops-specialist → Worker implementation
Track C: react-to-web-components-converter → Frontend adaptation
Track D: playwright-test-architect → Test suite creationDocument Version: 2.0 Status: Ready for Parallel Execution Execution Model: Single Feature Branch with Parallel Subagents Primary Skill: cloudflare-manager Estimated Timeline: 8 weeks (40% reduction from v1) Next Review: Daily progress checkpoints