File size: 37,803 Bytes
04bb755
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
import asyncio
import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware

from datetime import datetime, timedelta, timezone

from sqlalchemy import delete, text

from src.config import settings
from src.core.embeddings import MissingAPIKeyError
from src.core.exceptions import MarketplaceError
from src.core.logging import setup_logging
from src.database import engine
from src.middleware.request_id import RequestTracingMiddleware

logger = logging.getLogger(__name__)


async def _health_monitor_loop(
    interval_healthy: int = 600,
    interval_degraded: int = 120,
) -> None:
    """Adaptive health monitor β€” checks more frequently when agents are failing.

    Args:
        interval_healthy: Seconds between checks when all agents are healthy (default 10 min).
        interval_degraded: Seconds between checks when any agents are failing (default 2 min).
    """
    import random
    from src.database import async_session
    from src.services.health_monitor import HealthMonitorService

    interval = interval_healthy

    while True:
        try:
            # Add jitter (0-30s) to prevent thundering herd
            jitter = random.uniform(0, 30)
            await asyncio.sleep(interval + jitter)

            async with async_session() as db:
                service = HealthMonitorService(db)
                results = await service.check_all_active_agents()
                healthy = sum(1 for r in results if r.get("available"))
                total = len(results)
                failing = total - healthy

                logger.info(
                    "Health check: %d/%d agents healthy (next in %ds)",
                    healthy, total,
                    interval_degraded if failing else interval_healthy,
                )

                # Adaptive: check more frequently when agents are failing
                interval = interval_degraded if failing else interval_healthy

        except asyncio.CancelledError:
            break
        except Exception:
            logger.exception("Health monitor loop error")
            interval = interval_healthy  # Reset to slow interval on error


async def _workflow_pump_loop(interval: int = 3) -> None:
    """Single loop that advances ALL running workflows."""
    from src.database import async_session
    from src.services.workflow_execution import WorkflowExecutionService

    while True:
        try:
            await asyncio.sleep(interval)
            async with async_session() as db:
                engine = WorkflowExecutionService(db)
                await engine.pump_running_workflows()
        except asyncio.CancelledError:
            break
        except Exception:
            logger.exception("Workflow pump loop error")


async def _scheduler_loop(interval: int = 30) -> None:
    """Check for due schedules every 30 seconds."""
    from src.database import async_session
    from src.services.scheduler import SchedulerService

    while True:
        try:
            await asyncio.sleep(interval)
            async with async_session() as db:
                service = SchedulerService(db)
                await service.process_due_schedules()
        except asyncio.CancelledError:
            break
        except Exception:
            logger.exception("Scheduler loop error")


