regista 0.4.0

🎬 AI agent director β€” state-machine-driven pipeline for pi
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
//! Loop principal del orquestador.
//!
//! Carga historias, construye el grafo de dependencias, evalΓΊa deadlocks,
//! y dispara agentes segΓΊn la mΓ‘quina de estados. Es el corazΓ³n del pipeline.

use crate::agent::{self, AgentOptions};
use crate::checkpoint::OrchestratorState;
use crate::config::Config;
use crate::deadlock::{self, DeadlockResolution};
use crate::dependency_graph::DependencyGraph;
use crate::prompts::PromptContext;
use crate::providers;
use crate::state::Status;
use crate::story::Story;
use serde::Serialize;
use std::collections::HashMap;
use std::path::Path;
use std::time::Instant;

/// Opciones de filtrado y modo de ejecuciΓ³n para el orquestador.
#[derive(Debug, Clone, Default)]
pub struct RunOptions {
    /// Ejecutar una sola iteraciΓ³n y salir.
    pub once: bool,
    /// Solo procesar esta historia (ID exacto, ej: "STORY-001").
    pub story_filter: Option<String>,
    /// Solo procesar historias de esta Γ©pica (ej: "EPIC-001").
    pub epic_filter: Option<String>,
    /// Solo procesar historias en este rango de Γ©picas (inclusivo).
    /// Tupla (start, end), ej: ("EPIC-001", "EPIC-003").
    pub epics_range: Option<(String, String)>,
    /// Modo simulaciΓ³n: no invoca agentes ni modifica archivos.
    pub dry_run: bool,
    /// Suprimir logs de progreso (ΓΊtil con --json).
    pub quiet: bool,
}

/// Filtra historias segΓΊn las opciones de ejecuciΓ³n.
fn filter_stories(stories: Vec<Story>, options: &RunOptions) -> Vec<Story> {
    let mut stories = stories;

    if let Some(ref story_id) = options.story_filter {
        stories.retain(|s| s.id == *story_id);
    }

    if let Some(ref epic_id) = options.epic_filter {
        stories.retain(|s| s.epic.as_ref().is_some_and(|e| e == epic_id));
    }

    if let Some((ref start, ref end)) = options.epics_range {
        let start_num = extract_numeric(start);
        let end_num = extract_numeric(end);
        stories.retain(|s| {
            s.epic.as_ref().is_some_and(|e| {
                let num = extract_numeric(e);
                num >= start_num && num <= end_num
            })
        });
    }

    stories
}

/// Ejecuta el pipeline completo sobre un proyecto.
///
/// En modo normal invoca agentes `pi` y modifica archivos.
/// En modo dry-run simula todo el pipeline en memoria.
pub fn run(
    project_root: &Path,
    cfg: &Config,
    options: &RunOptions,
    resume_state: Option<OrchestratorState>,
) -> anyhow::Result<RunReport> {
    if options.dry_run {
        return run_dry(project_root, cfg, options);
    }
    run_real(project_root, cfg, options, resume_state)
}

