summaryrefslogblamecommitdiff
path: root/makima/src/server/handlers/directives.rs
blob: 7b13f1ce860557a02dfc92244b138a6ddb684642 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
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
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096


                                                         
                           






                           
                                                               
                                                                 
                                                                               
         
                                                                          


                                                                      
  

                     
                          

                                                                          

                                                                     
  

































































































































































                                                                                         








                                                                                                  
                                                                                      





























                                                                                       










                                                                                                  



                                           



































































































































































































































































































































































































































































































































































































































































                                                                                              





                                                                                            





                                                                                                    











                                                                                                


         





































                                                                                        


















                                                                                                  






                                                                                               
                                        
                                                               






                                                                        

                                                            
                    


                                                                     
                                 
         








                                                                               
 

                                                                                


                                                                                
 
                                                                                

               
                                             

                                                              
                                                                                     
                                                                   
                                                                               




                                                                                 
                               











                                                                             































                                                                                             












                                                                                                                           




                                                                                 
                    

                                                                        


                                 




















































                                                                                                              
                   
                                                                    

                                                  
                                                                          


                                 









                                                                                   

     








                                                                                   

         













                                                                                               
 

                                                                                

















































































                                                                                                 





























                                                                                      
                                


















                                                                                             























                                                                                                            












                                                                                               
                             
                                                                                                   













                                                                           
                                                               













































                                                                                                 






                                                                                                  









































































                                                                                                     
                                                            




                               



































































































































































































































































































































































































































































































































































































                                                                                                               











                                                                                
















































                                                                                    







































                                                                                               































































































































































                                                                                                            
//! HTTP handlers for directive CRUD and DAG progression.

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use uuid::Uuid;

use crate::db::models::{
    CleanupResponse, CreateDirectiveRequest, CreateTaskRequest,
    CreateDirectiveStepRequest, Directive, DirectiveListResponse,
    DirectiveRevision, DirectiveStep, DirectiveWithSteps, PickUpOrdersResponse,
    Task,
    UpdateDirectiveRequest, UpdateDirectiveStepRequest, UpdateGoalRequest,
    CreateDirectiveOrderGroupRequest, DirectiveOrderGroup,
    DirectiveOrderGroupListResponse, UpdateDirectiveOrderGroupRequest,
    OrderListResponse,
};
use serde::Serialize;
use utoipa::ToSchema;
use crate::db::repository;
use crate::orchestration::directive::{
    build_cleanup_prompt, build_order_pickup_prompt, classify_goal_change,
    try_cancel_running_planner, try_interrupt_planner_with_goal_edit,
    GoalChangeKind, GoalEditInterruptResult,
};
use crate::server::auth::Authenticated;
use crate::server::messages::ApiError;
use crate::server::state::SharedState;

// =============================================================================
// Directive CRUD
// =============================================================================