async def _webhook_log_cleanup_loop(retention_days: int = 90, interval: int = 86_400):
    """Delete webhook logs older than retention_days. Runs once per interval."""
    from src.database import async_session
    from src.models.webhook_log import WebhookLog

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(WebhookLog).where(WebhookLog.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("Webhook log cleanup: deleted %d logs older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("Webhook log cleanup error")
        await asyncio.sleep(interval)


async def _channel_message_cleanup_loop(retention_days: int = 90, interval: int = 86_400):
    """Purge channel messages older than retention_days (GDPR data retention)."""
    from src.database import async_session
    from src.models.channel import ChannelMessage

    while True:
        try:
            await asyncio.sleep(interval)
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(ChannelMessage).where(ChannelMessage.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("Channel message cleanup: purged %d messages older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("Channel message cleanup error")


async def _llm_call_cleanup_loop(retention_days: int = 7, interval: int = 86_400):
    """Delete llm_call records older than retention_days. High-volume table.

    Default 7d (was 30d) β€” aggressive free-tier mode. LLM call records are
    debug-only; recent week is plenty for incident analysis.
    """
    from src.database import async_session
    from src.models.llm_call import LLMCall

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(LLMCall).where(LLMCall.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("LLM call cleanup: deleted %d rows older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("LLM call cleanup error")
        await asyncio.sleep(interval)


async def _audit_log_cleanup_loop(retention_days: int = 90, interval: int = 86_400):
    """Delete audit_log entries older than retention_days. SOC 2 retention floor is 90d."""
    from src.database import async_session
    from src.models.audit_log import AuditLog

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(AuditLog).where(AuditLog.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("Audit log cleanup: deleted %d rows older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("Audit log cleanup error")
        await asyncio.sleep(interval)


async def _telemetry_cleanup_loop(retention_days: int = 3, interval: int = 86_400):
    """Delete telemetry events older than retention_days. Highest-volume table.

    Default 3d (was 14d) β€” aggressive free-tier mode. Telemetry is for trend
    lines; 3d is enough to spot regressions, longer history isn't worth the
    DB space on a 5 GB cap.
    """
    from src.database import async_session
    from src.models.telemetry import TelemetryEvent

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(TelemetryEvent).where(TelemetryEvent.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("Telemetry cleanup: deleted %d rows older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("Telemetry cleanup error")
        await asyncio.sleep(interval)


async def _infrastructure_metric_cleanup_loop(retention_days: int = 30, interval: int = 86_400):
    """Delete infrastructure_metric rows older than retention_days. Daily collector accrues quickly."""
    from src.database import async_session
    from src.models.infrastructure_metric import InfrastructureMetric

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(InfrastructureMetric).where(InfrastructureMetric.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info("Infrastructure metric cleanup: deleted %d rows older than %d days", result.rowcount, retention_days)
        except Exception:
            logger.exception("Infrastructure metric cleanup error")
        await asyncio.sleep(interval)


async def _failed_task_cleanup_loop(retention_days: int = 30, interval: int = 86_400):
    """Delete tasks in terminal failure states (failed/canceled/rejected) older than
    retention_days. Keeps all completed tasks regardless of age β€” those have artifacts
    users may reference. Failed task rows carry full message + error JSONB which is
    debug-only after the retention window.
    """
    from src.database import async_session
    from src.models.task import Task, TaskStatus

    junk_statuses = (TaskStatus.FAILED, TaskStatus.CANCELED, TaskStatus.REJECTED)

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(Task).where(
                        Task.status.in_(junk_statuses),
                        Task.created_at < cutoff,
                    )
                )
                await session.commit()
                if result.rowcount:
                    logger.info(
                        "Failed task cleanup: deleted %d failed/canceled/rejected tasks older than %d days",
                        result.rowcount, retention_days,
                    )
        except Exception:
            logger.exception("Failed task cleanup error")
        await asyncio.sleep(interval)


async def _workflow_run_cleanup_loop(retention_days: int = 30, interval: int = 86_400):
    """Delete completed/failed/canceled workflow_runs older than retention_days.
    workflow_step_runs cascade-delete via FK ON DELETE CASCADE.
    """
    from src.database import async_session
    from src.models.workflow import WorkflowRun

    terminal_statuses = ("completed", "failed", "canceled")

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(WorkflowRun).where(
                        WorkflowRun.status.in_(terminal_statuses),
                        WorkflowRun.created_at < cutoff,
                    )
                )
                await session.commit()
                if result.rowcount:
                    logger.info(
                        "Workflow run cleanup: deleted %d terminal runs older than %d days",
                        result.rowcount, retention_days,
                    )
        except Exception:
            logger.exception("Workflow run cleanup error")
        await asyncio.sleep(interval)


async def _supervisor_plan_cleanup_loop(retention_days: int = 30, interval: int = 86_400):
    """Delete supervisor_plans older than retention_days. These are LLM-generated
    workflow proposals β€” intermediate artifacts with no long-term value.
    """
    from src.database import async_session
    from src.models.supervisor_plan import SupervisorPlan

    while True:
        try:
            cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
            async with async_session() as session:
                result = await session.execute(
                    delete(SupervisorPlan).where(SupervisorPlan.created_at < cutoff)
                )
                await session.commit()
                if result.rowcount:
                    logger.info(
                        "Supervisor plan cleanup: deleted %d plans older than %d days",
                        result.rowcount, retention_days,
                    )
        except Exception:
            logger.exception("Supervisor plan cleanup error")
        await asyncio.sleep(interval)


async def _vacuum_loop(interval: int = 604_800):
    """Run VACUUM ANALYZE weekly to reclaim space after deletes.

    Postgres' autovacuum runs in the background but doesn't reclaim disk space β€”
    deleted rows leave dead tuples that bloat tables until VACUUM FULL or
    pg_repack. We run plain VACUUM ANALYZE which marks space reusable inside
    the table. On a free tier with 5 GB cap, reclaiming bloat matters.
    """
    from src.database import engine

    # Wait an hour after startup so cleanup loops have a chance to run first
    await asyncio.sleep(3600)

    while True:
        try:
            # VACUUM cannot run inside a transaction β€” use raw connection with autocommit
            async with engine.connect() as conn:
                await conn.execution_options(isolation_level="AUTOCOMMIT")
                for table in (
                    "llm_calls", "telemetry_events", "audit_logs",
                    "webhook_logs", "infrastructure_metrics",
                    "tasks", "workflow_runs", "workflow_step_runs",
                    "supervisor_plans",
                ):
                    try:
                        await conn.execute(text(f"VACUUM (ANALYZE) {table}"))
                    except Exception as e:
                        logger.warning("VACUUM %s failed: %s", table, e)
            logger.info("VACUUM ANALYZE pass complete")
        except Exception:
            logger.exception("VACUUM loop error")
        await asyncio.sleep(interval)


async def _db_quota_monitor_loop(
    warn_gb: float = 3.0,
    critical_gb: float = 4.0,
    interval: int = 21_600,  # 6h
):
    """Watch DB size against Supabase Free tier (5 GB). Alerts to Discord on threshold crossings."""
    from src.database import async_session

    last_alert_level: str | None = None
    while True:
        try:
            async with async_session() as session:
                result = await session.execute(text("SELECT pg_database_size(current_database())"))
                size_bytes = result.scalar_one()
                size_gb = size_bytes / 1024 / 1024 / 1024

                level = None
                if size_gb >= critical_gb:
                    level = "critical"
                elif size_gb >= warn_gb:
                    level = "warn"

                if level and level != last_alert_level:
                    msg = f"Supabase DB size: {size_gb:.2f} GB (free tier cap 5 GB)"
                    logger.warning("[%s] %s", level.upper(), msg)
                    webhook = os.environ.get("DISCORD_HEALTHCHECK_WEBHOOK")
                    if webhook:
                        try:
                            import httpx
                            color = 0xFF4444 if level == "critical" else 0xFFA500
                            embed = {
                                "title": f"DB Quota {level.upper()}",
                                "description": msg,
                                "color": color,
                            }
                            async with httpx.AsyncClient(timeout=10) as client:
                                await client.post(webhook, json={"embeds": [embed]})
                        except Exception:
                            logger.exception("DB quota alert webhook failed")
                    last_alert_level = level
                elif not level:
                    last_alert_level = None  # back below warn β†’ re-arm
                logger.info("DB size check: %.2f GB", size_gb)
        except Exception:
            logger.exception("DB quota monitor error")
        await asyncio.sleep(interval)


async def _stale_reservation_cleanup_loop(interval: int = 300):
    """Release credit reservations for stalled tasks. Runs every 5 minutes."""
    from src.database import async_session
    from src.services.task_broker import TaskBrokerService

    while True:
        try:
            await asyncio.sleep(interval)
            async with async_session() as db:
                service = TaskBrokerService(db)
                cleaned = await service.cleanup_stale_reservations()
                if cleaned:
                    logger.info("Stale reservation cleanup: released %d tasks", cleaned)
        except asyncio.CancelledError:
            break
        except Exception:
            logger.exception("Stale reservation cleanup error")


async def _infrastructure_metrics_loop(interval: int = 86_400) -> None:
    """Collect infrastructure metrics daily. Runs only in worker mode."""
    import random
    from src.database import async_session
    from src.services.infrastructure_monitor import InfrastructureMonitorService

    # Wait 60s after startup, then run immediately, then daily
    await asyncio.sleep(60)

    while True:
        try:
            async with async_session() as db:
                service = InfrastructureMonitorService(db)
                results = await service.collect_all()
                await service.send_daily_report(results)
                await service.check_threshold_crossings(results)
                logger.info("Infrastructure metrics collected: %d metrics", len(results))
        except asyncio.CancelledError:
            break
        except Exception:
            logger.exception("Infrastructure metrics collection error")

        # Sleep until ~02:00 UTC tomorrow with jitter
        now = datetime.now(timezone.utc)
        tomorrow_2am = (now + timedelta(days=1)).replace(hour=2, minute=0, second=0, microsecond=0)
        sleep_seconds = (tomorrow_2am - now).total_seconds() + random.uniform(0, 1800)
        await asyncio.sleep(sleep_seconds)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    setup_logging(settings.log_level, settings.log_format)

    # Initialize Sentry if DSN is configured
    import os
    sentry_dsn = os.environ.get("SENTRY_DSN", "")
    if sentry_dsn:
        try:
            import sentry_sdk
            from sentry_sdk.scrubber import EventScrubber, DEFAULT_DENYLIST
            sentry_sdk.init(
                dsn=sentry_dsn,
                send_default_pii=False,
                event_scrubber=EventScrubber(denylist=DEFAULT_DENYLIST + [
                    "api_key", "llm_api_keys", "firebase_credentials_json",
                    "stripe_secret_key", "stripe_webhook_secret", "email",
                    "hashed_password", "authorization", "x-api-key",
                ]),
                traces_sample_rate=0.1 if not settings.debug else 1.0,
                environment="staging" if settings.debug else "production",
            )
            logger.info("Sentry initialized")
        except ImportError:
            logger.warning("SENTRY_DSN set but sentry-sdk not installed")

    from src.core.auth import _init_firebase
    _init_firebase()

    # Validate database connectivity (fail fast if unreachable)
    try:
        async with engine.connect() as conn:
            await conn.execute(text("SELECT 1"))
        logger.info("Database connection verified")
    except Exception:
        logger.exception("Database connection failed")
        raise

    # Run Alembic migrations (non-blocking β€” skip on failure)
    # In API mode, skip migrations (worker handles them to prevent races)
    worker_mode = os.environ.get("WORKER_MODE", "").lower()
    if worker_mode == "api":
        logger.info("WORKER_MODE=api β€” skipping Alembic migrations (worker handles them)")
    elif "sqlite" not in settings.database_url:
        try:
            import subprocess
            result = subprocess.run(
                ["alembic", "upgrade", "head"],
                capture_output=True, text=True, timeout=30,
            )
            if result.returncode == 0:
                logger.info("Alembic migrations applied successfully")
            else:
                logger.warning("Alembic migration failed: %s", result.stderr[-500:] if result.stderr else "no output")
        except subprocess.TimeoutExpired:
            logger.warning("Alembic migration timed out (30s) β€” skipping")
        except Exception:
            logger.warning("Alembic migration error β€” skipping", exc_info=True)
    else:
        # Auto-create tables for SQLite (dev/local only)
        from src.database import init_db
        await init_db()
        logger.info("SQLite tables auto-created")

    settings.warn_insecure_defaults()

    # Recover stale workflow runs from previous crash (worker only)
    if worker_mode != "api":
        try:
            from src.database import async_session
            from src.services.workflow_execution import WorkflowExecutionService
            async with async_session() as db:
                wf_engine = WorkflowExecutionService(db)
                await wf_engine.recover_stale_runs()
        except Exception:
            logger.warning("Workflow recovery failed β€” skipping", exc_info=True)

    # Background tasks β€” only start in worker mode (or default/unset mode)
    # In API mode (WORKER_MODE=api), skip all background loops to avoid
    # duplicate processing when running multiple API instances.
    bg_tasks: list[asyncio.Task] = []

    if worker_mode != "api":
        bg_tasks.append(asyncio.create_task(_health_monitor_loop(
            interval_healthy=600, interval_degraded=120,
        )))
        bg_tasks.append(asyncio.create_task(_webhook_log_cleanup_loop(
            retention_days=int(os.environ.get("WEBHOOK_LOG_RETENTION_DAYS", "30")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_channel_message_cleanup_loop(
            retention_days=90, interval=86_400,
        )))
        # Free-tier DB quota cleanup β€” keep growth tables bounded so we
        # stay under Supabase 5 GB cap. Retention is conservative; tune
        # via env vars if needed.
        bg_tasks.append(asyncio.create_task(_llm_call_cleanup_loop(
            retention_days=int(os.environ.get("LLM_CALL_RETENTION_DAYS", "7")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_audit_log_cleanup_loop(
            retention_days=int(os.environ.get("AUDIT_LOG_RETENTION_DAYS", "90")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_telemetry_cleanup_loop(
            retention_days=int(os.environ.get("TELEMETRY_RETENTION_DAYS", "3")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_infrastructure_metric_cleanup_loop(
            retention_days=int(os.environ.get("INFRA_METRIC_RETENTION_DAYS", "30")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_failed_task_cleanup_loop(
            retention_days=int(os.environ.get("FAILED_TASK_RETENTION_DAYS", "30")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_workflow_run_cleanup_loop(
            retention_days=int(os.environ.get("WORKFLOW_RUN_RETENTION_DAYS", "30")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_supervisor_plan_cleanup_loop(
            retention_days=int(os.environ.get("SUPERVISOR_PLAN_RETENTION_DAYS", "30")),
            interval=86_400,
        )))
        bg_tasks.append(asyncio.create_task(_db_quota_monitor_loop(
            warn_gb=float(os.environ.get("DB_QUOTA_WARN_GB", "3.0")),
            critical_gb=float(os.environ.get("DB_QUOTA_CRITICAL_GB", "4.0")),
            interval=21_600,
        )))
        bg_tasks.append(asyncio.create_task(_vacuum_loop(interval=604_800)))
        bg_tasks.append(asyncio.create_task(_workflow_pump_loop(interval=3)))
        bg_tasks.append(asyncio.create_task(_scheduler_loop(interval=30)))
        bg_tasks.append(asyncio.create_task(
            _stale_reservation_cleanup_loop(interval=300)
        ))
        bg_tasks.append(asyncio.create_task(_infrastructure_metrics_loop()))
        logger.info("Started %d background tasks (worker mode)", len(bg_tasks))
    else:
        logger.info("WORKER_MODE=api β€” background tasks skipped")

    logger.info("CrewHub startup complete")
    yield

    # Shutdown
    for task in bg_tasks:
        task.cancel()
    for task in bg_tasks:
        try:
            await task
        except asyncio.CancelledError:
            pass
    logger.info("CrewHub shutting down")


app = FastAPI(
    title=settings.app_name,
    description="CrewHub β€” discover, negotiate, and transact between AI agents",
    version="0.4.0",
    lifespan=lifespan,
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
    openapi_url="/openapi.json" if settings.debug else None,
    # Disable automatic 307 redirects for trailing slashes. Behind HF Spaces
    # reverse proxy the Location header uses http:// causing Mixed Content
    # errors on the HTTPS frontend. Accept both /path and /path/ as-is.
    redirect_slashes=False,
)


# Security headers middleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["X-Frame-Options"] = "DENY"
        response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
        response.headers["X-XSS-Protection"] = "1; mode=block"
        if settings.force_https:
            response.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains"
        response.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
        return response


class RateLimitHeadersMiddleware(BaseHTTPMiddleware):
    """Inject X-RateLimit-* headers when rate limit info is available."""
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        info = getattr(request.state, "rate_limit_info", None)
        if info:
            response.headers["X-RateLimit-Limit"] = str(info["limit"])
            response.headers["X-RateLimit-Remaining"] = str(info["remaining"])
            response.headers["X-RateLimit-Reset"] = str(info["reset"])
        return response


app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(RateLimitHeadersMiddleware)
app.add_middleware(RequestTracingMiddleware)

# HTTPS redirect (production only)
if settings.force_https:
    from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
    app.add_middleware(HTTPSRedirectMiddleware)

# Request body size limit (10 MB)
MAX_BODY_SIZE = 10 * 1024 * 1024


@app.middleware("http")
async def security_headers(request: Request, call_next):
    """Add security headers to all responses (HSTS, CSP, X-headers)."""
    content_length = request.headers.get("content-length")
    if content_length and int(content_length) > MAX_BODY_SIZE:
        return JSONResponse(status_code=413, content={"detail": "Request body too large"})
    response = await call_next(request)
    response.headers["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains"
    response.headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
    return response


# CORS β€” allow the dashboard and existing site
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        # Primary domain
        "https://crewhubai.com",
        "https://www.crewhubai.com",
        "https://staging.crewhubai.com",
        "https://api.crewhubai.com",
        "https://api-staging.crewhubai.com",
        # Staging frontend
        "https://marketplace-staging.aidigitalcrew.com",
        # HuggingFace Spaces (direct access)
        "https://arimatch1-crewhub.hf.space",
        "https://arimatch1-crewhub-staging.hf.space",
        # Local development
        "http://localhost:3000",
        "http://localhost:5173",
        # Tauri desktop app
        "tauri://localhost",
        "https://tauri.localhost",
    ],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-Requested-With", "sentry-trace", "baggage"],
)


# Exception handlers
@app.exception_handler(MarketplaceError)
async def marketplace_error_handler(request: Request, exc: MarketplaceError):
    return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})


@app.exception_handler(MissingAPIKeyError)
async def missing_api_key_handler(request: Request, exc: MissingAPIKeyError):
    return JSONResponse(
        status_code=422,
        content={
            "detail": str(exc),
            "error_type": "missing_api_key",
            "provider": exc.provider,
        },
    )


@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
    """Catch-all for unhandled exceptions β€” log details, return sanitized 500."""
    logger.exception("Unhandled exception on %s %s", request.method, request.url.path)
    content = {"detail": "An internal error occurred. Please try again later."}
    if settings.debug:
        import traceback
        content["debug_error"] = f"{type(exc).__name__}: {exc}"
        content["debug_traceback"] = traceback.format_exc()
    return JSONResponse(status_code=500, content=content)


# Import and include routers
from src.api.agents import router as agents_router  # noqa: E402
from src.api.auth import router as auth_router  # noqa: E402
from src.api.credits import router as credits_router  # noqa: E402
from src.api.discovery import router as discovery_router  # noqa: E402
from src.api.health import router as health_router  # noqa: E402
from src.api.tasks import router as tasks_router  # noqa: E402
from src.api.llm_keys import router as llm_keys_router  # noqa: E402
from src.api.webhooks import router as webhooks_router  # noqa: E402
from src.api.imports import router as imports_router  # noqa: E402
from src.api.admin import router as admin_router  # noqa: E402
from src.api.a2a import router as a2a_router  # noqa: E402
from src.api.activity import router as activity_router  # noqa: E402
from src.api.llm_calls import router as llm_calls_router  # noqa: E402
from src.api.organizations import router as orgs_router  # noqa: E402
from src.api.anp import router as anp_router  # noqa: E402
from src.api.billing import router as billing_router  # noqa: E402
from src.api.suggestions import router as suggestions_router  # noqa: E402
from src.api.detect import router as detect_router  # noqa: E402
from src.api.validate import router as validate_router  # noqa: E402
from src.api.webhook_logs import router as webhook_logs_router  # noqa: E402
from src.mcp.router import router as mcp_resources_router  # noqa: E402
from src.api.telemetry import router as telemetry_router  # noqa: E402
from src.api.analytics import router as analytics_router  # noqa: E402
from src.api.crews import router as crews_router  # noqa: E402
from src.api.feedback import router as feedback_router  # noqa: E402
from src.api.guest_trial import router as guest_trial_router  # noqa: E402
from src.api.payouts import router as payouts_router  # noqa: E402
from src.api.supervisor import router as supervisor_router  # noqa: E402
from src.api.workflows import router as workflows_router  # noqa: E402
from src.api.schedules import router as schedules_router  # noqa: E402
from src.api.custom_agents import router as custom_agents_router  # noqa: E402
from src.api.channels import router as channels_router  # noqa: E402
from src.api.builder import router as builder_router  # noqa: E402
from src.api.langflow_proxy import router as langflow_router  # noqa: E402
from src.api.gateway import router as gateway_router  # noqa: E402
from src.api.mcp_servers import router as mcp_servers_router  # noqa: E402
from src.api.infrastructure import router as infrastructure_router  # noqa: E402

app.include_router(auth_router, prefix=settings.api_v1_prefix)
app.include_router(agents_router, prefix=settings.api_v1_prefix)
app.include_router(discovery_router, prefix=settings.api_v1_prefix)
app.include_router(tasks_router, prefix=settings.api_v1_prefix)
app.include_router(credits_router, prefix=settings.api_v1_prefix)
app.include_router(llm_keys_router, prefix=settings.api_v1_prefix)
app.include_router(health_router)
app.include_router(webhooks_router, prefix=settings.api_v1_prefix)
app.include_router(imports_router, prefix=settings.api_v1_prefix)
app.include_router(admin_router, prefix=settings.api_v1_prefix)
app.include_router(a2a_router, prefix=settings.api_v1_prefix)
app.include_router(activity_router, prefix=settings.api_v1_prefix)
app.include_router(llm_calls_router, prefix=settings.api_v1_prefix)
app.include_router(orgs_router, prefix=settings.api_v1_prefix)
app.include_router(anp_router, prefix=settings.api_v1_prefix)
app.include_router(billing_router, prefix=settings.api_v1_prefix)
app.include_router(suggestions_router, prefix=settings.api_v1_prefix)
app.include_router(detect_router, prefix=settings.api_v1_prefix)
app.include_router(validate_router, prefix=settings.api_v1_prefix)
app.include_router(webhook_logs_router, prefix=settings.api_v1_prefix)
app.include_router(mcp_resources_router, prefix=settings.api_v1_prefix)
app.include_router(mcp_servers_router, prefix=settings.api_v1_prefix)
app.include_router(telemetry_router, prefix=settings.api_v1_prefix)
app.include_router(analytics_router, prefix=settings.api_v1_prefix)
app.include_router(crews_router, prefix=settings.api_v1_prefix)
app.include_router(feedback_router, prefix=settings.api_v1_prefix)
app.include_router(guest_trial_router, prefix=settings.api_v1_prefix)
app.include_router(payouts_router, prefix=settings.api_v1_prefix)
app.include_router(supervisor_router, prefix=settings.api_v1_prefix)
app.include_router(channels_router, prefix=settings.api_v1_prefix)
app.include_router(workflows_router, prefix=settings.api_v1_prefix)
app.include_router(schedules_router, prefix=settings.api_v1_prefix)
app.include_router(custom_agents_router, prefix=settings.api_v1_prefix)
app.include_router(builder_router, prefix=settings.api_v1_prefix)
app.include_router(gateway_router, prefix=settings.api_v1_prefix)
app.include_router(langflow_router)  # mounted at root (no prefix) β€” /langflow/run/{flow_id}
# Also mount ANP well-known endpoint at root (no prefix)
app.include_router(anp_router)
app.include_router(infrastructure_router, prefix=settings.api_v1_prefix)

# Mount MCP server β€” auto-generates MCP tools from all FastAPI endpoints
import importlib.util
import logging as _logging

_mcp_logger = _logging.getLogger(__name__)

if importlib.util.find_spec("fastapi_mcp") is not None:
    from fastapi_mcp import FastApiMCP
    mcp = FastApiMCP(
        app,
        name="CrewHub",
        description="AI Agent Marketplace β€” discover, delegate, and manage AI agents",
    )
    mcp.mount_http()  # Streamable HTTP transport at /mcp (recommended, replaces deprecated mount())
    _mcp_logger.info("MCP server mounted at /mcp (HTTP transport)")
else:
    _mcp_logger.warning("fastapi-mcp not installed β€” MCP server endpoint disabled")


# Root β€” HF Spaces readiness probe hits GET /
@app.get("/")
async def root():
    return {"name": "CrewHub", "status": "ok", "docs": "/docs" if settings.debug else None}


# Well-known agent card
@app.get("/.well-known/agent-card.json")
async def well_known_agent_card():
    return {
        "name": settings.app_name,
        "description": "CrewHub β€” Agent-to-Agent discovery and delegation marketplace",
        "url": "https://api.crewhubai.com",
        "version": "0.4.0",
        "capabilities": {
            "streaming": True,
            "pushNotifications": True,
        },
        "authentication": {
            "schemes": ["bearer", "apiKey"],
            "credentials": {
                "bearer": {"headerName": "Authorization", "prefix": "Bearer"},
                "apiKey": {"headerName": "X-API-Key"},
            },
        },
        "provider": {
            "organization": "CrewHub",
            "url": "https://crewhubai.com",
        },
        "defaultInputModes": ["text"],
        "defaultOutputModes": ["text"],
        "skills": [
            {
                "id": "discover-agents",
                "name": "Discover Agents",
                "description": "Search and discover AI agents by capability, category, or intent",
            },
            {
                "id": "delegate-task",
                "name": "Delegate Task",
                "description": "Delegate a task to a discovered agent and track its completion",
            },
        ],
    }