/// EjecuciΓ³n real del pipeline (invocando agentes).
fn run_real(
    project_root: &Path,
    cfg: &Config,
    options: &RunOptions,
    resume_state: Option<OrchestratorState>,
) -> anyhow::Result<RunReport> {
    let start = Instant::now();
    let max_wall = std::time::Duration::from_secs(cfg.limits.max_wall_time_seconds);

    let (mut reject_cycles, mut story_iterations, mut story_errors, start_iteration) =
        if let Some(state) = resume_state {
            tracing::info!(
                "πŸ“‚ Reanudando desde checkpoint: iteraciΓ³n {}",
                state.iteration
            );
            (
                state.reject_cycles,
                state.story_iterations,
                state.story_errors,
                state.iteration,
            )
        } else {
            (HashMap::new(), HashMap::new(), HashMap::new(), 0u32)
        };

    let mut iteration: u32 = start_iteration;
    let mut stop_reason: Option<String> = None;

    // Calcular lΓ­mite efectivo de iteraciones una sola vez al inicio.
    // Si el usuario no lo configurΓ³ (0), se escala con el nΒΊ de historias.
    let initial_stories = load_all_stories(project_root, cfg)?;
    let effective_max = effective_max_iterations(cfg.limits.max_iterations, initial_stories.len());
    if effective_max != cfg.limits.max_iterations {
        tracing::info!(
            "max_iterations auto: {} ({} historias Γ— 6)",
            effective_max,
            initial_stories.len()
        );
    }

    loop {
        iteration += 1;
        if iteration > effective_max {
            stop_reason = Some(format!("max_iterations ({})", effective_max));
            tracing::warn!("Alcanzado el mΓ‘ximo de {} iteraciones", effective_max);
            break;
        }
        if start.elapsed() >= max_wall {
            stop_reason = Some(format!("max_wall_time ({}s)", max_wall.as_secs()));
            tracing::warn!("LΓ­mite de tiempo total alcanzado ({}s)", max_wall.as_secs());
            break;
        }

        if !options.quiet {
            tracing::info!("══════ IteraciΓ³n {iteration} ══════");
        }

        // 1. Cargar todas las historias
        let stories = load_all_stories(project_root, cfg)?;
        let full_graph = DependencyGraph::from_stories(&stories);

        // 2. Aplicar transiciones automΓ‘ticas sobre TODAS las historias
        let stories =
            apply_automatic_transitions(stories, &full_graph, &mut reject_cycles, cfg, false)?;

        // 3. Filtrar historias segΓΊn opciones de ejecuciΓ³n (--story, --epic, --epics)
        let stories = filter_stories(stories, options);
        if stories.is_empty() {
            tracing::info!("Sin historias que procesar con los filtros actuales.");
            break;
        }

        // 4. Reconstruir grafo solo con las historias filtradas
        let graph = DependencyGraph::from_stories(&stories);

        // 5. Detectar deadlock
        let resolution = deadlock::analyze(&stories, &graph);

        if !handle_deadlock(&resolution, project_root, cfg)? {
            break;
        }

        // Procesar segΓΊn la resoluciΓ³n
        match &resolution {
            DeadlockResolution::InvokePoFor {
                story_id, reason, ..
            } => {
                if !options.quiet {
                    tracing::info!("πŸ”“ Deadlock detectado: {reason}");
                }
                let story = stories.iter().find(|s| s.id == *story_id).unwrap();
                let iter = story_iterations.entry(story.id.clone()).or_insert(0);
                *iter += 1;
                let agent_opts = build_agent_opts(story, cfg);
                if let Err(e) =
                    process_story(story, project_root, cfg, &mut reject_cycles, &agent_opts)
                {
                    story_errors
                        .entry(story.id.clone())
                        .or_insert_with(|| e.to_string());
                }
                save_checkpoint(
                    project_root,
                    iteration,
                    &reject_cycles,
                    &story_iterations,
                    &story_errors,
                );
            }
            DeadlockResolution::NoDeadlock => {
                // 5. Procesar la historia de mayor prioridad en el flujo normal
                if let Some(story) = pick_next_actionable(&stories, &graph) {
                    let id = story.id.clone();
                    let iter = story_iterations.entry(id.clone()).or_insert(0);
                    *iter += 1;
                    let agent_opts = build_agent_opts(story, cfg);
                    if let Err(e) =
                        process_story(story, project_root, cfg, &mut reject_cycles, &agent_opts)
                    {
                        story_errors
                            .entry(id.clone())
                            .or_insert_with(|| e.to_string());
                    }
                    save_checkpoint(
                        project_root,
                        iteration,
                        &reject_cycles,
                        &story_iterations,
                        &story_errors,
                    );
                }
            }
            DeadlockResolution::PipelineComplete => {
                if !options.quiet {
                    tracing::info!("βœ… Pipeline completo: todas las historias en estado terminal.");
                }
                OrchestratorState::remove(project_root);
                break;
            }
        }

        if options.once {
            if !options.quiet {
                tracing::info!("🏁 Modo --once: completado tras una iteración.");
            }
            break;
        }
    }

    // Generar reporte final
    let stories = filter_stories(load_all_stories(project_root, cfg)?, options);
    build_report(
        &stories,
        iteration,
        start.elapsed(),
        &story_iterations,
        &reject_cycles,
        &story_errors,
        stop_reason,
    )
}

