codeframe-ai 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. codeframe/__init__.py +11 -0
  2. codeframe/__main__.py +20 -0
  3. codeframe/adapters/__init__.py +5 -0
  4. codeframe/adapters/e2b/__init__.py +13 -0
  5. codeframe/adapters/e2b/adapter.py +342 -0
  6. codeframe/adapters/e2b/budget.py +71 -0
  7. codeframe/adapters/e2b/credential_scanner.py +134 -0
  8. codeframe/adapters/llm/__init__.py +92 -0
  9. codeframe/adapters/llm/anthropic.py +414 -0
  10. codeframe/adapters/llm/base.py +444 -0
  11. codeframe/adapters/llm/mock.py +281 -0
  12. codeframe/adapters/llm/openai.py +483 -0
  13. codeframe/agents/__init__.py +8 -0
  14. codeframe/agents/dependency_resolver.py +714 -0
  15. codeframe/auth/__init__.py +16 -0
  16. codeframe/auth/api_key_router.py +238 -0
  17. codeframe/auth/api_keys.py +156 -0
  18. codeframe/auth/dependencies.py +358 -0
  19. codeframe/auth/manager.py +178 -0
  20. codeframe/auth/models.py +30 -0
  21. codeframe/auth/router.py +93 -0
  22. codeframe/auth/schemas.py +15 -0
  23. codeframe/auth/scopes.py +53 -0
  24. codeframe/cli/__init__.py +12 -0
  25. codeframe/cli/__main__.py +20 -0
  26. codeframe/cli/api_client.py +275 -0
  27. codeframe/cli/app.py +5688 -0
  28. codeframe/cli/auth.py +122 -0
  29. codeframe/cli/auth_commands.py +958 -0
  30. codeframe/cli/commands/__init__.py +5 -0
  31. codeframe/cli/config_commands.py +79 -0
  32. codeframe/cli/dashboard_commands.py +67 -0
  33. codeframe/cli/engines_commands.py +205 -0
  34. codeframe/cli/env_commands.py +409 -0
  35. codeframe/cli/helpers.py +56 -0
  36. codeframe/cli/hooks_commands.py +208 -0
  37. codeframe/cli/import_commands.py +129 -0
  38. codeframe/cli/pr_commands.py +549 -0
  39. codeframe/cli/proof_commands.py +415 -0
  40. codeframe/cli/stats_commands.py +311 -0
  41. codeframe/cli/telemetry_runtime.py +153 -0
  42. codeframe/cli/validators.py +123 -0
  43. codeframe/config/rate_limits.py +165 -0
  44. codeframe/core/__init__.py +15 -0
  45. codeframe/core/adapters/__init__.py +43 -0
  46. codeframe/core/adapters/agent_adapter.py +114 -0
  47. codeframe/core/adapters/builtin.py +326 -0
  48. codeframe/core/adapters/claude_code.py +62 -0
  49. codeframe/core/adapters/codex.py +393 -0
  50. codeframe/core/adapters/git_utils.py +40 -0
  51. codeframe/core/adapters/kilocode.py +126 -0
  52. codeframe/core/adapters/opencode.py +48 -0
  53. codeframe/core/adapters/streaming_chat.py +483 -0
  54. codeframe/core/adapters/subprocess_adapter.py +213 -0
  55. codeframe/core/adapters/verification_wrapper.py +269 -0
  56. codeframe/core/agent.py +2183 -0
  57. codeframe/core/agents_config.py +569 -0
  58. codeframe/core/api_key_service.py +211 -0
  59. codeframe/core/artifacts.py +428 -0
  60. codeframe/core/blocker_detection.py +218 -0
  61. codeframe/core/blockers.py +433 -0
  62. codeframe/core/checkpoints.py +481 -0
  63. codeframe/core/conductor.py +2255 -0
  64. codeframe/core/config.py +827 -0
  65. codeframe/core/config_watcher.py +268 -0
  66. codeframe/core/context.py +542 -0
  67. codeframe/core/context_packager.py +234 -0
  68. codeframe/core/credentials.py +735 -0
  69. codeframe/core/dependency_analyzer.py +229 -0
  70. codeframe/core/dependency_graph.py +290 -0
  71. codeframe/core/diagnostic_agent.py +712 -0
  72. codeframe/core/diagnostics.py +616 -0
  73. codeframe/core/editor.py +556 -0
  74. codeframe/core/engine_registry.py +256 -0
  75. codeframe/core/engine_stats.py +231 -0
  76. codeframe/core/environment.py +697 -0
  77. codeframe/core/events.py +375 -0
  78. codeframe/core/executor.py +1005 -0
  79. codeframe/core/fix_tracker.py +480 -0
  80. codeframe/core/gates.py +1322 -0
  81. codeframe/core/git.py +477 -0
  82. codeframe/core/github_connect_service.py +178 -0
  83. codeframe/core/github_integration_config.py +118 -0
  84. codeframe/core/github_issues_service.py +449 -0
  85. codeframe/core/hooks.py +184 -0
  86. codeframe/core/importers/__init__.py +1 -0
  87. codeframe/core/importers/ralph.py +540 -0
  88. codeframe/core/installer.py +650 -0
  89. codeframe/core/models.py +1026 -0
  90. codeframe/core/notifications_config.py +183 -0
  91. codeframe/core/planner.py +437 -0
  92. codeframe/core/prd.py +670 -0
  93. codeframe/core/prd_discovery.py +1118 -0
  94. codeframe/core/prd_stress_test.py +499 -0
  95. codeframe/core/progress.py +126 -0
  96. codeframe/core/proof/__init__.py +34 -0
  97. codeframe/core/proof/capture.py +79 -0
  98. codeframe/core/proof/evidence.py +56 -0
  99. codeframe/core/proof/ledger.py +574 -0
  100. codeframe/core/proof/models.py +162 -0
  101. codeframe/core/proof/obligations.py +103 -0
  102. codeframe/core/proof/runner.py +233 -0
  103. codeframe/core/proof/scope.py +81 -0
  104. codeframe/core/proof/stubs.py +156 -0
  105. codeframe/core/quick_fixes.py +558 -0
  106. codeframe/core/react_agent.py +1650 -0
  107. codeframe/core/reconciliation.py +183 -0
  108. codeframe/core/replay.py +788 -0
  109. codeframe/core/review.py +285 -0
  110. codeframe/core/runtime.py +1134 -0
  111. codeframe/core/sandbox/__init__.py +27 -0
  112. codeframe/core/sandbox/context.py +98 -0
  113. codeframe/core/sandbox/worktree.py +20 -0
  114. codeframe/core/schedule.py +396 -0
  115. codeframe/core/stall_detector.py +71 -0
  116. codeframe/core/stall_monitor.py +134 -0
  117. codeframe/core/state_machine.py +121 -0
  118. codeframe/core/streaming.py +502 -0
  119. codeframe/core/task_tree.py +400 -0
  120. codeframe/core/tasks.py +1022 -0
  121. codeframe/core/telemetry.py +232 -0
  122. codeframe/core/templates.py +221 -0
  123. codeframe/core/tools.py +942 -0
  124. codeframe/core/workspace.py +887 -0
  125. codeframe/core/worktrees.py +276 -0
  126. codeframe/git/__init__.py +5 -0
  127. codeframe/git/github_integration.py +505 -0
  128. codeframe/lib/__init__.py +0 -0
  129. codeframe/lib/audit_logger.py +248 -0
  130. codeframe/lib/metrics_tracker.py +800 -0
  131. codeframe/lib/quality/__init__.py +7 -0
  132. codeframe/lib/quality/complexity_analyzer.py +316 -0
  133. codeframe/lib/quality/owasp_patterns.py +284 -0
  134. codeframe/lib/quality/security_scanner.py +250 -0
  135. codeframe/lib/rate_limiter.py +312 -0
  136. codeframe/notifications/__init__.py +0 -0
  137. codeframe/notifications/webhook.py +380 -0
  138. codeframe/planning/__init__.py +30 -0
  139. codeframe/planning/issue_generator.py +219 -0
  140. codeframe/planning/prd_template_functions.py +137 -0
  141. codeframe/planning/prd_templates.py +975 -0
  142. codeframe/planning/task_scheduler.py +511 -0
  143. codeframe/planning/task_templates.py +533 -0
  144. codeframe/platform_store/__init__.py +5 -0
  145. codeframe/platform_store/database.py +277 -0
  146. codeframe/platform_store/repositories/__init__.py +24 -0
  147. codeframe/platform_store/repositories/api_key_repository.py +245 -0
  148. codeframe/platform_store/repositories/audit_repository.py +67 -0
  149. codeframe/platform_store/repositories/base.py +295 -0
  150. codeframe/platform_store/repositories/interactive_sessions.py +165 -0
  151. codeframe/platform_store/repositories/token_repository.py +598 -0
  152. codeframe/platform_store/repositories/workspace_registry_repository.py +175 -0
  153. codeframe/platform_store/schema_manager.py +321 -0
  154. codeframe/templates/AGENTS.md.default +94 -0
  155. codeframe/tui/__init__.py +5 -0
  156. codeframe/tui/app.py +256 -0
  157. codeframe/tui/data_service.py +103 -0
  158. codeframe/ui/__init__.py +0 -0
  159. codeframe/ui/dependencies.py +103 -0
  160. codeframe/ui/models.py +999 -0
  161. codeframe/ui/response_models.py +201 -0
  162. codeframe/ui/routers/__init__.py +5 -0
  163. codeframe/ui/routers/_helpers.py +29 -0
  164. codeframe/ui/routers/batches_v2.py +315 -0
  165. codeframe/ui/routers/blockers_v2.py +320 -0
  166. codeframe/ui/routers/checkpoints_v2.py +310 -0
  167. codeframe/ui/routers/costs_v2.py +322 -0
  168. codeframe/ui/routers/diagnose_v2.py +225 -0
  169. codeframe/ui/routers/discovery_v2.py +417 -0
  170. codeframe/ui/routers/environment_v2.py +284 -0
  171. codeframe/ui/routers/events_v2.py +75 -0
  172. codeframe/ui/routers/gates_v2.py +166 -0
  173. codeframe/ui/routers/git_v2.py +284 -0
  174. codeframe/ui/routers/github_integrations_v2.py +532 -0
  175. codeframe/ui/routers/interactive_sessions_v2.py +238 -0
  176. codeframe/ui/routers/pr_v2.py +709 -0
  177. codeframe/ui/routers/prd_v2.py +695 -0
  178. codeframe/ui/routers/proof_v2.py +755 -0
  179. codeframe/ui/routers/review_v2.py +360 -0
  180. codeframe/ui/routers/schedule_v2.py +214 -0
  181. codeframe/ui/routers/session_chat_ws.py +354 -0
  182. codeframe/ui/routers/settings_v2.py +562 -0
  183. codeframe/ui/routers/streaming_v2.py +155 -0
  184. codeframe/ui/routers/tasks_v2.py +1098 -0
  185. codeframe/ui/routers/templates_v2.py +232 -0
  186. codeframe/ui/routers/terminal_ws.py +267 -0
  187. codeframe/ui/routers/workspace_v2.py +527 -0
  188. codeframe/ui/server.py +568 -0
  189. codeframe/ui/shared.py +241 -0
  190. codeframe/workspace/__init__.py +5 -0
  191. codeframe/workspace/manager.py +249 -0
  192. codeframe_ai-0.9.0.dist-info/METADATA +517 -0
  193. codeframe_ai-0.9.0.dist-info/RECORD +197 -0
  194. codeframe_ai-0.9.0.dist-info/WHEEL +5 -0
  195. codeframe_ai-0.9.0.dist-info/entry_points.txt +3 -0
  196. codeframe_ai-0.9.0.dist-info/licenses/LICENSE +661 -0
  197. codeframe_ai-0.9.0.dist-info/top_level.txt +1 -0
