- Replace stub implementations with actual API calls
- POST /api/provision/orders/{order_id}/start
- POST /api/provision/orders/{order_id}/stop
- Add proper validation, logging, and error handling
- Follow existing code patterns (callProvisionAPI, __DIRECT__)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
P2-1: Tool selection fallback optimization
- Return only utility tools when no patterns match
- Reduces token usage by ~80% in fallback cases
P2-2: Minimum deposit amount validation
- Add MIN_DEPOSIT_AMOUNT = 1,000원
- Prevents spam with tiny deposits
P2-3: Standardize logging
- Replace console.log/error with structured logger
- bank-sms-parser.ts and security.ts
P2-4: Nameserver format validation
- Add validateNameservers() function
- Check minimum 2 NS, valid hostname format
- Clear error messages in Korean
P2-5: Optimistic lock error context
- Return specific error for version conflicts
- User-friendly message: "동시 요청으로 처리가 지연됨"
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
P1-1: Callback query error handling
- Add try-catch around domain registration and server order
- Send user-friendly error messages on failure
- Use answerCallbackQuery to acknowledge button clicks
- Add structured logging with createLogger
P1-2: Queue DLQ monitoring
- Add admin notification when server provisioning fails
- Update order status to 'failed' in database
- Include detailed context in notifications
- Apply rate limiting (1 notification per hour)
P1-3: Email handler error recovery
- Add admin notification when SMS parsing fails
- Include email preview in notifications
- Mask email addresses for privacy
- Add structured logging with emailLogger
Also add 'failed' status to ServerOrder type.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Enhance OpenAI message types with tool_calls support
- Improve security validation and rate limiting
- Update utility tools and weather tool
- Minor fixes in deposit-agent and domain-register
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add server-provision.ts for async server creation
- Add SERVER_PROVISION_QUEUE with DLQ for reliability
- Add cron job for auto-cleanup of pending orders (5min)
- Add server delete confirmation with inline keyboard
- Update types for server orders, images, and provisioning
- Add server tables to schema (server_orders, server_instances)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Fix USD price display: all prices now show in KRW (₩)
- Add Korea region auto-detection: extracts region preference from user messages
- Fix low-spec recommendation for high-performance requirements:
- Add extractTechStack() to detect PostgreSQL, Redis, MongoDB keywords
- Enhance inferExpectedUsers() to consider tech stack complexity
- SaaS/B2B services now recommend 4GB+ RAM servers
- Fix __DIRECT__ tag appearing in output:
- Reorder message concatenation in server-agent.ts
- Add stripping logic in conversation-service.ts and api.ts
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When user requests server recommendation while in an existing session
(e.g., selecting state), reset the session and start fresh instead of
continuing the old session context.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add response_format: { type: 'json_object' } for review mode to force JSON response
- Convert expectedDau and expectedConcurrent from string to number before API call
- Add enhanced KV session debugging with key names in logs
Fixes:
- AI returning plain text instead of JSON in review mode
- 400 error from recommend API due to string values in expected_users
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Previously cancellation only worked in 'selecting' or 'ordering' states.
Now users can cancel server consultation at any stage using keywords:
취소, 다시, 처음, 리셋, 초기화, 다시 시작, 처음부터
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add expectedDau and expectedConcurrent fields to ServerSession
- Update system prompts to explain DAU vs concurrent users concept
- AI now asks for clarification when users mention visitor counts
- Use concurrent users (5-10% of DAU) for server recommendations
- Update inference rules: personal=10, business=50 concurrent users
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Server Expert AI now reviews recommendation results before showing to user
- Changed flow: get recommendations first → AI reviews → show with comments
- AI provides specific advice based on actual recommended specs
- Reviews include: spec adequacy, bandwidth warnings, CDN suggestions
Before: AI gave generic advice without seeing recommendations
After: AI reviews actual results and gives contextual feedback
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add cancel logic for selecting/ordering states
- Keywords: 취소, 다시, 처음
- Delete session and return to normal conversation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add 'selecting' and 'ordering' status to ServerSession
- Add lastRecommendation field to store recommendation results
- Keep session alive after recommendation (don't delete immediately)
- Add selection pattern matching (1번, 첫번째, 1번 선택 등)
- Add order confirmation message with inline buttons
- Add server_order/server_cancel callback handlers
- Add ServerOrderKeyboardData type for button data
Flow: recommend → select number → confirm with buttons → order/cancel
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add server-agent.ts with 30-year senior architect persona
- Implement KV-based session management for multi-turn conversations
- Add search_trends (Brave Search) and lookup_framework_docs (Context7) tools
- Function Calling support with max 3 tool calls per request
- Auto-infer tech stack and expected users from use case/scale
- Prohibit competitor provider mentions (AWS, GCP, Azure, etc.)
- Simplify main AI system prompt, delegate complex logic to expert AI
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Remove Queue-based server provisioning (moved to cloud-orchestrator)
- Add manage_server tool with Service Binding to Cloud Orchestrator
- Add CDN cache hit rate estimation based on tech_stack
- Always display bandwidth info (show "포함 범위 내" when no overage)
- Add language auto-detection (ko, ja, zh, en)
- Update system prompt to always call tools fresh
- Add Server System documentation to CLAUDE.md
BREAKING: Server provisioning now requires cloud-orchestrator service
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add telegram-cli Worker with web chat UI for browser-based bot testing
- Add POST /api/chat authenticated endpoint (Bearer token, production enabled)
- Fix ENVIRONMENT to production in wrangler.toml (was blocking Service Binding)
- Add Service Binding (BOT_WORKER) for Worker-to-Worker communication
- Add cloud-db-schema.sql for local development
telegram-cli features:
- Web UI at GET / with dark theme
- JSON API at POST /api/chat
- Service Binding to telegram-summary-bot Worker
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Update CLAUDE.md with server provisioning docs
- Add server tables to schema.sql (cloud_providers, instance_specs, etc.)
- Register manage_server tool in tools/index.ts
- Minor fixes to conversation-service and summary-service
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add server recommendation integration (SERVER_RECOMMEND worker)
- Implement KV-based session management for multi-step ordering
- Add Linode/Vultr API clients for server provisioning
- Add server-tool for Function Calling support
refactor: major code reorganization (Phase 1-3)
- Remove 443 lines of deprecated callback handlers
- Extract handlers to separate files (message-handler, callback-handler)
- Extract cloud-spec-service, server-recommend-service
- Centralize constants (OS_IMAGES, REGION_FLAGS, NUM_EMOJIS)
- webhook.ts reduced from 1,951 to 30 lines
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Security:
- Add token+secret auth to /setup-webhook and /webhook-info endpoints
- Disable /api/test in production environment (ENVIRONMENT=production)
Performance:
- Add retryWithBackoff to weather-tool (maxRetries: 2)
- Add KV caching to executeLookupDocs (1h TTL)
Code Quality:
- Centralize error messages in src/constants/messages.ts
- Update 5 files to use centralized error constants
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Apply optimistic locking to deposit-matcher.ts (race condition fix)
- Add timing-safe comparison for API key validation
- Move admin IDs from wrangler.toml vars to secrets
- Add .env.example for secure credential management
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
DRY Improvements (api.ts):
- Extract requireApiKey() helper for API authentication
- Extract getCorsHeaders() helper for CORS header generation
- Eliminate ~20 lines of duplicated code
Type Safety (new utils/error.ts):
- Add toError() utility for safe error type conversion
- Replace all 6 `error as Error` assertions with toError()
- Proper handling of Error, string, and unknown types
Error Handling (api.ts):
- Add explicit JSON parsing error handling to all POST endpoints
- Return 400 Bad Request for malformed JSON
- Clearer error messages for API consumers
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Security (P1):
- Add optimistic locking to /api/deposit/deduct endpoint
- Prevent race conditions on concurrent balance deductions
- Return 409 Conflict on version mismatch with retry hint
Type Safety (P1):
- Add WttrResponse, WttrCurrentCondition, WttrWeatherDay types
- Remove `as any` from weather-tool.ts
- Add safety checks for malformed API responses
Both P1 issues from security review resolved.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add WorkersAIModel, WorkersAITextGenerationInput/Output types
- Remove `as any` from summary-service.ts (4 instances)
- Remove `as any` from bank-sms-parser.ts (3 instances)
- Remove `as any` from n8n-service.ts (2 instances)
- Add OpenAIResponse interface for API responses
Type-safe Workers AI calls with full IntelliSense support.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Type Safety Improvements:
- Add isErrorResult() type guard for API responses (domain-tool.ts)
- Replace `any` with `unknown` in executeTool args (tools/index.ts)
- Add JSON.parse error handling in function calling (openai-service.ts)
- Fix nullable price handling with nullish coalescing
- Add array type guard for nameservers validation
Code Quality Improvements:
- Extract convertNamecheapDate() to eliminate duplicate functions
- Move hardcoded bank account info to environment variables
- Add JSDoc documentation to executeDepositFunction
- Fix unused variables in optimistic-lock.ts
- Handle Error.captureStackTrace for Workers environment
All TypeScript strict mode checks now pass.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Implement optimistic locking for deposit balance updates
- Prevent race conditions in concurrent deposit requests
- Add automatic retry with exponential backoff (max 3 attempts)
- Add version column to user_deposits table
- Improve type safety across codebase
- Add explicit types for Namecheap API responses
- Add typed function arguments (ManageDepositArgs, etc.)
- Remove `any` types from deposit-agent and tool files
- Add reconciliation job for balance integrity verification
- Compare user_deposits.balance vs SUM(confirmed transactions)
- Alert admin on discrepancy detection
- Set up test environment with Vitest + Miniflare
- Add 50+ test cases for deposit system
- Add helper functions for test data creation
- Update documentation
- Add migration guide for version columns
- Document optimistic locking patterns
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Phase 5-3 모니터링 강화 작업의 통합을 완료했습니다.
변경사항:
- Logger 통합: console.log를 구조화된 로깅으로 전환 (9개 파일)
- JSON 기반 로그, 환경별 자동 전환 (개발/프로덕션)
- 타입 안전성 보장, 성능 측정 타이머 내장
- Metrics 통합: 실시간 성능 모니터링 시스템 연결 (3개 파일)
- Circuit Breaker 상태 추적 (api_call_count, error_count, state)
- Retry 재시도 횟수 추적 (retry_count)
- OpenAI API 응답 시간 측정 (api_call_duration)
- 알림 통합: 장애 자동 알림 시스템 구현 (2개 파일)
- Circuit Breaker OPEN 상태 → 관리자 Telegram 알림
- 재시도 실패 → 관리자 Telegram 알림
- Rate Limiting 적용 (1시간에 1회)
- 문서 업데이트:
- CLAUDE.md: coder 에이전트 설명 강화 (20년+ 시니어 전문가)
- README.md, docs/: 아키텍처 문서 추가
영향받은 파일: 16개 (수정 14개, 신규 2개)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- 도메인 조회(info): 내 도메인 아니면 자동으로 WHOIS 조회 (naver.com 등 지원)
- SMS 파싱: 정규식 실패 시 AI 폴백 로직 추가
- 리팩토링: UserService, ConversationService 분리
- 문서: README.md 및 CODE_REVIEW.md 업데이트
성능 개선:
- Namecheap API 호출 30-80% 감소
- 캐시 히트 시 응답 속도 ~100ms (API 대비 5-8배 향상)
- 비용 절감 효과
캐싱 전략:
- 단일 TLD 가격: "tld_price:{tld}" (예: tld_price:com)
- 전체 TLD 가격: "tld_price:all"
- TTL: 3600초 (1시간) - 가격 변동 주기 고려
구현 상세:
- 4개 헬퍼 함수 추가
- getCachedTLDPrice(): 단일 TLD 캐시 조회
- setCachedTLDPrice(): 단일 TLD 캐시 저장
- getCachedAllPrices(): 전체 TLD 캐시 조회
- setCachedAllPrices(): 전체 TLD 캐시 저장
- 캐싱 적용 함수
- executeDomainAction('price'): 단일 TLD 가격
- executeDomainAction('cheapest'): 전체 TLD 목록
- executeDomainAction('check'): 도메인 가용성 + 가격
- executeSuggestDomains(): 도메인 추천 시 가격
에러 핸들링:
- KV 오류 시 API 직접 호출로 폴백
- 서비스 가용성 우선, 캐시는 성능 향상 수단
로깅:
- [TLDCache] HIT/MISS/SET 로그로 성능 모니터링
바인딩:
- 기존 RATE_LIMIT_KV 재사용 (추가 설정 불필요)
테스트:
- .com 가격 조회 (캐시 MISS → HIT)
- 전체 TLD 목록 (캐시 MISS → HIT)
- 도메인 추천 (캐시된 가격 활용)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
보안 개선:
- API 키 하드코딩 제거 (NAMECHEAP_API_KEY_INTERNAL)
- CORS 정책: * → hosting.anvil.it.com 제한
- /health 엔드포인트 DB 정보 노출 방지
- Rate Limiting 인메모리 Map → Cloudflare KV 전환
- 분산 환경 일관성 보장
- 재시작 후에도 유지
- 자동 만료 (TTL)
문서:
- CLAUDE.md Security 섹션 추가
- KV Namespace 설정 가이드 추가
- 배포/마이그레이션 가이드 추가
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
은행 SMS는 입금자명을 7글자까지만 표시하므로,
매칭 시 SUBSTR(depositor_name, 1, 7)로 비교하도록 수정
- deposit-agent.ts: 사용자 입력 → bank_notifications 검색
- index.ts: SMS 수신 → deposit_transactions 검색
- CLAUDE.md: 매칭 로직 문서화
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- getOrCreateUser를 별도 try-catch로 감싸서 DB 오류 시 에러 메시지 전송
- 전체 메시지 처리 로직을 try-catch로 감싸서 모든 오류에 대해 사용자 응답 보장
- 기존: DB 오류 발생 시 webhook handler catch → 500 반환 (사용자 무응답)
- 변경: 오류 발생 시에도 "일시적인 오류" 메시지 전송
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- 웹페이지를 Excalidraw 스타일 손그림 디자인으로 전면 리디자인
- 라이트 모드 + 크림색 배경 + 격자 패턴
- 손글씨 폰트 (제목: Caveat, 본문: Noto Sans KR)
- 스케치 스타일 카드, 버튼, 스티커 노트 컴포넌트
- 문의 폼 추가 (이메일 + 메시지)
- /api/contact 엔드포인트 추가 (텔레그램 알림 연동)
- 이메일 실시간 유효성 검사
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- 도메인 등록 인라인 버튼 확인 플로우 (domain-register.ts)
- manage_domain에 cheapest action 추가 (가장 저렴한 TLD TOP 15)
- 24시간 경과 입금 대기 자동 취소 Cron (UTC 15:00)
- 거래 내역 한글 라벨 + description 표시
- CLAUDE.md 문서 업데이트
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Email Routing에서 수신한 이메일 파싱 수정
- Quoted-Printable UTF-8 디코딩 함수 추가
- HTML <br/> 태그를 줄바꿈으로 변환
- SMS 키워드 위치 기반 본문 추출
- 레거시 코드 삭제
- /api/bank-notification 엔드포인트 제거 (Email Routing으로 대체)
- BANK_API_SECRET 관련 코드 및 문서 제거
- DEPOSIT_AGENT_ID 제거 (Assistants API → 코드 직접 처리)
- CLI 테스트 클라이언트 개선
- .env 파일 자동 로드 지원
- WEBHOOK_SECRET 환경변수 불필요
- 문서 업데이트
- NAMECHEAP_API_KEY 설명 명확화 (래퍼 인증 키)
- CLI 테스트 섹션 추가
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Replace OpenAI Assistants API with direct function calling (AI Gateway)
- Add action-based parameters to manage_deposit tool (like manage_domain)
- Export executeDepositFunction for direct use in openai-service.ts
- Add formatDepositResult function for consistent response formatting
- Remove DEPOSIT_AGENT_ID dependency (no longer needed)
- Update CLAUDE.md documentation
Benefits:
- Bypasses regional restrictions via AI Gateway
- 100% consistent response formatting
- No Assistants API costs
- Faster execution (no thread creation)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>