/// EjecuciΓ³n simulada del pipeline (dry-run).
fn run_dry(project_root: &Path, cfg: &Config, options: &RunOptions) -> anyhow::Result<RunReport> {
    let start = Instant::now();

    tracing::info!("πŸ§ͺ DRY-RUN β€” No se ejecutarΓ‘n agentes ni se modificarΓ‘n archivos.");
    tracing::info!("");

    // Cargar historias UNA VEZ para el modo simulaciΓ³n
    let mut stories = filter_stories(load_all_stories(project_root, cfg)?, options);
    if stories.is_empty() {
        tracing::info!("Sin historias que procesar.");
        return build_report(
            &stories,
            0,
            start.elapsed(),
            &HashMap::new(),
            &HashMap::new(),
            &HashMap::new(),
            None,
        );
    }

    let reject_cycles: HashMap<String, u32> = HashMap::new();
    let mut story_iterations: HashMap<String, u32> = HashMap::new();
    let story_errors: HashMap<String, String> = HashMap::new();
    let mut iteration: u32 = 0;

    // Calcular lΓ­mite efectivo de iteraciones
    let effective_max = effective_max_iterations(cfg.limits.max_iterations, stories.len());
    if effective_max != cfg.limits.max_iterations {
        tracing::info!(
            "max_iterations auto: {} ({} historias Γ— 6)",
            effective_max,
            stories.len()
        );
    }

    loop {
        iteration += 1;
        if iteration > effective_max {
            break;
        }

        tracing::info!("═══ IteraciΓ³n {iteration} ═══");

        // Aplicar transiciones automΓ‘ticas en memoria
        // Primero recolectamos los estados actuales para evitar borrow conflict
        let status_snapshot: Vec<(String, Status, Vec<String>)> = stories
            .iter()
            .map(|s| (s.id.clone(), s.status, s.blockers.clone()))
            .collect();

        for (id, status, blockers) in &status_snapshot {
            if *status == Status::Blocked {
                let all_done = blockers.iter().all(|b| {
                    stories
                        .iter()
                        .any(|s| s.id == *b && s.status == Status::Done)
                });
                if all_done {
                    tracing::info!("  β†’ {id} (Blocked) desbloqueada automΓ‘ticamente β†’ Ready");
                    if let Some(story) = stories.iter_mut().find(|s| s.id == *id) {
                        story.advance_status_in_memory(Status::Ready);
                    }
                }
            }
        }

        let graph = DependencyGraph::from_stories(&stories);
        let resolution = deadlock::analyze(&stories, &graph);

        match &resolution {
            DeadlockResolution::PipelineComplete => {
                tracing::info!("βœ… Pipeline completo.");
                break;
            }
            DeadlockResolution::InvokePoFor {
                story_id,
                reason,
                unblocks,
                ..
            } => {
                tracing::info!("  β†’ {story_id} (Draft) serΓ­a procesada por PO (groom) β†’ Ready");
                tracing::info!("    RazΓ³n: {reason}");
                if *unblocks > 0 {
                    tracing::info!("    DesbloquearΓ­a: {unblocks} historias");
                }
                if let Some(story) = stories.iter_mut().find(|s| s.id == *story_id) {
                    let iter = story_iterations.entry(story.id.clone()).or_insert(0);
                    *iter += 1;
                    story.advance_status_in_memory(Status::Ready);
                }
            }
            DeadlockResolution::NoDeadlock => {
                if let Some(id) = {
                    let graph = DependencyGraph::from_stories(&stories);
                    pick_next_actionable(&stories, &graph).map(|s| s.id.clone())
                } {
                    if let Some(story) = stories.iter_mut().find(|s| s.id == id) {
                        let next = next_status(story.status);
                        let label = match story.status {
                            Status::Draft => "PO (groom)",
                            Status::Ready => "QA (tests)",
                            Status::TestsReady => "Dev (implement)",
                            Status::InProgress => "Dev (fix)",
                            Status::InReview => "Reviewer",
                            Status::BusinessReview => "PO (validate)",
                            _ => "?",
                        };
                        let iter = story_iterations.entry(story.id.clone()).or_insert(0);
                        *iter += 1;
                        tracing::info!(
                            "  β†’ {} ({}) serΓ­a procesada por {} β†’ {}",
                            story.id,
                            story.status,
                            label,
                            next
                        );
                        let unblocks = graph.blocks_count(&story.id);
                        if unblocks > 0 {
                            tracing::info!("    DesbloquearΓ­a: {unblocks} historias");
                        }
                        story.advance_status_in_memory(next);
                    }
                }
            }
        }

        if options.once {
            tracing::info!("🏁 Modo --once: simulada una iteración.");
            break;
        }
    }

    tracing::info!("");
    tracing::info!("═══ Resumen Dry-Run ═══");
    tracing::info!("  Total historias: {}", stories.len());
    let done = stories.iter().filter(|s| s.status == Status::Done).count();
    let failed = stories
        .iter()
        .filter(|s| s.status == Status::Failed)
        .count();
    let blocked = stories
        .iter()
        .filter(|s| s.status == Status::Blocked)
        .count();
    let draft = stories.iter().filter(|s| s.status == Status::Draft).count();
    tracing::info!("  Done:           {done}");
    tracing::info!("  Failed:         {failed}");
    tracing::info!("  Blocked:        {blocked}");
    tracing::info!("  Draft:          {draft}");
    tracing::info!("  Iteraciones estimadas: {iteration}");
    // Tiempo estimado: ~5 min por iteraciΓ³n como promedio entre agentes
    let est_minutes = iteration as u64 * 5;
    tracing::info!(
        "  Tiempo estimado: ~{}-{} min",
        est_minutes,
        est_minutes * 2
    );

    build_report(
        &stories,
        iteration,
        start.elapsed(),
        &story_iterations,
        &reject_cycles,
        &story_errors,
        None, // dry-run no tiene stop_reason relevante
    )
}