codeframe/ui/server.py ADDED
@@ -0,0 +1,568 @@
1
+ """FastAPI Status Server for CodeFRAME."""
2
+
3
+ # Standard library imports
4
+ import logging
5
+ import os
6
+ import subprocess
7
+ from contextlib import asynccontextmanager
8
+ from datetime import datetime, UTC
9
+ from enum import Enum
10
+ from pathlib import Path
11
+
12
+ # Third-party imports
13
+ from fastapi import Depends, FastAPI
14
+ from fastapi.middleware.cors import CORSMiddleware
15
+ from slowapi.errors import RateLimitExceeded
16
+ from slowapi.middleware import SlowAPIMiddleware
17
+
18
+ # Local imports - v2 only (no v1 persistence layer)
19
+ from codeframe.workspace import WorkspaceManager
20
+ from codeframe.ui.routers import (
21
+ # v2 routers only - delegate to codeframe.core modules
22
+ batches_v2,
23
+ blockers_v2,
24
+ checkpoints_v2,
25
+ costs_v2,
26
+ diagnose_v2,
27
+ discovery_v2,
28
+ environment_v2,
29
+ events_v2,
30
+ gates_v2,
31
+ git_v2,
32
+ github_integrations_v2,
33
+ interactive_sessions_v2,
34
+ pr_v2,
35
+ prd_v2,
36
+ proof_v2,
37
+ review_v2,
38
+ schedule_v2,
39
+ session_chat_ws,
40
+ settings_v2,
41
+ terminal_ws,
42
+ streaming_v2,
43
+ tasks_v2,
44
+ templates_v2,
45
+ workspace_v2,
46
+ )
47
+ from codeframe.auth import router as auth_router
48
+ from codeframe.auth.dependencies import require_auth
49
+ from codeframe.platform_store.database import Database
50
+ from codeframe.lib.rate_limiter import (
51
+ get_rate_limiter,
52
+ rate_limit_exceeded_handler,
53
+ )
54
+ from codeframe.config.rate_limits import get_rate_limit_config
55
+
56
+ # ============================================================================
57
+ # Configuration and Setup
58
+ # ============================================================================
59
+
60
+
61
+ class DeploymentMode(str, Enum):
62
+ """Deployment mode for CodeFRAME."""
63
+
64
+ SELF_HOSTED = "self_hosted"
65
+ HOSTED = "hosted"
66
+
67
+
68
+ def get_deployment_mode() -> DeploymentMode:
69
+ """Get current deployment mode from environment.
70
+
71
+ Returns:
72
+ DeploymentMode.SELF_HOSTED or DeploymentMode.HOSTED
73
+ """
74
+ mode = os.getenv("CODEFRAME_DEPLOYMENT_MODE", "self_hosted").lower()
75
+
76
+ if mode == "hosted":
77
+ return DeploymentMode.HOSTED
78
+ return DeploymentMode.SELF_HOSTED
79
+
80
+
81
+ def is_hosted_mode() -> bool:
82
+ """Check if running in hosted SaaS mode.
83
+
84
+ Returns:
85
+ True if hosted mode, False if self-hosted
86
+ """
87
+ return get_deployment_mode() == DeploymentMode.HOSTED
88
+
89
+
90
+ # Logger setup
91
+ logger = logging.getLogger(__name__)
92
+
93
+
94
+ # ============================================================================
95
+ # Application Lifespan
96
+ # ============================================================================
97
+
98
+
99
+ # Note: Session cleanup removed - v1 persistence layer not used in v2
100
+ # If session management is needed, implement in v2 core modules
101
+
102
+
103
+ def _validate_security_config():
104
+ """Validate security configuration at startup.
105
+
106
+ Raises:
107
+ RuntimeError: If security configuration is invalid for the deployment mode
108
+ """
109
+ from codeframe.auth.manager import SECRET, DEFAULT_SECRET
110
+
111
+ deployment_mode = get_deployment_mode()
112
+
113
+ # In hosted mode, fail fast if using default JWT secret
114
+ if deployment_mode == DeploymentMode.HOSTED and SECRET == DEFAULT_SECRET:
115
+ raise RuntimeError(
116
+ "🚨 SECURITY: AUTH_SECRET must be set in hosted/production mode. "
117
+ "Using the default secret compromises all JWT tokens. "
118
+ "Set the AUTH_SECRET environment variable to a secure random value."
119
+ )
120
+
121
+ # Log security status
122
+ if SECRET == DEFAULT_SECRET:
123
+ logger.warning(
124
+ "⚠️ Running with default AUTH_SECRET - acceptable for self-hosted development only"
125
+ )
126
+ else:
127
+ logger.info("🔐 AUTH_SECRET configured (custom secret in use)")
128
+
129
+
130
+ @asynccontextmanager
131
+ async def lifespan(app: FastAPI):
132
+ """Manage application lifespan - startup and shutdown."""
133
+ # Load environment variables from .env file
134
+ from codeframe.core.config import load_environment
135
+ load_environment()
136
+
137
+ # Validate security configuration before starting
138
+ _validate_security_config()
139
+
140
+ # Initialize workspace manager for v2 core
141
+ workspace_root_str = os.environ.get(
142
+ "WORKSPACE_ROOT", str(Path.cwd() / ".codeframe" / "workspaces")
143
+ )
144
+ workspace_root = Path(workspace_root_str)
145
+ app.state.workspace_manager = WorkspaceManager(workspace_root)
146
+
147
+ # Initialize global persistent DB (used by interactive_sessions and auth)
148
+ db_path = os.environ.get(
149
+ "DATABASE_PATH",
150
+ str(Path.cwd() / ".codeframe" / "state.db"),
151
+ )
152
+ db = Database(db_path)
153
+ db.initialize()
154
+ app.state.db = db
155
+
156
+ # Log the effective auth mode (#336: env-gated, secure by default)
157
+ from codeframe.auth.dependencies import auth_required
158
+
159
+ if auth_required():
160
+ logger.info("🔒 Authentication: ENABLED (default; set CODEFRAME_AUTH_REQUIRED=false to disable locally)")
161
+ else:
162
+ logger.warning("🔓 Authentication: DISABLED via CODEFRAME_AUTH_REQUIRED — do not expose this server publicly")
163
+
164
+ # Initialize rate limiting
165
+ rate_limit_config = get_rate_limit_config()
166
+ if rate_limit_config.enabled:
167
+ limiter = get_rate_limiter()
168
+ if limiter:
169
+ app.state.limiter = limiter
170
+ logger.info(
171
+ f"🚦 Rate limiting: ENABLED "
172
+ f"(storage={rate_limit_config.storage}, "
173
+ f"standard={rate_limit_config.standard_limit})"
174
+ )
175
+ else:
176
+ logger.info("🚦 Rate limiting: DISABLED")
177
+
178
+ yield
179
+
180
+ # Shutdown: nothing to clean up (v2 uses per-workspace databases managed by core)
181
+
182
+
183
+ # ============================================================================
184
+ # OpenAPI Tags and Metadata
185
+ # ============================================================================
186
+
187
+ OPENAPI_TAGS = [
188
+ {
189
+ "name": "health",
190
+ "description": "Health check endpoints - verify API availability and get deployment information.",
191
+ },
192
+ {
193
+ "name": "projects",
194
+ "description": "Project lifecycle and management - create, read, update, delete projects and access project status, tasks, activity, PRD, and session state.",
195
+ },
196
+ {
197
+ "name": "tasks",
198
+ "description": "Task creation, management, and approval workflow - create tasks, approve generated tasks to start development, and manually trigger task assignment.",
199
+ },
200
+ {
201
+ "name": "agents",
202
+ "description": "Agent lifecycle and assignment - start/pause/resume agents, assign agents to projects with roles, and manage multi-agent workflows.",
203
+ },
204
+ {
205
+ "name": "blockers",
206
+ "description": "Human-in-the-loop blocker management - list, view, and resolve blockers that require human guidance for agents to continue.",
207
+ },
208
+ {
209
+ "name": "checkpoints",
210
+ "description": "Project checkpoint and restore functionality - create snapshots of project state and restore to previous checkpoints.",
211
+ },
212
+ {
213
+ "name": "chat",
214
+ "description": "Chat and communication endpoints for real-time interaction with agents.",
215
+ },
216
+ {
217
+ "name": "context",
218
+ "description": "Context management for agent execution - manage codebase context, file references, and relevant information.",
219
+ },
220
+ {
221
+ "name": "discovery",
222
+ "description": "Discovery phase operations - codebase analysis, structure detection, and initial project understanding.",
223
+ },
224
+ {
225
+ "name": "git",
226
+ "description": "Git operations - commit, branch, diff, and repository management.",
227
+ },
228
+ {
229
+ "name": "lint",
230
+ "description": "Code linting operations - run and manage linting checks.",
231
+ },
232
+ {
233
+ "name": "metrics",
234
+ "description": "Metrics and analytics - project progress, agent performance, and quality metrics.",
235
+ },
236
+ {
237
+ "name": "quality_gates",
238
+ "description": "Quality gates and checks - run tests, type checking, coverage, and code review gates.",
239
+ },
240
+ {
241
+ "name": "review",
242
+ "description": "Code review functionality - trigger and manage AI-powered code reviews.",
243
+ },
244
+ {
245
+ "name": "schedule",
246
+ "description": "Task scheduling - view schedule predictions, bottlenecks, and critical path analysis.",
247
+ },
248
+ {
249
+ "name": "session",
250
+ "description": "Session management - track session state, progress, and continuity across work sessions.",
251
+ },
252
+ {
253
+ "name": "templates",
254
+ "description": "Project and task templates - list, view, and apply reusable templates.",
255
+ },
256
+ {
257
+ "name": "websocket",
258
+ "description": "WebSocket connections for real-time updates and event streaming.",
259
+ },
260
+ {
261
+ "name": "auth",
262
+ "description": "Authentication and authorization - login, logout, API keys, and session management.",
263
+ },
264
+ {
265
+ "name": "proof-v2",
266
+ "description": "PROOF9 quality system — capture requirements from glitches, run proof obligations, manage waivers, and query evidence.",
267
+ },
268
+ {
269
+ "name": "integrations",
270
+ "description": "External service integrations — connect a GitHub repository via Personal Access Token for issue import.",
271
+ },
272
+ ]
273
+
274
+ OPENAPI_DESCRIPTION = """
275
+ # CodeFRAME API
276
+
277
+ **CodeFRAME** is an AI-powered software development framework that orchestrates multiple agents
278
+ to complete programming tasks. This API provides real-time monitoring and control for CodeFRAME projects.
279
+
280
+ ## Overview
281
+
282
+ The CodeFRAME API enables you to:
283
+
284
+ - **Create and manage projects** - Initialize projects from git repos, local paths, or start empty
285
+ - **Generate and approve tasks** - AI generates implementation tasks from PRDs; approve to start development
286
+ - **Monitor agent execution** - Track agents as they work through tasks with real-time WebSocket updates
287
+ - **Handle blockers** - Provide human guidance when agents encounter decisions requiring input
288
+ - **Review and ship** - Run quality gates, review code changes, and manage the deployment process
289
+
290
+ ## Authentication
291
+
292
+ All `/api/v2/*` endpoints require authentication by default (disable for local
293
+ development with `CODEFRAME_AUTH_REQUIRED=false`). Public: `/`, `/health`, docs,
294
+ and the `/auth/*` login/register endpoints. Two authentication methods:
295
+
296
+ 1. **API Key** - Include `X-API-Key` header with your API key
297
+ 2. **Session Token** - Use JWT token from login endpoint in `Authorization: Bearer <token>` header
298
+
299
+ SSE streaming endpoints additionally accept the JWT as a `?token=` query
300
+ parameter (browser EventSource cannot send headers); this applies to the
301
+ streaming routes only.
302
+
303
+ ## Rate Limiting
304
+
305
+ The API implements rate limiting to ensure fair usage:
306
+ - **Standard endpoints**: Higher request limits for read operations
307
+ - **AI endpoints** (agent start, LLM calls): Lower limits due to computational cost
308
+
309
+ Rate limit headers are included in responses: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
310
+
311
+ ## WebSocket Events
312
+
313
+ For real-time updates, connect to the WebSocket endpoint. Events include:
314
+ - `task_assigned`, `task_completed`, `task_failed`
315
+ - `agent_created`, `agent_status`
316
+ - `blocker_created`, `blocker_resolved`
317
+ - `discovery_starting`, `discovery_completed`
318
+
319
+ ## Error Responses
320
+
321
+ All errors follow a consistent format:
322
+ ```json
323
+ {
324
+ "detail": "Error message describing what went wrong"
325
+ }
326
+ ```
327
+
328
+ Common HTTP status codes:
329
+ - `400` - Bad Request (validation error)
330
+ - `401` - Unauthorized (authentication required)
331
+ - `403` - Forbidden (insufficient permissions)
332
+ - `404` - Not Found (resource doesn't exist)
333
+ - `409` - Conflict (duplicate resource or state conflict)
334
+ - `422` - Unprocessable Entity (Pydantic validation failure)
335
+ - `429` - Too Many Requests (rate limit exceeded)
336
+ - `500` - Internal Server Error
337
+ """
338
+
339
+
340
+ # ============================================================================
341
+ # FastAPI Application
342
+ # ============================================================================
343
+
344
+ app = FastAPI(
345
+ title="CodeFRAME API",
346
+ description=OPENAPI_DESCRIPTION,
347
+ version="2.0.0",
348
+ lifespan=lifespan,
349
+ openapi_tags=OPENAPI_TAGS,
350
+ contact={
351
+ "name": "CodeFRAME Support",
352
+ "url": "https://github.com/frankbria/codeframe",
353
+ },
354
+ license_info={
355
+ "name": "MIT",
356
+ "identifier": "MIT",
357
+ },
358
+ )
359
+
360
+
361
+ # ============================================================================
362
+ # Rate Limiting Setup
363
+ # ============================================================================
364
+
365
+ # Add rate limiting exception handler
366
+ app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)
367
+
368
+ # Add rate limiting middleware if enabled
369
+ # Initialize limiter immediately so it's available before lifespan runs
370
+ rate_limit_config = get_rate_limit_config()
371
+ if rate_limit_config.enabled:
372
+ limiter = get_rate_limiter()
373
+ if limiter:
374
+ app.state.limiter = limiter
375
+ app.add_middleware(SlowAPIMiddleware)
376
+
377
+
378
+ # ============================================================================
379
+ # CORS Middleware
380
+ # ============================================================================
381
+
382
+ # CORS configuration from environment variables
383
+ # Get CORS_ALLOWED_ORIGINS from env (comma-separated list)
384
+ cors_origins_env = os.environ.get("CORS_ALLOWED_ORIGINS", "")
385
+
386
+ # Parse comma-separated origins
387
+ if cors_origins_env:
388
+ allowed_origins = [origin.strip() for origin in cors_origins_env.split(",") if origin.strip()]
389
+ else:
390
+ # Fallback to development defaults if not configured
391
+ allowed_origins = [
392
+ "http://localhost:3000", # Next.js dev server
393
+ "http://localhost:3001", # Next.js E2E test server
394
+ "http://localhost:5173", # Vite dev server
395
+ ]
396
+
397
+ # Log CORS configuration for debugging
398
+ print("🔒 CORS Configuration:")
399
+ print(f" CORS_ALLOWED_ORIGINS env: {cors_origins_env!r}")
400
+ print(f" Parsed allowed origins: {allowed_origins}")
401
+
402
+ app.add_middleware(
403
+ CORSMiddleware,
404
+ allow_origins=allowed_origins,
405
+ allow_credentials=True,
406
+ allow_methods=["*"],
407
+ allow_headers=["*"],
408
+ )
409
+
410
+
411
+ # ============================================================================
412
+ # Health Check Endpoints
413
+ # ============================================================================
414
+
415
+
416
+ @app.get(
417
+ "/",
418
+ summary="Basic health check",
419
+ description="Simple health check endpoint that returns online status. Use /health for detailed information.",
420
+ tags=["health"],
421
+ )
422
+ async def root():
423
+ """Health check endpoint."""
424
+ return {"status": "online", "service": "CodeFRAME API"}
425
+
426
+
427
+ @app.get(
428
+ "/health",
429
+ summary="Detailed health check",
430
+ description="Returns comprehensive health information including version, git commit, deployment time, "
431
+ "and database connection status. Useful for monitoring and debugging.",
432
+ tags=["health"],
433
+ )
434
+ async def health_check():
435
+ """Detailed health check with deployment info.
436
+
437
+ Returns:
438
+ - status: Service health status
439
+ - version: API version from FastAPI app
440
+ - commit: Git commit hash (short)
441
+ - deployed_at: Server startup timestamp
442
+ - database: Database connection status
443
+ """
444
+ # Get git commit hash
445
+ try:
446
+ git_commit = (
447
+ subprocess.check_output(
448
+ ["git", "rev-parse", "--short", "HEAD"],
449
+ cwd=Path(__file__).parent.parent.parent,
450
+ stderr=subprocess.DEVNULL,
451
+ )
452
+ .decode()
453
+ .strip()
454
+ )
455
+ except Exception:
456
+ git_commit = "unknown"
457
+
458
+ return {
459
+ "status": "healthy",
460
+ "service": "CodeFRAME Status Server",
461
+ "version": app.version,
462
+ "commit": git_commit,
463
+ "deployed_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
464
+ }
465
+
466
+
467
+ # ============================================================================
468
+ # Test-Only Endpoints (for WebSocket integration tests)
469
+ # ============================================================================
470
+
471
+
472
+ @app.post("/test/broadcast", dependencies=[Depends(require_auth)])
473
+ async def test_broadcast(message: dict, project_id: int = None):
474
+ """Trigger a WebSocket broadcast for testing purposes.
475
+
476
+ This endpoint is only intended for use in integration tests to trigger
477
+ broadcasts from the server subprocess. In production, broadcasts are
478
+ triggered by actual server-side events.
479
+
480
+ Args:
481
+ message: The message dict to broadcast
482
+ project_id: Optional project ID for filtered broadcasts
483
+
484
+ Returns:
485
+ Success confirmation
486
+ """
487
+ from codeframe.ui.shared import manager
488
+
489
+ await manager.broadcast(message, project_id=project_id)
490
+ return {"status": "broadcast_sent", "project_id": project_id}
491
+
492
+
493
+ # ============================================================================
494
+ # Router Mounting (v2 only)
495
+ # ============================================================================
496
+
497
+ # Authentication router
498
+ app.include_router(auth_router.router)
499
+
500
+ # v2 API routers - all delegate to codeframe.core modules
501
+ #
502
+ # Auth enforcement (issue #336): every v2 REST router is mounted with a
503
+ # blanket ``require_auth`` dependency. With CODEFRAME_AUTH_REQUIRED disabled
504
+ # (local opt-out) require_auth returns a synthetic principal instead of
505
+ # raising, so behavior is unchanged for local/dev use. The two WebSocket
506
+ # routers (session_chat_ws, terminal_ws) are intentionally excluded — they
507
+ # perform their own ?token= JWT auth and cannot use an HTTP 401 dependency.
508
+ # The auth_router (login/register) stays public.
509
+ _AUTH = [Depends(require_auth)]
510
+ app.include_router(batches_v2.router, dependencies=_AUTH) # /api/v2/batches
511
+ app.include_router(blockers_v2.router, dependencies=_AUTH) # /api/v2/blockers
512
+ app.include_router(checkpoints_v2.router, dependencies=_AUTH) # /api/v2/checkpoints
513
+ app.include_router(costs_v2.router, dependencies=_AUTH) # /api/v2/costs
514
+ app.include_router(diagnose_v2.router, dependencies=_AUTH) # /api/v2/tasks/{id}/diagnose
515
+ app.include_router(discovery_v2.router, dependencies=_AUTH) # /api/v2/discovery
516
+ app.include_router(environment_v2.router, dependencies=_AUTH) # /api/v2/env
517
+ app.include_router(events_v2.router, dependencies=_AUTH) # /api/v2/events
518
+ app.include_router(gates_v2.router, dependencies=_AUTH) # /api/v2/gates
519
+ app.include_router(git_v2.router, dependencies=_AUTH) # /api/v2/git
520
+ app.include_router(github_integrations_v2.router, dependencies=_AUTH) # /api/v2/integrations/github
521
+ app.include_router(interactive_sessions_v2.router, dependencies=_AUTH) # /api/v2/sessions
522
+ app.include_router(session_chat_ws.router) # /ws/sessions/{id}/chat (WS: own auth)
523
+ app.include_router(terminal_ws.router) # /ws/sessions/{id}/terminal (WS: own auth)
524
+ app.include_router(pr_v2.router, dependencies=_AUTH) # /api/v2/pr
525
+ app.include_router(prd_v2.router, dependencies=_AUTH) # /api/v2/prd
526
+ app.include_router(proof_v2.router, dependencies=_AUTH) # /api/v2/proof
527
+ app.include_router(review_v2.router, dependencies=_AUTH) # /api/v2/review
528
+ app.include_router(schedule_v2.router, dependencies=_AUTH) # /api/v2/schedule
529
+ app.include_router(settings_v2.router, dependencies=_AUTH) # /api/v2/settings
530
+ app.include_router(streaming_v2.router, dependencies=_AUTH) # /api/v2/tasks/{id}/stream (SSE)
531
+ app.include_router(tasks_v2.router, dependencies=_AUTH) # /api/v2/tasks
532
+ app.include_router(templates_v2.router, dependencies=_AUTH) # /api/v2/templates
533
+ app.include_router(workspace_v2.router, dependencies=_AUTH) # /api/v2/workspaces
534
+
535
+
536
+ # ============================================================================
537
+ # Server Startup
538
+ # ============================================================================
539
+
540
+
541
+ def run_server(host: str = "0.0.0.0", port: int = 8080):
542
+ """Run the Status Server."""
543
+ import uvicorn
544
+
545
+ uvicorn.run(app, host=host, port=port)
546
+
547
+
548
+ if __name__ == "__main__":
549
+ import argparse
550
+
551
+ # Parse command line arguments
552
+ parser = argparse.ArgumentParser(description="CodeFRAME Status Server")
553
+ parser.add_argument(
554
+ "--host",
555
+ type=str,
556
+ default=os.environ.get("HOST", "0.0.0.0"),
557
+ help="Host to bind to (default: 0.0.0.0 or HOST env var)",
558
+ )
559
+ parser.add_argument(
560
+ "--port",
561
+ type=int,
562
+ default=int(os.environ.get("BACKEND_PORT", os.environ.get("PORT", "8080"))),
563
+ help="Port to bind to (default: 8080 or BACKEND_PORT/PORT env var)",
564
+ )
565
+
566
+ args = parser.parse_args()
567
+
568
+ run_server(host=args.host, port=args.port)