-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathpost_gen_tasks.py
More file actions
1360 lines (1191 loc) · 55 KB
/
post_gen_tasks.py
File metadata and controls
1360 lines (1191 loc) · 55 KB
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Shared post-generation tasks for Cookiecutter and Copier.
This module provides common post-generation functionality used by both
template engines to avoid code duplication and ensure consistent behavior.
"""
import os
import shutil
import subprocess
from pathlib import Path
from typing import Any
import typer
from aegis.constants import (
AnswerKeys,
ComponentNames,
StorageBackends,
WorkerBackends,
)
from aegis.core.project_map import render_project_map
from aegis.i18n import t
# Task configuration constants (following tests/cli/test_utils.py pattern)
POST_GEN_TIMEOUT_INSTALL = 300 # 5 minutes for dependency installation
POST_GEN_TIMEOUT_FORMAT = 60 # 1 minute for code formatting
POST_GEN_TIMEOUT_MIGRATION = 30 # 30 seconds for database migration
POST_GEN_TIMEOUT_LLM_SYNC = 90 # 90 seconds for LLM catalog sync
POST_GEN_STDERR_MAX_LINES = 15 # Maximum stderr lines to display
def _truncate_stderr(stderr: str, max_lines: int = POST_GEN_STDERR_MAX_LINES) -> str:
"""
Truncate stderr output to a reasonable number of lines.
Args:
stderr: The stderr output to truncate
max_lines: Maximum number of lines to show
Returns:
Truncated stderr with indication if lines were omitted
"""
lines = stderr.strip().split("\n")
if len(lines) <= max_lines:
return stderr.strip()
# Show first and last portions
head_lines = max_lines // 2
tail_lines = max_lines - head_lines
omitted = len(lines) - max_lines
result = lines[:head_lines]
result.append(f" ... ({omitted} lines omitted) ...")
result.extend(lines[-tail_lines:])
return "\n".join(result)
# TODO: This entire file mapping + cleanup + shared_files approach needs to be
# refactored. Every new template file requires manual registration in 3 places:
# 1. get_component_file_mapping() below (for add/remove)
# 2. cleanup_components() (for init-time removal)
# 3. shared_files.py SHARED_TEMPLATE_FILES (for jinja regeneration on add-service)
# This is fragile and unmaintainable. Should be auto-discovered from the template
# directory structure or declared once in a single config.
def get_component_file_mapping() -> dict[str, list[str]]:
"""
Get mapping of components to their files.
Returns a dictionary mapping component names to lists of files/directories
that belong to that component. This is used by both cleanup_components()
and component_files.py for consistency.
Returns:
Dict mapping component names to file paths (relative to project root)
"""
return {
ComponentNames.SCHEDULER: [
"app/entrypoints/scheduler.py",
"app/components/scheduler",
"tests/components/test_scheduler.py",
"docs/components/scheduler.md",
"app/components/backend/api/scheduler.py",
"tests/api/test_scheduler_endpoints.py",
"app/components/frontend/dashboard/cards/scheduler_card.py",
"app/components/frontend/dashboard/modals/scheduler_modal.py",
"tests/services/test_scheduled_task_manager.py",
],
f"{ComponentNames.SCHEDULER}_persistence": [ # Only for sqlite backend
"app/services/scheduler",
"app/cli/tasks.py",
"app/components/backend/api/scheduler.py",
"tests/api/test_scheduler_endpoints.py",
"tests/services/test_scheduled_task_manager.py",
],
ComponentNames.WORKER: [
"app/components/worker",
"app/cli/load_test.py",
"app/services/load_test.py",
"app/services/load_test_models.py",
"app/services/load_test_workloads.py",
"tests/services/test_load_test_models.py",
"tests/services/test_load_test_service.py",
"tests/services/test_worker_health_registration.py",
"app/components/backend/api/worker.py",
"tests/api/test_worker_endpoints.py",
"app/components/frontend/dashboard/cards/worker_card.py",
"app/components/frontend/dashboard/modals/worker_modal.py",
"app/components/frontend/dashboard/modals/task_history_section.py",
],
ComponentNames.DATABASE: [
"app/core/db.py",
"app/components/frontend/dashboard/cards/database_card.py",
"app/components/frontend/dashboard/modals/database_modal.py",
],
ComponentNames.REDIS: [
"app/components/frontend/dashboard/cards/redis_card.py",
"app/components/frontend/dashboard/modals/redis_modal.py",
],
ComponentNames.INGRESS: [
"traefik",
"app/components/frontend/dashboard/cards/ingress_card.py",
"app/components/frontend/dashboard/modals/ingress_modal.py",
],
ComponentNames.OBSERVABILITY: [
"app/components/backend/middleware/logfire_tracing.py",
"app/components/frontend/dashboard/cards/observability_card.py",
"app/components/frontend/dashboard/modals/observability_modal.py",
],
AnswerKeys.SERVICE_AUTH: [
"app/components/backend/api/auth",
"app/models/user.py",
"app/services/auth",
"app/core/security.py",
"app/cli/auth.py",
"tests/api/test_auth_endpoints.py",
"tests/services/test_auth_integration.py",
# Note: alembic is now shared between auth and AI services
# Frontend dashboard files
"app/components/frontend/dashboard/cards/auth_card.py",
"app/components/frontend/dashboard/modals/auth_modal.py",
"app/components/frontend/dashboard/modals/auth_users_tab.py",
# Org-level files (cleaned up by post_gen if org not selected)
"app/models/org.py",
"app/components/backend/api/orgs",
"app/components/frontend/dashboard/modals/auth_orgs_tab.py",
"tests/services/test_org_integration.py",
"tests/api/test_org_endpoints.py",
],
AnswerKeys.SERVICE_AI: [
"app/components/backend/api/ai",
"app/services/ai",
"app/cli/ai.py",
"app/cli/ai_rendering.py",
"app/cli/marko_terminal_renderer.py",
"app/cli/chat_completer.py",
"app/cli/slash_commands.py",
"app/cli/llm.py",
"app/cli/status_line.py",
"app/core/formatting.py",
"app/models/conversation.py",
"tests/services/test_conversation_persistence.py",
"tests/cli/test_ai_rendering.py",
"tests/cli/test_conversation_memory.py",
"tests/cli/test_chat_completer.py",
"tests/services/ai",
# Frontend dashboard files
"app/components/frontend/dashboard/cards/ai_card.py",
"app/components/frontend/dashboard/modals/ai_modal.py",
"app/components/frontend/dashboard/modals/ai_analytics_tab.py",
"app/components/frontend/dashboard/modals/llm_catalog_tab.py",
"app/components/frontend/dashboard/modals/rag_tab.py",
"tests/components/frontend/test_ai_analytics_utils.py",
],
AnswerKeys.SERVICE_COMMS: [
"app/components/backend/api/comms",
"app/services/comms",
"app/cli/comms.py",
"tests/api/test_comms_endpoints.py",
"tests/services/comms",
"docs/services/comms",
# Frontend dashboard files
"app/components/frontend/dashboard/cards/comms_card.py",
"app/components/frontend/dashboard/modals/comms_modal.py",
],
AnswerKeys.AI_RAG: [
"app/components/backend/api/rag",
"app/services/rag",
"app/cli/rag.py",
"tests/services/rag",
],
AnswerKeys.AI_VOICE: [
"app/components/backend/api/voice",
"app/services/ai/voice",
"tests/services/ai/voice",
"tests/api/test_voice_endpoints.py",
"app/components/frontend/dashboard/modals/voice_settings_tab.py",
],
AnswerKeys.SERVICE_INSIGHTS: [
"app/components/backend/api/insights.py",
"app/services/insights",
"app/cli/insights.py",
"tests/services/test_insight_service.py",
"tests/services/test_insights_collectors.py",
"tests/services/test_query_service.py",
"tests/services/test_collector_service.py",
"tests/services/test_collector_github_traffic.py",
"tests/services/test_collector_github_events.py",
"tests/services/test_collector_github_stars.py",
"tests/services/test_collector_pypi.py",
"tests/services/test_collector_plausible.py",
"tests/services/test_collector_reddit.py",
"tests/api/test_insights_endpoints.py",
"tests/test_bulk_response.py",
"tests/test_cache_integration.py",
# Frontend dashboard files
"app/components/frontend/dashboard/cards/insights_card.py",
"app/components/frontend/dashboard/modals/insights_modal.py",
],
AnswerKeys.SERVICE_PAYMENT: [
"app/components/backend/api/payment",
"app/services/payment",
"app/cli/payment.py",
"tests/services/test_payment_service.py",
"tests/services/test_payment_models.py",
"tests/services/test_payment_catalog.py",
"tests/services/test_payment_webhook_forwarder.py",
"tests/cli/test_payment_trigger.py",
"tests/api/test_payment_endpoints.py",
# Backend lifecycle hooks (auto-forward stripe-cli webhooks in dev)
"app/components/backend/startup/payment_webhook_forwarder.py",
"app/components/backend/shutdown/payment_webhook_forwarder.py",
# Frontend dashboard files
"app/components/frontend/dashboard/cards/payment_card.py",
"app/components/frontend/dashboard/modals/payment_modal.py",
],
}
def remove_file(project_path: Path, filepath: str) -> None:
"""
Remove a file from the generated project.
Args:
project_path: Path to the project directory
filepath: Relative path to the file to remove
"""
full_path = project_path / filepath
if full_path.exists():
full_path.unlink()
def remove_dir(project_path: Path, dirpath: str) -> None:
"""
Remove a directory from the generated project.
Args:
project_path: Path to the project directory
dirpath: Relative path to the directory to remove
"""
full_path = project_path / dirpath
if full_path.exists():
shutil.rmtree(full_path)
def cleanup_components(project_path: Path, context: dict[str, Any]) -> None:
"""
Remove component files based on component selection.
This function handles component cleanup for both Cookiecutter and Copier
template engines, ensuring identical behavior.
Args:
project_path: Path to the generated project
context: Dictionary with component/service flags
Note:
Handles both Cookiecutter (string "yes"/"no") and Copier (boolean true/false)
context values for maximum compatibility.
"""
# Helper to handle both bool and string values from different template engines
def is_enabled(key: str) -> bool:
value = context.get(key)
return value is True or value == "yes"
# Remove scheduler component if not selected
if not is_enabled(AnswerKeys.SCHEDULER):
remove_file(project_path, "app/entrypoints/scheduler.py")
remove_dir(project_path, "app/components/scheduler")
remove_file(project_path, "tests/components/test_scheduler.py")
remove_file(project_path, "docs/components/scheduler.md")
remove_file(project_path, "app/components/backend/api/scheduler.py")
remove_file(project_path, "tests/api/test_scheduler_endpoints.py")
remove_file(
project_path, "app/components/frontend/dashboard/cards/scheduler_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/scheduler_modal.py"
)
remove_file(project_path, "tests/services/test_scheduled_task_manager.py")
# Remove scheduler service if using memory backend
# The service is only useful when we can persist to a database
scheduler_backend = context.get(
AnswerKeys.SCHEDULER_BACKEND, StorageBackends.MEMORY
)
if scheduler_backend == StorageBackends.MEMORY:
remove_dir(project_path, "app/services/scheduler")
remove_file(project_path, "app/cli/tasks.py")
remove_file(project_path, "app/components/backend/api/scheduler.py")
remove_file(project_path, "tests/api/test_scheduler_endpoints.py")
remove_file(project_path, "tests/services/test_scheduled_task_manager.py")
# Remove worker component if not selected
if not is_enabled(AnswerKeys.WORKER):
remove_dir(project_path, "app/components/worker")
remove_file(project_path, "app/cli/load_test.py")
remove_file(project_path, "app/services/load_test.py")
remove_file(project_path, "app/services/load_test_models.py")
remove_file(project_path, "app/services/load_test_workloads.py")
remove_file(project_path, "tests/services/test_load_test_models.py")
remove_file(project_path, "tests/services/test_load_test_service.py")
remove_file(project_path, "tests/services/test_worker_health_registration.py")
remove_file(project_path, "app/components/backend/api/worker.py")
remove_file(project_path, "app/components/backend/api/worker_taskiq.py")
remove_file(project_path, "tests/api/test_worker_endpoints.py")
remove_file(
project_path, "app/components/frontend/dashboard/cards/worker_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/worker_modal.py"
)
else:
# Worker is included - clean up backend-specific files
worker_backend = context.get(AnswerKeys.WORKER_BACKEND, WorkerBackends.ARQ)
queues_dir = project_path / "app/components/worker/queues"
worker_dir = project_path / "app/components/worker"
api_dir = project_path / "app/components/backend/api"
services_dir = project_path / "app/services"
# Helper: remove all files matching a suffix pattern
def _remove_backend_files(suffix: str) -> None:
"""Remove all files with the given backend suffix."""
for f in queues_dir.glob(f"*{suffix}"):
f.unlink()
for name in [
f"middleware{suffix}",
f"pools{suffix}",
f"registry{suffix}",
f"broker{suffix}",
]:
target = worker_dir / name
if target.exists():
target.unlink()
api_file = api_dir / f"worker{suffix}"
if api_file.exists():
api_file.unlink()
load_test_file = services_dir / f"load_test{suffix}"
if load_test_file.exists():
load_test_file.unlink()
# Helper: rename backend-specific files to canonical names
def _rename_backend_files(suffix: str) -> set[str]:
"""Rename *_<backend>.py files to *.py, return set of final names."""
final_names = {"__init__.py"}
# Rename queue files
if queues_dir.exists():
for backend_file in queues_dir.glob(f"*{suffix}"):
final_name = backend_file.name.replace(suffix, ".py")
arq_file = backend_file.with_name(final_name)
if arq_file.exists():
arq_file.unlink()
backend_file.rename(queues_dir / final_name)
final_names.add(final_name)
# Rename worker-dir files (pools, registry, middleware, broker)
for stem in ["pools", "registry", "middleware", "broker"]:
backend_file = worker_dir / f"{stem}{suffix}"
canonical = worker_dir / f"{stem}.py"
if backend_file.exists():
if canonical.exists():
canonical.unlink()
backend_file.rename(canonical)
# Rename API file
api_backend = api_dir / f"worker{suffix}"
api_canonical = api_dir / "worker.py"
if api_backend.exists():
if api_canonical.exists():
api_canonical.unlink()
api_backend.rename(api_canonical)
# Rename load_test service file
lt_backend = services_dir / f"load_test{suffix}"
lt_canonical = services_dir / "load_test.py"
if lt_backend.exists():
if lt_canonical.exists():
lt_canonical.unlink()
lt_backend.rename(lt_canonical)
return final_names
if queues_dir.exists():
if worker_backend == WorkerBackends.DRAMATIQ:
# Using Dramatiq: rename _dramatiq.py files, remove arq + taskiq
dramatiq_final_names = _rename_backend_files("_dramatiq.py")
# Remove arq-only queue files (those without dramatiq counterparts)
for py_file in queues_dir.glob("*.py"):
if py_file.name not in dramatiq_final_names:
py_file.unlink()
_remove_backend_files("_taskiq.py")
elif worker_backend == WorkerBackends.TASKIQ:
# Using TaskIQ: rename _taskiq.py files, remove arq + dramatiq
taskiq_final_names = _rename_backend_files("_taskiq.py")
# Remove arq-only queue files (those without taskiq counterparts)
for py_file in queues_dir.glob("*.py"):
if py_file.name not in taskiq_final_names:
py_file.unlink()
_remove_backend_files("_dramatiq.py")
else:
# Using arq (default): remove taskiq and dramatiq versions
_remove_backend_files("_taskiq.py")
_remove_backend_files("_dramatiq.py")
# Remove shared component integration tests only when BOTH scheduler AND worker disabled
if not is_enabled(AnswerKeys.SCHEDULER) and not is_enabled(AnswerKeys.WORKER):
remove_file(project_path, "tests/services/test_component_integration.py")
remove_file(project_path, "tests/services/test_health_logic.py")
# Remove database component if not selected
if not is_enabled(AnswerKeys.DATABASE):
remove_file(project_path, "app/core/db.py")
remove_file(
project_path, "app/components/frontend/dashboard/cards/database_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/database_modal.py"
)
# Remove redis component dashboard files if not selected
if not is_enabled(AnswerKeys.REDIS):
remove_file(
project_path, "app/components/frontend/dashboard/cards/redis_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/redis_modal.py"
)
# Remove ingress component if not selected
if not is_enabled(AnswerKeys.INGRESS):
remove_dir(project_path, "traefik")
remove_file(
project_path, "app/components/frontend/dashboard/cards/ingress_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/ingress_modal.py"
)
# Remove observability component if not selected
if not is_enabled(AnswerKeys.OBSERVABILITY):
remove_file(
project_path, "app/components/backend/middleware/logfire_tracing.py"
)
remove_file(
project_path,
"app/components/frontend/dashboard/cards/observability_card.py",
)
remove_file(
project_path,
"app/components/frontend/dashboard/modals/observability_modal.py",
)
# Remove cache component if not selected
if not is_enabled(AnswerKeys.CACHE):
pass # Placeholder - cache component doesn't exist yet
# Remove auth service if not selected
if not is_enabled(AnswerKeys.AUTH):
remove_dir(project_path, "app/components/backend/api/auth")
remove_file(project_path, "app/models/user.py")
remove_dir(project_path, "app/services/auth")
remove_file(project_path, "app/core/security.py")
remove_file(project_path, "app/cli/auth.py")
remove_file(project_path, "tests/api/test_auth_endpoints.py")
remove_file(project_path, "tests/services/test_auth_service.py")
remove_file(project_path, "tests/services/test_auth_integration.py")
remove_file(project_path, "tests/models/test_user.py")
# Goal service is auth-coupled (Goal.user_id FK to user table), so its
# tests are only meaningful when auth is on. The source file lives
# under app/services/insights/ but follows the auth cleanup path.
remove_file(project_path, "tests/services/test_goal_service.py")
# Note: alembic removal is handled below based on whether ANY service needs migrations
# Remove OAuth (social login) files when not selected. Auth-only
# projects without OAuth still have ``OAuthProvider`` /
# ``UserOAuthIdentity`` SQLModels in ``app/models/user.py`` (the
# tables ship with the auth migration unconditionally), but the
# routes, middleware, settings, and tests are scoped here.
if not is_enabled(AnswerKeys.AUTH_OAUTH):
remove_file(project_path, "app/components/backend/api/auth/oauth.py")
remove_file(project_path, "app/components/backend/middleware/session.py")
remove_file(project_path, "tests/api/test_oauth_endpoints.py")
remove_file(project_path, "tests/services/test_oauth_user_service.py")
# Remove auth org files if org level not selected (but auth is enabled)
if is_enabled(AnswerKeys.AUTH) and not is_enabled(AnswerKeys.AUTH_ORG):
remove_file(project_path, "app/models/org.py")
remove_file(project_path, "app/services/auth/org_service.py")
remove_file(project_path, "app/services/auth/membership_service.py")
remove_file(project_path, "app/services/auth/invite_service.py")
remove_dir(project_path, "app/components/backend/api/orgs")
remove_file(
project_path,
"app/components/frontend/dashboard/modals/auth_orgs_tab.py",
)
remove_file(project_path, "tests/services/test_org_integration.py")
remove_file(project_path, "tests/api/test_org_endpoints.py")
# Remove AI service if not selected
if not is_enabled(AnswerKeys.AI):
remove_dir(project_path, "app/components/backend/api/ai")
remove_dir(project_path, "app/services/ai")
remove_file(project_path, "app/cli/ai.py")
remove_file(project_path, "app/cli/ai_rendering.py")
remove_file(project_path, "app/cli/marko_terminal_renderer.py")
remove_file(project_path, "app/cli/chat_completer.py")
remove_file(project_path, "app/cli/slash_commands.py")
remove_file(project_path, "app/cli/llm.py")
remove_file(project_path, "app/cli/status_line.py")
remove_file(project_path, "app/core/formatting.py")
remove_file(project_path, "tests/api/test_ai_endpoints.py")
remove_file(project_path, "tests/services/test_conversation_persistence.py")
remove_file(project_path, "tests/cli/test_ai_rendering.py")
remove_file(project_path, "tests/cli/test_conversation_memory.py")
remove_file(project_path, "tests/cli/test_chat_completer.py")
remove_file(project_path, "tests/cli/test_llm_cli.py")
remove_file(project_path, "tests/cli/test_slash_commands.py")
remove_file(project_path, "tests/cli/test_status_line.py")
remove_dir(project_path, "tests/services/ai")
remove_file(project_path, "app/components/frontend/dashboard/cards/ai_card.py")
remove_file(
project_path, "app/components/frontend/dashboard/modals/ai_modal.py"
)
# Remove AI conversation SQLModel tables
remove_file(project_path, "app/models/conversation.py")
# AI conversation persistence handling
# When AI backend is memory (or not specified), remove database-related files
ai_backend = context.get(AnswerKeys.AI_BACKEND, StorageBackends.MEMORY)
if ai_backend == StorageBackends.MEMORY:
remove_file(project_path, "app/models/conversation.py")
# Remove LLM tracking models (only needed with persistence)
# Keep app/services/ai/models/__init__.py - contains core types (AIProvider, ProviderConfig)
remove_dir(project_path, "app/services/ai/models/llm")
remove_dir(project_path, "app/services/ai/etl")
remove_dir(project_path, "app/services/ai/fixtures")
# Remove persistence-related contexts (keep usage_context.py - no DB deps)
remove_file(project_path, "app/services/ai/llm_catalog_context.py")
remove_file(project_path, "app/services/ai/llm_service.py")
remove_file(project_path, "app/services/ai/provider_management.py")
# Remove persistence-related tests
remove_dir(project_path, "tests/services/ai/etl")
remove_file(project_path, "tests/services/ai/test_usage_tracking.py")
remove_file(project_path, "tests/services/ai/test_llm_catalog_context.py")
remove_file(project_path, "tests/services/ai/test_llm_service.py")
remove_file(project_path, "tests/services/ai/test_provider_management.py")
# Remove LLM CLI and API (catalog management needs database)
remove_file(project_path, "app/cli/llm.py")
remove_file(project_path, "tests/cli/test_llm_cli.py")
remove_dir(project_path, "app/components/backend/api/llm")
remove_file(project_path, "tests/api/test_llm_endpoints.py")
# Remove analytics UI (needs database for usage tracking)
remove_file(
project_path, "app/components/frontend/dashboard/modals/ai_analytics_tab.py"
)
remove_file(
project_path, "tests/components/frontend/test_ai_analytics_utils.py"
)
# ETL / LLM catalog depend transitively on Ollama: they import from
# ``app.services.ai.ollama`` (which is a stub when ``ollama_mode=none``)
# and from ``app.services.ai.etl``. When Ollama is off the whole
# chain must come out so the module graph stays importable.
ollama_mode = context.get(AnswerKeys.OLLAMA_MODE, "none")
if ollama_mode == "none":
remove_dir(project_path, "tests/services/ai/etl")
remove_dir(project_path, "app/services/ai/etl")
# llm router + API imports ``app.services.ai.etl`` at module load.
remove_dir(project_path, "app/components/backend/api/llm")
remove_file(project_path, "tests/api/test_llm_endpoints.py")
# LLM CLI also touches etl models.
remove_file(project_path, "app/cli/llm.py")
remove_file(project_path, "tests/cli/test_llm_cli.py")
# Remove RAG service if not enabled
if not is_enabled(AnswerKeys.AI_RAG):
remove_dir(project_path, "app/components/backend/api/rag")
remove_dir(project_path, "app/services/rag")
remove_file(project_path, "app/cli/rag.py")
remove_dir(project_path, "tests/services/rag")
# Remove RAG-related files within AI service
remove_file(project_path, "app/services/ai/rag_context.py")
remove_file(project_path, "app/services/ai/rag_stats_context.py")
remove_file(project_path, "tests/services/ai/test_rag_stats_context.py")
remove_file(project_path, "app/components/frontend/dashboard/modals/rag_tab.py")
# Remove voice (TTS/STT) if not enabled
if not is_enabled(AnswerKeys.AI_VOICE):
remove_dir(project_path, "app/components/backend/api/voice")
remove_dir(project_path, "app/services/ai/voice")
remove_dir(project_path, "tests/services/ai/voice")
remove_file(project_path, "tests/api/test_voice_endpoints.py")
remove_file(
project_path,
"app/components/frontend/dashboard/modals/voice_settings_tab.py",
)
# Remove comms service if not selected
if not is_enabled(AnswerKeys.COMMS):
remove_dir(project_path, "app/components/backend/api/comms")
remove_dir(project_path, "app/services/comms")
remove_file(project_path, "app/cli/comms.py")
remove_file(project_path, "tests/api/test_comms_endpoints.py")
remove_dir(project_path, "tests/services/comms")
remove_dir(project_path, "docs/services/comms")
remove_file(
project_path, "app/components/frontend/dashboard/cards/comms_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/comms_modal.py"
)
# Remove payment service if not selected
if not is_enabled(AnswerKeys.PAYMENT):
remove_dir(project_path, "app/components/backend/api/payment")
remove_dir(project_path, "app/services/payment")
remove_file(project_path, "app/cli/payment.py")
remove_file(project_path, "tests/services/test_payment_service.py")
remove_file(project_path, "tests/services/test_payment_models.py")
remove_file(project_path, "tests/services/test_payment_catalog.py")
remove_file(project_path, "tests/services/test_payment_webhook_forwarder.py")
remove_file(project_path, "tests/cli/test_payment_trigger.py")
remove_file(project_path, "tests/api/test_payment_endpoints.py")
remove_file(
project_path, "app/components/backend/startup/payment_webhook_forwarder.py"
)
remove_file(
project_path, "app/components/backend/shutdown/payment_webhook_forwarder.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/cards/payment_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/payment_modal.py"
)
# Remove insights service if not selected
if not is_enabled(AnswerKeys.INSIGHTS):
remove_dir(project_path, "app/components/backend/api/insights")
remove_dir(project_path, "app/services/insights")
remove_file(project_path, "app/components/backend/api/insights.py")
remove_file(project_path, "app/cli/insights.py")
remove_file(project_path, "tests/services/test_insights_service.py")
remove_file(project_path, "tests/services/test_insights_collectors.py")
remove_file(project_path, "tests/services/test_insight_service.py")
remove_file(project_path, "tests/services/test_query_service.py")
remove_file(project_path, "tests/services/test_collector_service.py")
remove_file(project_path, "tests/services/test_collector_github_traffic.py")
remove_file(project_path, "tests/services/test_collector_github_events.py")
remove_file(project_path, "tests/services/test_collector_github_stars.py")
remove_file(project_path, "tests/services/test_collector_pypi.py")
remove_file(project_path, "tests/services/test_collector_plausible.py")
remove_file(project_path, "tests/services/test_collector_reddit.py")
# Goal service tests import from app.services.insights, so they
# must be removed whenever insights is off — not just when auth is
# off (the auth-coupled cleanup above handles the auth-off path).
remove_file(project_path, "tests/services/test_goal_service.py")
remove_file(project_path, "tests/api/test_insights_endpoints.py")
remove_file(project_path, "tests/test_bulk_response.py")
remove_file(project_path, "tests/test_cache_integration.py")
remove_file(
project_path, "app/components/frontend/dashboard/cards/insights_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/insights_modal.py"
)
# Remove auth service dashboard files if not selected
if not is_enabled(AnswerKeys.AUTH):
remove_file(
project_path, "app/components/frontend/dashboard/cards/auth_card.py"
)
remove_file(
project_path, "app/components/frontend/dashboard/modals/auth_modal.py"
)
# Remove services_card.py only if NO services are enabled
# ServicesCard shows all services, so keep if ANY service is enabled
if (
not is_enabled(AnswerKeys.AUTH)
and not is_enabled(AnswerKeys.AI)
and not is_enabled(AnswerKeys.COMMS)
and not is_enabled(AnswerKeys.INSIGHTS)
and not is_enabled(AnswerKeys.PAYMENT)
):
remove_file(
project_path, "app/components/frontend/dashboard/cards/services_card.py"
)
# Remove Alembic directory only if NO service needs migrations
# Alembic is needed when: auth, insights, payment, or (AI with non-memory backend)
include_auth = is_enabled(AnswerKeys.AUTH)
include_ai = is_enabled(AnswerKeys.AI)
include_insights = is_enabled(AnswerKeys.INSIGHTS)
include_payment = is_enabled(AnswerKeys.PAYMENT)
ai_backend = context.get(AnswerKeys.AI_BACKEND, StorageBackends.MEMORY)
ai_needs_migrations = include_ai and ai_backend != StorageBackends.MEMORY
needs_migrations = (
include_auth or ai_needs_migrations or include_insights or include_payment
)
if not needs_migrations:
remove_dir(project_path, "alembic")
# Clean up empty docs/components directory if no components selected
if (
not is_enabled(AnswerKeys.SCHEDULER)
and not is_enabled(AnswerKeys.WORKER)
and not is_enabled(AnswerKeys.DATABASE)
and not is_enabled(AnswerKeys.CACHE)
):
remove_dir(project_path, "docs/components")
def _render_jinja_template(src: Path, dst: Path, project_path: Path) -> None:
"""
Render a Jinja2 template file and write to destination.
Args:
src: Path to the .jinja template file
dst: Path to write the rendered output (without .jinja extension)
project_path: Path to the project (used to derive template variables)
"""
from jinja2 import Environment, FileSystemLoader
# Get project name from project path
project_slug = project_path.name
# Set up Jinja2 environment
env = Environment(
loader=FileSystemLoader(src.parent),
keep_trailing_newline=True,
)
# Load and render template
template = env.get_template(src.name)
# Build context with common variables
# These match the variables used in copier.yml
context = {
"project_slug": project_slug,
"project_name": project_slug.replace("-", " ").title(),
# Service flags - assume true since we're copying service files
"include_auth": True,
"include_ai": True,
"include_comms": True,
"include_insights": True,
"include_payment": True,
# Component flags - check what exists in project
"include_scheduler": (project_path / "app/components/scheduler").exists(),
"include_worker": (project_path / "app/components/worker").exists(),
"include_database": (project_path / "app/core/db.py").exists(),
"include_observability": (
project_path / "app/components/backend/middleware/logfire_tracing.py"
).exists(),
"include_cache": (project_path / "app/components/cache").exists(),
# AI-specific settings (defaults)
"ai_framework": "anthropic",
"ai_backend": "sqlite",
"ai_provider_anthropic": True,
"ai_provider_openai": False,
}
rendered = template.render(**context)
# Write to destination
dst.write_text(rendered)
def copy_service_files(
project_path: Path, service_name: str, template_path: Path
) -> None:
"""
Copy service-specific files from template to project.
This is needed when services are added post-generation via Copier update.
Copier can only re-render existing files - it cannot copy new directories
that were excluded during initial generation.
Args:
project_path: Path to the project directory
service_name: Name of the service ('auth', 'ai', etc.)
template_path: Path to the Copier template directory
Note:
Uses get_component_file_mapping() to know which files belong to each service.
"""
# Get the file mapping for this service
file_mapping = get_component_file_mapping()
if service_name not in file_mapping:
typer.secho(
f"Unknown service '{service_name}' - skipping file copy",
fg=typer.colors.YELLOW,
)
return
service_files = file_mapping[service_name]
typer.secho(
f"Copying {service_name} service files from template...", fg=typer.colors.CYAN
)
# The template is at: aegis-stack/aegis/templates/copier-aegis-project/{{ project_slug }}/
# We need to find the template content directory
template_content = template_path / "{{ project_slug }}"
if not template_content.exists():
typer.secho(
f"Warning: Template content directory not found: {template_content}",
fg=typer.colors.YELLOW,
)
return
copied_count = 0
for rel_path in service_files:
src = template_content / rel_path
dst = project_path / rel_path
# Check for .jinja version if plain file doesn't exist
jinja_src = template_content / (rel_path + ".jinja")
is_jinja_template = False
if not src.exists() and jinja_src.exists():
src = jinja_src
is_jinja_template = True
# Skip if source doesn't exist (might be conditional on other settings)
if not src.exists():
continue
# Skip if destination already exists (don't overwrite existing customizations)
if dst.exists():
continue
# Create parent directory if needed
dst.parent.mkdir(parents=True, exist_ok=True)
# Copy file or directory
if src.is_dir():
shutil.copytree(src, dst)
copied_count += 1
elif is_jinja_template or src.suffix == ".jinja":
# Render Jinja2 template
_render_jinja_template(src, dst, project_path)
copied_count += 1
else:
# Copy regular file
shutil.copy2(src, dst)
copied_count += 1
if copied_count > 0:
typer.secho(
f"Copied {copied_count} {service_name} service files", fg=typer.colors.GREEN
)
else:
typer.echo(
f"No {service_name} files copied (may already exist or be templates)"
)
def install_dependencies(project_path: Path, python_version: str | None = None) -> bool:
"""
Install project dependencies using uv.
Args:
project_path: Path to the project directory
python_version: Python version for project (currently unused in implementation
but required for test mocking and future extensibility)
Returns:
True if installation succeeded, False otherwise
Note:
We pass --python to uv sync when python_version is specified to ensure
uv uses the correct Python version and respects the requires-python
constraint in pyproject.toml. This prevents uv from selecting incompatible
Python versions (e.g., 3.14 when requires-python = ">=3.11,<3.14").
When python_version is None, uv sync runs without version constraint,
allowing uv to auto-detect a compatible Python version.
"""
try:
typer.secho(t("postgen.deps_installing"), fg=typer.colors.CYAN)
# Unset VIRTUAL_ENV to avoid conflicts with parent project's venv
env = os.environ.copy()
env.pop("VIRTUAL_ENV", None)
# Build command with optional --python flag to enforce version constraint
cmd = ["uv", "sync"]
if python_version:
cmd.extend(["--python", python_version])
result = subprocess.run(
cmd,
cwd=project_path,
capture_output=True,
text=True,
timeout=POST_GEN_TIMEOUT_INSTALL,
env=env,
)
if result.returncode == 0:
typer.secho(t("postgen.deps_success"), fg=typer.colors.GREEN)
return True
else:
typer.secho(t("postgen.deps_warn_failed"), fg=typer.colors.YELLOW)
if result.stderr:
truncated = _truncate_stderr(result.stderr)
for line in truncated.split("\n"):
typer.echo(f" {line}")
typer.secho(t("postgen.deps_manual"), dim=True)
return False
except subprocess.TimeoutExpired:
typer.secho(t("postgen.deps_timeout"), fg=typer.colors.YELLOW)
return False
except FileNotFoundError:
typer.secho(t("postgen.deps_uv_missing"), fg=typer.colors.YELLOW)
typer.secho(t("postgen.deps_uv_install"), dim=True)
return False
except Exception as e:
typer.secho(t("postgen.deps_warn_error", error=e), fg=typer.colors.YELLOW)
typer.secho(t("postgen.deps_manual"), dim=True)
return False
def setup_env_file(project_path: Path) -> bool:
"""
Copy .env.example to .env if .env doesn't exist.
Args:
project_path: Path to the project directory
Returns:
True if setup succeeded or .env already exists, False on error
"""
try:
typer.secho(t("postgen.env_setup"), fg=typer.colors.CYAN)
env_example = project_path / ".env.example"
env_file = project_path / ".env"
if env_example.exists() and not env_file.exists():
shutil.copy(env_example, env_file)
typer.secho(t("postgen.env_created"), fg=typer.colors.GREEN)
return True
elif env_file.exists():
typer.echo(t("postgen.env_exists"))
return True
else:
typer.secho(t("postgen.env_missing"), fg=typer.colors.YELLOW)
return False
except Exception as e:
typer.secho(t("postgen.env_error", error=e), fg=typer.colors.YELLOW)
typer.secho(t("postgen.env_manual"), dim=True)
return False
def run_migrations(
project_path: Path,
include_migrations: bool = False,
python_version: str | None = None,
) -> bool:
"""
Run Alembic database migrations if any service requiring migrations is enabled.
Migrations are needed when:
- Auth service is enabled
- AI service is enabled with a persistence backend (not memory)
Args:
project_path: Path to the project directory
include_migrations: Whether any service requiring migrations is enabled
python_version: Python version to use (e.g., "3.13") for uv run