/// Construye el RunReport final a partir del estado de las historias.
fn build_report(
    stories: &[Story],
    iterations: u32,
    elapsed: std::time::Duration,
    story_iterations: &HashMap<String, u32>,
    reject_cycles: &HashMap<String, u32>,
    story_errors: &HashMap<String, String>,
    stop_reason: Option<String>,
) -> anyhow::Result<RunReport> {
    let done = stories.iter().filter(|s| s.status == Status::Done).count();
    let failed = stories
        .iter()
        .filter(|s| s.status == Status::Failed)
        .count();
    let blocked = stories
        .iter()
        .filter(|s| s.status == Status::Blocked)
        .count();
    let draft = stories.iter().filter(|s| s.status == Status::Draft).count();
    let total = stories.len();

    let story_records: Vec<StoryRecord> = stories
        .iter()
        .map(|s| {
            let iter_count = story_iterations.get(&s.id).copied().unwrap_or(0);
            let rej_count = reject_cycles.get(&s.id).copied().unwrap_or(0);
            let error = story_errors.get(&s.id).cloned();
            StoryRecord {
                id: s.id.clone(),
                status: s.status.to_string(),
                epic: s.epic.clone(),
                iterations: iter_count,
                reject_cycles: rej_count,
                error,
            }
        })
        .collect();

    Ok(RunReport {
        total,
        done,
        failed,
        blocked,
        draft,
        iterations,
        elapsed,
        elapsed_seconds: elapsed.as_secs(),
        stories: story_records,
        stop_reason,
    })
}

/// Reporte final de la ejecuciΓ³n del orquestador.
#[derive(Debug, Clone, Serialize)]
pub struct RunReport {
    pub total: usize,
    pub done: usize,
    pub failed: usize,
    pub blocked: usize,
    pub draft: usize,
    pub iterations: u32,
    #[serde(skip)]
    pub elapsed: std::time::Duration,
    pub elapsed_seconds: u64,
    pub stories: Vec<StoryRecord>,
    /// RazΓ³n de parada temprana (None = pipeline terminΓ³ naturalmente).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
}

