File size: 41,667 Bytes
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
"""Run management commands โ€” local execution."""

import asyncio
import json
import subprocess
import time
from datetime import datetime
from pathlib import Path
from typing import Any

import click
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn

from solar_eval.cli.commands.projects import _resolve_project_id
from solar_eval.cli.formatters import format_runs_table, format_results_table, format_scores


#: run ์ด ๋๋‚œ ๋’ค ์ž๋™ ์ ์žฌ์— ํ—ˆ์šฉํ•˜๋Š” ์‹œ๊ฐ„. ์ „์ฒด ์•„์นด์ด๋ธŒ๊ฐ€ ์•„๋‹ˆ๋ผ ํ”„๋กœ์ ํŠธ ํ•˜๋‚˜๋งŒ
#: ์ ์žฌํ•˜๋ฏ€๋กœ ๋ณดํ†ต ์ˆ˜ ์ดˆ๋ฉด ๋๋‚œ๋‹ค โ€” ๋„˜์–ด๊ฐ€๋ฉด ๋ญ”๊ฐ€ ์ž˜๋ชป๋œ ๊ฒƒ์ด๋ผ ๊ธฐ๋‹ค๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
INGEST_TIMEOUT_SECONDS = 180


@click.group("runs")
def runs_group() -> None:
    """Manage evaluation runs."""


@runs_group.command("list")
@click.argument("project")
@click.option("--task", "-t", default=None, help="Filter by task name")
@click.pass_context
def list_runs(ctx: click.Context, project: str, task: str | None) -> None:
    """List runs for a project."""
    cfg = ctx.obj["config"]
    if not cfg.is_remote:
        # List local run directories
        artifacts = cfg.artifacts_dir(project)
        if not artifacts.exists():
            click.secho("No local runs found.", fg="yellow")
            return
        runs = []
        for d in sorted(artifacts.iterdir()):
            if d.is_dir() and (d / "run.json").exists():
                run_data = json.loads((d / "run.json").read_text())
                if task and run_data.get("task") != task:
                    continue
                runs.append(
                    {
                        "id": d.name,
                        "task": run_data.get("task", "-"),
                        "model": run_data.get("model", "-"),
                        "prompt": run_data.get("prompt", run_data.get("prompt_version", "-")),
                        "pipeline": run_data.get("pipeline", "-"),
                        "status": run_data.get("status", "unknown"),
                        "total_samples": run_data.get("total_samples", 0),
                        "completed_samples": run_data.get("completed_samples", 0),
                        "created_at": run_data.get("started_at", "-"),
                    }
                )
        if not runs:
            click.secho("No local runs found.", fg="yellow")
            return
        click.secho(format_runs_table(runs), fg="blue")
        return

    from solar_eval.cli.client import EvalClient

    client = EvalClient(cfg.remote_url, cfg.timeout)
    project_id = _resolve_project_id(client, project)
    params = {"task": task} if task else {}
    runs = client.get(f"/api/projects/{project_id}/runs", params=params)
    if not runs:
        click.secho("No runs found.", fg="yellow")
        return
    click.secho(format_runs_table(runs), fg="blue")


@runs_group.command("start")
@click.argument("project")
@click.option("--task", "-t", required=True, help="Task name")
@click.option("--prompt", "-p", "prompt_name", required=True, help="Prompt name (YAML in prompts/)")
@click.option("--model", "-m", required=True, help="Model name (e.g. solar-pro3)")
@click.option(
    "--pipeline",
    "-P",
    "pipeline_name",
    default=None,
    help="Pipeline template name (overrides project default)",
)
@click.option(
    "--reasoning-effort",
    "-re",
    default=None,
    help="Reasoning effort (low/medium/high)",
)
@click.option("--temperature", "-T", default=0.0, type=float, help="Temperature (default: 0.0)")
@click.option("--max-tokens", default=4000, type=int, help="Max tokens (default: 4000)")
@click.option("--max-workers", "-w", default=5, type=int, help="Max parallel workers")
@click.option(
    "--limit", "-n", default=None, type=int, help="Limit number of samples (for quick testing)"
)
@click.option(
    "--note",
    default=None,
    help="์ด run ์„ ์™œ ๋Œ๋ฆฌ๋Š”์ง€ ํ•œ ์ค„ (run.json ์— ๊ธฐ๋ก๋˜๊ณ  evalhub ๊ฐ€ ๊ทธ๋Œ€๋กœ ์ฝ๋Š”๋‹ค)",
)
@click.option(
    "--set",
    "set_options",
    multiple=True,
    metavar="PATH=VALUE",
    help=(
        "ํŒŒ์ดํ”„๋ผ์ธ ์„ค์ • ํ•œ ์ถ•๋งŒ ๋ฐ”๊ฟ”์„œ ๋Œ๋ฆฐ๋‹ค (ํŒŒ์ผ์„ ๋งŒ๋“ค์ง€ ์•Š๋Š”๋‹ค). "
        "์˜ˆ: --set steps.basic_correction.reasoning_effort=high. ์—ฌ๋Ÿฌ ๋ฒˆ ์“ธ ์ˆ˜ ์žˆ๋‹ค."
    ),
)
@click.option(
    "--no-ingest",
    is_flag=True,
    help="run ์ด ๋๋‚œ ๋’ค evalhub ์ž๋™ ์ ์žฌ๋ฅผ ๊ฑด๋„ˆ๋›ด๋‹ค (์—ฌ๋Ÿฌ run ์„ ๋Œ๋ฆฌ๊ณ  ํ•œ ๋ฒˆ์— ์ ์žฌํ•  ๋•Œ)",
)
@click.pass_context
def start_run(
    ctx: click.Context,
    project: str,
    task: str,
    prompt_name: str,
    model: str,
    pipeline_name: str | None,
    reasoning_effort: str | None,
    temperature: float,
    max_tokens: int,
    max_workers: int,
    limit: int | None,
    note: str | None,
    set_options: tuple[str, ...],
    no_ingest: bool,
) -> None:
    """Start an evaluation run.

    Example:
        solar-eval runs start chosun-proofreading -t ci-v1-all \\
            -p dev_260329_pro3_v1 -m solar-pro3 -P 251231_pro3 \\
            --note "v24 SC+judge ๊ฐ€ ci-v1 ์—์„œ๋„ prod ๋ฅผ ๋„˜๋Š”์ง€"

        solar-eval runs start chosun-proofreading -t paragraph-small \\
            -p prompt_dev_v23 -m solar-pro3 -P pipeline_dev_v24 \\
            --set steps.basic_correction.repeat_temperatures='[0.0, 0.5]' \\
            --note "SC ์˜จ๋„ ํญ ์Šค์œ•"
    """
    cfg = ctx.obj["config"]

    _start_local(
        cfg,
        project=project,
        task=task,
        prompt_name=prompt_name,
        model=model,
        pipeline_name=pipeline_name,
        reasoning_effort=reasoning_effort,
        temperature=temperature,
        max_tokens=max_tokens,
        max_workers=max_workers,
        limit=limit,
        note=note,
        set_options=set_options,
        no_ingest=no_ingest,
    )


