File size: 43,421 Bytes
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88b2c34
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88b2c34
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
925189c
 
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88b2c34
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88b2c34
 
5da7ffb
 
88b2c34
 
 
5da7ffb
 
 
 
 
88b2c34
5da7ffb
 
 
 
88b2c34
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88b2c34
 
 
 
5da7ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""CareerCompass Gradio chat. Python 3.10+.

Install: python -m pip install 'FalkorDB>=1.8,<2' 'pydantic>=2.13,<3' 'gradio==6.30.0'
Launch:  python app.py
Open:    http://127.0.0.1:7860
Same FALKORDB_* connection variables as ingestion; optional FALKORDB_GRAPH.
GRADIO_SERVER_NAME / GRADIO_SERVER_PORT override the local bind. No public share.
OPENAI_API_KEY optionally enables graph-grounded rephrasing; no key is required.
"""
from __future__ import annotations

import html
import json
import logging
import os
import textwrap
import re
import tempfile
import time
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal
from typing import Annotated

os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
import gradio as gr
from pydantic import Field, ValidationError, field_validator

from agent import CareerCompass, Reply, Session, UserInput, Validated, Draft, SkillLevel, Name, SOC, Clarify, _profile, norm
from redis.exceptions import RedisError

EXAMPLES = [
    'What skills am I missing for Data Scientists? I have Critical Thinking=3, Mathematics.',
    'Which jobs match my skills: Critical Thinking, Mathematics, Reading Comprehension?',
    'How can I transition from Software Developers to Data Scientists?',
]
MAX_DISPLAY_ROWS = 20
MAX_FEATURES = 20
MAX_RENDER_CHARS = 54000  # Headroom below Turn's 60,000-character caps.

BASE = Path(__file__).resolve().parent
def optional_text(path):
    """Presentation assets are optional; the working app can use its theme alone."""
    try:
        return path.read_text(encoding='utf-8')
    except FileNotFoundError:
        return ''


CSS = optional_text(BASE / 'assets' / 'theme.css')
PALETTE = gr.themes.colors.Color(name='compass', c50='#eff8f3', c100='#e0f0e8',
    c200='#b8d8ca', c300='#8cbaa8', c400='#548e78', c500='#126859',
    c600='#0c5548', c700='#0a453a', c800='#16343b', c900='#112b30', c950='#0c2023')
THEME = gr.themes.Soft(primary_hue=PALETTE, neutral_hue='slate',
    font=['system-ui', 'sans-serif'], font_mono=['monospace']).set(
    body_text_color_subdued='#4b6168', input_placeholder_color='#526b64',
    button_primary_background_fill_hover='#0a453a')
# This demo uses one deliberately consistent light palette in either OS mode.
_theme_values = THEME.to_dict()['theme']
THEME.set(**{key: _theme_values[key[:-5]] for key in _theme_values
             if key.endswith('_dark') and key[:-5] in _theme_values})
TITLE = 'CareerCompass — Career Paths, Backed by Graph Evidence'
MODES = [('Find careers', 'skill_match'), ('Compare my skills', 'skill_gap'), ('Explore a transition', 'career_paths')]
SOURCES = [
    {'title': 'O*NET Database 31.0', 'url': 'https://www.onetcenter.org/database.html',
     'publisher': 'USDOL/ETA', 'license': 'CC BY 4.0', 'license_url': 'https://creativecommons.org/licenses/by/4.0/'},
    {'title': 'BLS OEWS national annual median wages, May 2025',
     'url': 'https://www.bls.gov/oes/special-requests/oesm25nat.zip'},
]
CAVEATS = [
    'Scores describe requirement overlap, not hiring probability.',
    'Missing means absent from the supplied profile, not a proven personal deficiency.',
    'Skill names without levels do not establish proficiency; levels use the O*NET 0–7 scale.',
    'Wages are national annual medians in USD for the stated year and parent SOC, not individual salary predictions.',
    'Unavailable wages stay unknown; wages do not change rankings.',
    'Career routes are suggested connections through shared skills, knowledge, and exact task text, not observed worker transitions.',
    'Job zones describe preparation, not training duration or licensing eligibility.',
    'Importance >=3 and at least three shared features per hop are application policies.',
]
EXPORT_DIR = tempfile.TemporaryDirectory(prefix='careercompass-exports-')



def safe(value):
    """Escape source/user strings before embedding them in Markdown/HTML."""
    raw = str(value)
    if len(raw) > 1000:
        raw = raw[:1000] + '… [label shortened]'
    value = html.escape(raw, quote=True).replace('\n', ' ')
    for char in ('\\', '`', '*', '_', '[', ']', '|', '#'):
        value = value.replace(char, '\\' + char)
    return value


def table(headers, data):
    lines = ['| ' + ' | '.join(headers) + ' |', '| ' + ' | '.join(['---'] * len(headers)) + ' |']
    lines.extend('| ' + ' | '.join(safe(v) for v in row) + ' |' for row in data)
    return '\n'.join(lines)



def bounded_markdown(text):
    if len(text) <= MAX_RENDER_CHARS:
        return text
    # Avoid cutting a table row in half; close a JSON fence if the cutoff is in
    # a parameter/trace block. Rendering must not fail validation on large data.
    clipped = text[:MAX_RENDER_CHARS - 200].rsplit('\n', 1)[0]
    if clipped.count('```') % 2:
        clipped += '\n```'
    return clipped + '\n\n[Display shortened to fit this chat turn; remaining content is not shown.]'


def row_note(total, displayed):
    return f'\n\nShowing first {displayed} of {total} results.' if total > displayed else ''


def display_number(value):
    return 'Not assessed' if value is None else f'{value:.2f}'


def display_wage(wage):
    wage = wage or {}
    value = wage.get('median_annual')
    if value is None:
        return 'Not available' + (' (top-coded)' if wage.get('status') == 'top_coded' else '')
    return f"${value:,.0f} · {wage['year']} · SOC {wage['soc']}"


def route_diagram(reply):
    """Offline SVG: only the first Cypher-returned route and its evidence.

    No JavaScript, network assets, inferred edges, or graph recomputation.
    The display samples four shared features per hop; scores use all features.
    All source labels are XML-escaped, including tooltips.
    """
    if reply.intent != 'career_paths' or not reply.rows:
        return ''
    route = reply.rows[0]
    occupations, steps = route['occupations'][:3], route['steps'][:2]
    height = 160 + 310 * len(steps)
    esc = lambda value: html.escape(str(value), quote=True)
    parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 {height}" '
             'role="img" aria-label="Top career route with shared features and job zones" '
             'style="width:100%;min-width:660px;height:auto;font-family:Arial,sans-serif">',
             '<title>Top career route — graph evidence</title>',
             '<desc>Each occupation connects through actual shared features to the next occupation. '
             'Up to four features are displayed per step. Job zones describe preparation, not licensing.</desc>',
             '<defs><marker id="route-arrow" viewBox="0 0 10 10" refX="9" refY="5" '
             'markerWidth="7" markerHeight="7" orient="auto-start-reverse">'
             '<path d="M 0 0 L 10 5 L 0 10 z" fill="#668a91"/></marker></defs>']

    def label(x, y, content, fill, size=14):
        halo = ' style="paint-order:stroke;stroke:#f7fbfa;stroke-width:4px;stroke-linejoin:round"' if fill in ('#385960', '#52646a') else ''
        parts.append(f'<text x="{x}" y="{y}" text-anchor="middle" fill="{fill}" font-size="{size}"{halo}>{esc(content)}</text>')

    for i, step in enumerate(steps):
        features = sorted(step['shared'], key=lambda f: (not f['key'].startswith('Skill:'), f['key']))[:4]
        fy, upper, lower = 195 + i * 310, 115 + i * 310, 335 + i * 310
        for j, feature in enumerate(features):
            x = 500 + (j - (len(features) - 1) / 2) * 240
            parts.append(f'<path d="M 500 {upper} L {x} {fy}" fill="none" stroke="#668a91" stroke-width="1.8" marker-end="url(#route-arrow)"/>')
            parts.append(f'<path d="M {x} {fy+70} L 500 {lower}" fill="none" stroke="#668a91" stroke-width="1.8" marker-end="url(#route-arrow)"/>')
            parts.append(f'<rect x="{x-112}" y="{fy}" width="224" height="70" rx="16" fill="#e4f4f1" stroke="#78aaa0"><title>{esc(feature["name"])} ({esc(feature["key"])})</title></rect>')
            lines = textwrap.wrap(str(feature['name'])[:1000], width=27, max_lines=2, placeholder='…')
            for line_index, line in enumerate(lines):
                label(x, fy+22+line_index*16, line, '#123d43', 13)
            label(x, fy+60, feature['key'].split(':', 1)[0], '#3e6663', 11)
        label(500, fy - 22, f"{step['shared_count']} shared features · {step['overlap']:.1%} overlap · zone jump {step['zone_jump']}", '#385960')
        label(500, fy+97, f'Showing {len(features)} of {len(step["shared"])} shared features; expand evidence for more.', '#52646a', 12)
    for i, occupation in enumerate(occupations):
        y = 25 + i * 310
        parts.append(f'<rect x="290" y="{y}" width="420" height="90" rx="18" fill="#123d43"><title>{esc(occupation["occupation"])}</title></rect>')
        for line_index, line in enumerate(textwrap.wrap(str(occupation['occupation'])[:1000], width=43, max_lines=2, placeholder='…')):
            label(500, y+27+line_index*20, line, '#ffffff', 17)
        zone = occupation['zone'] if occupation['zone'] is not None else 'unknown'
        label(500, y+74, f'{occupation["soc"]} · Job zone {zone}', '#bde6de', 13)
    parts.append('</svg>')
    return ('<section aria-label="Career path diagram"><h3>Top route · shared graph evidence</h3>'
            '<div class="cc-desktop-route" style="overflow-x:auto;background:#f7fbfa;border-radius:16px;padding:8px">'
            + ''.join(parts) + '</div>' + mobile_route(route) + '<p>Arrows show a suggested transition through shared features. '
            'They do not establish licensing eligibility.</p></section>')


def mobile_route(route):
    """A vertical, full-size node-link presentation of the same route evidence."""
    esc = lambda value: html.escape(str(value), quote=True)
    pieces = ['<div class="cc-mobile-route" aria-label="Top route, mobile view">']
    for i, occupation in enumerate(route['occupations'][:3]):
        zone = occupation['zone'] if occupation['zone'] is not None else 'unknown'
        pieces.append(f'<div class="occupation-node">{esc(occupation["occupation"])}'
                      f'<small>{esc(occupation["soc"])} · Job zone {esc(zone)}</small></div>')
        if i < len(route['steps'][:2]):
            step = route['steps'][i]
            features = sorted(step['shared'], key=lambda f: (not f['key'].startswith('Skill:'), f['key']))[:4]
            pieces.append(f'<div class="feature-bridge"><p>↓ Through {step["shared_count"]} shared features · '
                          f'{step["overlap"]:.1%} overlap · zone jump {step["zone_jump"]}</p>')
            for feature in features:
                pieces.append(f'<div class="feature-node">{esc(feature["name"])}</div>')
            pieces.append(f'<p>Showing {len(features)} of {len(step["shared"])} features. ↓</p></div>')
    return ''.join(pieces) + '</div>'


def decision_summary(reply):
    """Presentation of returned metrics; no Python ranking or gap computation."""
    if not reply.rows:
        if reply.intent == 'error':
            return '**The graph is temporarily unavailable.** Your question and profile are kept. Retry the question below; if this persists, check the graph connection.'
        if reply.intent == 'career_paths':
            return '**No qualifying route in this search.** Try another target or compare its skill requirements. This search covers direct moves and one intermediate role.'
        if reply.intent == 'skill_match':
            return '**No match at this cutoff.** Edit your profile and select additional canonical skills to try again.'
        if reply.intent == 'skill_gap':
            detail = reply.context[0] if reply.context else {}
            zone = detail.get('zone')
            preparation = str(zone) if zone is not None else 'unknown'
            outcome = ('**Your profile meets all assessed important skill requirements.**'
                       if reply.rating_coverage else
                       '**No usable skill ratings at this cutoff.** A skill gap cannot be assessed.')
            return (f'**Skill comparison · {safe(reply.occupation)} ({safe(reply.params.get("soc", ""))})**\n\n'
                    f'{outcome} No overall fit score is calculated for skill gaps. '
                    f'**Preparation zone:** {preparation}.\n\n'
                    f'**Annual median (USD, parent SOC):** {safe(display_wage(detail.get("wage")))}.\n\n'
                    '**Next:** compare another target or update your skill levels. '
                    'This comparison covers assessed requirements at the importance cutoff; it does not establish hiring or licensing eligibility.')
        return ''
    top = reply.rows[0]
    if reply.intent == 'career_paths':
        roles = top['occupations']
        title = ' → '.join(safe(o['occupation']) for o in roles)
        zones = ' → '.join(str(o['zone']) if o['zone'] is not None else 'unknown' for o in roles)
        wages = '; '.join(f"{safe(o['occupation'])}: {safe(display_wage(o.get('wage')))}" for o in roles)
        return (f'**Top route · {title}**\n\n'
                f'**Shared-feature requirement overlap:** {top["bottleneck_overlap"]:.1%} at the weakest step. '
                f'**Preparation zones:** {zones}. **Largest zone jump:** {top["largest_zone_jump"]}.\n\n'
                f'**Annual medians (USD, parent SOC):** {wages}.\n\n'
                '**Next:** check gaps for a role on this route. Overlap is not hiring probability; zones do not establish licensing eligibility.')
    detail = reply.context[0] if reply.context else {}
    zone = detail.get('zone')
    preparation = str(zone) if zone is not None else 'unknown'
    wage = display_wage(detail.get('wage') or top.get('wage'))
    if reply.intent == 'skill_match':
        heading = f'**Top match · {safe(top["occupation"])} ({safe(top["soc"])})**'
        metric = (f'**Requirement overlap:** {top["overlap_fraction"]:.1%} '
                  f'({int(top["matched_skills"])}/{top["required_skills"]} skills); '
                  f'**importance coverage:** {top["importance_coverage"]:.1%}.')
        action = 'Check gaps for this occupation using your saved profile.'
    else:
        heading = f'**Skill comparison · {safe(reply.occupation)} ({safe(reply.params.get("soc", ""))})**'
        metric = f'**Highest-priority returned requirement:** {safe(top["skill"])} · importance {display_number(top["importance"])}/5. No overall fit score is calculated for skill gaps.'
        has_levels = bool(reply.params.get('levels'))
        action = ('Your supplied levels are shown in the table below. Update them or compare another target.'
                  if has_levels else 'Add levels for your selected skills, or compare another target.')
    return (heading + '\n\n' + metric + f' **Preparation zone:** {preparation}.\n\n'
            f'**Annual median (USD, parent SOC):** {safe(wage)}.\n\n'
            f'**Next:** {action} Scores describe requirement overlap, not hiring probability.')


def answer_markdown(reply):
    body = decision_summary(reply) + '\n\n' + safe(reply.text)
    rows = reply.rows[:MAX_DISPLAY_ROWS]
    if not rows: return body
    if reply.intent == 'skill_gap':
        body += '\n\n' + table(['Skill', 'Status', 'Importance /5', 'Required /7', 'Yours /7', 'Gap'],
            [[r['skill'], r['status'], display_number(r['importance']), display_number(r['required_level']),
              display_number(r['user_level']), display_number(r['level_gap'])] for r in rows])
    elif reply.intent == 'skill_match':
        body += '\n\n' + table(['Occupation', 'SOC', 'Matched', 'Overlap', 'Coverage', 'Median USD'],
            [[r['occupation'], r['soc'], f"{int(r['matched_skills'])}/{r['required_skills']}",
              f"{r['overlap_fraction']:.1%}", f"{r['importance_coverage']:.1%}", display_wage(r.get('wage'))] for r in rows])
    elif reply.intent == 'career_paths':
        body += '\n\n' + table(['Route', 'Bottleneck', 'Zone jump', 'Steps', 'Medians USD'],
            [[' → '.join(str(o['occupation'])[:1000] for o in r['occupations'][:3]), f"{r['bottleneck_overlap']:.1%}",
              r['largest_zone_jump'], r['transitions'], ' → '.join(display_wage(o.get('wage')) for o in r['occupations'][:3])] for r in rows])
    body += ('\n\nWages: BLS OEWS national annual medians, May 2025. '
             'O*NET specialties share the displayed parent SOC estimate. Wages do not change rankings.')
    return bounded_markdown(body + row_note(len(reply.rows), len(rows)))


def fenced_json(value):
    # JSON Unicode escapes keep the payload valid/recoverable while preventing
    # source strings from terminating the Markdown code fence or injecting HTML.
    return (json.dumps(value, indent=2, ensure_ascii=False)
            .replace('`', r'\u0060').replace('<', r'\u003c').replace('>', r'\u003e'))


def evidence_markdown(reply):
    """Actual graph evidence plus parameters; never a simulated reasoning trace."""
    parts = ['**Explanation:** ' + safe(reply.explanation_source) +
             (f' · {reply.llm_elapsed_ms:.1f} ms (separate from graph time)' if reply.llm_elapsed_ms is not None else '')]
    if reply.intent == 'career_paths':
        parts.append('**Graph traversal:** Occupation → Skill / Knowledge / Task → TaskText ← Occupation. '
                     'Each occupation also connects to its JobZone through IN_ZONE. The Skill/Knowledge branch uses REQUIRES; '
                     'the task branch uses PERFORMS → HAS_TEXT. At least 3 distinct shared features are required on every hop. '
                     'Overlap = intersection / union. Rank by maximum zone jump, bottleneck overlap, total jump, steps, mean overlap, then SOC. '
                     'An unknown zone remains null and gives its hop a ranking penalty of 4.')
        for i, row in enumerate(reply.rows[:3], 1):
            parts.append(f'\n**Route {i} — evidence for each step**')
            for step in row['steps'][:2]:
                a = next((o for o in row['occupations'] if o['soc'] == step['from_soc']), None)
                b = next((o for o in row['occupations'] if o['soc'] == step['to_soc']), None)
                if a is None or b is None:
                    parts.append('A step was omitted because its occupation reference is unavailable.')
                    continue
                parts.append(f"\n**{safe(a['occupation'])} [zone {a['zone'] if a['zone'] is not None else 'unknown'}] → "
                             f"{step['shared_count']} shared features → {safe(b['occupation'])} "
                             f"[zone {b['zone'] if b['zone'] is not None else 'unknown'}]**  \n"
                             f"Overlap: {step['overlap']:.1%}; zone-jump score: {step['zone_jump']}.")
                parts.append('\n' + '; '.join(f"{safe(x['name'])} ({safe(x['key'])})" for x in step['shared'][:MAX_FEATURES]))
                if len(step['shared']) > MAX_FEATURES:
                    parts.append(f'\nShowing first {MAX_FEATURES} of {len(step["shared"])} shared features for this step.')
        if len(reply.rows) > 3: parts.append('\nExpanded feature evidence shows the first three returned routes.')
    elif reply.intent == 'skill_match':
        parts.append('**Graph traversal:** supplied skill names ← Skill ← REQUIRES ← Occupation. '
                     'Only usable importance ratings ≥3 are counted. Skill overlap = matched / required. '
                     'Importance coverage = matched normalized importance / total normalized importance. '
                     'Normalized importance = (raw importance − 1) / 4. Results rank by matched count, coverage, matched weight, then SOC.')
        for row in reply.rows[:MAX_DISPLAY_ROWS]:
            parts.append(f"\n- **{safe(row['occupation'])}** → " + ', '.join(safe(x) for x in row['matched_names'][:35]))
            if len(row['matched_names']) > 35:
                parts.append(f'\nShowing first 35 of {len(row["matched_names"])} matched skill names.')
        parts.append('\nJob zones are not part of the skill-match score.')
    elif reply.intent == 'skill_gap':
        parts.append(f"**Graph traversal:** {safe(reply.occupation)} ({safe(reply.params.get('soc', ''))}) → REQUIRES → Skill. "
                     'Use usable importance ratings ≥3. Compare supplied levels with usable required levels on the 0–7 scale. '
                     'Duplicate supplied levels use their maximum. Sort by importance, then known level gap. '
                     'Supplied levels that meet or exceed a requirement appear as “meets_level” and are never hidden. '
                     'Unreported skills are missing from this profile; names without levels are unassessed. '
                     'Job zones are not part of the skill-gap calculation.')
    else:
        parts.append('Clarification or input validation was required. No scoring tool ran. Any name-lookup queries are listed below.')
    if reply.params:
        parts.append('\n**Verified query:** `' + reply.intent + '.cypher`')
        parts.append('\n**Cypher parameters**\n```json\n' + fenced_json(reply.params) + '\n```')
    parts.append('\n**Read-only call log (milliseconds)**\n```json\n' + fenced_json(reply.traces) + '\n```')
    parts.append(row_note(len(reply.rows), min(len(reply.rows), MAX_DISPLAY_ROWS)))
    return bounded_markdown('\n\n'.join(parts))


class Turn(Validated):
    question: Annotated[str, Field(max_length=4000)]
    answer: Annotated[str, Field(max_length=60000)]
    evidence: Annotated[str, Field(max_length=60000)]


class Profile(Validated):
    skills: Annotated[list[Name], Field(max_length=35)] = Field(default_factory=list)
    levels: Annotated[list[SkillLevel], Field(max_length=35)] = Field(default_factory=list)

    @field_validator('skills')
    @classmethod
    def normalized_skills(cls, values):
        # Dropdown labels are canonical titles; values and persisted state use
        # the same normalized keys, including replies returned by chat tools.
        return list(dict.fromkeys(norm(value) for value in values))

    @field_validator('levels')
    @classmethod
    def normalized_levels(cls, values):
        return [SkillLevel(name=norm(value.name), level=value.level) for value in values]


class GuidedInput(Profile):
    mode: Literal['skill_gap', 'skill_match', 'career_paths']
    # Free text is accepted here (the occupation boxes allow custom values);
    # the agent resolves titles/SOC codes via exact + fuzzy lookup before scoring.
    source: Name | None = None
    target: Name | None = None


class Comparison(Validated):
    question: Annotated[str, Field(max_length=4000)]
    text: Annotated[str, Field(max_length=60000)]
    intent: Literal['skill_gap', 'skill_match', 'career_paths']
    rows: Annotated[list[dict], Field(max_length=100)]
    params: dict
    traces: list[dict]
    occupation: str = ''
    context: list[dict] = Field(default_factory=list)
    rating_coverage: int | None = None
    explanation_source: str = 'deterministic'
    llm_elapsed_ms: float | None = None

    def reply(self):
        return Reply(**self.model_dump(exclude={'question'}))


class ViewState(Validated):
    turns: Annotated[list[Turn], Field(max_length=20)] = Field(default_factory=list)
    session: Session = Field(default_factory=Session)
    profile: Profile = Field(default_factory=Profile)
    latest: Comparison | None = None
    retry_message: str = ''


def messages(turns):
    result = []
    for turn in turns:
        result.extend([
            {'role': 'user', 'content': turn.question},
            {'role': 'assistant', 'content': turn.answer},
            {'role': 'assistant', 'content': turn.evidence,
             'metadata': {'title': 'How this was computed', 'status': 'done'}},
        ])
    return result


def profile_input(skills, levels_text):
    """Validate all editor input before lookup, including level membership."""
    profile = Profile(skills=skills or [])
    UserInput(message=levels_text or 'No levels supplied')
    if levels_text.strip():
        names, levels = _profile(levels_text)
        if not levels or any(norm(name) not in {norm(x.name) for x in levels} for name in names):
            raise Clarify('Enter optional levels as Skill=number, for example Critical Thinking=3.', 'skills')
        if any(norm(x.name) not in {norm(s) for s in profile.skills} for x in levels):
            raise Clarify('Select a skill chip before assigning its level. Your selections are kept.', 'skills')
        profile.levels = levels
    return profile


def result_choices(comparison):
    if comparison is None:
        return []
    if comparison.intent == 'skill_gap':
        return [(f'{comparison.occupation} ({comparison.params["soc"]})', comparison.params['soc'])]
    roles = comparison.rows if comparison.intent == 'skill_match' else [o for r in comparison.rows for o in r['occupations']]
    return list(dict.fromkeys((f'{r["occupation"]} ({r["soc"]})', r['soc']) for r in roles))


def export_comparison(state):
    current = ViewState.model_validate(state)
    if current.latest is None:
        raise gr.Error('Run a comparison first. Your inputs are still available.')
    # Create only on explicit download, in process-temporary storage. Never
    # serialize the environment, credentials, or another session's history.
    for old in Path(EXPORT_DIR.name).glob('*.json'):
        if old.stat().st_mtime < time.time() - 3600:
            old.unlink(missing_ok=True)
    payload = {'format': 'careercompass-comparison-v1',
               'exported_at': datetime.now(timezone.utc).isoformat(),
               'comparison': current.latest.model_dump(), 'sources': SOURCES,
               'caveats': CAVEATS, 'scope': 'Full returned rows; UI tables and feature labels may be sampled.'}
    with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', prefix='comparison-', suffix='.json',
                                     dir=EXPORT_DIR.name, delete=False) as output:
        json.dump(payload, output, ensure_ascii=False, indent=2, allow_nan=False)
        return output.name


def build_app(agent=None):
    agent = agent or CareerCompass()

    def complete(message, current, progress):
        request = UserInput(message=message, session=current.session)
        reply = agent.ask(request.message, request.session.model_dump(), progress=progress)
        turn = Turn(question=request.message, answer=answer_markdown(reply), evidence=evidence_markdown(reply))
        updated = current.model_copy(deep=True)
        updated.turns = (current.turns + [turn])[-20:]
        updated.session = Session.model_validate(reply.session)
        updated.retry_message = request.message if reply.intent == 'error' else ''
        if reply.intent in ('skill_gap', 'skill_match', 'career_paths'):
            data = asdict(reply)
            data.pop('session')
            updated.latest = Comparison(question=request.message, **data)
            if 'skills' in reply.params:
                updated.profile = Profile.model_validate({'skills': reply.params['skills'], 'levels': reply.params.get('levels', [x.model_dump() for x in current.profile.levels if norm(x.name) in {norm(n) for n in reply.params['skills']}])})
        scoring = next((t for t in reversed(reply.traces) if t['tool'] in ('skill_gap', 'skill_match', 'career_paths')), None)
        status = (f"{reply.intent.replace('_', ' ').title()} · {len(reply.rows)} results · "
                  f"{scoring['elapsed_ms']:.1f} ms graph query · O*NET 31.0" if scoring else reply.intent.replace('_', ' ').title())
        if reply.intent == 'error': status = 'Graph unavailable · your inputs are kept · retry when ready'
        elif reply.intent == 'clarification': status = 'One more detail needed · continue below or use the guided editor'
        return messages(updated.turns), updated.model_dump(), request.message if reply.intent == 'error' else '', route_diagram(reply), status

    def respond(message, state, progress=gr.Progress()):
        try:
            current = ViewState.model_validate(state or {})
            UserInput(message=message, session=current.session)
        except ValidationError:
            raise gr.Error('Please enter 1–4,000 readable characters. Your conversation is kept; correct the question and try again.')
        return complete(message, current, progress)

    def catalogs():
        try:
            occupations, skills = agent.catalogs()
            choices = [(f'{o["name"]} ({o["soc"]})', o['soc']) for o in occupations]
            skill_choices = [(s['name'], norm(s['name'])) for s in skills]
            return (gr.update(choices=choices), gr.update(choices=choices), gr.update(choices=skill_choices),
                    f'{len(occupations):,} occupations · {len(skills)} skill categories · live graph catalog')
        except (RedisError, OSError):
            return gr.skip(), gr.skip(), gr.skip(), 'Catalog unavailable. Your inputs are kept. Retry the catalog or ask in chat once the graph reconnects.'

    def mode_changed(mode):
        if mode not in dict((v, k) for k, v in MODES): raise gr.Error('Choose one of the three comparison types.')
        return gr.update(visible=mode == 'career_paths'), gr.update(visible=mode != 'skill_match'), gr.update(visible=mode != 'career_paths')

    def start(mode):
        example = {'skill_gap': EXAMPLES[0], 'skill_match': EXAMPLES[1], 'career_paths': EXAMPLES[2]}[mode]
        return mode, gr.update(open=True), example, *mode_changed(mode)

    def save_profile(skills, levels, state):
        try:
            profile = profile_input(skills, levels)
            current = ViewState.model_validate(state)
        except (ValidationError, Clarify) as exc:
            raise gr.Error('Profile not saved. Use selected skills and finite levels from 0 to 7; for example Critical Thinking=3. Your editor values are kept.') from None
        current.profile = profile
        return current.model_dump(), f'Profile saved for this conversation · {len(profile.skills)} skills · {len(profile.levels)} levels. Run a comparison to apply changes.'

    def guided(mode, source, target, skills, levels, state, progress=gr.Progress()):
        try:
            profile = profile_input(skills, levels)
            form = GuidedInput(mode=mode, source=source, target=target, **profile.model_dump())
            current = ViewState.model_validate(state)
        except (ValidationError, Clarify) as exc:
            raise gr.Error('Check your selections and optional levels (0–7). Your editor values are kept.') from None
        if mode != 'career_paths' and not form.skills:
            raise gr.Error('Choose at least one skill chip. A blank profile cannot be scored; your conversation is kept.')
        if mode != 'skill_match' and not target: raise gr.Error('Select a target occupation from the searchable list.')
        if mode == 'career_paths' and not source: raise gr.Error('Select your starting occupation from the searchable list.')
        current.profile = profile
        draft = Draft(intent=mode, source=source, target=target, skills=profile.skills or None, levels=profile.levels)
        # Structured slots avoid parsing punctuation in occupation names. The
        # normal agent still validates/resolves every skill and SOC before scoring.
        current.session = Session(pending=draft, need=None)
        label = dict((v, k) for k, v in MODES)[mode]
        question = f'{label} using my selected profile' + (f' for {target}' if target else '') + (f' from {source}' if source else '') + '.'
        return complete(question, current, progress)

    def sync_ui(state):
        current = ViewState.model_validate(state)
        choices = result_choices(current.latest)
        return (gr.update(value=current.profile.skills),
                ', '.join(f'{x.name}={x.level:g}' for x in current.profile.levels),
                f'Profile in this conversation · {len(current.profile.skills)} skills · {len(current.profile.levels)} levels. Edit and run again without restarting.',
                gr.update(choices=choices, value=choices[0][1] if choices else None),
                gr.update(visible=current.latest is not None), gr.update(value=None, visible=False),
                gr.update(value=('### Latest completed comparison\n\n' + decision_summary(current.latest.reply())) if current.latest else '', visible=current.latest is not None))

    def follow_gap(soc, state):
        current = ViewState.model_validate(state)
        if not isinstance(soc, str) or soc not in {x[1] for x in result_choices(current.latest)}:
            raise gr.Error('Choose an occupation from the latest comparison.')
        return 'skill_gap', gr.update(value=soc, visible=True), gr.update(open=True), gr.update(visible=False), gr.update(visible=True)

    def another_target():
        return 'skill_gap', gr.update(value=None, visible=True), gr.update(open=True), gr.update(visible=False), gr.update(visible=True)

    with gr.Blocks(title=TITLE, analytics_enabled=False, delete_cache=(3600, 3600)) as demo:
        gr.HTML('<header id="masthead"><div class="cc-brand"><span class="cc-mark" aria-hidden="true">↗</span> CareerCompass</div>'
                '<div class="cc-kicker">Career paths, backed by graph evidence</div><h1>Find your next step.<br>See why it fits.</h1>'
                '<p>Explore careers, compare your skills, and trace a transition through shared requirements. Every result comes with evidence you can inspect.</p>'
                '<div class="cc-tags"><span>O*NET 31.0</span><span>Powered by FalkorDB</span><span>Official BLS wages</span></div></header>')
        if os.getenv('OPENAI_API_KEY', '').strip():
            gr.Markdown('AI explanations enabled: your question and selected graph results are sent to OpenAI. Scores, tables, and diagrams always come from FalkorDB. If AI is unavailable, a template explains the results.')
        with gr.Tabs():
            with gr.Tab('Explore careers'):
                with gr.Row(elem_id='start-cards'):
                    starts = []
                    for label, mode in MODES:
                        with gr.Column(min_width=220, elem_classes=['start-card']):
                            gr.Markdown(f'### {label}\n' + {'skill_match':'Discover occupations that use the skills you already report.', 'skill_gap':'Compare your profile with one occupation’s requirements.', 'career_paths':'See what connects your current role to a new direction.'}[mode])
                            starts.append((gr.Button(label, variant='secondary'), mode))
                with gr.Accordion('Build a comparison · edit your profile', open=False, elem_id='planner') as planner:
                    mode = gr.Radio(choices=MODES, value='skill_match', label='What would you like to explore?')
                    with gr.Row():
                        source = gr.Dropdown(choices=[], label='Starting occupation · type to search', info='Fuzzy search accepts keywords, e.g. "watch repair".', filterable=True, visible=False, allow_custom_value=True)
                        target = gr.Dropdown(choices=[], label='Target occupation · type to search', info='Fuzzy search accepts keywords, e.g. "data science".', filterable=True, visible=False, allow_custom_value=True)
                    with gr.Column() as profile_panel:
                        skills = gr.Dropdown(choices=[], value=[], multiselect=True, max_choices=35, filterable=True, allow_custom_value=False,
                                             label='Your skills', info='Pick canonical O*NET skill categories (e.g., Programming, Mathematics). Software names like Python or SQL are technologies, not skills — choose Programming for coding ability.')
                        levels = gr.Textbox(label='Skill levels (optional) · format: Skill=number, 0–7', placeholder='critical thinking=3, mathematics=4', lines=1,
                                            info='Example: Programming=5, Mathematics=6. Use the 0–7 O*NET level scale (not years of experience or %). Only for skills you selected above; leave blank if unsure — a name alone is unassessed.')
                        save = gr.Button('Save profile', size='sm')
                        profile_note = gr.Markdown('Your profile stays in this conversation. Nothing is written to the graph.', elem_id='profile-note')
                    run = gr.Button('Run comparison', variant='primary')
                    catalog_status = gr.Markdown('Loading searchable graph catalogs…', elem_id='catalog-status')
                    reload_catalog = gr.Button('Retry catalog', size='sm')
                gr.Markdown('**Or ask in your own words.** Try an example below, or describe the comparison you want.')
                text = gr.Textbox(label='Your career question', placeholder='Which jobs match my skills: Critical Thinking, Mathematics?', lines=2, max_lines=5)
                with gr.Row():
                    send = gr.Button('Explore careers', variant='primary')
                    clear = gr.Button('New conversation', variant='secondary')
                gr.Markdown('**Try a real graph question** — runs immediately:')
                with gr.Row():
                    example_buttons = [gr.Button(ex, size='sm', variant='secondary') for ex in EXAMPLES]
                status = gr.Markdown('Ready when you are · no AI key required · graph queries are read-only', elem_id='status')
                latest_summary = gr.Markdown('', visible=False, elem_id='decision-summary')
                chat = gr.Chatbot(label='Your comparisons', height=620, layout='bubble', elem_id='chat',
                                  placeholder='Your comparison will appear here, with scores, sources, and next steps.',
                                  sanitize_html=True, allow_tags=False, buttons=['copy'], feedback_options=(), group_consecutive_messages=False)
                diagram = gr.HTML(value='', label='Top career route')
                with gr.Column(visible=False, elem_id='followups') as followups:
                    gr.Markdown('### Keep exploring\nActions use your latest completed comparison. Your saved skills stay with you.')
                    choice = gr.Dropdown(choices=[], label='Occupation from this comparison', filterable=True, allow_custom_value=False)
                    with gr.Row():
                        gap_action = gr.Button('Check gaps for this occupation')
                        another = gr.Button('Compare another target')
                        download = gr.Button('Download this comparison')
                    exported = gr.File(label='Comparison export · JSON', interactive=False, visible=False)
                    gr.Markdown('Export includes full returned results, parameters, sources, and limitations. It contains your supplied profile; share it only if you intend to.')
            brief = optional_text(BASE / 'JUDGE_BRIEF.md')
            if brief:
                with gr.Tab('Inside the graph'):
                    gr.Markdown(brief)
        state = gr.State(ViewState().model_dump())
        outputs = [chat, state, text, diagram, status]
        synced = [skills, levels, profile_note, choice, followups, exported, latest_summary]
        api = gr.on(triggers=[send.click, text.submit], fn=respond, inputs=[text, state], outputs=outputs,
                    api_name='ask', concurrency_limit=2, concurrency_id='comparisons', trigger_mode='once', show_progress='full', show_progress_on=[status])
        api.success(sync_ui, inputs=state, outputs=synced, api_visibility='private')
        for btn, ex in zip(example_buttons, EXAMPLES):
            ex_run = btn.click(lambda x=ex: x, outputs=text, api_visibility='private')
            ex_run.then(respond, inputs=[text, state], outputs=outputs, show_progress_on=[status],
                        api_visibility='private').success(sync_ui, inputs=state, outputs=synced, api_visibility='private')
        guided_event = run.click(guided, inputs=[mode, source, target, skills, levels, state], outputs=outputs,
                                api_name='compare', concurrency_limit=2, concurrency_id='comparisons', show_progress_on=[status])
        guided_event.success(sync_ui, inputs=state, outputs=synced, api_visibility='private')
        reset = clear.click(lambda: ([], ViewState().model_dump(), '', '', 'New conversation'), outputs=outputs, api_name='reset')
        reset.success(sync_ui, inputs=state, outputs=synced, api_visibility='private')
        reset.success(lambda: (None, None), outputs=[source, target], api_visibility='private')
        mode.change(mode_changed, inputs=mode, outputs=[source, target, profile_panel], api_visibility='private')
        for button, start_mode in starts:
            button.click(lambda m=start_mode: start(m), outputs=[mode, planner, text, source, target, profile_panel], api_visibility='private')
        save.click(save_profile, inputs=[skills, levels, state], outputs=[state, profile_note], api_name='save_profile')
        # API clients do not execute the browser's chained sync_ui event. Check
        # membership against the validated latest comparison in follow_gap,
        # rather than the potentially stale component choices during preprocessing.
        follow_event = gap_action.click(follow_gap, inputs=[choice, state], outputs=[mode, target, planner, source, profile_panel], api_name='follow_gap', preprocess=False)
        another_event = another.click(another_target, outputs=[mode, target, planner, source, profile_panel], api_visibility='private')
        for event in (follow_event, another_event):
            event.success(fn=None, js="() => document.getElementById('planner')?.scrollIntoView({behavior:'smooth',block:'start'})", api_visibility='private')
        export_event = download.click(export_comparison, inputs=state, outputs=exported, api_name='export_comparison')
        export_event.success(lambda: gr.update(visible=True), outputs=exported, api_visibility='private')
        demo.load(catalogs, outputs=[source, target, skills, catalog_status], api_name='catalogs')
        reload_catalog.click(catalogs, outputs=[source, target, skills, catalog_status], api_visibility='private')
        gr.Markdown('Data: [O*NET® Database 31.0](https://www.onetcenter.org/database.html), '
                    'U.S. Department of Labor, Employment and Training Administration (USDOL/ETA), '
                    '[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). '
                    'CareerCompass transforms the data and computes its own rankings; USDOL/ETA has not approved or endorsed them. '
                    'Wages: [BLS OEWS, May 2025](https://www.bls.gov/oes/tables.htm), national annual medians in USD. '
                    'Explanations use deterministic templates unless optional AI rephrasing is configured. '
                    'Profile and chat are temporary; reloads or restarts may clear them.', elem_id='source')
    return demo


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(message)s')
    build_app().queue(max_size=24).launch(
        server_name=os.getenv('GRADIO_SERVER_NAME', '127.0.0.1'),
        server_port=int(os.getenv('GRADIO_SERVER_PORT', '7860')),
        share=False, show_error=False, footer_links=[],
        theme=THEME, css=CSS,
    )