/// Registro individual de una historia para el reporte JSON.
#[derive(Debug, Clone, Serialize)]
pub struct StoryRecord {
    pub id: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub epic: Option<String>,
    pub iterations: u32,
    pub reject_cycles: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// ── helpers ──────────────────────────────────────────────────────────────

/// Carga todas las historias del directorio configurado.
fn load_all_stories(project_root: &Path, cfg: &Config) -> anyhow::Result<Vec<Story>> {
    let stories_dir = project_root.join(&cfg.project.stories_dir);
    let pattern = stories_dir.join(&cfg.project.story_pattern);

    let mut stories = vec![];
    for entry in glob::glob(pattern.to_str().unwrap())? {
        let path = entry?;
        match Story::load(&path) {
            Ok(story) => stories.push(story),
            Err(e) => tracing::warn!("Error cargando {}: {e}", path.display()),
        }
    }

    Ok(stories)
}

/// Aplica transiciones que ejecuta el orquestador sin intervenciΓ³n de agentes:
/// - Blocked β†’ Ready: todas las dependencias estΓ‘n Done.
/// - * β†’ Failed: se superΓ³ max_reject_cycles.
///
/// Si `simulate` es true, no escribe a disco (dry-run).
fn apply_automatic_transitions(
    stories: Vec<Story>,
    _graph: &DependencyGraph,
    reject_cycles: &mut HashMap<String, u32>,
    cfg: &Config,
    simulate: bool,
) -> anyhow::Result<Vec<Story>> {
    let mut stories = stories;

    // Primero verificamos ciclos de rechazo y marcamos Failed
    for story in stories.iter_mut() {
        if story.status.is_terminal() {
            continue;
        }
        let cycles = reject_cycles.get(&story.id).copied().unwrap_or(0);
        if cycles >= cfg.limits.max_reject_cycles {
            tracing::warn!(
                "❌ {}: {} ciclos de rechazo agotados β†’ Failed",
                story.id,
                cycles
            );
            if simulate {
                story.advance_status_in_memory(Status::Failed);
            } else {
                story.set_status(Status::Failed)?;
            }
            continue;
        }

        // Si la historia estΓ‘ en flujo de rechazo (InProgress/InReview pero con ciclos altos)
        if cycles > 0 && cycles >= cfg.limits.max_reject_cycles {
            if simulate {
                story.advance_status_in_memory(Status::Failed);
            } else {
                story.set_status(Status::Failed)?;
            }
        }
    }

    // Luego: Blocked β†’ Ready si dependencias resueltas
    let status_map: HashMap<String, Status> =
        stories.iter().map(|s| (s.id.clone(), s.status)).collect();

    for story in stories.iter_mut() {
        if story.status != Status::Blocked {
            continue;
        }

        let all_blockers_done = story
            .blockers
            .iter()
            .all(|b| status_map.get(b).is_some_and(|s| *s == Status::Done));

        if all_blockers_done {
            tracing::info!("πŸ”“ {}: dependencias resueltas β†’ Ready", story.id);
            if simulate {
                story.advance_status_in_memory(Status::Ready);
            } else {
                story.set_status(Status::Ready)?;
            }
        }
    }

    // Verificar si historias accionables tienen dependencias no resueltas β†’ Blocked
    let status_map_after: HashMap<String, Status> =
        stories.iter().map(|s| (s.id.clone(), s.status)).collect();

    for story in stories.iter_mut() {
        if story.status.is_terminal() || story.status == Status::Blocked {
            continue;
        }
        if story.blockers.is_empty() {
            continue;
        }

        let any_blocker_not_done = story
            .blockers
            .iter()
            .any(|b| !status_map_after.get(b).is_some_and(|s| *s == Status::Done));

        if any_blocker_not_done {
            tracing::info!("β›” {}: dependencias no resueltas β†’ Blocked", story.id);
            if simulate {
                story.advance_status_in_memory(Status::Blocked);
            } else {
                story.set_status(Status::Blocked)?;
            }
        }
    }

    Ok(stories)
}

/// Procesa el resultado del deadlock analysis.
/// Retorna false si debemos salir del loop (pipeline completo).
fn handle_deadlock(
    resolution: &DeadlockResolution,
    _project_root: &Path,
    _cfg: &Config,
) -> anyhow::Result<bool> {
    match resolution {
        DeadlockResolution::PipelineComplete => {
            tracing::info!("βœ… Pipeline completo.");
            Ok(false)
        }
        DeadlockResolution::InvokePoFor {
            story_id, reason, ..
        } => {
            tracing::info!("πŸ”“ Deadlock β†’ PO debe refinar {story_id}: {reason}");
            Ok(true)
        }
        DeadlockResolution::NoDeadlock => Ok(true),
    }
}

/// Elige la siguiente historia accionable con mayor prioridad.
///
/// Prioridad por estado + cantidad de historias que desbloquea.
fn pick_next_actionable<'a>(stories: &'a [Story], graph: &DependencyGraph) -> Option<&'a Story> {
    stories
        .iter()
        .filter(|s| s.status.is_actionable())
        .max_by_key(|s| {
            (
                status_priority(s.status),
                graph.blocks_count(&s.id),
                // Negativo del ID numΓ©rico para priorizar mΓ‘s bajos
                -(extract_numeric(&s.id) as i32),
            )
        })
}

/// Prioridad numΓ©rica de un estado (mayor = mΓ‘s urgente).
fn status_priority(status: Status) -> u32 {
    match status {
        Status::BusinessReview => 6,
        Status::InReview => 5,
        Status::InProgress => 4,
        Status::TestsReady => 3,
        Status::Ready => 2,
        _ => 0,
    }
}