def _resolve_prompt(prompts_dir: Path, prompt_name: str) -> Path:
    """Resolve prompt from prompts/ directory (directory or YAML file).

    Resolution order:
    1. prompts/{name}/          (directory TXT format)
    2. prompts/{name}.yaml      (flat YAML layout)
    3. prompts/_library/{name}.yaml  (legacy layout)
    """
    # Directory TXT format (new)
    dir_path = prompts_dir / prompt_name
    if dir_path.is_dir():
        return dir_path
    # Flat YAML layout
    yaml_path = prompts_dir / f"{prompt_name}.yaml"
    if yaml_path.exists():
        return yaml_path
    # Legacy _library layout
    legacy_path = prompts_dir / "_library" / f"{prompt_name}.yaml"
    if legacy_path.exists():
        return legacy_path
    raise click.ClickException(
        f"Prompt '{prompt_name}' not found. Searched:\n"
        f"  {dir_path}/ (directory)\n"
        f"  {yaml_path} (YAML)\n"
        f"  {legacy_path} (legacy)"
    )


def _resolve_pipeline_file(project_dir: Path, pipeline_name: str) -> Path:
    """Resolve pipeline YAML from pipelines/ directory."""
    path = project_dir / "pipelines" / f"{pipeline_name}.yaml"
    if not path.exists():
        raise click.ClickException(f"Pipeline '{pipeline_name}' not found: {path}")
    return path


def _compose_pipeline_config(project_dir: Path, pipeline_name: str, overrides: dict) -> dict:
    """ํŒŒ์ดํ”„๋ผ์ธ์„ `extends`/override ๊นŒ์ง€ ํ•ด์„ํ•ด ๋Œ๋ ค์ค€๋‹ค.

    ์กฐ๋ฆฝ ์‹คํŒจ(์—†๋Š” base, ์—†๋Š” ์Šคํ…์„ ๊ฐ€๋ฆฌํ‚ค๋Š” override ๋“ฑ)๋Š” run ์„ ์‹œ์ž‘ํ•˜๊ธฐ ์ „์—
    ์ฃฝ์ธ๋‹ค โ€” ํšจ๊ณผ ์—†๋Š” override ๋กœ ๋Œ์•„๊ฐ„ run ์€ ๊ฒฐ๋ก ์„ ์กฐ์šฉํžˆ ์˜ค์—ผ์‹œํ‚จ๋‹ค.
    """
    from solar_eval.core.pipeline_compose import PipelineCompositionError, compose_pipeline
    from solar_eval.core.project_loader import load_pipeline_file

    pipelines_dir = _resolve_pipeline_file(project_dir, pipeline_name).parent
    try:
        composed = load_pipeline_file(pipelines_dir, pipeline_name)
        if overrides:
            composed = compose_pipeline(composed, overrides=overrides)
        return composed
    except (PipelineCompositionError, FileNotFoundError) as e:
        raise click.ClickException(str(e)) from None


def _build_run_name(task: str, pipeline_name: str, prompt_name: str) -> str:
    """Build a readable run name: {task}__{pipeline}__{prompt}__{YYMMDD}_{HHMMSS}"""
    ts = datetime.now().strftime("%y%m%d_%H%M%S")
    return f"{task}__{pipeline_name}__{prompt_name}__{ts}"


_RUN_DIR_MAX_ATTEMPTS = 20
_RUN_DIR_RETRY_DELAY_SECONDS = 0.05


def _make_run_dir(
    artifacts_dir: Path, task: str, pipeline_name: str, prompt_name: str
) -> tuple[str, Path]:
    """run_name ์„ ์ง“๊ณ  ๊ทธ ๋””๋ ‰ํ„ฐ๋ฆฌ๋ฅผ ์›์ž์ ์œผ๋กœ ๋งŒ๋“ ๋‹ค.

    ๊ฐ™์€ ์ดˆ์— ๊ฐ™์€ (task, pipeline, prompt) ์กฐํ•ฉ์œผ๋กœ ๋‘ run ์ด ์‹œ์ž‘๋˜๋ฉด
    `_build_run_name` ์ด ๊ฐ™์€ ์ด๋ฆ„์„ ๋‚ธ๋‹ค. `mkdir(exist_ok=False)` ๋ฅผ ์“ฐ๋ฉด ๋‘ ํ”„๋กœ์„ธ์Šค๊ฐ€
    ๋™์‹œ์— ๊ฐ™์€ ์ด๋ฆ„์œผ๋กœ mkdir ํ•ด๋„ ์ •ํ™•ํžˆ ํ•˜๋‚˜๋งŒ ์„ฑ๊ณตํ•˜๊ณ , ์ง„ ์ชฝ์€ ์ƒˆ ํƒ€์ž„์Šคํƒฌํ”„๋กœ
    ์žฌ์‹œ๋„ํ•œ๋‹ค โ€” ํŒŒ์ผ ํฌ๋งท ์ž์ฒด๋Š” ์•ˆ ๋ฐ”๊พธ๋ฏ€๋กœ evalhub ์˜ run_id ํŒŒ์‹ฑ๊ณผ ํ˜ธํ™˜๋œ๋‹ค.
    """
    for _ in range(_RUN_DIR_MAX_ATTEMPTS):
        run_name = _build_run_name(task, pipeline_name, prompt_name)
        run_dir = artifacts_dir / run_name
        try:
            run_dir.mkdir(parents=True, exist_ok=False)
            return run_name, run_dir
        except FileExistsError:
            time.sleep(_RUN_DIR_RETRY_DELAY_SECONDS)
    raise click.ClickException(f"Could not allocate a unique run directory under {artifacts_dir}")


def _config_source(cfg, project: str) -> str:
    """run ์˜ config ์ถœ์ฒ˜ โ€” ๋ ˆํฌ ๊ด€๋ฆฌ ํ”„๋กœ์ ํŠธ๋ฉด ๋ ˆํฌ ์ƒ๋Œ€ ๊ฒฝ๋กœ, ์•„๋‹ˆ๋ฉด ๋ฐ์ดํ„ฐ ํ™ˆ ์ ˆ๋Œ€ ๊ฒฝ๋กœ."""
    config_dir = cfg.config_dir(project)
    if cfg.is_repo_managed(project) and cfg.repo_root is not None:
        return str(config_dir.relative_to(cfg.repo_root))
    return str(config_dir)


