File size: 12,027 Bytes
4eeda37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import logging
import re
from typing import Dict, Optional

from pinecone import Pinecone
from dotenv import load_dotenv

load_dotenv()
logger = logging.getLogger(__name__)


class PineconeUserContextExtractor:
    """

    Extracts structured user context from Pinecone.



    Design goals:

    - Stable contract for SCN

    - Extensible for future user attributes

    - Safe against missing metadata

    - No hardcoded vector dimension

    """

    def __init__(self, index_name: Optional[str] = None):
        self.index_name = index_name or os.getenv("PINECONE_INDEX_NAME")
        self.api_key = os.getenv("PINECONE_API_KEY")

        if not self.api_key:
            raise ValueError("PINECONE_API_KEY not set")

        if not self.index_name:
            raise ValueError("PINECONE_INDEX_NAME not set")

        self.pc = Pinecone(api_key=self.api_key)
        self.index = self.pc.Index(self.index_name)

        # 🔥 Read actual index dimension dynamically
        stats = self.index.describe_index_stats()
        self.dimension = stats.get("dimension")

        if not self.dimension:
            raise RuntimeError("Could not determine Pinecone index dimension")

        logger.info(
            f"Pinecone extractor initialized | index={self.index_name}, dimension={self.dimension}"
        )

    # -------------------------------------------------------
    # Public API
    # -------------------------------------------------------

    def get_user_context(self, namespace: str) -> Dict:
        """

        Returns structured user context.



        Output contract (stable):

        {

            user_name: str | None,

            role: str | None,

            age: int | None,

            summary: str | None,

            resume_summary: str | None,

            skills: list[str],

            interests: list[str],

            traits: list[str],

        }

        """

        context = {
            "user_name": None,
            "role": None,
            "age": None,
            "summary": None,
            "resume_summary": None,
            "skills": [],
            "interests": [],
            "traits": [],
        }

        try:
            dummy_vector = [0.0] * self.dimension

            results = self.index.query(
                vector=dummy_vector,
                top_k=20,
                include_metadata=True,
                namespace=str(namespace),
            )

            matches = results.get("matches", []) or []

            for match in matches:
                meta = match.get("metadata") or {}
                doc_type = meta.get("doc_type")

                # -------------------------------------------
                # Conversation Summary (Highest Signal)
                # -------------------------------------------
                if doc_type == "conversation_summary":
                    if not context["summary"]:
                        context["summary"] = meta.get("text")

                # -------------------------------------------
                # Resume Summary
                # -------------------------------------------
                elif doc_type == "resume_summary":
                    text = meta.get("text", "")

                    if not context["resume_summary"]:
                        context["resume_summary"] = text

                    # Extract structured fields from text if needed
                    self._extract_from_resume_text(text, context)

                # -------------------------------------------
                # Optional structured metadata types
                # -------------------------------------------
                elif doc_type == "skills":
                    context["skills"].extend(meta.get("items", []))

                elif doc_type == "interests":
                    context["interests"].extend(meta.get("items", []))

                elif doc_type == "traits":
                    context["traits"].extend(meta.get("items", []))

            # Deduplicate lists
            for key in ["skills", "interests", "traits"]:
                context[key] = list(set(context[key]))

            logger.info(
                f"Pinecone context extracted | namespace={namespace} | "
                f"summary={'YES' if context['summary'] else 'NO'} | "
                f"resume={'YES' if context['resume_summary'] else 'NO'}"
            )

        except Exception as e:
            logger.error(
                f"Failed to extract Pinecone context for namespace={namespace}: {e}",
                exc_info=True
            )

        return context

    # -------------------------------------------------------
    # Internal Helpers
    # -------------------------------------------------------

    def _extract_from_resume_text(self, text: str, context: Dict) -> None:
        if not text:
            return

        # ---------------------------
        # Extract Name
        # ---------------------------
        if not context["user_name"]:
            name_match = re.search(r"Name:\s*(.+)", text)
            if name_match:
                context["user_name"] = name_match.group(1).strip()

        # ---------------------------
        # Extract Role
        # ---------------------------
        if not context["role"]:
            role_match = re.search(r"Role:\s*(.+)", text)
            if role_match:
                context["role"] = role_match.group(1).strip()

        # ---------------------------
        # Extract Age
        # ---------------------------
        if not context["age"]:
            age_match = re.search(r"Age:\s*(\d+)", text)
            if age_match:
                context["age"] = int(age_match.group(1))

        # ---------------------------
        # Extract Skills Block
        # ---------------------------
        skills_match = re.search(r"Skills:\s*(.*?)\n\n", text, re.DOTALL)
        if skills_match:
            skills_block = skills_match.group(1)

            skill_lines = re.findall(r"-\s*(.+)", skills_block)

            parsed_skills = []
            for line in skill_lines:
                parts = [s.strip() for s in line.split(",")]
                parsed_skills.extend(parts)

            context["skills"].extend(parsed_skills)

        # ---------------------------
        # Extract Learning Goals
        # ---------------------------
        goals_match = re.search(r"Learning Goals:\s*(.*?)\n\n", text, re.DOTALL)
        if goals_match:
            goals_block = goals_match.group(1)
            goals = re.findall(r"-\s*(.+)", goals_block)
            context["interests"].extend(goals)

        # ---------------------------
        # Extract Hobbies
        # ---------------------------
        hobby_match = re.search(r"Hobbies:\s*(.*?)$", text, re.DOTALL)
        if hobby_match:
            hobby_block = hobby_match.group(1)
            hobbies = re.findall(r"-\s*(.+)", hobby_block)
            context["interests"].extend(hobbies)

    def get_latest_roadmap(self, user_id: str) -> Optional[dict]:
        import json

        try:
            dummy_vector = [0.0] * self.dimension

            response = self.index.query(
                vector=dummy_vector,
                top_k=10,
                namespace=str(user_id),
                include_metadata=True,
                filter={"doc_type": {"$eq": "roadmap"}}
            )

            matches = response.get("matches", []) or []

            if not matches:
                logger.warning(f"[ROADMAP FETCH] No roadmap found for user: {user_id}")
                return None

            matches.sort(
                key=lambda x: (x.get("metadata") or {}).get("generated_at", ""),
                reverse=True
            )

            best_metadata = matches[0].get("metadata") or {}

            if not best_metadata.get("full_roadmap_stored"):
                logger.warning(f"[ROADMAP FETCH] full_roadmap_stored=False for user: {user_id}")
                return None

            raw_json = best_metadata.get("full_roadmap_json", "")
            if not raw_json:
                return None

            roadmap = json.loads(raw_json)
            roadmap = self._normalize_roadmap(roadmap)

            logger.info(
                f"[ROADMAP FETCH] ✓ Roadmap retrieved for user {user_id} | "
                f"milestones={len(roadmap.get('milestones', []))} | "
                f"target_role={roadmap.get('target_role', 'unknown')}"
            )
            return roadmap

        except Exception as e:
            logger.error(f"[ROADMAP FETCH] Error: {e}", exc_info=True)
            return None


    def _normalize_roadmap(self, roadmap: dict) -> dict:
        """

        Normalizes abbreviated milestone keys to standard names.

        Handles both old schema (abbreviated) and new schema (full names).

        """
        for milestone in roadmap.get("milestones", []):

            # Normalize milestone-level fields
            if not milestone.get("identity_label"):
                milestone["identity_label"] = (
                    milestone.get("t") or
                    milestone.get("label") or
                    milestone.get("milestone_id", "")
                )

            if not milestone.get("market_value_display"):
                milestone["market_value_display"] = (
                    milestone.get("sal") or
                    milestone.get("salary") or
                    ""
                )

            if not milestone.get("identity_statement"):
                milestone["identity_statement"] = (
                    milestone.get("o") or
                    milestone.get("outcome") or
                    ""
                )

            # Normalize module-level fields
            for module in milestone.get("modules", []):
                if not module.get("module_id"):
                    module["module_id"] = module.get("id", "")

                # Normalize skill-level fields
                for skill in module.get("skills", []):
                    if not skill.get("description"):
                        skill["description"] = skill.get("n", "")

                    # Ensure why_this_skill exists (needed for Beat 5)
                    if not skill.get("why_this_skill"):
                        scenario = skill.get("content_flow", {}).get("scenario", {})
                        skill["why_this_skill"] = (
                            f"This skill is tested in: {scenario.get('title', '')}"
                            if scenario.get("title") else ""
                        )

        return roadmap

    def get_onboarding_summary(self, user_id: str) -> Optional[dict]:
        """

        Fetch structured onboarding summary stored by seed script or memory_service.

        Returns the parsed summary dict or None.

        """
        import json
        try:
            vector_id = f"{user_id}_onboarding_summary"
            fetch_result = self.index.fetch(
                ids=[vector_id],
                namespace=str(user_id)
            )
            if not (fetch_result and fetch_result.vectors and vector_id in fetch_result.vectors):
                logger.warning(f"[SUMMARY] No onboarding_summary vector for: {user_id}")
                return None

            metadata = fetch_result.vectors[vector_id].metadata or {}
            text = metadata.get("text", "")
            if not text:
                return None

            data = json.loads(text)
            logger.info(f"[SUMMARY] Found onboarding_summary for: {user_id}")
            return data

        except Exception as e:
            logger.error(f"[SUMMARY] Error fetching onboarding_summary for {user_id}: {e}")
            return None