-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlearning_service.py
More file actions
2419 lines (2204 loc) · 96.9 KB
/
Copy pathlearning_service.py
File metadata and controls
2419 lines (2204 loc) · 96.9 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
import json
import logging
import posixpath
import re
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta, timezone
from math import log1p
from pathlib import Path
from threading import RLock
from time import monotonic
from typing import Any, Dict, List, Optional, Set, Tuple
from sqlalchemy.orm import Session
from src.config import settings
from src.core.llm.openai_llm import OpenAILLM
from src.core.vectorstore.chroma_store import ChromaStore
from src.models.codetour_schemas import CodeTour, CodeTourStep
from src.models.database import (
CodeDependency,
CodeFile,
LearningLesson,
LearningSyllabus,
Repository,
)
from src.models.learning import (
CacheInfo,
CodeReference,
DependencyGraph,
GraphEdge,
GraphMeta,
GraphNode,
GraphNodeMetrics,
GraphStats,
Lesson,
LessonContent,
Module,
Persona,
Syllabus,
)
logger = logging.getLogger(__name__)
class LearningService:
_graph_cache: Dict[str, Tuple[float, DependencyGraph]] = {}
_graph_cache_lock = RLock()
LESSON_CODE_EXTENSIONS = {
".ts", ".tsx", ".js", ".jsx", ".py", ".rs", ".go", ".java", ".c", ".cpp",
".h", ".hpp", ".cs", ".rb", ".php", ".swift", ".kt", ".scala", ".vue",
".svelte", ".astro", ".yaml", ".yml", ".json", ".toml", ".sql",
}
REQUIRED_LESSON_SECTIONS = [
"mission brief",
"objectives",
"architecture walkthrough",
"code deep dive",
"pitfalls",
"recap",
]
PERSONA_BLUEPRINTS: Dict[str, Dict[str, Any]] = {
"new_hire": {
"retrieval_query": "onboarding architecture setup conventions workflow entrypoints",
"tone": "clear, step-by-step, confidence building",
"mission": "Help the learner become productive with safe first contributions.",
"pillars": ["project structure", "dev setup", "key patterns", "first delivery path"],
"relevance_terms": ["onboarding", "convention", "entrypoint", "setup", "workflow"],
},
"auditor": {
"retrieval_query": "authentication authorization validation security middleware secrets compliance",
"tone": "risk-focused, evidence-first, precise",
"mission": "Help the learner audit trust boundaries and high-risk flows quickly.",
"pillars": ["auth boundaries", "input validation", "sensitive data flow", "vulnerability hotspots"],
"relevance_terms": ["auth", "authorization", "validation", "threat", "risk", "security"],
},
"fullstack": {
"retrieval_query": "frontend backend api database integration state management data flow",
"tone": "systems-oriented, integration-heavy, practical",
"mission": "Help the learner understand end-to-end feature delivery across the stack.",
"pillars": ["ui flow", "api contracts", "persistence layer", "deployment/runtime considerations"],
"relevance_terms": ["frontend", "backend", "api", "database", "integration", "state"],
},
"archaeologist": {
"retrieval_query": "legacy modules history migration debt architecture evolution backwards compatibility",
"tone": "forensic, context-rich, decision-history aware",
"mission": "Help the learner reconstruct why the system evolved and where debt accumulates.",
"pillars": ["legacy hotspots", "evolution path", "design tradeoffs", "debt containment"],
"relevance_terms": ["legacy", "migration", "history", "tradeoff", "debt", "compatibility"],
},
}
def __init__(self, db: Session, llm: OpenAILLM, vector_store: ChromaStore):
self._db = db
self._llm = llm
self._vector_store = vector_store
def get_personas(self) -> List[Persona]:
"""Return available learning personas."""
return [
Persona(
id="new_hire",
name="The New Hire",
description="Just joined the team? Get up to speed on architecture, setup, and key conventions.",
icon="🎓"
),
Persona(
id="auditor",
name="The Security Auditor",
description="Focus on authentication, authorization, API endpoints, and data validation.",
icon="🔒"
),
Persona(
id="fullstack",
name="The Full Stack Dev",
description="Deep dive into how the frontend connects to the backend and database.",
icon="⚡"
),
Persona(
id="archaeologist",
name="The Archaeologist",
description="Explore the history, legacy modules, and core design decisions.",
icon="🏺"
)
]
async def generate_curriculum(
self,
repo_id: str,
persona_id: str,
force_regenerate: bool = False,
include_quality_meta: bool = False,
) -> Syllabus:
"""Generate a personalized syllabus for the repository."""
if not settings.learning_v2_enabled:
return await self._generate_curriculum_v1(repo_id, persona_id)
try:
return await self._generate_curriculum_v2(
repo_id,
persona_id,
force_regenerate=force_regenerate,
include_quality_meta=include_quality_meta,
)
except Exception as exc:
logger.error("Learning V2 curriculum failed, falling back to V1: %s", exc)
return await self._generate_curriculum_v1(repo_id, persona_id)
async def _generate_curriculum_v1(self, repo_id: str, persona_id: str) -> Syllabus:
repo = self._db.query(Repository).filter(Repository.id == repo_id).first()
if not repo:
raise ValueError(f"Repository {repo_id} not found")
persona = next((p for p in self.get_personas() if p.id == persona_id), self.get_personas()[0])
context_docs = await self._vector_store.search(
collection_name=repo_id,
query_embedding=await self._vector_store._embedding_service.embed_query("architecture overview project structure"),
limit=20,
)
summaries: List[str] = []
for result in context_docs:
doc = result.content
summaries.append(doc if len(doc) < 1000 else doc[:1000] + "...")
context_str = "\n---\n".join(summaries)
prompt = f"""
You are an expert developer creating a university-style course for a new codebase.
Target Audience: {persona.name} ({persona.description})
Repository: {repo.github_owner}/{repo.github_name}
Based on the code snippets below, create a 4-module syllabus that takes the student from "Zero" to "Hero".
Each module must have 2-4 lessons.
Context from codebase:
{context_str}
Return clean JSON matching this structure:
{{
"title": "Course Title",
"description": "Course description",
"modules": [
{{
"title": "Module Title",
"description": "Module description",
"lessons": [
{{
"id": "slug-id",
"title": "Lesson Title",
"description": "One sentence on what this covers",
"type": "concept",
"estimated_minutes": 10
}}
]
}}
]
}}
"""
messages = [
{"role": "system", "content": "You are a curriculum designer. Output valid JSON only."},
{"role": "user", "content": prompt},
]
response = await self._llm.generate(messages)
try:
cleaned = response.replace("```json", "").replace("```", "").strip()
data = json.loads(cleaned)
return Syllabus(
repo_id=repo_id,
persona=persona_id,
title=data.get("title", f"Course: {repo.github_name}"),
description=data.get("description", "AI Generated Course"),
modules=[
Module(
title=m.get("title") or "Module",
description=m.get("description") or "",
lessons=[Lesson(**lesson_data) for lesson_data in m.get("lessons", [])],
)
for m in data.get("modules", [])
],
)
except Exception as exc:
logger.error("Failed to generate curriculum V1: %s", exc)
return Syllabus(
repo_id=repo_id,
persona=persona_id,
title="Generation Failed",
description="Could not generate curriculum. Please try again.",
modules=[],
)
async def _generate_curriculum_v2(
self,
repo_id: str,
persona_id: str,
force_regenerate: bool = False,
include_quality_meta: bool = False,
) -> Syllabus:
repo = self._db.query(Repository).filter(Repository.id == repo_id).first()
if not repo:
raise ValueError(f"Repository {repo_id} not found")
persona_id = self._normalize_persona(persona_id)
persona = next((p for p in self.get_personas() if p.id == persona_id), self.get_personas()[0])
blueprint = self.PERSONA_BLUEPRINTS[persona_id]
now = datetime.now(timezone.utc)
ttl = timedelta(days=max(1, int(settings.learning_cache_ttl_days)))
cached = (
self._db.query(LearningSyllabus)
.filter(
LearningSyllabus.repository_id == repo_id,
LearningSyllabus.persona == persona_id,
)
.order_by(LearningSyllabus.created_at.desc())
.first()
)
if (
cached
and not force_regenerate
and (cached.expires_at is None or cached.expires_at > now.replace(tzinfo=None))
):
payload = cached.syllabus_json or {}
syllabus = self._syllabus_from_payload(repo_id, persona_id, payload)
syllabus.cache_info = CacheInfo(
source="cache",
generated_at=cached.created_at.replace(tzinfo=timezone.utc).isoformat() if cached.created_at else None,
expires_at=cached.expires_at.replace(tzinfo=timezone.utc).isoformat() if cached.expires_at else None,
prompt_version=str(payload.get("prompt_version") or settings.learning_prompt_version),
cache_hit=True,
)
if include_quality_meta:
syllabus.quality_meta = payload.get("quality_meta")
else:
syllabus.quality_meta = None
return syllabus
retrieval_query = f"{blueprint['retrieval_query']} architecture file map"
context_docs = await self._vector_store.search(
collection_name=repo_id,
query_embedding=await self._vector_store._embedding_service.embed_query(retrieval_query),
limit=24,
)
snippets: List[str] = []
for doc in context_docs[:24]:
file_path = doc.metadata.get("file_path", "unknown")
snippets.append(f"File: {file_path}\n{doc.content[:900]}")
context_str = "\n\n---\n\n".join(snippets)
prompt = f"""
You are designing a 4-module codebase learning track.
Persona: {persona.name}
Persona Mission: {blueprint["mission"]}
Persona Tone: {blueprint["tone"]}
Required Topic Pillars: {", ".join(blueprint["pillars"])}
Repository: {repo.github_owner}/{repo.github_name}
Requirements:
- Exactly 4 modules.
- Each module has 2 to 4 lessons.
- Every lesson id must be lowercase kebab-case and unique across all modules.
- Every module and lesson must be concrete to this repository.
- Keep lesson types to: concept, code_tour, quiz.
Context:
{context_str}
Return valid JSON only:
{{
"title": "Track title",
"description": "Track description",
"modules": [
{{
"title": "Module title",
"description": "Module description",
"lessons": [
{{
"id": "example-lesson-id",
"title": "Lesson title",
"description": "One sentence",
"type": "concept",
"estimated_minutes": 10
}}
]
}}
]
}}
"""
raw = await self._llm.generate(
[
{"role": "system", "content": "You are a curriculum designer. Output valid JSON only."},
{"role": "user", "content": prompt},
]
)
fallback_used = False
fallback_reason: Optional[str] = None
lesson_id_seen: Set[str] = set()
modules: List[Module] = []
quality = {"persona_term_hits": 0, "persona_term_score": 0.0, "validation_errors": []}
try:
payload = json.loads(self._repair_json_like(self._extract_json_block(raw)))
modules_payload = payload.get("modules", [])
for m_idx, raw_module in enumerate(modules_payload[:4], start=1):
raw_lessons = raw_module.get("lessons", [])[:4]
if len(raw_lessons) < 2:
quality["validation_errors"].append(f"module_{m_idx}_too_few_lessons")
continue
lessons: List[Lesson] = []
for l_idx, raw_lesson in enumerate(raw_lessons, start=1):
lesson_title = (raw_lesson.get("title") or f"Lesson {m_idx}.{l_idx}").strip()
raw_id = (raw_lesson.get("id") or self._slugify(lesson_title)).strip().lower()
lesson_id = self._slugify(raw_id)
if not lesson_id or lesson_id in lesson_id_seen:
lesson_id = self._slugify(f"{persona_id}-{m_idx}-{l_idx}-{lesson_title}")
lesson_id_seen.add(lesson_id)
lesson_type = raw_lesson.get("type") or "concept"
if lesson_type not in {"concept", "code_tour", "quiz"}:
lesson_type = "concept"
estimated_minutes = int(raw_lesson.get("estimated_minutes") or 12)
estimated_minutes = max(5, min(40, estimated_minutes))
lessons.append(
Lesson(
id=lesson_id,
title=lesson_title,
description=(raw_lesson.get("description") or "Understand this area of the codebase.").strip(),
type=lesson_type,
estimated_minutes=estimated_minutes,
)
)
modules.append(
Module(
title=(raw_module.get("title") or f"Module {m_idx}").strip(),
description=(raw_module.get("description") or "").strip(),
lessons=lessons[:4],
)
)
if len(modules) != 4:
quality["validation_errors"].append("invalid_module_count")
raise ValueError("invalid module count")
joined = " ".join(
[payload.get("title", ""), payload.get("description", "")]
+ [m.title + " " + m.description for m in modules]
+ [lesson.title + " " + lesson.description for m in modules for lesson in m.lessons]
).lower()
hits = sum(1 for term in blueprint["relevance_terms"] if term in joined)
quality["persona_term_hits"] = hits
quality["persona_term_score"] = round(hits / max(1, len(blueprint["relevance_terms"])), 2)
if hits < 2:
quality["validation_errors"].append("weak_persona_relevance")
raise ValueError("weak persona relevance")
syllabus = Syllabus(
repo_id=repo_id,
persona=persona_id,
title=(payload.get("title") or f"{persona.name} Track for {repo.github_name}").strip(),
description=(payload.get("description") or "Persona-specific learning track").strip(),
modules=modules,
)
except Exception as exc:
fallback_used = True
fallback_reason = str(exc)
syllabus = self._fallback_curriculum(repo_id, repo.github_name, persona_id, blueprint)
quality_meta = {
"mode": "v2",
"fallback_used": fallback_used,
"fallback_reason": fallback_reason,
"persona_term_hits": quality["persona_term_hits"],
"persona_term_score": quality["persona_term_score"],
"validation_errors": quality["validation_errors"],
}
expires_at = now + ttl
syllabus.cache_info = CacheInfo(
source="generated",
generated_at=now.isoformat(),
expires_at=expires_at.isoformat(),
prompt_version=settings.learning_prompt_version,
cache_hit=False,
)
if include_quality_meta:
syllabus.quality_meta = quality_meta
cache_payload = syllabus.model_dump()
cache_payload["quality_meta"] = quality_meta
cache_payload["prompt_version"] = settings.learning_prompt_version
self._db.query(LearningSyllabus).filter(
LearningSyllabus.repository_id == repo_id,
LearningSyllabus.persona == persona_id,
).delete(synchronize_session=False)
self._db.add(
LearningSyllabus(
repository_id=repo_id,
persona=persona_id,
syllabus_json=cache_payload,
created_at=now.replace(tzinfo=None),
expires_at=expires_at.replace(tzinfo=None),
)
)
self._db.commit()
logger.info(
"learning_v2 curriculum generated repo=%s persona=%s fallback=%s",
repo_id,
persona_id,
fallback_used,
)
return syllabus
async def generate_lesson(
self,
repo_id: str,
lesson_id: str,
lesson_title: str,
persona_id: Optional[str] = None,
module_id: Optional[str] = None,
force_regenerate: bool = False,
) -> Optional[LessonContent]:
"""Generate detailed content for a specific lesson."""
if not settings.learning_v2_enabled:
return await self._generate_lesson_v1(repo_id, lesson_id, lesson_title)
try:
return await self._generate_lesson_v2(
repo_id=repo_id,
lesson_id=lesson_id,
lesson_title=lesson_title,
persona_id=persona_id,
module_id=module_id,
force_regenerate=force_regenerate,
)
except Exception as exc:
logger.error("Learning V2 lesson failed, falling back to V1: %s", exc)
return await self._generate_lesson_v1(repo_id, lesson_id, lesson_title)
async def get_or_generate_lesson(
self,
repo_id: str,
lesson_id: str,
persona_id: str,
module_id: Optional[str] = None,
force_regenerate: bool = False,
) -> Optional[LessonContent]:
title = self._resolve_lesson_title(repo_id, lesson_id, persona_id) or f"Lesson {lesson_id}"
return await self.generate_lesson(
repo_id=repo_id,
lesson_id=lesson_id,
lesson_title=title,
persona_id=persona_id,
module_id=module_id,
force_regenerate=force_regenerate,
)
async def _generate_lesson_v1(self, repo_id: str, lesson_id: str, lesson_title: str) -> Optional[LessonContent]:
context_docs = await self._vector_store.search(
collection_name=repo_id,
query_embedding=await self._vector_store._embedding_service.embed_query(lesson_title),
limit=15,
)
available_files = set()
for d in context_docs:
file_path = d.metadata.get("file_path")
if file_path and Path(file_path).suffix.lower() in self.LESSON_CODE_EXTENSIONS:
available_files.add(file_path)
files_list = "\n".join(sorted(available_files)) if available_files else "No code files indexed."
context_str = "\n\n---\n\n".join(
[f"File: {d.metadata.get('file_path', 'unknown')}\n{d.content[:2000]}" for d in context_docs]
)
prompt = f"""You are an expert technical instructor creating an in-depth lesson titled "{lesson_title}" for this codebase.
## Requirements:
1. **Opening Hook** (2-3 sentences): Why this topic matters, real-world relevance
2. **Learning Objectives**: 3-5 bullet points of what the student will understand
3. **Core Concepts**: 3-5 detailed sections explaining the topic with specific code references
4. **How It Works Here**: Explain how this concept is implemented in THIS specific codebase
5. **Common Pitfalls**: 2-3 mistakes to avoid when working with this code
6. **Summary**: Key takeaways in a concise list
## Style Guidelines:
- Be specific to THIS codebase, avoid generic explanations
- Minimum 600 words of content
- Use markdown formatting (headers, bold, lists)
- Reference specific files and explain WHY they matter
- Do NOT include code blocks in content_markdown - use code_references instead
- If you provide diagram_mermaid, it must be meaningful (minimum 5 nodes) and use real component/file names.
- Never use placeholder nodes like A, B, C.
## Available Code Files (use ONLY these for code_references):
{files_list}
## Codebase Context:
{context_str}
Return clean JSON:
{{
"content_markdown": "Rich, structured lesson content following the requirements above (min 600 words)",
"code_references": [
{{
"file_path": "MUST be from Available Code Files list",
"start_line": 1,
"end_line": 30,
"description": "What to look for and WHY it's important"
}}
],
"diagram_mermaid": "Optional Mermaid flowchart with real node labels and real relationships from this codebase"
}}
"""
messages = [
{"role": "system", "content": "You are a coding instructor. Output valid JSON only."},
{"role": "user", "content": prompt},
]
response = await self._llm.generate(messages)
try:
cleaned = response.replace("```json", "").replace("```", "").strip()
data = json.loads(cleaned)
filtered_refs = self._normalize_code_references(
data.get("code_references", []),
self._load_file_line_map(repo_id),
available_files=available_files,
)
diagram_mermaid, _diagram_source = self._select_high_quality_mermaid(
raw_code=data.get("diagram_mermaid"),
lesson_title=lesson_title,
persona_id="new_hire",
module_id=None,
references=filtered_refs,
available_files=available_files,
)
return LessonContent(
id=lesson_id,
title=lesson_title,
content_markdown=data.get("content_markdown", "No content generated."),
code_references=filtered_refs,
diagram_mermaid=diagram_mermaid,
)
except Exception as exc:
logger.error("Failed to generate lesson V1: %s", exc)
return None
async def _generate_lesson_v2(
self,
repo_id: str,
lesson_id: str,
lesson_title: str,
persona_id: Optional[str] = None,
module_id: Optional[str] = None,
force_regenerate: bool = False,
) -> Optional[LessonContent]:
persona_id = self._normalize_persona(persona_id or "new_hire")
blueprint = self.PERSONA_BLUEPRINTS[persona_id]
now = datetime.now(timezone.utc)
ttl = timedelta(days=max(1, int(settings.learning_cache_ttl_days)))
line_map = self._load_file_line_map(repo_id)
cache_query = (
self._db.query(LearningLesson)
.filter(
LearningLesson.repository_id == repo_id,
LearningLesson.lesson_id == lesson_id,
LearningLesson.persona == persona_id,
)
.order_by(LearningLesson.created_at.desc())
)
if module_id:
cache_query = cache_query.filter(LearningLesson.module_id == module_id)
cached = cache_query.first()
if (
cached
and not force_regenerate
and (cached.expires_at is None or cached.expires_at > now.replace(tzinfo=None))
):
payload = cached.lesson_json or {}
content = self._lesson_from_payload(repo_id, lesson_id, lesson_title, persona_id, module_id, payload)
content.cache_info = CacheInfo(
source="cache",
generated_at=cached.created_at.replace(tzinfo=timezone.utc).isoformat() if cached.created_at else None,
expires_at=cached.expires_at.replace(tzinfo=timezone.utc).isoformat() if cached.expires_at else None,
prompt_version=cached.prompt_version or settings.learning_prompt_version,
cache_hit=True,
)
return content
query = f"{lesson_title} {' '.join(blueprint['pillars'])} {blueprint['retrieval_query']}"
context_docs = await self._vector_store.search(
collection_name=repo_id,
query_embedding=await self._vector_store._embedding_service.embed_query(query),
limit=20,
)
available_files: Set[str] = set()
context_parts: List[str] = []
for doc in context_docs:
file_path = doc.metadata.get("file_path")
if file_path and Path(file_path).suffix.lower() in self.LESSON_CODE_EXTENSIONS:
available_files.add(file_path)
context_parts.append(f"File: {file_path or 'unknown'}\n{doc.content[:1500]}")
prompt = f"""
You are an expert technical instructor producing a persona-specific lesson.
Lesson Title: {lesson_title}
Persona: {persona_id}
Mission: {blueprint["mission"]}
Tone: {blueprint["tone"]}
Required Pillars: {", ".join(blueprint["pillars"])}
Module Context: {module_id or "general"}
Output requirements:
- Markdown MUST contain these exact section headings:
1) Mission Brief
2) Objectives
3) Architecture Walkthrough
4) Code Deep Dive
5) Pitfalls
6) Recap
- Minimum 550 words.
- Explain concrete files and rationale.
- No code fences inside content_markdown.
- diagram_mermaid must be a real architecture diagram with minimum 5 nodes and real labels.
- NEVER output placeholder nodes (A, B, C) or generic toy graphs.
Code files (valid for references only):
{chr(10).join(sorted(available_files)) if available_files else "No code files indexed"}
Repository context:
{chr(10).join(context_parts)}
Return strict JSON:
{{
"content_markdown": "markdown string",
"code_references": [
{{"file_path":"...", "start_line":1, "end_line":20, "description":"..."}}
],
"diagram_mermaid": "Mermaid flowchart using actual component/file names from this codebase"
}}
"""
raw = await self._llm.generate(
[
{"role": "system", "content": "You are a coding instructor. Output valid JSON only."},
{"role": "user", "content": prompt},
]
)
fallback_used = False
fallback_reason: Optional[str] = None
quality: Dict[str, Any] = {
"mode": "v2",
"section_score": 0.0,
"persona_term_score": 0.0,
"reference_count": 0,
"fallback_used": False,
"fallback_reason": None,
}
try:
payload = json.loads(self._repair_json_like(self._extract_json_block(raw)))
content_markdown = str(payload.get("content_markdown") or "").strip()
references = self._normalize_code_references(
payload.get("code_references", []),
line_map,
available_files=available_files,
)
diagram_mermaid, diagram_source = self._select_high_quality_mermaid(
raw_code=payload.get("diagram_mermaid"),
lesson_title=lesson_title,
persona_id=persona_id,
module_id=module_id,
references=references,
available_files=available_files,
)
section_hits = self._score_lesson_sections(content_markdown)
quality["section_score"] = round(section_hits / len(self.REQUIRED_LESSON_SECTIONS), 2)
lowered = content_markdown.lower()
term_hits = sum(1 for term in blueprint["relevance_terms"] if term in lowered)
quality["persona_term_score"] = round(term_hits / max(1, len(blueprint["relevance_terms"])), 2)
quality["reference_count"] = len(references)
quality["diagram_quality"] = diagram_source
if quality["section_score"] < 0.66:
raise ValueError("missing required lesson sections")
if quality["persona_term_score"] < 0.2:
raise ValueError("weak persona relevance")
if available_files and len(references) < 1:
raise ValueError("no valid references")
lesson = LessonContent(
id=lesson_id,
title=lesson_title,
content_markdown=content_markdown,
code_references=references,
diagram_mermaid=diagram_mermaid,
persona=persona_id,
module_id=module_id,
quality_meta=quality,
)
except Exception as exc:
fallback_used = True
fallback_reason = str(exc)
fallback_refs = self._normalize_code_references(
[
{
"file_path": file_path,
"start_line": 1,
"end_line": min(40, line_map.get(file_path, 40)),
"description": "Start here to map this lesson to concrete implementation details.",
}
for file_path in sorted(available_files)[:3]
],
line_map,
available_files=available_files,
)
quality["fallback_used"] = True
quality["fallback_reason"] = fallback_reason
quality["reference_count"] = len(fallback_refs)
quality["diagram_quality"] = "fallback"
lesson = LessonContent(
id=lesson_id,
title=lesson_title,
content_markdown=self._build_lesson_fallback_markdown(lesson_title, persona_id, module_id, blueprint),
code_references=fallback_refs,
diagram_mermaid=self._build_fallback_mermaid(
lesson_title=lesson_title,
persona_id=persona_id,
module_id=module_id,
references=fallback_refs,
available_files=available_files,
),
persona=persona_id,
module_id=module_id,
quality_meta=quality,
)
expires_at = now + ttl
lesson.cache_info = CacheInfo(
source="generated",
generated_at=now.isoformat(),
expires_at=expires_at.isoformat(),
prompt_version=settings.learning_prompt_version,
cache_hit=False,
)
cache_payload = lesson.model_dump()
cache_payload["prompt_version"] = settings.learning_prompt_version
stale_query = self._db.query(LearningLesson).filter(
LearningLesson.repository_id == repo_id,
LearningLesson.lesson_id == lesson_id,
LearningLesson.persona == persona_id,
)
if module_id:
stale_query = stale_query.filter(LearningLesson.module_id == module_id)
stale_query.delete(synchronize_session=False)
self._db.add(
LearningLesson(
repository_id=repo_id,
persona=persona_id,
lesson_id=lesson_id,
module_id=module_id,
lesson_json=cache_payload,
quality_meta=quality,
prompt_version=settings.learning_prompt_version,
created_at=now.replace(tzinfo=None),
expires_at=expires_at.replace(tzinfo=None),
)
)
self._db.commit()
logger.info(
"learning_v2 lesson generated repo=%s persona=%s lesson=%s fallback=%s",
repo_id,
persona_id,
lesson_id,
fallback_used,
)
return lesson
def _normalize_persona(self, persona_id: str) -> str:
candidate = (persona_id or "new_hire").strip().lower()
if candidate not in self.PERSONA_BLUEPRINTS:
return "new_hire"
return candidate
def _slugify(self, value: str) -> str:
normalized = re.sub(r"[^a-z0-9]+", "-", (value or "").lower()).strip("-")
normalized = re.sub(r"-{2,}", "-", normalized)
return normalized[:90] or "lesson"
def _fallback_curriculum(
self,
repo_id: str,
repo_name: str,
persona_id: str,
blueprint: Dict[str, Any],
) -> Syllabus:
modules: List[Module] = []
for idx, pillar in enumerate(blueprint["pillars"][:4], start=1):
lesson_one = Lesson(
id=self._slugify(f"{persona_id}-m{idx}-foundations"),
title=f"{pillar.title()} Foundations",
description=f"Build working knowledge of {pillar} in this repository.",
type="concept",
estimated_minutes=12,
)
lesson_two = Lesson(
id=self._slugify(f"{persona_id}-m{idx}-walkthrough"),
title=f"{pillar.title()} Code Walkthrough",
description=f"Trace the core files that implement {pillar}.",
type="code_tour",
estimated_minutes=15,
)
modules.append(
Module(
title=f"Module {idx}: {pillar.title()}",
description=f"Persona-focused mastery of {pillar}.",
lessons=[lesson_one, lesson_two],
)
)
return Syllabus(
repo_id=repo_id,
persona=persona_id,
title=f"{persona_id.replace('_', ' ').title()} Track for {repo_name}",
description=blueprint["mission"],
modules=modules,
)
def _syllabus_from_payload(self, repo_id: str, persona_id: str, payload: Dict[str, Any]) -> Syllabus:
modules: List[Module] = []
for raw_module in payload.get("modules", []):
lessons: List[Lesson] = []
for raw_lesson in raw_module.get("lessons", []):
try:
lessons.append(
Lesson(
id=self._slugify(str(raw_lesson.get("id") or raw_lesson.get("title") or "lesson")),
title=str(raw_lesson.get("title") or "Lesson"),
description=str(raw_lesson.get("description") or ""),
type=(raw_lesson.get("type") or "concept"),
estimated_minutes=max(5, int(raw_lesson.get("estimated_minutes") or 10)),
)
)
except Exception:
continue
modules.append(
Module(
title=str(raw_module.get("title") or "Module"),
description=str(raw_module.get("description") or ""),
lessons=lessons,
)
)
return Syllabus(
repo_id=repo_id,
persona=persona_id,
title=str(payload.get("title") or "Learning Track"),
description=str(payload.get("description") or ""),
modules=modules,
quality_meta=payload.get("quality_meta"),
)
def _resolve_lesson_title(self, repo_id: str, lesson_id: str, persona_id: Optional[str] = None) -> Optional[str]:
persona_id = self._normalize_persona(persona_id or "new_hire")
query = self._db.query(LearningSyllabus).filter(LearningSyllabus.repository_id == repo_id)
if persona_id:
persona_first = query.filter(LearningSyllabus.persona == persona_id).order_by(LearningSyllabus.created_at.desc()).first()
if persona_first:
title = self._lesson_title_from_syllabus_payload(persona_first.syllabus_json, lesson_id)
if title:
return title
for syllabus in query.order_by(LearningSyllabus.created_at.desc()).all():
title = self._lesson_title_from_syllabus_payload(syllabus.syllabus_json, lesson_id)
if title:
return title
return None
def _lesson_title_from_syllabus_payload(self, payload: Dict[str, Any], lesson_id: str) -> Optional[str]:
for module in (payload or {}).get("modules", []):
for lesson in module.get("lessons", []):
if lesson.get("id") == lesson_id:
return lesson.get("title")
return None
def _load_file_line_map(self, repo_id: str) -> Dict[str, int]:
rows = self._db.query(CodeFile.path, CodeFile.line_count).filter(CodeFile.repository_id == repo_id).all()
return {path: int(line_count or 1) for path, line_count in rows if path}
def _normalize_code_references(
self,
references: List[Dict[str, Any]],
file_line_map: Dict[str, int],
available_files: Optional[Set[str]] = None,
) -> List[CodeReference]:
normalized: List[CodeReference] = []
allowed_files = set(available_files or set())
for raw in references or []:
file_path = str(raw.get("file_path") or "").strip()
if not file_path:
continue
if allowed_files and file_path not in allowed_files:
continue
if Path(file_path).suffix.lower() not in self.LESSON_CODE_EXTENSIONS:
continue
if file_path not in file_line_map:
continue
max_line = max(1, int(file_line_map.get(file_path, 1)))
start = max(1, int(raw.get("start_line") or 1))
end = max(start, int(raw.get("end_line") or start))
if start > max_line:
continue
end = min(end, max_line)
normalized.append(
CodeReference(
file_path=file_path,
start_line=start,
end_line=end,
description=str(raw.get("description") or "Relevant implementation details for this lesson."),
)
)
# Keep deterministic order and avoid duplicate windows.
dedup: Dict[str, CodeReference] = {}
for item in normalized:
key = f"{item.file_path}:{item.start_line}:{item.end_line}"
if key not in dedup:
dedup[key] = item
return list(dedup.values())[:8]
def _score_lesson_sections(self, markdown: str) -> int:
lowered = (markdown or "").lower()
return sum(1 for heading in self.REQUIRED_LESSON_SECTIONS if heading in lowered)
def _is_placeholder_mermaid(self, code: Optional[str]) -> bool:
text = (code or "").strip()
if not text:
return True
lowered = text.lower()
if not any(keyword in lowered for keyword in ("graph", "flowchart", "sequencediagram", "classdiagram", "statediagram")):
return True
if re.search(r"\b[aA]\s*-->", text):
# Very common toy output from LLMs.
return True
edges = re.findall(r"-->|---|==>", text)
if len(edges) < 3:
return True
raw_labels = re.findall(r"\b[A-Za-z][A-Za-z0-9_]*\[(.*?)\]", text)
labels = [label.strip().strip('"').strip("'") for label in raw_labels if label.strip()]
if labels:
meaningful = [label for label in labels if len(label.strip()) > 2]
if len(meaningful) < 4:
return True
# If labels are all single tokens like A/B/C it's low-value.
short_tokens = [label for label in meaningful if re.fullmatch(r"[A-Za-z]{1,2}\d*", label.strip())]
if short_tokens and len(short_tokens) >= int(len(meaningful) * 0.6):
return True
generic_terms = {
"node",
"component",
"service",