/// Procesa una historia individual: dispara el agente correspondiente.
fn process_story(
    story: &Story,
    project_root: &Path,
    cfg: &Config,
    reject_cycles: &mut HashMap<String, u32>,
    agent_opts: &AgentOptions,
) -> anyhow::Result<()> {
    let ctx = PromptContext {
        story_id: story.id.clone(),
        stories_dir: cfg.project.stories_dir.clone(),
        decisions_dir: cfg.project.decisions_dir.clone(),
        last_rejection: story.last_rejection.clone(),
        from: story.status,
        to: next_status(story.status),
    };

    // Determinar el rol, provider, y path de instrucciones
    let role = map_status_to_role(story.status);
    let provider_name = cfg.agents.provider_for_role(role);
    let provider = providers::from_name(&provider_name);
    let skill_path_str = cfg.agents.skill_for_role(role);
    let instruction_path = project_root.join(&skill_path_str);

    // Prompt segΓΊn el estado (sin cambios)
    let (prompt, label) = match story.status {
        Status::Draft => (ctx.po_groom(), "PO (groom)"),
        Status::Ready => (ctx.qa_tests(), "QA (tests)"),
        Status::TestsReady => {
            if story.last_actor().as_deref() == Some("Dev") {
                let qa_ctx = PromptContext {
                    to: Status::TestsReady,
                    story_id: ctx.story_id.clone(),
                    stories_dir: ctx.stories_dir.clone(),
                    decisions_dir: ctx.decisions_dir.clone(),
                    last_rejection: ctx.last_rejection.clone(),
                    from: ctx.from,
                };
                (qa_ctx.qa_fix_tests(), "QA (fix tests)")
            } else {
                (ctx.dev_implement(), "Dev (implement)")
            }
        }
        Status::InProgress => (ctx.dev_fix(), "Dev (fix)"),
        Status::InReview => (ctx.reviewer(), "Reviewer"),
        Status::BusinessReview => (ctx.po_validate(), "PO (validate)"),
        _ => {
            tracing::warn!("{}: estado {} no procesable", story.id, story.status);
            return Ok(());
        }
    };

    tracing::info!(
        "  🎯 {label} ({}) | {} ({} β†’ {})",
        provider.display_name(),
        story.id,
        story.status,
        ctx.to
    );

    // Snapshot git antes de la invocaciΓ³n (si estΓ‘ habilitado)
    let prev_hash = if cfg.git.enabled {
        crate::git::snapshot(project_root, &format!("{label}-{}", story.id))
    } else {
        None
    };

    let result = agent::invoke_with_retry(
        provider.as_ref(),
        &instruction_path,
        &prompt,
        &cfg.limits,
        agent_opts,
    );

    match result {
        Ok(_) => {
            // Verificar que el agente realmente cambiΓ³ el estado
            let updated = Story::load(&story.path)?;
            if updated.status == story.status {
                tracing::warn!(
                    "  ⚠ {}: el agente no cambió el estado (sigue en {})",
                    story.id,
                    story.status
                );
            } else if (updated.status == Status::InProgress || updated.status == Status::InReview)
                && (story.status == Status::InReview || story.status == Status::BusinessReview)
            {
                // El agente rechazΓ³: incrementar contador
                let cycles = reject_cycles.entry(story.id.clone()).or_insert(0);
                *cycles += 1;
                tracing::info!(
                    "  πŸ“Š {}: ciclo de rechazo {}/{}",
                    story.id,
                    cycles,
                    cfg.limits.max_reject_cycles
                );
            }

            // Ejecutar hook post-fase si estΓ‘ definido
            let hook_result = match story.status {
                Status::Ready => crate::hooks::run_hook(cfg.hooks.post_qa.as_deref(), "post_qa"),
                Status::TestsReady | Status::InProgress => {
                    crate::hooks::run_hook(cfg.hooks.post_dev.as_deref(), "post_dev")
                }
                Status::InReview => {
                    crate::hooks::run_hook(cfg.hooks.post_reviewer.as_deref(), "post_reviewer")
                }
                _ => Ok(()),
            };

            if let Err(e) = hook_result {
                tracing::warn!("  ❌ hook falló: {e}");
                if let Some(ref hash) = prev_hash {
                    crate::git::rollback(project_root, hash, label);
                }
            }
        }
        Err(e) => {
            tracing::error!("  ❌ {}: falló la invocación del agente: {e}", story.id);
            // Rollback si hay snapshot
            if let Some(ref hash) = prev_hash {
                crate::git::rollback(project_root, hash, label);
            }
        }
    }

    Ok(())
}

/// Infiere el estado esperado tras la intervenciΓ³n del agente.
fn next_status(current: Status) -> Status {
    match current {
        Status::Draft => Status::Ready,
        Status::Ready => Status::TestsReady,
        Status::TestsReady => Status::InReview,
        Status::InProgress => Status::InReview,
        Status::InReview => Status::BusinessReview,
        Status::BusinessReview => Status::Done,
        _ => current,
    }
}

/// Mapea un estado del workflow al rol canΓ³nico que lo procesa.
fn map_status_to_role(status: Status) -> &'static str {
    match status {
        Status::Draft | Status::BusinessReview => "product_owner",
        Status::Ready => "qa_engineer",
        Status::TestsReady | Status::InProgress => "developer",
        Status::InReview => "reviewer",
        _ => "product_owner", // fallback seguro
    }
}

/// Extrae el nΓΊmero de un ID tipo "STORY-NNN".
fn extract_numeric(id: &str) -> u32 {
    id.chars()
        .filter(|c| c.is_ascii_digit())
        .collect::<String>()
        .parse()
        .unwrap_or(0)
}