/// List all directives for the authenticated user.
#[utoipa::path(
    get,
    path = "/api/v1/directives",
    responses(
        (status = 200, description = "List of directives", body = DirectiveListResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn list_directives(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::list_directives_for_owner(pool, auth.owner_id).await {
        Ok(directives) => {
            let total = directives.len() as i64;
            Json(DirectiveListResponse { directives, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list directives: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("LIST_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Create a new directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives",
    request_body = CreateDirectiveRequest,
    responses(
        (status = 201, description = "Directive created", body = Directive),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn create_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Json(req): Json<CreateDirectiveRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::create_directive_for_owner(pool, auth.owner_id, req).await {
        Ok(directive) => (StatusCode::CREATED, Json(directive)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create directive: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get a directive with all its steps.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Directive with steps", body = DirectiveWithSteps),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn get_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::get_directive_with_steps_for_owner(pool, auth.owner_id, id).await {
        Ok(Some((directive, steps))) => {
            Json(DirectiveWithSteps { directive, steps }).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get directive: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a directive.
#[utoipa::path(
    put,
    path = "/api/v1/directives/{id}",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = UpdateDirectiveRequest,
    responses(
        (status = 200, description = "Directive updated", body = Directive),
        (status = 404, description = "Not found", body = ApiError),
        (status = 409, description = "Version conflict", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn update_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(req): Json<UpdateDirectiveRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Capture the BEFORE state so we can detect a pr_url transition (null
    // → some-value), which is when the orchestrator's completion task has
    // raised a PR for this directive. That transition is the trigger for
    // freezing a directive_revisions snapshot.
    let before_pr_url = match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(d)) => d.pr_url.clone(),
        _ => None,
    };

    match repository::update_directive_for_owner(pool, auth.owner_id, id, req).await {
        Ok(Some(directive)) => {
            // Detect "PR was just raised" — pr_url went from None to Some.
            // Snapshot the current goal as a revision tied to this PR.
            // Best-effort: a snapshot failure should not fail the update,
            // because the directive's pr_url has already been written.
            if before_pr_url.is_none() {
                if let Some(ref new_pr_url) = directive.pr_url {
                    if let Err(e) = repository::create_directive_revision(
                        pool,
                        directive.id,
                        &directive.goal,
                        new_pr_url,
                        directive.pr_branch.as_deref(),
                    )
                    .await
                    {
                        tracing::warn!(
                            directive_id = %directive.id,
                            pr_url = %new_pr_url,
                            error = %e,
                            "Failed to snapshot directive revision on PR creation — \
                             continuing; revision history will be incomplete"
                        );
                    } else {
                        tracing::info!(
                            directive_id = %directive.id,
                            pr_url = %new_pr_url,
                            "Snapshotted directive revision on PR creation"
                        );
                    }

                    // Transition the contract to 'inactive' now that its
                    // iteration is "shipped" — editing the goal again starts
                    // an amendment cycle, surfaced via the New draft action.
                    if let Err(e) = repository::set_directive_inactive(pool, directive.id).await {
                        tracing::warn!(
                            directive_id = %directive.id,
                            error = %e,
                            "Failed to mark directive inactive after PR creation"
                        );
                    }
                }
            }
            Json(directive).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(repository::RepositoryError::VersionConflict { expected, actual }) => (
            StatusCode::CONFLICT,
            Json(ApiError::new(
                "VERSION_CONFLICT",
                &format!("Expected version {}, but current is {}", expected, actual),
            )),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to update directive: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("UPDATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Delete a directive.
#[utoipa::path(
    delete,
    path = "/api/v1/directives/{id}",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 204, description = "Deleted"),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn delete_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::delete_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(true) => StatusCode::NO_CONTENT.into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to delete directive: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DELETE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

// =============================================================================
// Step CRUD
// =============================================================================

/// Create a step in a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/steps",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = CreateDirectiveStepRequest,
    responses(
        (status = 201, description = "Step created", body = DirectiveStep),
        (status = 404, description = "Directive not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn create_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(req): Json<CreateDirectiveStepRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership
    match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    match repository::create_directive_step(pool, id, req).await {
        Ok(step) => (StatusCode::CREATED, Json(step)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create step: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Batch create steps in a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/steps/batch",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = Vec<CreateDirectiveStepRequest>,
    responses(
        (status = 201, description = "Steps created", body = Vec<DirectiveStep>),
        (status = 404, description = "Directive not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn batch_create_steps(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(steps): Json<Vec<CreateDirectiveStepRequest>>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership
    match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    match repository::batch_create_directive_steps(pool, id, steps).await {
        Ok(created) => (StatusCode::CREATED, Json(created)).into_response(),
        Err(e) => {
            tracing::error!("Failed to batch create steps: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a step.
#[utoipa::path(
    put,
    path = "/api/v1/directives/{id}/steps/{step_id}",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("step_id" = Uuid, Path, description = "Step ID"),
    ),
    request_body = UpdateDirectiveStepRequest,
    responses(
        (status = 200, description = "Step updated", body = DirectiveStep),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn update_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
    Json(req): Json<UpdateDirectiveStepRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership
    match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    match repository::update_directive_step(pool, step_id, req).await {
        Ok(Some(step)) => Json(step).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Step not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to update step: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("UPDATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Delete a step.
#[utoipa::path(
    delete,
    path = "/api/v1/directives/{id}/steps/{step_id}",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("step_id" = Uuid, Path, description = "Step ID"),
    ),
    responses(
        (status = 204, description = "Deleted"),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn delete_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership
    match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    match repository::delete_directive_step(pool, step_id).await {
        Ok(true) => StatusCode::NO_CONTENT.into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Step not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to delete step: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DELETE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

// =============================================================================
// Directive Lifecycle Actions
// =============================================================================

/// Start a directive: sets status=active, advances ready steps.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/start",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Directive started", body = DirectiveWithSteps),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn start_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Set to active
    match repository::set_directive_status(pool, auth.owner_id, id, "active").await {
        Ok(Some(directive)) => {
            // Advance ready steps
            let _ = repository::advance_directive_ready_steps(pool, id).await;
            let steps = repository::list_directive_steps(pool, id).await.unwrap_or_default();
            Json(DirectiveWithSteps { directive, steps }).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to start directive: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("START_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Pause a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/pause",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Directive paused", body = Directive),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn pause_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::set_directive_status(pool, auth.owner_id, id, "paused").await {
        Ok(Some(directive)) => Json(directive).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("PAUSE_FAILED", &e.to_string())),
        )
            .into_response(),
    }
}

/// Advance a directive: find newly-ready steps. If all steps done, set idle.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/advance",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Advance result", body = DirectiveWithSteps),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn advance_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify ownership
    let directive = match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(d)) => d,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // Advance ready steps
    let _ = repository::advance_directive_ready_steps(pool, id).await;

    // Check if idle
    let _ = repository::check_directive_idle(pool, id).await;

    // Return updated state
    let directive = match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(d)) => d,
        _ => directive,
    };
    let steps = repository::list_directive_steps(pool, id).await.unwrap_or_default();
    Json(DirectiveWithSteps { directive, steps }).into_response()
}

/// Mark a step as completed.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/steps/{step_id}/complete",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("step_id" = Uuid, Path, description = "Step ID"),
    ),
    responses(
        (status = 200, description = "Step completed", body = DirectiveStep),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn complete_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    step_status_change(state, auth, id, step_id, "completed").await
}

/// Mark a step as failed.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/steps/{step_id}/fail",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("step_id" = Uuid, Path, description = "Step ID"),
    ),
    responses(
        (status = 200, description = "Step failed", body = DirectiveStep),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn fail_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    step_status_change(state, auth, id, step_id, "failed").await
}

/// Mark a step as skipped.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/steps/{step_id}/skip",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("step_id" = Uuid, Path, description = "Step ID"),
    ),
    responses(
        (status = 200, description = "Step skipped", body = DirectiveStep),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn skip_step(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, step_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    step_status_change(state, auth, id, step_id, "skipped").await
}

/// Helper for step status changes.
async fn step_status_change(
    state: SharedState,
    auth: crate::server::auth::AuthenticatedUser,
    directive_id: Uuid,
    step_id: Uuid,
    new_status: &str,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership
    match repository::get_directive_for_owner(pool, auth.owner_id, directive_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    let req = UpdateDirectiveStepRequest {
        status: Some(new_status.to_string()),
        ..Default::default()
    };

    match repository::update_directive_step(pool, step_id, req).await {
        Ok(Some(step)) => {
            // After step status change, advance the DAG
            let _ = repository::advance_directive_ready_steps(pool, directive_id).await;
            let _ = repository::check_directive_idle(pool, directive_id).await;
            Json(step).into_response()
        }
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Step not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to update step status: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("UPDATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a directive's goal (triggers re-planning).
#[utoipa::path(
    put,
    path = "/api/v1/directives/{id}/goal",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = UpdateGoalRequest,
    responses(
        (status = 200, description = "Goal updated", body = Directive),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn update_goal(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(req): Json<UpdateGoalRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Fetch the current directive so we can:
    //   1. Save the old goal to history (best-effort).
    //   2. Decide whether to fire a goal-edit interrupt at a running planner.
    let current = match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(d)) => Some(d),
        Ok(None) => None,
        Err(e) => {
            tracing::warn!(
                directive_id = %id,
                error = %e,
                "Failed to fetch current directive for goal history — continuing with goal update"
            );
            None
        }
    };

    // Save old goal to history before overwriting (best-effort).
    if let Some(ref current) = current {
        if let Err(e) = repository::save_directive_goal_history(pool, id, &current.goal).await {
            tracing::warn!(
                directive_id = %id,
                error = %e,
                "Failed to save goal history before update — continuing with goal update"
            );
        }
    }

    // Goal-edit interrupt cycle: if a planner task is currently running for
    // this directive AND the goal change classifies as 'small', interrupt the
    // running planner via SendMessage instead of clearing it (which would
    // trigger a fresh replan on the next orchestrator tick).
    let mut interrupted = false;
    if let Some(ref current) = current {
        if current.orchestrator_task_id.is_some()
            && classify_goal_change(&current.goal, &req.goal) == GoalChangeKind::Small
        {
            match try_interrupt_planner_with_goal_edit(
                pool,
                &state,
                id,
                &current.goal,
                &req.goal,
            )
            .await
            {
                Ok(GoalEditInterruptResult::Sent) => {
                    interrupted = true;
                }
                Ok(GoalEditInterruptResult::Skipped) => {}
                Err(e) => {
                    tracing::warn!(
                        directive_id = %id,
                        error = %e,
                        "Goal-edit interrupt attempt errored — falling back to replan"
                    );
                }
            }
        }
    }

    // If we successfully interrupted a running planner, persist the new goal
    // WITHOUT clearing the orchestrator task — the planner will react to the
    // SendMessage and adjust in-flight. Otherwise, fall through to the normal
    // path which clears orchestrator_task_id and lets phase_replanning kick
    // in on the next tick.
    //
    // CRITICAL: when going down the "clear" path, we must also CANCEL the
    // running planner. Otherwise the orphaned task keeps producing add-step
    // calls based on the old goal, racing the freshly-spawned replanner.
    if !interrupted {
        if let Some(ref current) = current {
            if let Some(orch_task_id) = current.orchestrator_task_id {
                if let Err(e) = try_cancel_running_planner(pool, &state, id, orch_task_id).await {
                    tracing::warn!(
                        directive_id = %id,
                        task_id = %orch_task_id,
                        error = %e,
                        "Failed to cancel orphaned planner — proceeding with clear anyway"
                    );
                }
            }
        }
    }

    let update_result = if interrupted {
        repository::update_directive_goal_keep_orchestrator(pool, auth.owner_id, id, &req.goal)
            .await
    } else {
        repository::update_directive_goal(pool, auth.owner_id, id, &req.goal).await
    };

    let response = match update_result {
        Ok(Some(directive)) => Json(directive).into_response(),
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to update goal: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("UPDATE_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // Nudge the directive reconciler so the user does not wait up to 15s for
    // the next interval tick before the new planner is spawned (clear path) or
    // the small-edit interrupt is consumed (keep path). Best-effort: if the
    // channel is full or closed we just rely on the normal interval.
    state.kick_directive_reconciler();

    response
}

// =============================================================================
// Task Cleanup
// =============================================================================


/// Clean up merged steps for an idle directive by spawning a verification task.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/cleanup",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Cleanup task spawned", body = CleanupResponse),
        (status = 404, description = "Not found", body = ApiError),
        (status = 409, description = "Directive is not idle", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn cleanup_directive(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Get the directive with steps and verify ownership
    let (directive, _steps) =
        match repository::get_directive_with_steps_for_owner(pool, auth.owner_id, id).await {
            Ok(Some(ds)) => ds,
            Ok(None) => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", "Directive not found")),
                )
                    .into_response();
            }
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GET_FAILED", &e.to_string())),
                )
                    .into_response();
            }
        };

    // Verify directive is idle
    if directive.status != "idle" {
        return (
            StatusCode::CONFLICT,
            Json(ApiError::new(
                "NOT_IDLE",
                "Directive must be idle to run cleanup",
            )),
        )
            .into_response();
    }

    // Auto-remove completed steps that were already included in a merged PR
    if directive.pr_url.is_some() || directive.pr_branch.is_some() {
        match crate::orchestration::directive::remove_already_merged_steps(pool, id).await {
            Ok(count) if count > 0 => {
                tracing::info!("Auto-removed {} completed steps already in PR for directive {} during cleanup", count, id);
            }
            Err(e) => {
                tracing::warn!("Failed to auto-remove merged steps during cleanup for directive {}: {}", id, e);
            }
            _ => {}
        }
    }

    // Get completed step tasks for branch name computation
    let step_tasks = match repository::get_completed_step_tasks(pool, id).await {
        Ok(tasks) => tasks,
        Err(e) => {
            tracing::error!("Failed to get completed step tasks: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_STEPS_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    if step_tasks.is_empty() {
        return Json(CleanupResponse {
            message: "No completed steps to clean up".to_string(),
            task_id: None,
        })
        .into_response();
    }

    let pr_branch = match &directive.pr_branch {
        Some(b) => b.clone(),
        None => {
            return Json(CleanupResponse {
                message: "No PR branch set — nothing to verify against".to_string(),
                task_id: None,
            })
            .into_response();
        }
    };

    let base_branch = directive.base_branch.as_deref().unwrap_or("main");

    // Build the cleanup prompt
    let prompt = build_cleanup_prompt(&directive, &step_tasks, &pr_branch, base_branch);

    // Create the cleanup task (following pick_up_orders pattern)
    let req = CreateTaskRequest {
        contract_id: None,
        name: format!("Cleanup: {}", directive.title),
        description: Some("Directive cleanup — verify merged branches and remove merged steps".to_string()),
        plan: prompt,
        parent_task_id: None,
        is_supervisor: false,
        priority: 0,
        repository_url: directive.repository_url.clone(),
        base_branch: directive.base_branch.clone(),
        target_branch: None,
        merge_mode: None,
        target_repo_path: None,
        completion_action: None,
        continue_from_task_id: None,
        copy_files: None,
        checkpoint_sha: None,
        branched_from_task_id: None,
        conversation_history: None,
        supervisor_worktree_task_id: None,
        directive_id: Some(directive.id),
        directive_step_id: None,
    };

    let task = match repository::create_task_for_owner(pool, auth.owner_id, req).await {
        Ok(t) => t,
        Err(e) => {
            tracing::error!("Failed to create cleanup task: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_TASK_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // Assign as orchestrator task
    if let Err(e) = repository::assign_orchestrator_task(pool, id, task.id).await {
        tracing::error!("Failed to assign orchestrator task: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("ASSIGN_TASK_FAILED", &e.to_string())),
        )
            .into_response();
    }

    // Cancel old planning tasks
    let cancelled = repository::cancel_old_planning_tasks(pool, id, task.id).await;
    if let Ok(count) = cancelled {
        if count > 0 {
            tracing::info!(
                directive_id = %id,
                cancelled_count = count,
                "Cancelled old planning tasks superseded by cleanup"
            );
        }
    }

    // Set directive to active
    if let Err(e) = repository::set_directive_status(pool, auth.owner_id, id, "active").await {
        tracing::warn!("Failed to set directive status to active: {}", e);
    }

    // Advance ready steps
    let _ = repository::advance_directive_ready_steps(pool, id).await;

    Json(CleanupResponse {
        message: format!("Cleanup task spawned for {} completed steps", step_tasks.len()),
        task_id: Some(task.id),
    })
    .into_response()
}

// =============================================================================
// PR Creation
// =============================================================================

/// Trigger PR creation or update for a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/create-pr",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "PR task spawned", body = DirectiveWithSteps),
        (status = 404, description = "Not found", body = ApiError),
        (status = 409, description = "Completion task already running", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn create_pr(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match crate::orchestration::directive::trigger_completion_task(
        pool,
        &state,
        id,
        auth.owner_id,
    )
    .await
    {
        Ok(_task_id) => {
            // Return the updated directive with steps
            match repository::get_directive_with_steps_for_owner(pool, auth.owner_id, id).await {
                Ok(Some((directive, steps))) => {
                    Json(DirectiveWithSteps { directive, steps }).into_response()
                }
                Ok(None) => (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", "Directive not found")),
                )
                    .into_response(),
                Err(e) => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GET_FAILED", &e.to_string())),
                )
                    .into_response(),
            }
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("not found") {
                (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", &msg)),
                )
                    .into_response()
            } else if msg.contains("already running") || msg.contains("already claimed") {
                (
                    StatusCode::CONFLICT,
                    Json(ApiError::new("COMPLETION_IN_PROGRESS", &msg)),
                )
                    .into_response()
            } else {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("CREATE_PR_FAILED", &msg)),
                )
                    .into_response()
            }
        }
    }
}

// =============================================================================
// Order Pickup
// =============================================================================

/// Pick up available open orders for a directive by spawning a planning task.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/pick-up-orders",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Orders picked up", body = PickUpOrdersResponse),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn pick_up_orders(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership and get directive with steps
    let (directive, mut steps) =
        match repository::get_directive_with_steps_for_owner(pool, auth.owner_id, id).await {
            Ok(Some((d, s))) => (d, s),
            Ok(None) => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", "Directive not found")),
                )
                    .into_response();
            }
            Err(e) => {
                tracing::error!("Failed to get directive: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GET_FAILED", &e.to_string())),
                )
                    .into_response();
            }
        };

    // Auto-remove completed steps that were already included in a PR
    if directive.pr_url.is_some() || directive.pr_branch.is_some() {
        match crate::orchestration::directive::remove_already_merged_steps(pool, id).await {
            Ok(count) if count > 0 => {
                tracing::info!("Auto-removed {} completed steps already in PR for directive {}", count, id);
                // Re-fetch steps since some were removed
                steps = match repository::list_directive_steps(pool, id).await {
                    Ok(s) => s,
                    Err(e) => {
                        tracing::error!("Failed to re-fetch steps after cleanup: {}", e);
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(ApiError::new("REFETCH_STEPS_FAILED", &e.to_string())),
                        ).into_response();
                    }
                };
            }
            Err(e) => {
                tracing::warn!("Failed to auto-remove merged steps for directive {}: {}", id, e);
            }
            _ => {}
        }
    }

    // Reconcile existing orders: mark done if step completed, under_review if step in progress
    match repository::reconcile_directive_orders(pool, auth.owner_id, id).await {
        Ok(count) => {
            if count > 0 {
                tracing::info!("Reconciled {} orders for directive {}", count, id);
            }
        }
        Err(e) => {
            tracing::warn!("Failed to reconcile directive orders: {}", e);
            // Non-fatal: continue with pickup even if reconciliation fails
        }
    }

    // Fetch available orders
    let orders = match repository::get_available_orders_for_pickup(pool, auth.owner_id, id).await {
        Ok(o) => o,
        Err(e) => {
            tracing::error!("Failed to fetch available orders: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("FETCH_ORDERS_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // If no orders available, return early
    if orders.is_empty() {
        return Json(PickUpOrdersResponse {
            message: "No orders available to plan".to_string(),
            order_count: 0,
            task_id: None,
        })
        .into_response();
    }

    let order_count = orders.len() as i64;
    let order_ids: Vec<Uuid> = orders.iter().map(|o| o.id).collect();

    // Get generation and goal history for the planning prompt
    let generation =
        match repository::get_directive_max_generation(pool, id).await {
            Ok(g) => g + 1,
            Err(e) => {
                tracing::error!("Failed to get max generation: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GENERATION_FAILED", &e.to_string())),
                )
                    .into_response();
            }
        };

    let goal_history = match repository::get_directive_goal_history(pool, id, 3).await {
        Ok(h) => h,
        Err(e) => {
            tracing::warn!("Failed to get goal history: {}", e);
            vec![]
        }
    };

    // Build the specialized planning prompt
    let plan = build_order_pickup_prompt(&directive, &steps, &orders, generation, &goal_history);

    // Link orders to the directive
    if let Err(e) =
        repository::bulk_link_orders_to_directive(pool, auth.owner_id, &order_ids, id).await
    {
        tracing::error!("Failed to link orders to directive: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("LINK_ORDERS_FAILED", &e.to_string())),
        )
            .into_response();
    }

    // Mark picked-up orders as in_progress
    if let Err(e) =
        repository::bulk_update_order_status(pool, auth.owner_id, &order_ids, "in_progress").await
    {
        tracing::warn!("Failed to update order status to in_progress: {}", e);
    }

    // Create the planning task
    let req = CreateTaskRequest {
        contract_id: None,
        name: format!("Pick up orders: {}", directive.title),
        description: Some("Directive order pickup planning task".to_string()),
        plan,
        parent_task_id: None,
        is_supervisor: false,
        priority: 0,
        repository_url: directive.repository_url.clone(),
        base_branch: directive.base_branch.clone(),
        target_branch: None,
        merge_mode: None,
        target_repo_path: None,
        completion_action: None,
        continue_from_task_id: None,
        copy_files: None,
        checkpoint_sha: None,
        branched_from_task_id: None,
        conversation_history: None,
        supervisor_worktree_task_id: None,
        directive_id: Some(directive.id),
        directive_step_id: None,
    };

    let task = match repository::create_task_for_owner(pool, auth.owner_id, req).await {
        Ok(t) => t,
        Err(e) => {
            tracing::error!("Failed to create pickup planning task: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_TASK_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // Assign as orchestrator task
    if let Err(e) = repository::assign_orchestrator_task(pool, id, task.id).await {
        tracing::error!("Failed to assign orchestrator task: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("ASSIGN_TASK_FAILED", &e.to_string())),
        )
            .into_response();
    }

    // Cancel old planning tasks
    let cancelled = repository::cancel_old_planning_tasks(pool, id, task.id).await;
    if let Ok(count) = cancelled {
        if count > 0 {
            tracing::info!(
                directive_id = %id,
                cancelled_count = count,
                "Cancelled old planning tasks superseded by order pickup"
            );
        }
    }

    // Set directive to active if draft/idle/paused
    match directive.status.as_str() {
        "draft" | "idle" | "paused" => {
            if let Err(e) = repository::set_directive_status(pool, auth.owner_id, id, "active").await
            {
                tracing::warn!("Failed to set directive status to active: {}", e);
            }
        }
        _ => {}
    }

    // Advance ready steps
    let _ = repository::advance_directive_ready_steps(pool, id).await;

    Json(PickUpOrdersResponse {
        message: format!("Planning {} orders", order_count),
        order_count,
        task_id: Some(task.id),
    })
    .into_response()
}

// =============================================================================
// Directive Order Group (DOG) CRUD
// =============================================================================

/// List all DOGs for a directive.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}/dogs",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "List of DOGs", body = DirectiveOrderGroupListResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn list_dogs(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::list_directive_order_groups(pool, id, auth.owner_id).await {
        Ok(dogs) => {
            let total = dogs.len() as i64;
            Json(DirectiveOrderGroupListResponse { dogs, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list DOGs: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("LIST_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Create a new DOG for a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/dogs",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = CreateDirectiveOrderGroupRequest,
    responses(
        (status = 201, description = "DOG created", body = DirectiveOrderGroup),
        (status = 400, description = "Invalid directive", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn create_dog(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(req): Json<CreateDirectiveOrderGroupRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify the directive exists and belongs to this owner
    match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new(
                    "INVALID_DIRECTIVE",
                    "directive_id must reference a valid directive owned by you",
                )),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("VALIDATION_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    match repository::create_directive_order_group(pool, id, auth.owner_id, req).await {
        Ok(dog) => (StatusCode::CREATED, Json(dog)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create DOG: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Get a DOG by ID.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}/dogs/{dog_id}",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("dog_id" = Uuid, Path, description = "DOG ID"),
    ),
    responses(
        (status = 200, description = "DOG details", body = DirectiveOrderGroup),
        (status = 404, description = "Not found", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn get_dog(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, dog_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let _ = id; // directive_id is in the path for REST nesting but we scope by owner_id

    match repository::get_directive_order_group(pool, dog_id, auth.owner_id).await {
        Ok(Some(dog)) => Json(dog).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "DOG not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to get DOG: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Update a DOG.
#[utoipa::path(
    patch,
    path = "/api/v1/directives/{id}/dogs/{dog_id}",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("dog_id" = Uuid, Path, description = "DOG ID"),
    ),
    request_body = UpdateDirectiveOrderGroupRequest,
    responses(
        (status = 200, description = "DOG updated", body = DirectiveOrderGroup),
        (status = 404, description = "Not found", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn update_dog(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, dog_id)): Path<(Uuid, Uuid)>,
    Json(req): Json<UpdateDirectiveOrderGroupRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let _ = id; // directive_id is in the path for REST nesting but we scope by owner_id

    // Validate status if provided
    if let Some(ref status) = req.status {
        if !["open", "in_progress", "done", "archived"].contains(&status.as_str()) {
            return (
                StatusCode::BAD_REQUEST,
                Json(ApiError::new(
                    "VALIDATION_FAILED",
                    "status must be one of: open, in_progress, done, archived",
                )),
            )
                .into_response();
        }
    }

    match repository::update_directive_order_group(pool, dog_id, auth.owner_id, req).await {
        Ok(Some(dog)) => Json(dog).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "DOG not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to update DOG: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("UPDATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Delete a DOG.
#[utoipa::path(
    delete,
    path = "/api/v1/directives/{id}/dogs/{dog_id}",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("dog_id" = Uuid, Path, description = "DOG ID"),
    ),
    responses(
        (status = 204, description = "Deleted"),
        (status = 404, description = "Not found", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn delete_dog(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, dog_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let _ = id; // directive_id is in the path for REST nesting but we scope by owner_id

    match repository::delete_directive_order_group(pool, dog_id, auth.owner_id).await {
        Ok(true) => StatusCode::NO_CONTENT.into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "DOG not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to delete DOG: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DELETE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// List orders belonging to a specific DOG.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}/dogs/{dog_id}/orders",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("dog_id" = Uuid, Path, description = "DOG ID"),
    ),
    responses(
        (status = 200, description = "List of orders in the DOG", body = OrderListResponse),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn list_dog_orders(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, dog_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    let _ = id; // directive_id is in the path for REST nesting but we scope by owner_id

    match repository::list_orders_by_dog(pool, dog_id, auth.owner_id).await {
        Ok(orders) => {
            let total = orders.len() as i64;
            Json(OrderListResponse { orders, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list orders for DOG: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("LIST_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Pick up orders for a specific DOG. Like the directive pick-up-orders
/// endpoint but filtered to orders belonging to the specified DOG.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/dogs/{dog_id}/pick-up-orders",
    params(
        ("id" = Uuid, Path, description = "Directive ID"),
        ("dog_id" = Uuid, Path, description = "DOG ID"),
    ),
    responses(
        (status = 200, description = "Orders picked up for planning", body = PickUpOrdersResponse),
        (status = 404, description = "Directive or DOG not found", body = ApiError),
        (status = 401, description = "Unauthorized", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directive Order Groups"
)]
pub async fn pick_up_dog_orders(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path((id, dog_id)): Path<(Uuid, Uuid)>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Verify directive ownership and get directive with steps
    let (directive, mut steps) =
        match repository::get_directive_with_steps_for_owner(pool, auth.owner_id, id).await {
            Ok(Some((d, s))) => (d, s),
            Ok(None) => {
                return (
                    StatusCode::NOT_FOUND,
                    Json(ApiError::new("NOT_FOUND", "Directive not found")),
                )
                    .into_response();
            }
            Err(e) => {
                tracing::error!("Failed to get directive: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GET_FAILED", &e.to_string())),
                )
                    .into_response();
            }
        };

    // Verify the DOG exists and belongs to this owner
    match repository::get_directive_order_group(pool, dog_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "DOG not found")),
            )
                .into_response();
        }
        Err(e) => {
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("GET_FAILED", &e.to_string())),
            )
                .into_response();
        }
    }

    // Auto-remove completed steps that were already included in a PR
    if directive.pr_url.is_some() || directive.pr_branch.is_some() {
        match crate::orchestration::directive::remove_already_merged_steps(pool, id).await {
            Ok(count) if count > 0 => {
                tracing::info!("Auto-removed {} completed steps already in PR for directive {}", count, id);
                steps = match repository::list_directive_steps(pool, id).await {
                    Ok(s) => s,
                    Err(e) => {
                        tracing::error!("Failed to re-fetch steps after cleanup: {}", e);
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(ApiError::new("REFETCH_STEPS_FAILED", &e.to_string())),
                        ).into_response();
                    }
                };
            }
            Err(e) => {
                tracing::warn!("Failed to auto-remove merged steps for directive {}: {}", id, e);
            }
            _ => {}
        }
    }

    // Reconcile existing orders
    match repository::reconcile_directive_orders(pool, auth.owner_id, id).await {
        Ok(count) => {
            if count > 0 {
                tracing::info!("Reconciled {} orders for directive {}", count, id);
            }
        }
        Err(e) => {
            tracing::warn!("Failed to reconcile directive orders: {}", e);
        }
    }

    // Fetch available orders filtered to this DOG
    let orders = match repository::get_available_orders_for_dog_pickup(pool, auth.owner_id, id, dog_id).await {
        Ok(o) => o,
        Err(e) => {
            tracing::error!("Failed to fetch available orders for DOG: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("FETCH_ORDERS_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // If no orders available, return early
    if orders.is_empty() {
        return Json(PickUpOrdersResponse {
            message: "No orders available to plan for this DOG".to_string(),
            order_count: 0,
            task_id: None,
        })
        .into_response();
    }

    let order_count = orders.len() as i64;
    let order_ids: Vec<Uuid> = orders.iter().map(|o| o.id).collect();

    // Get generation and goal history for the planning prompt
    let generation =
        match repository::get_directive_max_generation(pool, id).await {
            Ok(g) => g + 1,
            Err(e) => {
                tracing::error!("Failed to get max generation: {}", e);
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ApiError::new("GENERATION_FAILED", &e.to_string())),
                )
                    .into_response();
            }
        };

    let goal_history = match repository::get_directive_goal_history(pool, id, 3).await {
        Ok(h) => h,
        Err(e) => {
            tracing::warn!("Failed to get goal history: {}", e);
            vec![]
        }
    };

    // Build the specialized planning prompt
    let plan = build_order_pickup_prompt(&directive, &steps, &orders, generation, &goal_history);

    // Link orders to the directive
    if let Err(e) =
        repository::bulk_link_orders_to_directive(pool, auth.owner_id, &order_ids, id).await
    {
        tracing::error!("Failed to link orders to directive: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("LINK_ORDERS_FAILED", &e.to_string())),
        )
            .into_response();
    }

    // Mark picked-up orders as in_progress
    if let Err(e) =
        repository::bulk_update_order_status(pool, auth.owner_id, &order_ids, "in_progress").await
    {
        tracing::warn!("Failed to update order status to in_progress: {}", e);
    }

    // Create the planning task
    let req = CreateTaskRequest {
        contract_id: None,
        name: format!("Pick up DOG orders: {}", directive.title),
        description: Some("Directive order group pickup planning task".to_string()),
        plan,
        parent_task_id: None,
        is_supervisor: false,
        priority: 0,
        repository_url: directive.repository_url.clone(),
        base_branch: directive.base_branch.clone(),
        target_branch: None,
        merge_mode: None,
        target_repo_path: None,
        completion_action: None,
        continue_from_task_id: None,
        copy_files: None,
        checkpoint_sha: None,
        branched_from_task_id: None,
        conversation_history: None,
        supervisor_worktree_task_id: None,
        directive_id: Some(directive.id),
        directive_step_id: None,
    };

    let task = match repository::create_task_for_owner(pool, auth.owner_id, req).await {
        Ok(t) => t,
        Err(e) => {
            tracing::error!("Failed to create DOG pickup planning task: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_TASK_FAILED", &e.to_string())),
            )
                .into_response();
        }
    };

    // Assign as orchestrator task
    if let Err(e) = repository::assign_orchestrator_task(pool, id, task.id).await {
        tracing::error!("Failed to assign orchestrator task: {}", e);
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ApiError::new("ASSIGN_TASK_FAILED", &e.to_string())),
        )
            .into_response();
    }

    // Cancel old planning tasks
    let cancelled = repository::cancel_old_planning_tasks(pool, id, task.id).await;
    if let Ok(count) = cancelled {
        if count > 0 {
            tracing::info!(
                directive_id = %id,
                cancelled_count = count,
                "Cancelled old planning tasks superseded by DOG order pickup"
            );
        }
    }

    // Set directive to active if draft/idle/paused
    match directive.status.as_str() {
        "draft" | "idle" | "paused" => {
            if let Err(e) = repository::set_directive_status(pool, auth.owner_id, id, "active").await
            {
                tracing::warn!("Failed to set directive status to active: {}", e);
            }
        }
        _ => {}
    }

    // Advance ready steps
    let _ = repository::advance_directive_ready_steps(pool, id).await;

    Json(PickUpOrdersResponse {
        message: format!("Planning {} orders from DOG", order_count),
        order_count,
        task_id: Some(task.id),
    })
    .into_response()
}

// =============================================================================
// Directive Revisions (per-PR snapshots)
// =============================================================================

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DirectiveRevisionListResponse {
    pub revisions: Vec<DirectiveRevision>,
    pub total: i64,
}

/// Reset a directive for a new draft cycle — clears its goal and detaches
/// the current PR linkage. Past revisions remain attached as history.
///
/// Intended for the sidebar's "New draft" right-click on an inactive
/// directive: the contract has shipped, the user wants to start the next
/// iteration on a clean slate without losing the prior PR's record.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/new-draft",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Directive reset to draft", body = Directive),
        (status = 404, description = "Not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn new_directive_draft(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::reset_directive_for_new_draft(pool, auth.owner_id, id).await {
        Ok(Some(directive)) => Json(directive).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(ApiError::new("NOT_FOUND", "Directive not found")),
        )
            .into_response(),
        Err(e) => {
            tracing::error!("Failed to reset directive for new draft: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("RESET_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// List all per-PR revisions for a directive, newest first.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}/revisions",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "Revision history", body = DirectiveRevisionListResponse),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn list_directive_revisions(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::list_directive_revisions_for_owner(pool, auth.owner_id, id).await {
        Ok(revisions) => {
            let total = revisions.len() as i64;
            Json(DirectiveRevisionListResponse { revisions, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list directive revisions: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("LIST_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

// =============================================================================
// Ephemeral tasks under a directive
//
// A directive can spin up ad-hoc one-off tasks that are NOT part of its DAG.
// They live in the `tasks` table with `directive_id` set and
// `directive_step_id = NULL` — the existing schema already supports this; we
// just expose the create path through a directive-scoped endpoint and
// inherit repo/branch from the parent directive when the caller doesn't
// override.
// =============================================================================

/// Request body for creating an ephemeral task under a directive.
#[derive(Debug, serde::Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateDirectiveTaskRequest {
    /// Human-readable name (used for branch/commit names).
    pub name: String,
    /// Plan / instructions for the Claude Code session.
    pub plan: String,
    /// Optional override for the directive's repository.
    pub repository_url: Option<String>,
    /// Optional override for the directive's base branch.
    pub base_branch: Option<String>,
}

/// List the ephemeral tasks (no directive_step_id) attached to a directive.
#[utoipa::path(
    get,
    path = "/api/v1/directives/{id}/tasks",
    params(("id" = Uuid, Path, description = "Directive ID")),
    responses(
        (status = 200, description = "List of ephemeral tasks", body = crate::db::models::TaskListResponse),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn list_directive_tasks(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    match repository::list_ephemeral_directive_tasks_for_owner(pool, auth.owner_id, id).await {
        Ok(tasks) => {
            let total = tasks.len() as i64;
            Json(crate::db::models::TaskListResponse { tasks, total }).into_response()
        }
        Err(e) => {
            tracing::error!("Failed to list ephemeral tasks: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("LIST_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}

/// Create an ephemeral task attached to a directive.
#[utoipa::path(
    post,
    path = "/api/v1/directives/{id}/tasks",
    params(("id" = Uuid, Path, description = "Directive ID")),
    request_body = CreateDirectiveTaskRequest,
    responses(
        (status = 201, description = "Ephemeral task created", body = Task),
        (status = 404, description = "Directive not found", body = ApiError),
        (status = 503, description = "Database not configured", body = ApiError),
    ),
    security(("bearer_auth" = []), ("api_key" = [])),
    tag = "Directives"
)]
pub async fn create_directive_task(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(id): Path<Uuid>,
    Json(req): Json<CreateDirectiveTaskRequest>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ApiError::new("DB_UNAVAILABLE", "Database not configured")),
        )
            .into_response();
    };

    // Look up the parent directive so we can inherit its repository/base branch
    // when the caller doesn't override them. Also gates the request on
    // ownership: if the directive isn't visible to this owner, 404.
    let directive = match repository::get_directive_for_owner(pool, auth.owner_id, id).await {
        Ok(Some(d)) => d,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(ApiError::new("NOT_FOUND", "Directive not found")),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Failed to load directive for ephemeral task: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("DB_ERROR", &e.to_string())),
            )
                .into_response();
        }
    };

    let repo_url = req
        .repository_url
        .or_else(|| directive.repository_url.clone());
    let base_branch = req.base_branch.or_else(|| directive.base_branch.clone());

    let create_req = CreateTaskRequest {
        contract_id: None,
        name: req.name,
        description: None,
        plan: req.plan,
        parent_task_id: None,
        is_supervisor: false,
        priority: 0,
        repository_url: repo_url,
        base_branch,
        target_branch: None,
        merge_mode: None,
        target_repo_path: None,
        completion_action: None,
        continue_from_task_id: None,
        copy_files: None,
        checkpoint_sha: None,
        branched_from_task_id: None,
        conversation_history: None,
        supervisor_worktree_task_id: None,
        directive_id: Some(directive.id),
        // No directive_step_id — this is what makes the task "ephemeral":
        // it lives under the directive folder but isn't part of the DAG.
        directive_step_id: None,
    };

    match repository::create_task_for_owner(pool, auth.owner_id, create_req).await {
        Ok(task) => (StatusCode::CREATED, Json(task)).into_response(),
        Err(e) => {
            tracing::error!("Failed to create ephemeral directive task: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ApiError::new("CREATE_FAILED", &e.to_string())),
            )
                .into_response()
        }
    }
}