def _git_commit(repo_root: Path | None) -> str | None:
    """์žฌํ˜„์šฉ ๋„์žฅ: ๋ ˆํฌ HEAD ์ปค๋ฐ‹. ์ž‘์—… ํŠธ๋ฆฌ๊ฐ€ ๋”๋Ÿฌ์šฐ๋ฉด '-dirty' ๋ฅผ ๋ถ™์ธ๋‹ค."""
    if repo_root is None:
        return None
    try:
        head = subprocess.run(
            ["git", "-C", str(repo_root), "rev-parse", "--short", "HEAD"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        status = subprocess.run(
            ["git", "-C", str(repo_root), "status", "--porcelain"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        return f"{head}-dirty" if status else head
    except (OSError, subprocess.CalledProcessError):
        return None


def _start_local(
    cfg,
    project: str,
    task: str,
    prompt_name: str,
    model: str,
    pipeline_name: str | None,
    reasoning_effort: str | None,
    temperature: float,
    max_tokens: int,
    max_workers: int,
    limit: int | None,
    note: str | None = None,
    set_options: tuple[str, ...] = (),
    no_ingest: bool = False,
) -> None:
    """Start run locally with the new prompt/model/pipeline interface."""
    from solar_eval.core.dataset_loader import DatasetLoader
    from solar_eval.core.fingerprint import pipeline_fingerprint, prompt_fingerprint
    from solar_eval.core.pipeline_compose import PipelineCompositionError, parse_set_option
    from solar_eval.core.project_loader import load_all_project_configs
    from solar_eval.core.runner import BatchRunner
    from solar_eval.models.prompt_version import (
        detect_prompt_format,
        load_prompt_messages,
        load_step_prompts,
    )
    from solar_eval.providers import UpstageProvider
    from solar_eval.providers.openai_provider import OpenAIProvider
    from solar_eval.stores import JsonlStore

    # Load project config
    configs = load_all_project_configs(cfg.projects_dir, cfg.config_dirs)
    project_config = next((c for c in configs if c["name"] == project), None)
    if not project_config:
        raise click.ClickException(f"Project not found in {cfg.projects_dir}: {project}")

    task_config = next((t for t in project_config.get("tasks", []) if t["name"] == task), None)
    if not task_config:
        raise click.ClickException(f"Task '{task}' not found in project '{project}'")

    # Resolve prompt file
    prompts_dir = cfg.prompts_dir(project)
    prompt_path = _resolve_prompt(prompts_dir, prompt_name)

    fmt = detect_prompt_format(prompt_path)
    if fmt == "multi_step":
        step_prompts = load_step_prompts(prompt_path)
        prompt = {
            "step_prompts": step_prompts,
            "model": model,
            "temperature": temperature,
            "max_tokens": max_tokens,
        }
    else:
        messages = load_prompt_messages(prompt_path)
        prompt = {
            "messages": messages,
            "model": model,
            "temperature": temperature,
            "max_tokens": max_tokens,
        }

    if reasoning_effort:
        prompt["reasoning_effort"] = reasoning_effort

    # Resolve pipeline โ€” config ๋Š” ๋ ˆํฌ ๊ด€๋ฆฌ ํ”„๋กœ์ ํŠธ๋ฉด git ์ชฝ์ด ์ •๋ณธ.
    # `extends` ์ƒ์†๊ณผ `--set` override ๋Š” ์—ฌ๊ธฐ์„œ ์ „๋ถ€ ํ•ด์„๋ผ, ์‹คํ–‰ ์—”์ง„์—๋Š” ์™„์„ฑ๋œ
    # steps ๋ชฉ๋ก๋งŒ ๋„˜์–ด๊ฐ„๋‹ค.
    try:
        cli_overrides = parse_set_option(set_options)
    except PipelineCompositionError as e:
        raise click.ClickException(str(e)) from None

    effective_pipeline = pipeline_name
    if pipeline_name:
        pipeline_config = _compose_pipeline_config(
            cfg.config_dir(project), pipeline_name, cli_overrides
        )
        task_config = {**task_config, "pipeline_config": pipeline_config}
    else:
        # Use default from project.yaml (already resolved by project_loader)
        pc = task_config.get("pipeline_config", {})
        effective_pipeline = pc.get("name", "default") if isinstance(pc, dict) else str(pc)
        if cli_overrides:
            raise click.ClickException("--set requires an explicit --pipeline/-P")
        pipeline_config = pc if isinstance(pc, dict) else {}

    # Build run name and directory -- ์ด๋ฆ„ ์ถฉ๋Œ์€ ์—ฌ๊ธฐ์„œ ์›์ž์ ์œผ๋กœ ๊ฑธ๋Ÿฌ์ง„๋‹ค(F10).
    run_name, run_dir = _make_run_dir(
        cfg.artifacts_dir(project), task, effective_pipeline, prompt_name
    )
    store = JsonlStore(run_dir)

    # Save run metadata
    run_meta = {
        "task": task,
        "model": model,
        "prompt": prompt_name,
        "pipeline": effective_pipeline,
        "temperature": temperature,
        "max_tokens": max_tokens,
        "reasoning_effort": reasoning_effort,
        # ์™œ ๋Œ๋ ธ๋Š”์ง€ โ€” ์˜ˆ์ „์—๋Š” ๋ณ„๋„ ๋žฉ๋…ธํŠธ(experiments/*.yaml)๊ฐ€ ๋‹ด์•˜์ง€๋งŒ run ๊ณผ ๋ถ„๋ฆฌ๋ผ ์žˆ์–ด
        # ์ฐธ์กฐ๊ฐ€ ๋Š์–ด์ง€๊ณ  ์ฉ์—ˆ๋‹ค. run ๊ณผ ๊ฐ™์€ ํŒŒ์ผ์— ๋‘๋ฉด ๋Š์–ด์งˆ ์ˆ˜๊ฐ€ ์—†๋‹ค.
        "note": note,
        # provenance: ์ด run ์˜ config(ํ”„๋กฌํ”„ํŠธยทํŒŒ์ดํ”„๋ผ์ธ)๊ฐ€ ์–ด๋””์„œ ์™”๋Š”์ง€ (W&B/DVC ์‹ ๋„์žฅ)
        "config_source": _config_source(cfg, project),
        "git_commit": _git_commit(cfg.repo_root) if cfg.is_repo_managed(project) else None,
        # ๋‚ด์šฉ ์ง€๋ฌธ โ€” ์ด๋ฆ„์ด ์•„๋‹ˆ๋ผ ๋‚ด์šฉ์œผ๋กœ ์„ค์ •์„ ์‹๋ณ„ํ•œ๋‹ค. ์ด๋ฆ„๋งŒ ๋‹ค๋ฅธ ์‚ฌ๋ณธ,
        # `extends` ๋กœ ์กฐ๋ฆฝํ•œ ๊ฒƒ, `--set` ์œผ๋กœ ์ฆ‰์„์—์„œ ๋งŒ๋“  ๊ฒƒ์ด ๋ชจ๋‘ ๊ฐ™์€ ๊ฐ’์ด๋ฉด
        # ๊ฐ™์€ ์ง€๋ฌธ์„ ๊ฐ–๋Š”๋‹ค (core/fingerprint.py).
        "prompt_sha": prompt_fingerprint(prompt_path),
        "pipeline_sha": pipeline_fingerprint(pipeline_config),
        # ํŒŒ์ผ ์—†์ด ๋Œ๋ฆฐ ์‹คํ—˜์ด๋ฉด ๋ฌด์—‡์„ ๋ฐ”๊ฟจ๋Š”์ง€๊ฐ€ ์—ฌ๊ธฐ ๋‚จ๋Š”๋‹ค.
        "pipeline_overrides": cli_overrides or None,
    }
    # run_dir ์€ _make_run_dir ์ด ์ด๋ฏธ ์›์ž์ ์œผ๋กœ ๋งŒ๋“ค์—ˆ๋‹ค -- ์—ฌ๊ธฐ์„œ ๋‹ค์‹œ mkdir ํ•˜์ง€ ์•Š๋Š”๋‹ค.
    (run_dir / "run.json").write_text(json.dumps(run_meta, ensure_ascii=False, indent=2))

    # Log run info
    click.secho(f"Prompt: {prompt_name} [{fmt}]", fg="blue")
    click.secho(f"Model: {model}", fg="blue")
    click.secho(f"Pipeline: {effective_pipeline}", fg="blue")
    for path, value in cli_overrides.items():
        click.secho(f"  override: {path} = {value!r}", fg="magenta")
    click.secho(
        f"Fingerprint: prompt {run_meta['prompt_sha']} / pipeline {run_meta['pipeline_sha']}",
        fg="blue",
    )
    if reasoning_effort:
        click.secho(f"Reasoning effort: {reasoning_effort}", fg="blue")
    if limit:
        click.secho(f"Limit: {limit} samples", fg="yellow")
    click.secho(f"Starting local run: {project}/{run_name}", fg="blue")
    click.secho(f"Output: {run_dir}", fg="blue")

    # Create runner
    provider = UpstageProvider()
    judge_provider = OpenAIProvider()
    dataset_loader = DatasetLoader(base_dir=cfg.projects_dir)
    runner = BatchRunner(
        store=store,
        inference_provider=provider,
        judge_provider=judge_provider,
        dataset_loader=dataset_loader,
    )

    # Run with progress display
    _run_with_progress(runner, run_name, project_config, task_config, prompt, max_workers, limit)

    _warn_if_incomplete(run_dir)
    click.echo(f"\nResults saved to: {run_dir}/")
    if not no_ingest:
        _ingest_into_evalhub(cfg, project, run_dir)


def _ingest_into_evalhub(cfg, project: str, run_dir: Path) -> None:
    """๋ฐฉ๊ธˆ ๋งŒ๋“  run ์„ evalhub ๋กœ ์ ์žฌํ•œ๋‹ค.

    **์‹คํŒจํ•ด๋„ run ์€ ์„ฑ๊ณต์ด๋‹ค** โ€” ๊ฒฐ๊ณผ๋Š” ์ด๋ฏธ ๋””์Šคํฌ์— ์žˆ๊ณ , ์ ์žฌ๋Š” ๋‚˜์ค‘์— ๋‹ค์‹œ
    ๋Œ๋ฆฌ๋ฉด ๋˜๋Š” ๋ฉฑ๋“ฑ ์ž‘์—…์ด๋‹ค. ๊ทธ๋ž˜์„œ ์–ด๋–ค ์‹คํŒจ๋„ exit code ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ 
    "๋ฌด์—‡์ด ์•ˆ ๋๊ณ  ์–ด๋–ป๊ฒŒ ๋˜์‚ด๋ฆฌ๋Š”์ง€"๋งŒ ์•Œ๋ฆฐ๋‹ค. ์ ์žฌ๋ฅผ ๋ชป ํ–ˆ๋‹ค๋Š” ์‚ฌ์‹ค ์ž์ฒด๋ฅผ
    ์กฐ์šฉํžˆ ๋„˜๊ธฐ์ง€๋„ ์•Š๋Š”๋‹ค โ€” ๊ทธ๋Ÿฌ๋ฉด evalhub ํ™”๋ฉด์ด ๋‚ก์€ ์ฑ„๋กœ ๋‚จ๋Š”๋‹ค.

    ๋ ˆํฌ ๋ฐ– standalone ์„ค์น˜์—๋Š” evalhub ์ž์ฒด๊ฐ€ ์—†์œผ๋ฏ€๋กœ ์กฐ์šฉํžˆ ๊ฑด๋„ˆ๋›ด๋‹ค.
    """
    if cfg.repo_root is None:
        return

    click.secho("\nevalhub ์ ์žฌ ์ค‘...", fg="blue")
    try:
        result = subprocess.run(
            ["pnpm", "--filter", "@poc/eval-store", "ingest", "--only", project],
            cwd=str(cfg.repo_root),
            capture_output=True,
            text=True,
            timeout=INGEST_TIMEOUT_SECONDS,
        )
    except FileNotFoundError:
        _warn_ingest_skipped(project, run_dir, "pnpm ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค")
        return
    except subprocess.TimeoutExpired:
        _warn_ingest_skipped(project, run_dir, f"{INGEST_TIMEOUT_SECONDS}์ดˆ ์•ˆ์— ๋๋‚˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")
        return
    except OSError as e:
        _warn_ingest_skipped(project, run_dir, str(e))
        return

    if result.returncode == 0:
        click.secho(f"  evalhub ์ ์žฌ ์™„๋ฃŒ โ€” {project}", fg="green")
        return
    _warn_ingest_skipped(project, run_dir, _ingest_failure_reason(result))


def _ingest_failure_reason(result: subprocess.CompletedProcess[str]) -> str:
    """ingest ์‹คํŒจ ์ถœ๋ ฅ์—์„œ ์‚ฌ๋žŒ์ด ์ฝ์„ ํ•œ ์ค„์„ ๋ฝ‘๋Š”๋‹ค.

    stderr ์ „์ฒด๋Š” node ์ŠคํƒํŠธ๋ ˆ์ด์Šค๋ผ ๊ทธ๋Œ€๋กœ ๋ณด์—ฌ์ฃผ๋ฉด ์ •์ž‘ ์›์ธ์ด ๋ฌปํžŒ๋‹ค.
    ๊ฐ€์žฅ ํ”ํ•œ ์›์ธ(๋ฐฑ์—”๋“œ ๋ฏธ๊ธฐ๋™)์€ ์—ฐ๊ฒฐ ๊ฑฐ๋ถ€๋กœ ๋‚˜ํƒ€๋‚˜๋ฏ€๋กœ ๋จผ์ € ์งš๋Š”๋‹ค.
    """
    output = f"{result.stderr}\n{result.stdout}"
    if "ECONNREFUSED" in output or "connect ECONNREFUSED" in output:
        return "Postgres ์— ์—ฐ๊ฒฐํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค (๋ฐฑ์—”๋“œ๊ฐ€ ๊บผ์ ธ ์žˆ๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค)"
    for line in result.stderr.splitlines():
        stripped = line.strip()
        if stripped and not stripped.startswith("at ") and "node_modules" not in stripped:
            return stripped[:160]
    return f"ingest ๊ฐ€ exit {result.returncode} ๋กœ ๋๋‚ฌ์Šต๋‹ˆ๋‹ค"


def _warn_ingest_skipped(project: str, run_dir: Path, reason: str) -> None:
    """์ ์žฌ ์‹คํŒจ๋ฅผ ์•Œ๋ฆฌ๊ณ  ๋˜์‚ด๋ฆฌ๋Š” ๋ช…๋ น์„ ๊ทธ๋Œ€๋กœ ์‹ค์–ด ์ค€๋‹ค (exit code ๋Š” 0 ์œ ์ง€)."""
    click.secho(f"\n  โš  evalhub ์ ์žฌ๋ฅผ ๊ฑด๋„ˆ๋›ฐ์—ˆ์Šต๋‹ˆ๋‹ค โ€” {reason}", fg="yellow", bold=True)
    click.secho(f"    run ๊ฒฐ๊ณผ๋Š” ๊ทธ๋Œ€๋กœ ์žˆ์Šต๋‹ˆ๋‹ค: {run_dir}", fg="yellow")
    click.secho("    ๋ฐฑ์—”๋“œ๋ฅผ ๋„์šด ๋’ค ์•„๋ž˜๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ๋ฐ˜์˜๋ฉ๋‹ˆ๋‹ค:", fg="yellow")
    click.secho("      make evalhub-up", fg="yellow")
    click.secho(f"      make evalhub-ingest ONLY={project}", fg="yellow")


def _warn_if_incomplete(run_dir: Path) -> None:
    """์ƒ˜ํ”Œ์ด ์œ ์‹ค๋œ ์ฑ„ ๋๋‚ฌ์œผ๋ฉด ์ ์ˆ˜ ์˜†์— ํฌ๊ฒŒ ์•Œ๋ฆฐ๋‹ค.

    ์œ ์‹ค์€ ์กฐ์šฉํ•˜๋‹ค: ์‹คํŒจํ•œ ์ƒ˜ํ”Œ์€ `results.jsonl` ์— ํ–‰ ์ž์ฒด๊ฐ€ ๋‚จ์ง€ ์•Š๊ณ (error ํ•„๋“œ๋„
    ์—†๋‹ค) ์ ์ˆ˜๋Š” ์‚ด์•„๋‚จ์€ ์ƒ˜ํ”Œ๋งŒ์œผ๋กœ ์ง‘๊ณ„๋œ๋‹ค. ์‹ค์ œ๋กœ 429 ์žฌ์‹œ๋„ ์†Œ์ง„์œผ๋กœ 159๊ฑด ์ค‘
    17๊ฑด์ด ๋น ์ง„ run ์ด "์™„๋ฃŒ"๋กœ ๋๋‚˜๋ฉฐ ์ ์ˆ˜๋ฅผ ๋ƒˆ๊ณ , `run.json` ์˜
    completed/total ์„ ์ง์ ‘ ๋Œ€์กฐํ•˜๊ธฐ ์ „๊นŒ์ง€ ์•„๋ฌด๋„ ๋ชฐ๋ž๋‹ค.

    ๋ถ€๋ถ„ ๊ฒฐ๊ณผ๋ผ๋„ ์ง€์šฐ์ง€๋Š” ์•Š๋Š”๋‹ค โ€” ์žฌํ˜„ ๋น„์šฉ์ด ํฌ๊ณ , ์™„๋ฃŒ์œจ์„ ์•Œ๊ณ  ๋ณด๋ฉด ์“ธ๋ชจ๊ฐ€ ์žˆ๋‹ค.
    """
    try:
        meta = json.loads((run_dir / "run.json").read_text())
    except (OSError, json.JSONDecodeError):
        return

    total, done = meta.get("total_samples"), meta.get("completed_samples")
    if not isinstance(total, int) or not isinstance(done, int) or done >= total:
        return

    click.secho(
        f"\n  โš  ์ƒ˜ํ”Œ {total - done}๊ฑด์ด ์œ ์‹ค๋์Šต๋‹ˆ๋‹ค ({done}/{total} ์™„๋ฃŒ). "
        f"์ ์ˆ˜๋Š” ์™„๋ฃŒ๋œ ์ƒ˜ํ”Œ๋งŒ์œผ๋กœ ๊ณ„์‚ฐ๋œ ๊ฐ’์ด๋ผ ๋‹ค๋ฅธ run ๊ณผ ์ง์ ‘ ๋น„๊ตํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.",
        fg="yellow",
        bold=True,
    )
    click.secho(
        "    ํ”ํ•œ ์›์ธ์€ API 429 ์ž…๋‹ˆ๋‹ค โ€” `-w/--max-workers` ๋ฅผ ๋‚ฎ์ถฐ ๋‹ค์‹œ ๋Œ๋ฆฌ์„ธ์š”.",
        fg="yellow",
    )


def _run_with_progress(
    runner,
    run_id,
    project_config,
    task_config,
    prompt,
    max_workers,
    limit,
    completed_results: list[dict[str, Any]] | None = None,
):
    """Execute a run with Rich progress bar display.

    `completed_results` ๋Š” resume ์ด ์ด๋ฏธ ๋๋‚œ ์ƒ˜ํ”Œ์„ ๋‹ค์‹œ ๋Œ๋ฆฌ์ง€ ์•Š๊ฒŒ ํ•˜๋Š” ๋‹ค๋ฆฌ๋‹ค --
    ์—ฌ๊ธฐ์„œ ์•ˆ ๋„˜๊ธฐ๋ฉด runner ๊ฐ€ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๊ฐ–๊ณ  ์žˆ์–ด๋„ ์†Œ์šฉ์ด ์—†๋‹ค(F2).

    `execute_run` ์€ ์น˜๋ช…์  ์‹คํŒจ์—์„œ raise ํ•˜๋ฏ€๋กœ ์ด ํ•จ์ˆ˜๋„ raise ํ•œ๋‹ค --
    ์ผ๋ถ€๋Ÿฌ ๊ฐ์‹ธ์ง€ ์•Š๋Š”๋‹ค. ์œ„์ชฝ `on_progress` ์˜ "error" ์ด๋ฒคํŠธ๊ฐ€ ์ด๋ฏธ ์‚ฌ๋žŒ์ด ์ฝ์„
    ๋ฉ”์‹œ์ง€๋ฅผ ์ฐ์—ˆ๊ณ , ์—ฌ๊ธฐ์„œ ๋˜ ๊ฐ์‹ธ๋ฉด ๊ฐ™์€ ๋‚ด์šฉ์ด ๋‘ ๋ฒˆ ๋‚˜์˜จ๋‹ค.
    """
    import logging as _logging

    from rich.console import Console
    from rich.live import Live
    from rich.text import Text

    console = Console(stderr=True)
    use_rich = True
    live_ctx: Live | None = None

    progress_bar = Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TextColumn("{task.completed}/{task.total}"),
        TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
        TimeElapsedColumn(),
    )

    try:
        live_ctx = Live(progress_bar, console=console, refresh_per_second=8)
        live_ctx.start()
    except Exception:
        use_rich = False

    # Redirect pipeline/runner logs above the progress bar
    class _LiveLogHandler(_logging.Handler):
        def emit(self, record):
            if live_ctx:
                live_ctx.console.print(Text(record.getMessage(), style="dim"))

    _log_names = (
        "solar_eval.pipelines.pipeline",
        "solar_eval.pipelines.steps.llm",
        "solar_eval.core.runner",
        "solar_eval.providers.upstage",
    )
    if use_rich:
        _live_handler = _LiveLogHandler()
        for name in _log_names:
            lg = _logging.getLogger(name)
            lg.addHandler(_live_handler)
            lg.propagate = False
        _logging.getLogger("httpx").setLevel(_logging.WARNING)

    def _cleanup_live():
        if use_rich:
            live_ctx.stop()
            for name in _log_names:
                _logging.getLogger(name).removeHandler(_live_handler)
                _logging.getLogger(name).propagate = True

    inference_task_id = None
    eval_task_id = None

    async def on_progress(event):
        nonlocal inference_task_id, eval_task_id
        etype = event.get("type")
        if etype == "dataset_loaded":
            total = event["total"]
            if use_rich:
                inference_task_id = progress_bar.add_task("Inference", total=total)
            else:
                click.secho(f"  Dataset loaded: {total} samples", fg="blue")
        elif etype == "inference_progress":
            if use_rich and inference_task_id is not None:
                progress_bar.update(inference_task_id, completed=event["completed"])
            elif not use_rich:
                c, t = event["completed"], event["total"]
                if c % 10 == 0 or c == t:
                    click.echo(f"  Inference: {c}/{t}")
        elif etype == "inference_complete":
            if use_rich and inference_task_id is not None:
                progress_bar.update(inference_task_id, completed=event["total"])
            else:
                click.secho(f"  Inference complete: {event['total']} samples", fg="green")
        elif etype == "evaluation_start":
            total = event.get("total", 0)
            if use_rich:
                eval_task_id = progress_bar.add_task("Evaluation", total=total or 1)
            else:
                click.secho("  Starting evaluation...", fg="blue")
        elif etype == "evaluation_progress":
            if use_rich and eval_task_id is not None:
                progress_bar.update(eval_task_id, completed=event["completed"])
        elif etype == "done":
            if use_rich and eval_task_id is not None:
                progress_bar.update(eval_task_id, completed=progress_bar.tasks[eval_task_id].total)
            _cleanup_live()
            click.echo()
            click.secho("Run completed!", fg="green", bold=True)
            overall = event.get("overall_score")
            if overall is not None:
                click.echo(f"  Overall Score: {overall:.4f}")
            scores = event.get("scores", {})
            if scores:
                click.echo(f"  Scores:        {format_scores(scores)}")
        elif etype == "error":
            _cleanup_live()
            click.echo()
            click.secho(f"  Run failed: {event.get('error')}", fg="red", bold=True)

    asyncio.run(
        runner.execute_run(
            run_id=run_id,
            project_config=project_config,
            task_config=task_config,
            prompt=prompt,
            on_progress=on_progress,
            max_workers=max_workers,
            limit=limit,
            completed_results=completed_results,
        )
    )


@runs_group.command("batch")
@click.argument("project")
@click.option("--task", "-t", required=True, help="Task name")
@click.option("--prompts", required=True, help="Comma-separated prompt names")
@click.option("--model", "-m", required=True, help="Model name")
@click.option(
    "--pipeline",
    "-P",
    "pipeline_name",
    default=None,
    help="Pipeline template name (overrides project default)",
)
@click.option("--reasoning-effort", "-re", default=None, help="Reasoning effort")
@click.option("--max-workers", "-w", default=5, type=int, help="Max parallel workers")
@click.pass_context
def batch_runs(ctx, project, task, prompts, model, pipeline_name, reasoning_effort, max_workers):
    """Run evaluation for multiple prompts sequentially."""
    cfg = ctx.obj["config"]
    if cfg.is_remote:
        raise click.ClickException("Batch is local-mode only")

    prompt_list = [p.strip() for p in prompts.split(",")]
    click.secho(f"Batch run: {project}/{task} โ€” prompts: {prompt_list}", fg="blue", bold=True)

    for pname in prompt_list:
        click.secho(f"\n{'=' * 50}", fg="blue")
        click.secho(f"Running prompt: {pname}...", fg="blue", bold=True)
        click.secho(f"{'=' * 50}", fg="blue")
        try:
            _start_local(
                cfg,
                project=project,
                task=task,
                prompt_name=pname,
                model=model,
                pipeline_name=pipeline_name,
                reasoning_effort=reasoning_effort,
                temperature=0.0,
                max_tokens=4000,
                max_workers=max_workers,
                limit=None,
            )
        except Exception as e:
            click.secho(f"  {pname} failed: {e}", fg="red")

    click.secho(f"\n{'=' * 50}", fg="blue")
    click.secho("Batch complete!", fg="green", bold=True)


@runs_group.command("resume")
@click.argument("project")
@click.option("--run-id", "-r", required=True, help="Run ID to resume")
@click.option("--max-workers", "-w", default=5, type=int, help="Max parallel workers")
@click.pass_context
def resume_run(ctx: click.Context, project: str, run_id: str, max_workers: int) -> None:
    """Resume an interrupted evaluation run."""
    cfg = ctx.obj["config"]
    if cfg.is_remote:
        raise click.ClickException("Resume is local-mode only")

    from solar_eval.core.dataset_loader import DatasetLoader
    from solar_eval.core.project_loader import load_all_project_configs
    from solar_eval.core.runner import BatchRunner
    from solar_eval.providers import UpstageProvider
    from solar_eval.providers.openai_provider import OpenAIProvider
    from solar_eval.stores import JsonlStore

    # Find the run directory
    run_dir = cfg.artifacts_dir(project) / run_id
    if not run_dir.exists():
        raise click.ClickException(f"Run directory not found: {run_dir}")

    store = JsonlStore(run_dir)
    run_meta = store.load_run_meta()

    if not run_meta:
        raise click.ClickException(f"No run.json found in {run_dir}")

    status = run_meta.get("status", "unknown")
    if status == "completed":
        raise click.ClickException(f"Run {run_id} is already completed. Nothing to resume.")

    task = run_meta.get("task")
    if not task:
        raise click.ClickException("Cannot determine task from run.json")

    # Load existing results
    existing_results = store.load_existing_results()
    completed_indices = {r["sample_idx"] for r in existing_results}
    click.secho(f"Resuming run: {run_id}", fg="blue", bold=True)
    click.secho(f"  Task: {task}, Already completed: {len(completed_indices)} samples", fg="blue")

    # Load project/task config
    configs = load_all_project_configs(cfg.projects_dir, cfg.config_dirs)
    project_config = next((c for c in configs if c["name"] == project), None)
    if not project_config:
        raise click.ClickException(f"Project not found: {project}")

    task_config = next((t for t in project_config.get("tasks", []) if t["name"] == task), None)
    if not task_config:
        raise click.ClickException(f"Task '{task}' not found in project '{project}'")

    # Resolve prompt from run.json
    prompt_name = run_meta.get("prompt")
    pipeline_name = run_meta.get("pipeline")
    model = run_meta.get("model", "solar-pro2")

    if not prompt_name:
        raise click.ClickException(
            "Cannot determine prompt from run.json. Only runs created with the new CLI can be resumed."
        )

    from solar_eval.models.prompt_version import (
        detect_prompt_format,
        load_prompt_messages,
        load_step_prompts,
    )

    prompt_path = _resolve_prompt(cfg.prompts_dir(project), prompt_name)
    fmt = detect_prompt_format(prompt_path)
    if fmt == "multi_step":
        prompt = {
            "step_prompts": load_step_prompts(prompt_path),
            "model": model,
            "temperature": run_meta.get("temperature", 0.0),
            "max_tokens": run_meta.get("max_tokens", 4000),
        }
    else:
        prompt = {
            "messages": load_prompt_messages(prompt_path),
            "model": model,
            "temperature": run_meta.get("temperature", 0.0),
            "max_tokens": run_meta.get("max_tokens", 4000),
        }
    if run_meta.get("reasoning_effort"):
        prompt["reasoning_effort"] = run_meta["reasoning_effort"]

    # Override pipeline if specified โ€” ์›๋ž˜ run ์ด `--set` ์œผ๋กœ ๋ฐ”๊ฟ” ๋Œ๋ฆฐ ๊ฒƒ์ด๋ฉด
    # ๊ทธ override ๊นŒ์ง€ ๋ณต์›ํ•ด์•ผ ๊ฐ™์€ ์„ค์ •์œผ๋กœ ์ด์–ด์ง„๋‹ค.
    if pipeline_name and pipeline_name != "default":
        task_config = {
            **task_config,
            "pipeline_config": _compose_pipeline_config(
                cfg.config_dir(project),
                pipeline_name,
                run_meta.get("pipeline_overrides") or {},
            ),
        }

    click.secho(f"  Model: {model}", fg="blue")

    # ์ด์ „ ํ‰๊ฐ€๋ฅผ ๋ฏธ๋ฆฌ ์ง€์šฐ์ง€ ์•Š๋Š”๋‹ค(F3) -- ์žฌํ‰๊ฐ€๊ฐ€ ๋„์ค‘์— ์ฃฝ์œผ๋ฉด ๋ณต๊ตฌํ•  ์ ์ˆ˜๊ฐ€
    # ์—†์–ด์ง„๋‹ค. create_evaluation() ์ด ์›์ž์  ๊ต์ฒด๋ผ ์ง€์šฐ์ง€ ์•Š์•„๋„ ์•ˆ์ „ํ•˜๋‹ค.

    # Setup providers and runner
    provider = UpstageProvider()
    judge_provider = OpenAIProvider()
    dataset_loader = DatasetLoader(base_dir=cfg.projects_dir)
    runner = BatchRunner(
        store=store,
        inference_provider=provider,
        judge_provider=judge_provider,
        dataset_loader=dataset_loader,
    )

    _run_with_progress(
        runner,
        run_id,
        project_config,
        task_config,
        prompt,
        max_workers,
        limit=None,
        # ์ด๋ฏธ ๋๋‚œ ์ƒ˜ํ”Œ์€ ๊ฑด๋„ˆ๋›ด๋‹ค -- ์•ˆ ๋„˜๊ธฐ๋ฉด resume ์ด ์ „ ์ƒ˜ํ”Œ์„ ๋‹ค์‹œ ์œ ๋ฃŒ ํ˜ธ์ถœํ•˜๊ณ 
        # results.jsonl ์— ๊ฐ™์€ sample_idx ๋ฅผ ์ค‘๋ณต append ํ•œ๋‹ค(F2).
        completed_results=existing_results,
    )

    click.echo(f"\nResults saved to: {run_dir}/")


@runs_group.command("eval")
@click.argument("project")
@click.option(
    "--run-id",
    "-r",
    required=True,
    help="Run ID to evaluate",
)
@click.pass_context
def eval_run(ctx: click.Context, project: str, run_id: str) -> None:
    """Run evaluation only on existing inference results (no new inference)."""
    cfg = ctx.obj["config"]
    if cfg.is_remote:
        raise click.ClickException("Eval is local-mode only")

    from solar_eval.core.project_loader import load_all_project_configs
    from solar_eval.core.runner import build_eval_sample_from_result
    from solar_eval.evaluators.registry import create_evaluator
    from solar_eval.stores import JsonlStore

    # Find run directory
    run_dir = cfg.artifacts_dir(project) / run_id
    if not run_dir.exists():
        raise click.ClickException(f"Run directory not found: {run_dir}")

    store = JsonlStore(run_dir)
    run_meta = store.load_run_meta()
    if not run_meta:
        raise click.ClickException(f"No run.json found in {run_dir}")

    task = run_meta.get("task")
    if not task:
        raise click.ClickException("Cannot determine task from run.json")

    # Load results
    results = store.load_existing_results()
    if not results:
        raise click.ClickException(f"No inference results found in {run_dir}/results.jsonl")

    click.secho(f"Evaluating run: {run_id}", fg="blue", bold=True)
    click.secho(f"  Task: {task}, Samples: {len(results)}", fg="blue")

    # Load task config for evaluator settings
    configs = load_all_project_configs(cfg.projects_dir, cfg.config_dirs)
    project_config = next((c for c in configs if c["name"] == project), None)
    if not project_config:
        raise click.ClickException(f"Project not found: {project}")

    task_config = next((t for t in project_config.get("tasks", []) if t["name"] == task), None)
    if not task_config:
        raise click.ClickException(f"Task '{task}' not found in project '{project}'")

    # ์ด์ „ ํ‰๊ฐ€๋ฅผ ๋ฏธ๋ฆฌ ์ง€์šฐ์ง€ ์•Š๋Š”๋‹ค(F3) -- ์•„๋ž˜ ์žฌํ‰๊ฐ€๊ฐ€ ์‹คํŒจํ•ด๋„ ์˜› ์ ์ˆ˜๋Š” ๋‚จ๋Š”๋‹ค.

    # Run evaluation
    evaluator = create_evaluator(task_config.get("evaluator", {"type": "llm_judge"}))
    # judge provider ๋ฅผ ์•ˆ ๋„˜๊ธฐ๋ฉด llm_judge ๊ณ„์—ด์€ ์ „ ์ƒ˜ํ”Œ์—์„œ ์‹คํŒจํ•œ๋‹ค -- ๊ทธ๋ฆฌ๊ณ 
    # ๊ทธ ์‹คํŒจ๊ฐ€ ์˜ˆ์ „์—” 0์  placeholder ๋กœ ๋ฎ์—ฌ ์กฐ์šฉํžˆ completed ๋กœ ๋๋‚ฌ๋‹ค(F8).
    from solar_eval.providers.openai_provider import OpenAIProvider

    judge_provider = OpenAIProvider()

    from datetime import timezone

    async def run_eval():
        # ์ฑ„์  ์‹คํŒจ๋Š” ์ ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ ์‹คํŒจ๋กœ ๋‚จ๊ธด๋‹ค -- aggregate() ์—๋Š” ์„ฑ๊ณต๋ถ„๋งŒ ๋„˜๊ธด๋‹ค.
        eval_results: list[dict[str, Any]] = []
        eval_failures: list[dict[str, Any]] = []

        for result in results:
            # ๋ฆฌ์ŠคํŠธ ์œ„์น˜๊ฐ€ ์•„๋‹ˆ๋ผ ์›๋ณธ sample_idx ๊ฐ€ ์ •๋ณธ์ด๋‹ค(F6).
            sample_idx = result["sample_idx"]
            try:
                eval_sample = build_eval_sample_from_result(result, reference=result.get("golden"))
                evaluator.validate_required_fields(eval_sample)
                eval_result = await evaluator.evaluate(sample=eval_sample, provider=judge_provider)
                eval_results.append({**eval_result, "sample_idx": sample_idx})
            except Exception as e:
                click.secho(f"  Sample {sample_idx} eval failed: {e}", fg="yellow")
                eval_failures.append({"sample_idx": sample_idx, "error": str(e)})

        # Aggregate and save
        aggregated = evaluator.aggregate(eval_results)
        # ์„ฑ๊ณตํ•œ ์ฑ„์ ์ด ํ•˜๋‚˜๋„ ์—†์œผ๋ฉด ์ ์ˆ˜ ์ž๋ฆฌ๋ฅผ ๋น„์šด๋‹ค -- 0.0 ์€ "0์ "์ด๋ผ๋Š” ์ธก์ •๊ฐ’์ด๋ผ
        # "์ธก์ •์ด ์—†์—ˆ๋‹ค"์™€ ๊ตฌ๋ถ„๋˜์ง€ ์•Š๋Š”๋‹ค(runner.py ์™€ ๊ฐ™์€ ๊ทœ์น™).
        overall_score = aggregated.get("overall_score", 0.0) if eval_results else None
        eval_id = await store.create_evaluation(
            {
                "run_id": run_id,
                "scores": aggregated.get("scores", {}),
                "overall_score": overall_score,
                "eval_model": "local",
                "eval_success_count": len(eval_results),
                "eval_failed_count": len(eval_failures),
                "failed_sample_indices": [f["sample_idx"] for f in eval_failures],
            }
        )

        # Save per-sample eval details -- ์„ฑ๊ณต/์‹คํŒจ ๋‘˜ ๋‹ค ํ•œ ํ–‰์”ฉ ๋‚จ๊ธด๋‹ค.
        eval_detail_docs = []
        for er in eval_results:
            eval_detail_docs.append(
                {
                    "evaluation_id": eval_id,
                    "sample_idx": er["sample_idx"],
                    "category_scores": er.get("category_scores", {}),
                    "error_counts": {
                        k: v.get("error_count", 0)
                        for k, v in er.get("details", {}).items()
                        if isinstance(v, dict)
                    },
                    "severity": er.get("severity", ""),
                    "score": er.get("score", 0.0),
                }
            )
        for f in eval_failures:
            eval_detail_docs.append(
                {
                    "evaluation_id": eval_id,
                    "sample_idx": f["sample_idx"],
                    "category_scores": {},
                    "error_counts": {},
                    "severity": None,
                    # 0.0 ์ด ์•„๋‹ˆ๋ผ None -- ์ฑ„์  ์‹คํŒจ๋ฅผ ์ตœ์ € ์ ์ˆ˜์™€ ๊ตฌ๋ถ„ํ•œ๋‹ค.
                    "score": None,
                    "error": f["error"],
                }
            )
        await store.insert_eval_details(eval_detail_docs)

        # Update run status
        await store.update_run(
            run_id,
            {
                "status": "completed",
                "completed_at": datetime.now(timezone.utc),
            },
        )

        return {**aggregated, "overall_score": overall_score, "failed": len(eval_failures)}

    aggregated = asyncio.run(run_eval())

    click.echo()
    click.secho("Evaluation completed!", fg="green", bold=True)
    overall = aggregated.get("overall_score")
    if overall is None:
        # ์ฑ„์ ์ด ํ•œ ๊ฑด๋„ ์„ฑ๊ณตํ•˜์ง€ ๋ชปํ–ˆ๋‹ค -- ์ˆซ์ž๋ฅผ ์ฐ์œผ๋ฉด "0์ "์œผ๋กœ ์ฝํžŒ๋‹ค.
        click.secho("  Overall Score: ์ธก์ • ์—†์Œ (์ „ ์ƒ˜ํ”Œ ์ฑ„์  ์‹คํŒจ)", fg="red", bold=True)
    else:
        click.echo(f"  Overall Score: {overall:.4f}")
    failed = aggregated.get("failed", 0)
    if failed:
        click.secho(f"  ์ฑ„์  ์‹คํŒจ: {failed}๊ฑด (score: null ๋กœ ๊ธฐ๋ก๋จ)", fg="yellow")
    scores = aggregated.get("scores", {})
    if scores:
        click.echo(f"  Scores:        {format_scores(scores)}")
    click.echo(f"\nResults saved to: {run_dir}/")


@runs_group.command("results")
@click.argument("run_ref")
@click.option("--limit", "-n", default=None, type=int, help="Limit results")
@click.pass_context
def show_results(ctx: click.Context, run_ref: str, limit: int | None) -> None:
    """Show per-sample results for a run."""
    cfg = ctx.obj["config"]

    if cfg.is_remote:
        # run_ref format: "project/run_id"
        from solar_eval.cli.client import EvalClient

        client = EvalClient(cfg.remote_url, cfg.timeout)
        parts = run_ref.split("/")
        if len(parts) != 2:
            raise click.ClickException("Remote mode: use 'project-name/run-id' format")
        project_id = _resolve_project_id(client, parts[0])
        results = client.get(f"/api/projects/{project_id}/runs/{parts[1]}/results")
    else:
        # run_ref format: "project/run_name"
        parts = run_ref.split("/")
        if len(parts) != 2:
            raise click.ClickException("Local mode: use 'project-name/run-name' format")
        results_file = cfg.artifacts_dir(parts[0]) / parts[1] / "results.jsonl"
        if not results_file.exists():
            raise click.ClickException(f"Results not found: {results_file}")
        results = [
            json.loads(line) for line in results_file.read_text().strip().split("\n") if line
        ]

    if not results:
        click.secho("No results found.", fg="yellow")
        return
    if limit:
        results = results[:limit]
    click.secho(format_results_table(results), fg="blue")
    click.echo(f"\nShowing {len(results)} result(s)")