/// Calcula el nΓΊmero mΓ‘ximo efectivo de iteraciones.
///
/// Si el usuario configurΓ³ un valor explΓ­cito (>0), se respeta.
/// Si es 0 (default), se calcula como `max(10, story_count * 6)`
/// para escalar automΓ‘ticamente con el tamaΓ±o del proyecto.
fn effective_max_iterations(cfg_max: u32, story_count: usize) -> u32 {
    if cfg_max > 0 {
        cfg_max
    } else {
        let computed = story_count as u32 * 6;
        computed.max(10)
    }
}

/// Construye AgentOptions con los valores de configuraciΓ³n actuales.
fn build_agent_opts(story: &Story, cfg: &Config) -> AgentOptions {
    AgentOptions {
        story_id: Some(story.id.clone()),
        decisions_dir: Some(Path::new(&cfg.project.decisions_dir).to_path_buf()),
        inject_feedback: cfg.limits.inject_feedback_on_retry,
    }
}

/// Guarda el checkpoint del orquestador.
fn save_checkpoint(
    project_root: &Path,
    iteration: u32,
    reject_cycles: &HashMap<String, u32>,
    story_iterations: &HashMap<String, u32>,
    story_errors: &HashMap<String, String>,
) {
    let state = OrchestratorState {
        iteration,
        reject_cycles: reject_cycles.clone(),
        story_iterations: story_iterations.clone(),
        story_errors: story_errors.clone(),
    };
    if let Err(e) = state.save(project_root) {
        tracing::warn!("⚠️  no se pudo guardar el checkpoint: {e}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn status_priority_order() {
        assert!(status_priority(Status::BusinessReview) > status_priority(Status::InReview));
        assert!(status_priority(Status::InReview) > status_priority(Status::TestsReady));
        assert!(status_priority(Status::TestsReady) > status_priority(Status::Ready));
        assert!(status_priority(Status::Ready) > status_priority(Status::Draft));
    }

    #[test]
    fn next_status_follows_happy_path() {
        assert_eq!(next_status(Status::Draft), Status::Ready);
        assert_eq!(next_status(Status::Ready), Status::TestsReady);
        assert_eq!(next_status(Status::TestsReady), Status::InReview);
        assert_eq!(next_status(Status::InReview), Status::BusinessReview);
        assert_eq!(next_status(Status::BusinessReview), Status::Done);
    }

    #[test]
    fn next_status_fix_path() {
        assert_eq!(next_status(Status::InProgress), Status::InReview);
    }

    // ── filter_stories ──────────────────────────────────────────────

    fn story_fixture(id: &str, status: Status, epic: Option<&str>) -> Story {
        Story {
            id: id.to_string(),
            path: format!("stories/{id}.md").into(),
            status,
            epic: epic.map(|s| s.to_string()),
            blockers: vec![],
            last_rejection: None,
            raw_content: String::new(),
        }
    }

    #[test]
    fn filter_no_options_keeps_all() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, Some("EPIC-001")),
            story_fixture("STORY-002", Status::Draft, Some("EPIC-002")),
            story_fixture("STORY-003", Status::Done, None),
        ];
        let options = RunOptions::default();
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 3);
    }

    #[test]
    fn filter_by_story_id_includes_only_match() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, None),
            story_fixture("STORY-002", Status::Draft, None),
            story_fixture("STORY-003", Status::Done, None),
        ];
        let options = RunOptions {
            story_filter: Some("STORY-002".into()),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id, "STORY-002");
    }

    #[test]
    fn filter_by_story_id_empty_when_no_match() {
        let stories = vec![story_fixture("STORY-001", Status::Ready, None)];
        let options = RunOptions {
            story_filter: Some("STORY-999".into()),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert!(filtered.is_empty());
    }

    #[test]
    fn filter_by_epic_includes_only_matching_epic() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, Some("EPIC-001")),
            story_fixture("STORY-002", Status::Draft, Some("EPIC-001")),
            story_fixture("STORY-003", Status::Ready, Some("EPIC-002")),
            story_fixture("STORY-004", Status::Draft, None),
        ];
        let options = RunOptions {
            epic_filter: Some("EPIC-001".into()),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 2);
        assert!(filtered
            .iter()
            .all(|s| s.epic.as_deref() == Some("EPIC-001")));
    }

    #[test]
    fn filter_by_epic_excludes_stories_without_epic() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, None),
            story_fixture("STORY-002", Status::Ready, Some("EPIC-001")),
        ];
        let options = RunOptions {
            epic_filter: Some("EPIC-001".into()),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id, "STORY-002");
    }

    #[test]
    fn filter_by_epics_range_inclusive() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, Some("EPIC-001")),
            story_fixture("STORY-002", Status::Draft, Some("EPIC-002")),
            story_fixture("STORY-003", Status::Ready, Some("EPIC-003")),
            story_fixture("STORY-004", Status::Draft, Some("EPIC-004")),
            story_fixture("STORY-005", Status::Ready, Some("EPIC-005")),
        ];
        let options = RunOptions {
            epics_range: Some(("EPIC-002".into(), "EPIC-004".into())),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 3);
        let ids: Vec<&str> = filtered.iter().map(|s| s.id.as_str()).collect();
        assert!(ids.contains(&"STORY-002"));
        assert!(ids.contains(&"STORY-003"));
        assert!(ids.contains(&"STORY-004"));
    }

    #[test]
    fn filter_by_epics_range_single_epic() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, Some("EPIC-001")),
            story_fixture("STORY-002", Status::Draft, Some("EPIC-001")),
            story_fixture("STORY-003", Status::Ready, Some("EPIC-002")),
        ];
        let options = RunOptions {
            epics_range: Some(("EPIC-001".into(), "EPIC-001".into())),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 2);
    }

    #[test]
    fn filter_combined_story_and_epic_both_must_match() {
        // Ambos filtros actΓΊan como AND (aunque la CLI no permite combinarlos)
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, Some("EPIC-001")),
            story_fixture("STORY-002", Status::Draft, Some("EPIC-002")),
        ];
        let options = RunOptions {
            story_filter: Some("STORY-001".into()),
            epic_filter: Some("EPIC-001".into()),
            ..Default::default()
        };
        let filtered = filter_stories(stories, &options);
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].id, "STORY-001");
    }

    // ── RunOptions defaults ──────────────────────────────────────────

    #[test]
    fn run_options_default_has_no_filters() {
        let opts = RunOptions::default();
        assert!(!opts.once);
        assert!(opts.story_filter.is_none());
        assert!(opts.epic_filter.is_none());
        assert!(opts.epics_range.is_none());
    }

    // ── extract_numeric ──────────────────────────────────────────────

    #[test]
    fn extract_numeric_from_story_id() {
        assert_eq!(extract_numeric("STORY-001"), 1);
        assert_eq!(extract_numeric("STORY-042"), 42);
        assert_eq!(extract_numeric("story-007"), 7);
    }

    #[test]
    fn extract_numeric_from_epic_id() {
        assert_eq!(extract_numeric("EPIC-001"), 1);
        assert_eq!(extract_numeric("EPIC-010"), 10);
        assert_eq!(extract_numeric("EPIC-123"), 123);
    }

    #[test]
    fn extract_numeric_fallback_zero() {
        assert_eq!(extract_numeric("ABC"), 0);
        assert_eq!(extract_numeric(""), 0);
    }

    // ── pick_next_actionable ─────────────────────────────────────────

    #[test]
    fn pick_next_actionable_returns_highest_priority() {
        let stories = vec![
            story_fixture("STORY-001", Status::Ready, None),
            story_fixture("STORY-002", Status::BusinessReview, None),
            story_fixture("STORY-003", Status::TestsReady, None),
        ];
        let graph = DependencyGraph::from_stories(&stories);
        let picked = pick_next_actionable(&stories, &graph);
        assert!(picked.is_some());
        // BusinessReview tiene la prioridad mΓ‘s alta
        assert_eq!(picked.unwrap().id, "STORY-002");
    }

    #[test]
    fn pick_next_actionable_breaks_tie_by_lower_id() {
        let stories = vec![
            story_fixture("STORY-005", Status::Ready, None),
            story_fixture("STORY-002", Status::Ready, None),
        ];
        let graph = DependencyGraph::from_stories(&stories);
        let picked = pick_next_actionable(&stories, &graph);
        assert!(picked.is_some());
        // Mismo estado, gana ID mΓ‘s bajo
        assert_eq!(picked.unwrap().id, "STORY-002");
    }

    #[test]
    fn pick_next_actionable_returns_none_when_no_actionable() {
        let stories = vec![
            story_fixture("STORY-001", Status::Draft, None),
            story_fixture("STORY-002", Status::Done, None),
            story_fixture("STORY-003", Status::Blocked, None),
            story_fixture("STORY-004", Status::Failed, None),
        ];
        let graph = DependencyGraph::from_stories(&stories);
        let picked = pick_next_actionable(&stories, &graph);
        assert!(picked.is_none());
    }
}