summaryrefslogblamecommitdiff
path: root/makima/src/server/handlers/contract_chat.rs
blob: 06b3a7cdb463c8588a623dd67a30ee065c1a5a0c (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
















                                                                                 




                                                                                                 


                 
                                                                     
                                                    

                                                             
                                                  
                                                                           

                                                            





















































































































































































































































































































































































































                                                                                                                                                                                                                                  

                                                                                            





                                                              

                                                                        
 
                                     
                                                                            




                                                           
                                                                                                                                                     




                                                                   
                                                                  


                                                               
                                

                       








                                                                       



















































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                   
                                                                       


















                                                                                                        
                                                          



                                                                   
                                 


                                       
                                                             




                                                                                       
                                                                      


                                          









                                                                     




                                                                            

















                                                                                                        

                                                                               
 


















                                                                                                                         
                                  
                                                                                                                               
                                      


                                                        
                        
















                                                                                                                           

                                                 
                                                                                   




                               























                                                                                            
                                               














                                            

                                            
                                                                               













































































                                                                                                 
                                               














                                                       

                                            
                                                                               









































































































                                                                                                                    

                                                                                              
                                                                                             

                                                                                           

                    
                              

              
















                                                                                                          
                                       

                                           

                                     
                           
                                 
                                                                               
















































                                                                                                                 

                                                                                                                           







                                                                              

                                                            







































                                                                                                 
                                                                                 
































                                                                                                        












                                                                                              

                                                                                                

                                                                               




                                                              



                                                                  
                                        

                               





















                                                                                                        



















                                                                                           

                                                                                                             




























                                                                                                                   













                                                                                                                                 
















                                                                                                                                                                                                                
                                                              



                                                                        
                                                         


                                                         
                                                                                             






                                                                                                                                                                           

                                                                                                              
                                                                               
                                                                                                                              
 


                                                                                      
                               




                                                                                   






                                                                            
                                                                                 

                                          
                                                 

                                                           



                                                                                         








































































































                                                                                               
                                                                                                              

                                                                                       




                                                                      
                                                                                                                                                                                     






                                                                                    
                                                                   








                                                                                














                                                                                  
                                                                                                              

                                                                                       





                                                                      


                                                                          
                                                

                                       





                                                                         
                                                

                                       

























                                                                                              















































































                                                                                                       
                                                   













                                                            
                                             

                                                
                                                                                   
























































































































































































































                                                                                                                       










































































































































































                                                                                                        
                                                                 
                                                            
                                      
                                  
                                 
                                       
                                  





































































































                                                                                                                          
                                                       

















                                                                                         
                                                     

                                                    
                                                                                       


























                                                                                                  























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                         























































































































































































                                                                                                                   





                                                                                       


                                    




                                                                                               















                                                                                                                   


                                                                               


                                    






                                                                                                     


















































































































































































                                                                                                                      
//! Chat endpoint for LLM-powered contract management.
//!
//! This handler provides an agentic loop for managing contracts: creating tasks,
//! adding files, managing repositories, and handling phase transitions.

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use utoipa::ToSchema;
use uuid::Uuid;

use crate::db::{
    models::{
        ContractChatHistoryResponse, ContractWithRelations, CreateTaskRequest, UpdateFileRequest,
        AddContractDefinitionRequest, UpdateContractDefinitionRequest, CreateChainRequest,
        CreateChainDirectiveRequest, CreateContractEvaluationRequest,
    },
    repository,
};
use crate::llm::{
    analyze_task_output, body_to_markdown, format_checklist_markdown,
    format_parsed_tasks, parse_tasks_from_breakdown,
    claude::{self, ClaudeClient, ClaudeError, ClaudeModel},
    groq::{GroqClient, GroqError, Message, ToolCallResponse},
    parse_contract_tool_call, ContractToolRequest,
    LlmModel, TaskInfo, ToolCall, ToolResult, UserQuestion, CONTRACT_TOOLS,
    format_transcript_for_analysis, calculate_speaker_stats,
    build_analysis_prompt, parse_analysis_response,
};
use crate::server::auth::Authenticated;
use crate::server::state::{DaemonCommand, SharedState};

/// Maximum number of tool-calling rounds to prevent infinite loops
const MAX_TOOL_ROUNDS: usize = 30;

#[derive(Debug, Clone, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ContractChatHistoryMessage {
    /// Role: "user" or "assistant"
    pub role: String,
    /// Message content
    pub content: String,
}

#[derive(Debug, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ContractChatRequest {
    /// The user's message/instruction
    pub message: String,
    /// Optional model selection: "claude-sonnet" (default), "claude-opus", or "groq"
    #[serde(default)]
    pub model: Option<String>,
    /// Optional conversation history for context continuity
    #[serde(default)]
    pub history: Option<Vec<ContractChatHistoryMessage>>,
}

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ContractChatResponse {
    /// The LLM's response message
    pub response: String,
    /// Tool calls that were executed
    pub tool_calls: Vec<ContractToolCallInfo>,
    /// Questions pending user answers (pauses conversation)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pending_questions: Option<Vec<UserQuestion>>,
}

#[derive(Debug, Serialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ContractToolCallInfo {
    pub name: String,
    pub result: ToolResult,
}

/// Enum to hold LLM clients
enum LlmClient {
    Groq(GroqClient),
    Claude(ClaudeClient),
}

/// Unified result from LLM call
struct LlmResult {
    content: Option<String>,
    tool_calls: Vec<ToolCall>,
    raw_tool_calls: Vec<ToolCallResponse>,
    finish_reason: String,
}

/// Helper to get contract with all relations
async fn get_contract_with_relations(
    pool: &sqlx::PgPool,
    contract_id: Uuid,
    owner_id: Uuid,
) -> Result<Option<ContractWithRelations>, sqlx::Error> {
    let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await? {
        Some(c) => c,
        None => return Ok(None),
    };

    let repositories = repository::list_contract_repositories(pool, contract_id)
        .await
        .unwrap_or_default();

    let files = repository::list_files_in_contract(pool, contract_id, owner_id)
        .await
        .unwrap_or_default();

    let tasks = repository::list_tasks_in_contract(pool, contract_id, owner_id)
        .await
        .unwrap_or_default();

    Ok(Some(ContractWithRelations {
        contract,
        repositories,
        files,
        tasks,
    }))
}

/// Chat with a contract using LLM tool calling for management
#[utoipa::path(
    post,
    path = "/api/v1/contracts/{id}/chat",
    request_body = ContractChatRequest,
    responses(
        (status = 200, description = "Chat completed successfully", body = ContractChatResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Contract not found"),
        (status = 500, description = "Internal server error")
    ),
    params(
        ("id" = Uuid, Path, description = "Contract ID")
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Contracts"
)]
pub async fn contract_chat_handler(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(contract_id): Path<Uuid>,
    Json(request): Json<ContractChatRequest>,
) -> impl IntoResponse {
    // Check if database is configured
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "Database not configured" })),
        )
            .into_response();
    };

    // Get the contract (scoped by owner)
    let contract = match get_contract_with_relations(pool, contract_id, auth.owner_id).await {
        Ok(Some(c)) => c,
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "Contract not found" })),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Database error: {}", e) })),
            )
                .into_response();
        }
    };

    // Parse model selection (default to Claude Sonnet)
    let model = request
        .model
        .as_ref()
        .and_then(|m| LlmModel::from_str(m))
        .unwrap_or(LlmModel::ClaudeSonnet);

    tracing::info!("Contract chat using LLM model: {:?}", model);

    // Initialize the appropriate LLM client
    let llm_client = match model {
        LlmModel::ClaudeSonnet => match ClaudeClient::from_env(ClaudeModel::Sonnet) {
            Ok(client) => LlmClient::Claude(client),
            Err(ClaudeError::MissingApiKey) => {
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    Json(json!({ "error": "ANTHROPIC_API_KEY not configured" })),
                )
                    .into_response();
            }
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": format!("Claude client error: {}", e) })),
                )
                    .into_response();
            }
        },
        LlmModel::ClaudeOpus => match ClaudeClient::from_env(ClaudeModel::Opus) {
            Ok(client) => LlmClient::Claude(client),
            Err(ClaudeError::MissingApiKey) => {
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    Json(json!({ "error": "ANTHROPIC_API_KEY not configured" })),
                )
                    .into_response();
            }
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": format!("Claude client error: {}", e) })),
                )
                    .into_response();
            }
        },
        LlmModel::GroqKimi => match GroqClient::from_env() {
            Ok(client) => LlmClient::Groq(client),
            Err(GroqError::MissingApiKey) => {
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    Json(json!({ "error": "GROQ_API_KEY not configured" })),
                )
                    .into_response();
            }
            Err(e) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({ "error": format!("Groq client error: {}", e) })),
                )
                    .into_response();
            }
        },
    };

    // Build contract context
    let contract_context = build_contract_context(&contract);

    // Build system prompt for contract management
    let system_prompt = format!(
        r#"You are an intelligent contract management agent. You guide users through the contract lifecycle from research to completion, helping them organize work, create documentation, set up repositories, and execute tasks.

## Your Capabilities
You have access to tools for:
- **Query**: get_contract_status, list_contract_files, list_contract_tasks, list_contract_repositories, read_file
- **File Management**: create_file_from_template, create_empty_file, list_available_templates
- **Task Management**: create_contract_task, delegate_content_generation, start_task
- **Phase Management**: get_phase_info, suggest_phase_transition, advance_phase
- **Repository Management**: list_daemon_directories, add_repository, set_primary_repository
- **Interactive**: ask_user

## Content Generation Deferral
When asked to write substantial content, fill templates, or generate documentation:
- **Use delegate_content_generation** to create a task for the content generation
- This delegates the work to a task agent that can do more thorough research and writing

**Use delegation for:**
- Filling in template content with real data
- Writing documentation based on requirements
- Generating user stories or specifications
- Creating detailed design documents
- Any substantial writing that requires research or analysis

**Direct actions (no delegation needed):**
- Listing files/tasks/repos
- Reading files
- Phase transitions
- Creating empty files or templates
- Simple queries and status checks
- Asking user questions

## Contract Lifecycle Phases

### 1. RESEARCH Phase
**Purpose**: Gather information and understand the problem space
**Key Activities**:
- Conduct user research and interviews
- Analyze competitors and existing solutions
- Document findings and insights
- Identify opportunities and constraints
**Suggested Actions**:
- Create a "Research Notes" document to capture findings
- Create a "Competitor Analysis" document
- When research is complete, suggest transitioning to Specify phase

### 2. SPECIFY Phase
**Purpose**: Define what needs to be built
**Key Activities**:
- Write clear requirements
- Create user stories with acceptance criteria
- Define scope and constraints
- Document technical constraints
**Suggested Actions**:
- Create a "Requirements" document
- Create "User Stories" with acceptance criteria
- When specifications are clear, suggest transitioning to Plan phase

### 3. PLAN Phase
**Purpose**: Design the solution and break down the work
**Key Activities**:
- Design system architecture
- Create technical specifications
- Break work into implementable tasks
- Set up repositories for development
**Suggested Actions**:
- Create an "Architecture" document
- Create a "Task Breakdown" document
- **IMPORTANT**: Help set up a repository if not already configured
- When planning is complete and a repository is set, suggest transitioning to Execute phase

### 4. EXECUTE Phase
**Purpose**: Implement the solution
**Key Activities**:
- Create and run tasks to implement features
- Write and run tests
- Track progress
- Document implementation decisions
**Suggested Actions**:
- Create tasks based on the task breakdown
- Monitor task progress and help resolve blockers
- When all tasks are complete, suggest transitioning to Review phase

### 5. REVIEW Phase
**Purpose**: Validate and document the completed work
**Key Activities**:
- Review completed work
- Create release notes
- Conduct retrospective
- Document learnings
**Suggested Actions**:
- Create a "Release Notes" document
- Create a "Retrospective" document
- Help mark the contract as complete when review is done

## Current Contract
{contract_context}

## Proactive Guidance

### Repository Setup (Critical for Plan/Execute phases)
When the user wants to add a local repository or set up for execution:
1. **First call list_daemon_directories** to get available paths from connected agents
2. Present the suggested directories to the user
3. Ask which path they want to use, or let them specify a custom path
4. Then call add_repository with the chosen path

Example flow:
```
User: "Set up a repository for this contract"
You: Call list_daemon_directories first
You: "I found these directories from your connected agent:
      - /Users/alice/projects (Working Directory)
      - /Users/alice/.makima/home (Makima Home)
      Which would you like to use, or provide a custom path?"
```

### Phase Transitions
- Phases progress in order: research -> specify -> plan -> execute -> review
- You can ONLY advance forward one step at a time to the NEXT phase
- ALWAYS use suggest_phase_transition FIRST to get the exact nextPhase value
- Then use advance_phase with that exact nextPhase value
- Example: If currentPhase is "specify", nextPhase will be "plan" - use advance_phase with new_phase="plan"
- NEVER suggest advancing to the same phase the contract is already in

### New Users
When a new contract is created or the user seems unsure:
1. Explain the current phase and what should be done
2. Suggest creating appropriate documents
3. Guide them toward the next milestone

## Agentic Behavior Guidelines

### 1. Understand Before Acting
- For complex requests, first gather information about the contract's current state
- Use get_contract_status or list_contract_files to understand what exists
- Consider the current phase when suggesting actions

### 2. Phase-Appropriate Suggestions
- Suggest templates and actions appropriate for the current phase
- When creating files, prefer templates that match the contract's phase
- Advise when the contract might be ready for the next phase

### 3. Help Plan Work
- When asked to plan work, read existing files to understand context
- Suggest creating tasks based on requirements or plans in files
- Offer to create task breakdowns from design documents

### 4. Repository Management
- When adding local repositories, ALWAYS use list_daemon_directories first to get suggestions
- This provides the user with valid paths from their connected agents
- Don't ask users to manually type paths when suggestions are available

### 5. Task Creation and Execution
- When creating tasks, derive plans from existing contract files when possible
- Use the contract's primary repository for tasks by default
- Create clear, actionable task plans
- After creating a task, you can use **start_task** to immediately begin execution
- A daemon must be connected for start_task to work

### 6. Be Proactive but Efficient
- Guide users through the contract flow
- Don't over-analyze simple requests
- Use the minimum number of tool calls needed
- Provide clear summaries of actions taken

## Important Notes
- This contract's ID is: {contract_id}
- All operations are scoped to this contract
- When creating tasks or files, they are automatically associated with this contract"#,
        contract_context = contract_context,
        contract_id = contract_id
    );

    // Run the agentic loop
    run_contract_agentic_loop(
        pool,
        &state,
        &llm_client,
        system_prompt,
        &request,
        contract_id,
        auth.owner_id,
    )
    .await
}

fn build_contract_context(contract: &crate::db::models::ContractWithRelations) -> String {
    let c = &contract.contract;
    let mut context = format!(
        "Name: {}\nID: {}\nPhase: {}\nStatus: {}\nContract Type: {}\nAutonomous Loop: {}\n",
        c.name, c.id, c.phase, c.status, c.contract_type, c.autonomous_loop
    );

    if let Some(ref desc) = c.description {
        context.push_str(&format!("Description: {}\n", desc));
    }

    // Get completed deliverables for the current phase
    let completed_deliverables = c.get_completed_deliverables(&c.phase);

    // Build task infos for checklist
    let task_infos: Vec<TaskInfo> = contract.tasks.iter().map(|t| TaskInfo {
        name: t.name.clone(),
        status: t.status.clone(),
    }).collect();

    let has_repository = !contract.repositories.is_empty();
    let phase_checklist = crate::llm::get_phase_checklist_for_type(&c.phase, &completed_deliverables, &task_infos, has_repository, &c.contract_type);

    // Add phase checklist to context
    context.push_str("\n");
    context.push_str(&format_checklist_markdown(&phase_checklist));

    // Add deliverable check result for phase transition readiness
    let deliverable_check = crate::llm::check_deliverables_met(
        &c.phase,
        &c.contract_type,
        &completed_deliverables,
        &task_infos,
        has_repository,
    );

    // Add deliverable prompt guidance
    context.push_str(&crate::llm::generate_deliverable_prompt_guidance(
        &c.phase,
        &c.contract_type,
        &deliverable_check,
    ));

    // Files summary
    context.push_str(&format!("\n### Files ({} total)\n", contract.files.len()));
    if !contract.files.is_empty() {
        for file in contract.files.iter().take(5) {
            let phase_label = file.contract_phase.as_deref().unwrap_or("none");
            context.push_str(&format!("- {} [{}] (ID: {})\n", file.name, phase_label, file.id));
        }
        if contract.files.len() > 5 {
            context.push_str(&format!("... and {} more\n", contract.files.len() - 5));
        }
    }

    // Tasks summary
    context.push_str(&format!("\n### Tasks ({} total)\n", contract.tasks.len()));
    if !contract.tasks.is_empty() {
        let pending = contract.tasks.iter().filter(|t| t.status == "pending").count();
        let running = contract.tasks.iter().filter(|t| t.status == "running").count();
        let done = contract.tasks.iter().filter(|t| t.status == "done").count();
        context.push_str(&format!("{} pending, {} running, {} done\n", pending, running, done));
        for task in contract.tasks.iter().take(5) {
            context.push_str(&format!("- {} ({}) - ID: {}\n", task.name, task.status, task.id));
        }
        if contract.tasks.len() > 5 {
            context.push_str(&format!("... and {} more\n", contract.tasks.len() - 5));
        }
    }

    // Repositories summary
    context.push_str(&format!("\n### Repositories ({} total)\n", contract.repositories.len()));
    if !contract.repositories.is_empty() {
        for repo in &contract.repositories {
            let primary = if repo.is_primary { " (primary)" } else { "" };
            let url_or_path = repo.repository_url.as_deref()
                .or(repo.local_path.as_deref())
                .unwrap_or("managed");
            context.push_str(&format!("- {}: {}{}\n", repo.name, url_or_path, primary));
        }
    }

    context
}

/// Summarize older conversation history to reduce token usage
async fn summarize_conversation_history(
    llm_client: &LlmClient,
    messages: &[&crate::db::models::ContractChatMessageRecord],
) -> String {
    // Build conversation text for summarization
    let mut conversation_text = String::new();
    for msg in messages {
        let role_label = if msg.role == "user" { "User" } else { "Assistant" };
        // Limit each message to avoid overwhelming the summarizer
        let content = if msg.content.len() > 500 {
            format!("{}...", &msg.content[..500])
        } else {
            msg.content.clone()
        };
        conversation_text.push_str(&format!("{}: {}\n", role_label, content));
    }

    // Limit total text to summarize
    if conversation_text.len() > 8000 {
        conversation_text = format!("{}...", &conversation_text[..8000]);
    }

    let summary_prompt = format!(
        "Summarize this conversation history in 2-3 sentences, focusing on key decisions, actions taken, and current state:\n\n{}",
        conversation_text
    );

    // Use a simple chat call without tools for summarization
    let summary = match llm_client {
        LlmClient::Claude(client) => {
            let claude_messages = vec![claude::Message {
                role: "user".to_string(),
                content: claude::MessageContent::Text(summary_prompt.clone()),
            }];
            match client.chat_with_tools(claude_messages, &[]).await {
                Ok(response) => response.content.unwrap_or_default(),
                Err(e) => {
                    tracing::warn!("Failed to summarize conversation: {}", e);
                    "Previous conversation covered contract management tasks.".to_string()
                }
            }
        }
        LlmClient::Groq(client) => {
            let groq_messages = vec![Message {
                role: "user".to_string(),
                content: Some(summary_prompt.clone()),
                tool_calls: None,
                tool_call_id: None,
            }];
            match client.chat_with_tools(groq_messages, &[]).await {
                Ok(response) => response.content.unwrap_or_default(),
                Err(e) => {
                    tracing::warn!("Failed to summarize conversation: {}", e);
                    "Previous conversation covered contract management tasks.".to_string()
                }
            }
        }
    };

    // Limit summary length
    if summary.len() > 500 {
        format!("{}...", &summary[..500])
    } else {
        summary
    }
}

/// Run the agentic loop for contract chat
async fn run_contract_agentic_loop(
    pool: &sqlx::PgPool,
    state: &SharedState,
    llm_client: &LlmClient,
    system_prompt: String,
    request: &ContractChatRequest,
    contract_id: Uuid,
    owner_id: Uuid,
) -> axum::response::Response {
    // Get or create the conversation for persistent history
    let conversation = match repository::get_or_create_contract_conversation(pool, contract_id, owner_id).await {
        Ok(conv) => conv,
        Err(e) => {
            tracing::error!("Failed to get/create contract conversation: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Failed to initialize conversation: {}", e) })),
            )
                .into_response();
        }
    };

    // Load ALL existing messages from database
    let saved_messages = match repository::list_contract_chat_messages(pool, conversation.id, None).await {
        Ok(msgs) => msgs,
        Err(e) => {
            tracing::warn!("Failed to load contract chat history: {}", e);
            Vec::new()
        }
    };

    // Build initial messages
    let mut messages = vec![Message {
        role: "system".to_string(),
        content: Some(system_prompt),
        tool_calls: None,
        tool_call_id: None,
    }];

    // Add saved conversation history, summarizing older messages if needed
    // to stay under rate limits (~25k chars ≈ ~6k tokens for history)
    const MAX_HISTORY_CHARS: usize = 25000;
    const RECENT_MESSAGES_TO_KEEP: usize = 6; // Keep last 3 turns intact

    // Filter to user/assistant messages only
    let history_messages: Vec<_> = saved_messages
        .iter()
        .filter(|m| m.role == "user" || m.role == "assistant")
        .collect();

    // Calculate total character count
    let total_chars: usize = history_messages.iter().map(|m| m.content.len()).sum();

    if total_chars > MAX_HISTORY_CHARS && history_messages.len() > RECENT_MESSAGES_TO_KEEP {
        // Need to summarize older messages
        let split_point = history_messages.len().saturating_sub(RECENT_MESSAGES_TO_KEEP);
        let older_messages = &history_messages[..split_point];
        let recent_messages = &history_messages[split_point..];

        // Generate summary of older conversation
        let summary = summarize_conversation_history(&llm_client, older_messages).await;

        // Add summary as context
        messages.push(Message {
            role: "user".to_string(),
            content: Some(format!("[Previous conversation summary: {}]", summary)),
            tool_calls: None,
            tool_call_id: None,
        });
        messages.push(Message {
            role: "assistant".to_string(),
            content: Some("I understand the previous context. Let's continue.".to_string()),
            tool_calls: None,
            tool_call_id: None,
        });

        // Add recent messages in full
        for saved_msg in recent_messages {
            messages.push(Message {
                role: saved_msg.role.clone(),
                content: Some(saved_msg.content.clone()),
                tool_calls: None,
                tool_call_id: None,
            });
        }

        tracing::info!(
            total_messages = history_messages.len(),
            summarized = older_messages.len(),
            kept_recent = recent_messages.len(),
            "Summarized older conversation history"
        );
    } else {
        // Add all messages directly
        for saved_msg in history_messages {
            messages.push(Message {
                role: saved_msg.role.clone(),
                content: Some(saved_msg.content.clone()),
                tool_calls: None,
                tool_call_id: None,
            });
        }
    }

    // Add current user message
    messages.push(Message {
        role: "user".to_string(),
        content: Some(request.message.clone()),
        tool_calls: None,
        tool_call_id: None,
    });

    // Save the user message to database
    if let Err(e) = repository::add_contract_chat_message(
        pool,
        conversation.id,
        "user",
        &request.message,
        None,
        None,
    ).await {
        tracing::warn!("Failed to save user message to contract chat history: {}", e);
    }

    // State for tracking
    let mut all_tool_call_infos: Vec<ContractToolCallInfo> = Vec::new();
    let mut final_response: Option<String> = None;
    let mut consecutive_failures = 0;
    const MAX_CONSECUTIVE_FAILURES: usize = 3;
    let mut pending_questions: Option<Vec<UserQuestion>> = None;

    // Multi-turn agentic tool calling loop
    for round in 0..MAX_TOOL_ROUNDS {
        tracing::info!(
            round = round,
            total_tool_calls = all_tool_call_infos.len(),
            "Contract agentic loop iteration"
        );

        // Check consecutive failures
        if consecutive_failures >= MAX_CONSECUTIVE_FAILURES {
            tracing::warn!(
                "Breaking contract loop due to {} consecutive failures",
                consecutive_failures
            );
            final_response = Some(
                "I encountered multiple consecutive errors and stopped. \
                Please check the contract state and try again."
                    .to_string(),
            );
            break;
        }

        // Call the appropriate LLM API
        let result = match llm_client {
            LlmClient::Groq(groq) => {
                match groq.chat_with_tools(messages.clone(), &CONTRACT_TOOLS).await {
                    Ok(r) => LlmResult {
                        content: r.content,
                        tool_calls: r.tool_calls,
                        raw_tool_calls: r.raw_tool_calls,
                        finish_reason: r.finish_reason,
                    },
                    Err(e) => {
                        tracing::error!("Groq API error: {}", e);
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(json!({ "error": format!("LLM API error: {}", e) })),
                        )
                            .into_response();
                    }
                }
            }
            LlmClient::Claude(claude_client) => {
                let claude_messages = claude::groq_messages_to_claude(&messages);
                match claude_client
                    .chat_with_tools(claude_messages, &CONTRACT_TOOLS)
                    .await
                {
                    Ok(r) => {
                        let raw_tool_calls: Vec<ToolCallResponse> = r
                            .tool_calls
                            .iter()
                            .map(|tc| ToolCallResponse {
                                id: tc.id.clone(),
                                call_type: "function".to_string(),
                                function: crate::llm::groq::FunctionCall {
                                    name: tc.name.clone(),
                                    arguments: tc.arguments.to_string(),
                                },
                            })
                            .collect();

                        LlmResult {
                            content: r.content,
                            tool_calls: r.tool_calls,
                            raw_tool_calls,
                            finish_reason: r.stop_reason,
                        }
                    }
                    Err(e) => {
                        tracing::error!("Claude API error: {}", e);
                        return (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            Json(json!({ "error": format!("LLM API error: {}", e) })),
                        )
                            .into_response();
                    }
                }
            }
        };

        // Check if there are tool calls to execute
        if result.tool_calls.is_empty() {
            final_response = result.content;
            break;
        }

        // Add assistant message with tool calls to conversation
        messages.push(Message {
            role: "assistant".to_string(),
            content: result.content.clone(),
            tool_calls: Some(result.raw_tool_calls.clone()),
            tool_call_id: None,
        });

        // Execute each tool call
        for (i, tool_call) in result.tool_calls.iter().enumerate() {
            tracing::info!(tool = %tool_call.name, round = round, "Executing contract tool call");

            // Parse the tool call
            let mut execution_result = parse_contract_tool_call(tool_call);

            // Handle async contract tool requests
            if let Some(contract_request) = execution_result.request.take() {
                let async_result =
                    handle_contract_request(pool, &state.daemon_connections, contract_request, contract_id, owner_id).await;
                execution_result.success = async_result.success;
                execution_result.message = async_result.message;
                execution_result.data = async_result.data;
            }

            // Track consecutive failures
            if execution_result.success {
                consecutive_failures = 0;
            } else {
                consecutive_failures += 1;
                tracing::warn!(
                    tool = %tool_call.name,
                    consecutive_failures = consecutive_failures,
                    "Contract tool call failed"
                );
            }

            // Check for pending user questions
            if let Some(questions) = execution_result.pending_questions {
                tracing::info!(
                    question_count = questions.len(),
                    "Contract LLM requesting user input"
                );
                pending_questions = Some(questions);
                all_tool_call_infos.push(ContractToolCallInfo {
                    name: tool_call.name.clone(),
                    result: ToolResult {
                        success: execution_result.success,
                        message: execution_result.message.clone(),
                    },
                });
                break;
            }

            // Build tool result message
            let result_content = if let Some(data) = &execution_result.data {
                json!({
                    "success": execution_result.success,
                    "message": execution_result.message,
                    "data": data
                })
                .to_string()
            } else {
                json!({
                    "success": execution_result.success,
                    "message": execution_result.message
                })
                .to_string()
            };

            // Add tool result message
            let tool_call_id = match llm_client {
                LlmClient::Groq(_) => result.raw_tool_calls[i].id.clone(),
                LlmClient::Claude(_) => tool_call.id.clone(),
            };

            messages.push(Message {
                role: "tool".to_string(),
                content: Some(result_content),
                tool_calls: None,
                tool_call_id: Some(tool_call_id),
            });

            // Track for response
            all_tool_call_infos.push(ContractToolCallInfo {
                name: tool_call.name.clone(),
                result: ToolResult {
                    success: execution_result.success,
                    message: execution_result.message,
                },
            });
        }

        // If user questions are pending, pause
        if pending_questions.is_some() {
            final_response = result.content;
            break;
        }

        // If finish reason indicates completion, exit loop
        let finish_lower = result.finish_reason.to_lowercase();
        if finish_lower == "stop" || finish_lower == "end_turn" {
            final_response = result.content;
            break;
        }
    }

    // Build response
    let response_text = final_response.unwrap_or_else(|| {
        if all_tool_call_infos.is_empty() {
            "I couldn't understand your request. Please try rephrasing.".to_string()
        } else {
            format!(
                "Done! Executed {} tool{}.",
                all_tool_call_infos.len(),
                if all_tool_call_infos.len() == 1 { "" } else { "s" }
            )
        }
    });

    // Save assistant response to database
    let tool_calls_json = if all_tool_call_infos.is_empty() {
        None
    } else {
        serde_json::to_value(&all_tool_call_infos).ok()
    };

    let pending_questions_json = pending_questions.as_ref().and_then(|q| serde_json::to_value(q).ok());

    if let Err(e) = repository::add_contract_chat_message(
        pool,
        conversation.id,
        "assistant",
        &response_text,
        tool_calls_json,
        pending_questions_json,
    ).await {
        tracing::warn!("Failed to save assistant response to contract chat history: {}", e);
    }

    (
        StatusCode::OK,
        Json(ContractChatResponse {
            response: response_text,
            tool_calls: all_tool_call_infos,
            pending_questions,
        }),
    )
        .into_response()
}

/// Result from handling an async contract tool request
struct ContractRequestResult {
    success: bool,
    message: String,
    data: Option<serde_json::Value>,
}

/// Handle async contract tool requests that require database access
async fn handle_contract_request(
    pool: &sqlx::PgPool,
    daemon_connections: &dashmap::DashMap<String, crate::server::state::DaemonConnectionInfo>,
    request: ContractToolRequest,
    contract_id: Uuid,
    owner_id: Uuid,
) -> ContractRequestResult {
    match request {
        ContractToolRequest::ListDaemonDirectories => {
            let mut directories = Vec::new();

            // Iterate over connected daemons belonging to this owner
            for entry in daemon_connections.iter() {
                let daemon = entry.value();

                // Only include daemons belonging to this owner
                if daemon.owner_id != owner_id {
                    continue;
                }

                // Add working directory if available
                if let Some(ref working_dir) = daemon.working_directory {
                    directories.push(json!({
                        "path": working_dir,
                        "label": "Working Directory",
                        "type": "working",
                        "hostname": daemon.hostname,
                    }));
                }

                // Add home directory if available
                if let Some(ref home_dir) = daemon.home_directory {
                    directories.push(json!({
                        "path": home_dir,
                        "label": "Makima Home",
                        "type": "home",
                        "hostname": daemon.hostname,
                    }));
                }
            }

            if directories.is_empty() {
                ContractRequestResult {
                    success: true,
                    message: "No daemon directories available. Connect a daemon to get directory suggestions.".to_string(),
                    data: Some(json!({ "directories": [] })),
                }
            } else {
                ContractRequestResult {
                    success: true,
                    message: format!("Found {} suggested directories from connected daemons", directories.len()),
                    data: Some(json!({ "directories": directories })),
                }
            }
        }

        ContractToolRequest::GetContractStatus => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let c = &cwr.contract;
                    ContractRequestResult {
                        success: true,
                        message: format!(
                            "Contract '{}' is in '{}' phase with status '{}'",
                            c.name, c.phase, c.status
                        ),
                        data: Some(json!({
                            "name": c.name,
                            "phase": c.phase,
                            "status": c.status,
                            "description": c.description,
                            "fileCount": cwr.files.len(),
                            "taskCount": cwr.tasks.len(),
                            "repositoryCount": cwr.repositories.len(),
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::ListContractFiles => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let files: Vec<serde_json::Value> = cwr
                        .files
                        .iter()
                        .map(|f| {
                            json!({
                                "fileId": f.id,
                                "name": f.name,
                                "description": f.description,
                                "phase": f.contract_phase,
                            })
                        })
                        .collect();

                    ContractRequestResult {
                        success: true,
                        message: format!("Found {} files", files.len()),
                        data: Some(json!({ "files": files })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::ListContractTasks => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let tasks: Vec<serde_json::Value> = cwr
                        .tasks
                        .iter()
                        .map(|t| {
                            json!({
                                "taskId": t.id,
                                "name": t.name,
                                "status": t.status,
                                "priority": t.priority,
                            })
                        })
                        .collect();

                    ContractRequestResult {
                        success: true,
                        message: format!("Found {} tasks", tasks.len()),
                        data: Some(json!({ "tasks": tasks })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::ListContractRepositories => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let repos: Vec<serde_json::Value> = cwr
                        .repositories
                        .iter()
                        .map(|r| {
                            json!({
                                "repositoryId": r.id,
                                "name": r.name,
                                "repositoryUrl": r.repository_url,
                                "localPath": r.local_path,
                                "isPrimary": r.is_primary,
                            })
                        })
                        .collect();

                    ContractRequestResult {
                        success: true,
                        message: format!("Found {} repositories", repos.len()),
                        data: Some(json!({ "repositories": repos })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::ReadFile { file_id } => {
            match repository::get_file_for_owner(pool, file_id, owner_id).await {
                Ok(Some(file)) => {
                    // Verify file belongs to this contract
                    if file.contract_id != Some(contract_id) {
                        return ContractRequestResult {
                            success: false,
                            message: "File does not belong to this contract".to_string(),
                            data: None,
                        };
                    }

                    // Convert body to markdown for LLM consumption
                    let markdown = body_to_markdown(&file.body);

                    ContractRequestResult {
                        success: true,
                        message: format!("Read file '{}'", file.name),
                        data: Some(json!({
                            "fileId": file.id,
                            "name": file.name,
                            "description": file.description,
                            "summary": file.summary,
                            "plainText": markdown,
                            "phase": file.contract_phase,
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "File not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::CreateEmptyFile { name, description } => {
            // Verify contract exists and get current phase
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Contract not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    }
                }
            };

            // Create the file with current contract phase
            let create_req = crate::db::models::CreateFileRequest {
                contract_id,
                name: Some(name.clone()),
                description,
                body: Vec::new(),
                transcript: Vec::new(),
                location: None,
                repo_file_path: None,
                contract_phase: Some(contract.phase.clone()),
            };

            match repository::create_file_for_owner(pool, owner_id, create_req).await {
                Ok(file) => ContractRequestResult {
                    success: true,
                    message: format!("Created empty file '{}'", name),
                    data: Some(json!({
                        "fileId": file.id,
                        "name": file.name,
                    })),
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to create file: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::MarkDeliverableComplete {
            deliverable_id,
            phase,
        } => {
            // Get the contract to determine current phase and contract type
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Contract not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    }
                }
            };

            // Use specified phase or default to current contract phase
            let target_phase = phase.unwrap_or_else(|| contract.phase.clone());

            // Validate the deliverable ID exists for this phase/contract type
            let phase_deliverables = crate::llm::get_phase_deliverables_for_type(&target_phase, &contract.contract_type);
            let deliverable_exists = phase_deliverables.deliverables.iter().any(|d| d.id == deliverable_id);

            if !deliverable_exists {
                let valid_ids: Vec<&str> = phase_deliverables.deliverables.iter().map(|d| d.id.as_str()).collect();
                return ContractRequestResult {
                    success: false,
                    message: format!(
                        "Invalid deliverable_id '{}' for {} phase. Valid IDs: {:?}",
                        deliverable_id, target_phase, valid_ids
                    ),
                    data: None,
                };
            }

            // Check if already completed
            if contract.is_deliverable_complete(&target_phase, &deliverable_id) {
                return ContractRequestResult {
                    success: true,
                    message: format!("Deliverable '{}' is already marked complete for {} phase", deliverable_id, target_phase),
                    data: Some(json!({
                        "deliverableId": deliverable_id,
                        "phase": target_phase,
                        "alreadyComplete": true,
                    })),
                };
            }

            // Mark the deliverable as complete
            match repository::mark_deliverable_complete(pool, contract_id, &target_phase, &deliverable_id).await {
                Ok(updated_contract) => {
                    let completed = updated_contract.get_completed_deliverables(&target_phase);
                    ContractRequestResult {
                        success: true,
                        message: format!("Marked deliverable '{}' as complete for {} phase", deliverable_id, target_phase),
                        data: Some(json!({
                            "deliverableId": deliverable_id,
                            "phase": target_phase,
                            "completedDeliverables": completed,
                        })),
                    }
                }
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to mark deliverable complete: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::CreateContractTask {
            name,
            plan,
            repository_url,
            base_branch,
        } => {
            // Get primary repository if not specified
            let repo_url = if repository_url.is_some() {
                repository_url
            } else {
                // Find primary repository
                match get_contract_with_relations(pool, contract_id, owner_id).await {
                    Ok(Some(contract)) => {
                        contract
                            .repositories
                            .iter()
                            .find(|r| r.is_primary)
                            .and_then(|r| r.repository_url.clone().or(r.local_path.clone()))
                    }
                    _ => None,
                }
            };

            let create_req = CreateTaskRequest {
                contract_id: Some(contract_id),
                name: name.clone(),
                description: None,
                plan,
                parent_task_id: None,
                repository_url: repo_url,
                base_branch,
                target_branch: None,
                merge_mode: None,
                priority: 0,
                target_repo_path: None,
                completion_action: None,
                continue_from_task_id: None,
                copy_files: None,
                is_supervisor: false,
                checkpoint_sha: None,
                branched_from_task_id: None,
                conversation_history: None,
                supervisor_worktree_task_id: None, // Not spawned by supervisor
            };

            match repository::create_task_for_owner(pool, owner_id, create_req).await {
                Ok(task) => ContractRequestResult {
                    success: true,
                    message: format!("Created task '{}' in contract", name),
                    data: Some(json!({
                        "taskId": task.id,
                        "name": task.name,
                        "status": task.status,
                    })),
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to create task: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::DelegateContentGeneration {
            file_id,
            instruction,
            context,
        } => {
            // Build a task plan that includes the content generation instruction
            let mut plan = format!(
                "Content Generation Task\n\n\
                ## Instruction\n{}\n\n",
                instruction
            );

            if let Some(ctx) = context {
                plan.push_str(&format!("## Context\n{}\n\n", ctx));
            }

            // If file_id is provided, get file details and include them
            let (file_name, file_info) = if let Some(fid) = file_id {
                match repository::get_file_for_owner(pool, fid, owner_id).await {
                    Ok(Some(file)) => {
                        let info = format!(
                            "## Target File\n\
                            - File ID: {}\n\
                            - Name: {}\n\
                            - Description: {}\n\n\
                            The generated content should be structured to update this file.\n",
                            fid,
                            file.name,
                            file.description.as_deref().unwrap_or("(no description)")
                        );
                        (Some(file.name.clone()), Some(info))
                    }
                    _ => (None, None),
                }
            } else {
                (None, None)
            };

            if let Some(info) = file_info {
                plan.push_str(&info);
            }

            // Get primary repository
            let repo_url = match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(contract)) => contract
                    .repositories
                    .iter()
                    .find(|r| r.is_primary)
                    .and_then(|r| r.repository_url.clone().or(r.local_path.clone())),
                _ => None,
            };

            let task_name = format!(
                "Generate content{}",
                file_name.map(|n| format!(": {}", n)).unwrap_or_default()
            );

            let create_req = CreateTaskRequest {
                contract_id: Some(contract_id),
                name: task_name.clone(),
                description: Some(instruction.clone()),
                plan,
                parent_task_id: None,
                repository_url: repo_url,
                base_branch: None,
                target_branch: None,
                merge_mode: None,
                priority: 0,
                target_repo_path: None,
                completion_action: None,
                continue_from_task_id: None,
                copy_files: None,
                is_supervisor: false,
                checkpoint_sha: None,
                branched_from_task_id: None,
                conversation_history: None,
                supervisor_worktree_task_id: None, // Not spawned by supervisor
            };

            match repository::create_task_for_owner(pool, owner_id, create_req).await {
                Ok(task) => ContractRequestResult {
                    success: true,
                    message: format!(
                        "Created content generation task '{}'. Start the task to generate the content.",
                        task_name
                    ),
                    data: Some(json!({
                        "taskId": task.id,
                        "name": task.name,
                        "status": task.status,
                        "targetFileId": file_id,
                    })),
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to create content generation task: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::StartTask { task_id } => {
            // Get the task
            let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
                Ok(Some(t)) => t,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Task not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Failed to get task: {}", e),
                        data: None,
                    }
                }
            };

            // Check if task can be started
            let startable_statuses = ["pending", "failed", "interrupted", "done", "merged"];
            if !startable_statuses.contains(&task.status.as_str()) {
                return ContractRequestResult {
                    success: false,
                    message: format!("Task cannot be started from status: {}", task.status),
                    data: None,
                };
            }

            // Find a connected daemon for this owner
            let daemon_entry = daemon_connections
                .iter()
                .find(|d| d.value().owner_id == owner_id);

            let (target_daemon_id, command_sender) = match daemon_entry {
                Some(entry) => {
                    let daemon = entry.value();
                    (daemon.id, daemon.command_sender.clone())
                }
                None => {
                    return ContractRequestResult {
                        success: false,
                        message: "No daemon connected. Start a daemon to run tasks.".to_string(),
                        data: None,
                    };
                }
            };

            // Check if this is an orchestrator
            let subtask_count = match repository::list_subtasks_for_owner(pool, task_id, owner_id).await {
                Ok(subtasks) => subtasks.len(),
                Err(_) => 0,
            };
            let is_orchestrator = task.depth == 0 && subtask_count > 0;

            // Update task status to 'starting' and assign daemon_id
            let update_req = crate::db::models::UpdateTaskRequest {
                status: Some("starting".to_string()),
                daemon_id: Some(target_daemon_id),
                version: Some(task.version),
                ..Default::default()
            };

            let _updated_task = match repository::update_task_for_owner(pool, task_id, owner_id, update_req).await {
                Ok(Some(t)) => t,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Task not found".to_string(),
                        data: None,
                    };
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Failed to update task: {}", e),
                        data: None,
                    };
                }
            };

            // Get local_only and auto_merge_local from contract if task has one
            let (local_only, auto_merge_local) = if let Some(contract_id) = task.contract_id {
                match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                    Ok(Some(contract)) => (contract.local_only, contract.auto_merge_local),
                    _ => (false, false),
                }
            } else {
                (false, false)
            };

            // Send SpawnTask command to daemon
            let command = DaemonCommand::SpawnTask {
                task_id,
                task_name: task.name.clone(),
                plan: task.plan.clone(),
                repo_url: task.repository_url.clone(),
                base_branch: task.base_branch.clone(),
                target_branch: task.target_branch.clone(),
                parent_task_id: task.parent_task_id,
                depth: task.depth,
                is_orchestrator,
                target_repo_path: task.target_repo_path.clone(),
                completion_action: task.completion_action.clone(),
                continue_from_task_id: task.continue_from_task_id,
                copy_files: task.copy_files.as_ref().and_then(|v| serde_json::from_value(v.clone()).ok()),
                contract_id: task.contract_id,
                is_supervisor: task.is_supervisor,
                autonomous_loop: false,
                resume_session: false,
                conversation_history: None,
                patch_data: None,
                patch_base_sha: None,
                local_only,
                auto_merge_local,
                supervisor_worktree_task_id: None, // Not spawned by supervisor
            };

            if let Err(e) = command_sender.send(command).await {
                // Rollback: reset status since command failed
                let rollback_req = crate::db::models::UpdateTaskRequest {
                    status: Some("pending".to_string()),
                    clear_daemon_id: true,
                    ..Default::default()
                };
                let _ = repository::update_task_for_owner(pool, task_id, owner_id, rollback_req).await;
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to send task to daemon: {}", e),
                    data: None,
                };
            }

            // Note: TaskUpdateNotification broadcast is handled by the mesh handler when daemon reports status
            ContractRequestResult {
                success: true,
                message: format!("Started task '{}'. The task is now running on a connected daemon.", task.name),
                data: Some(json!({
                    "taskId": task_id,
                    "name": task.name,
                    "status": "starting",
                })),
            }
        }

        ContractToolRequest::GetPhaseInfo => {
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Contract not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    }
                }
            };

            let phase_info = get_phase_description(&contract.phase);
            let phase_deliverables = crate::llm::get_phase_deliverables_for_type(&contract.phase, &contract.contract_type);
            let deliverable_names: Vec<String> = phase_deliverables.deliverables.iter().map(|d| d.name.clone()).collect();

            ContractRequestResult {
                success: true,
                message: format!("Contract is in '{}' phase", contract.phase),
                data: Some(json!({
                    "phase": contract.phase,
                    "description": phase_info.0,
                    "activities": phase_info.1,
                    "deliverables": deliverable_names,
                    "guidance": phase_deliverables.guidance,
                    "nextPhase": get_next_phase(&contract.phase),
                })),
            }
        }

        ContractToolRequest::SuggestPhaseTransition => {
            let contract = match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Contract not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    }
                }
            };

            let analysis = analyze_phase_readiness(&contract);

            ContractRequestResult {
                success: true,
                message: analysis.summary.clone(),
                data: Some(json!({
                    "currentPhase": contract.contract.phase,
                    "nextPhase": get_next_phase(&contract.contract.phase),
                    "ready": analysis.ready,
                    "summary": analysis.summary,
                    "reasons": analysis.reasons,
                    "suggestions": analysis.suggestions,
                })),
            }
        }

        ContractToolRequest::AdvancePhase { new_phase, confirmed, feedback } => {
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Contract not found".to_string(),
                        data: None,
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    }
                }
            };

            // Validate phase transition
            let current_phase = &contract.phase;
            let valid_next = get_next_phase(current_phase);

            if valid_next.as_deref() != Some(&new_phase) {
                return ContractRequestResult {
                    success: false,
                    message: format!(
                        "Cannot transition from '{}' to '{}'. Next valid phase is: {:?}",
                        current_phase, new_phase, valid_next
                    ),
                    data: None,
                };
            }

            // Check if deliverables are met before allowing transition
            let cwr = match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) | Err(_) => {
                    // Fall through - we'll just skip the deliverables check
                    return ContractRequestResult {
                        success: false,
                        message: "Failed to load contract for deliverables check".to_string(),
                        data: None,
                    };
                }
            };

            // Get completed deliverables for the current phase
            let completed_deliverables = cwr.contract.get_completed_deliverables(current_phase);

            let task_infos: Vec<TaskInfo> = cwr.tasks.iter().map(|t| TaskInfo {
                name: t.name.clone(),
                status: t.status.clone(),
            }).collect();

            let has_repository = !cwr.repositories.is_empty();

            let check_result = crate::llm::check_deliverables_met(
                current_phase,
                &contract.contract_type,
                &completed_deliverables,
                &task_infos,
                has_repository,
            );

            // Block transition if deliverables are not met
            if !check_result.deliverables_met {
                return ContractRequestResult {
                    success: false,
                    message: format!(
                        "Cannot advance to '{}' phase: deliverables not met. {}",
                        new_phase, check_result.summary
                    ),
                    data: Some(json!({
                        "status": "deliverables_not_met",
                        "currentPhase": current_phase,
                        "requestedPhase": new_phase,
                        "deliverablesMet": false,
                        "requiredDeliverables": check_result.required_deliverables,
                        "missing": check_result.missing,
                        "action": "Complete the missing deliverables before advancing to the next phase"
                    })),
                };
            }

            // Check if phase_guard is enabled
            if contract.phase_guard {
                // If user provided feedback, return it for the task to address
                if let Some(ref user_feedback) = feedback {
                    return ContractRequestResult {
                        success: true,
                        message: format!(
                            "Phase transition to '{}' requires changes. User feedback: {}",
                            new_phase, user_feedback
                        ),
                        data: Some(json!({
                            "status": "changes_requested",
                            "currentPhase": current_phase,
                            "requestedPhase": new_phase,
                            "feedback": user_feedback,
                            "action": "Address the user feedback and try again when ready"
                        })),
                    };
                }

                // If not confirmed, return requires_confirmation with phase deliverables
                // This applies to ALL callers (including supervisors) - phase_guard enforcement at API level
                if !confirmed {
                    // Get files created in this phase
                    let phase_files = match repository::list_files_in_contract(pool, contract_id, owner_id).await {
                        Ok(files) => files
                            .into_iter()
                            .filter(|f| f.contract_phase.as_deref() == Some(current_phase))
                            .map(|f| json!({
                                "id": f.id,
                                "name": f.name,
                                "description": f.description
                            }))
                            .collect::<Vec<_>>(),
                        Err(_) => Vec::new(),
                    };

                    // Get tasks completed in this contract
                    let phase_tasks = match repository::list_tasks_in_contract(pool, contract_id, owner_id).await {
                        Ok(tasks) => tasks
                            .into_iter()
                            .filter(|t| t.status == "done" || t.status == "completed")
                            .map(|t| json!({
                                "id": t.id,
                                "name": t.name,
                                "status": t.status
                            }))
                            .collect::<Vec<_>>(),
                        Err(_) => Vec::new(),
                    };

                    // Get phase deliverables with completion status
                    let phase_deliverables = crate::llm::get_phase_deliverables_for_type(current_phase, &contract.contract_type);
                    let completed_deliverables = contract.get_completed_deliverables(current_phase);

                    let deliverables: Vec<serde_json::Value> = phase_deliverables
                        .deliverables
                        .iter()
                        .map(|d| json!({
                            "id": d.id,
                            "name": d.name,
                            "completed": completed_deliverables.contains(&d.id)
                        }))
                        .collect();

                    // Build deliverables summary
                    let deliverables_summary = format!(
                        "Phase '{}' deliverables: {} files created, {} tasks completed.",
                        current_phase,
                        phase_files.len(),
                        phase_tasks.len()
                    );

                    let transition_id = uuid::Uuid::new_v4().to_string();

                    return ContractRequestResult {
                        success: true,
                        message: format!(
                            "Phase transition to '{}' requires user confirmation. Review the deliverables and call advance_phase again with confirmed=true to proceed, or provide feedback to request changes.",
                            new_phase
                        ),
                        data: Some(json!({
                            "status": "requires_confirmation",
                            "transitionId": transition_id,
                            "currentPhase": current_phase,
                            "nextPhase": new_phase,
                            "deliverablesSummary": deliverables_summary,
                            "deliverables": deliverables,
                            "phaseFiles": phase_files,
                            "phaseTasks": phase_tasks,
                            "requiresConfirmation": true,
                            "message": "Phase guard is enabled. User confirmation required.",
                            "instructions": "To proceed: call advance_phase with confirmed=true. To request changes: call advance_phase with feedback='your feedback here'"
                        })),
                    };
                }
            }

            // Update phase (either phase_guard is disabled, or user confirmed)
            match repository::change_contract_phase_for_owner(pool, contract_id, owner_id, &new_phase).await {
                Ok(Some(updated)) => {
                    // Get deliverables for the new phase (using contract type)
                    let phase_deliverables = crate::llm::get_phase_deliverables_for_type(&new_phase, &contract.contract_type);

                    // Build deliverables list
                    let deliverables_list: Vec<serde_json::Value> = phase_deliverables
                        .deliverables
                        .iter()
                        .map(|d| json!({
                            "id": d.id,
                            "name": d.name,
                            "priority": format!("{:?}", d.priority).to_lowercase(),
                            "description": d.description,
                        }))
                        .collect();

                    ContractRequestResult {
                        success: true,
                        message: format!(
                            "Advanced contract from '{}' to '{}' phase. {}",
                            current_phase, new_phase, phase_deliverables.guidance
                        ),
                        data: Some(json!({
                            "status": "advanced",
                            "previousPhase": current_phase,
                            "newPhase": updated.phase,
                            "phaseGuidance": phase_deliverables.guidance,
                            "deliverables": deliverables_list,
                            "requiresRepository": phase_deliverables.requires_repository,
                            "requiresTasks": phase_deliverables.requires_tasks,
                        })),
                    }
                },
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Failed to update phase".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to update phase: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::AddRepository {
            repo_type,
            name,
            url,
            is_primary,
        } => {
            let add_result = match repo_type.as_str() {
                "remote" => {
                    let url = url.unwrap_or_default();
                    repository::add_remote_repository(
                        pool,
                        contract_id,
                        &name,
                        &url,
                        is_primary,
                    )
                    .await
                }
                "local" => {
                    let path = url.unwrap_or_default();
                    repository::add_local_repository(
                        pool,
                        contract_id,
                        &name,
                        &path,
                        is_primary,
                    )
                    .await
                }
                "managed" => {
                    repository::create_managed_repository(pool, contract_id, &name, is_primary)
                        .await
                }
                _ => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Invalid repository type: {}", repo_type),
                        data: None,
                    }
                }
            };

            match add_result {
                Ok(repo) => ContractRequestResult {
                    success: true,
                    message: format!("Added {} repository '{}'", repo_type, name),
                    data: Some(json!({
                        "repositoryId": repo.id,
                        "name": repo.name,
                        "isPrimary": repo.is_primary,
                    })),
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to add repository: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::SetPrimaryRepository { repository_id } => {
            match repository::set_repository_primary(pool, repository_id, contract_id).await {
                Ok(true) => ContractRequestResult {
                    success: true,
                    message: "Set repository as primary".to_string(),
                    data: Some(json!({
                        "repositoryId": repository_id,
                    })),
                },
                Ok(false) => ContractRequestResult {
                    success: false,
                    message: "Repository not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to set primary repository: {}", e),
                    data: None,
                },
            }
        }

        // =============================================================================
        // Phase Guidance Handlers
        // =============================================================================

        ContractToolRequest::GetPhaseChecklist => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let completed_deliverables = cwr.contract.get_completed_deliverables(&cwr.contract.phase);

                    let task_infos: Vec<TaskInfo> = cwr.tasks.iter().map(|t| TaskInfo {
                        name: t.name.clone(),
                        status: t.status.clone(),
                    }).collect();

                    let has_repository = !cwr.repositories.is_empty();
                    let checklist = crate::llm::get_phase_checklist_for_type(&cwr.contract.phase, &completed_deliverables, &task_infos, has_repository, &cwr.contract.contract_type);

                    ContractRequestResult {
                        success: true,
                        message: checklist.summary.clone(),
                        data: Some(json!({
                            "phase": checklist.phase,
                            "completionPercentage": checklist.completion_percentage,
                            "deliverables": checklist.deliverables,
                            "hasRepository": checklist.has_repository,
                            "repositoryRequired": checklist.repository_required,
                            "taskStats": checklist.task_stats,
                            "suggestions": checklist.suggestions,
                            "summary": checklist.summary,
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::CheckDeliverablesMet => {
            match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(cwr)) => {
                    let completed_deliverables = cwr.contract.get_completed_deliverables(&cwr.contract.phase);

                    let task_infos: Vec<TaskInfo> = cwr.tasks.iter().map(|t| TaskInfo {
                        name: t.name.clone(),
                        status: t.status.clone(),
                    }).collect();

                    let has_repository = !cwr.repositories.is_empty();

                    let check_result = crate::llm::check_deliverables_met(
                        &cwr.contract.phase,
                        &cwr.contract.contract_type,
                        &completed_deliverables,
                        &task_infos,
                        has_repository,
                    );

                    // Check if we should auto-progress
                    let auto_progress = crate::llm::should_auto_progress(
                        &cwr.contract.phase,
                        &cwr.contract.contract_type,
                        &completed_deliverables,
                        &task_infos,
                        has_repository,
                        cwr.contract.autonomous_loop,
                    );

                    ContractRequestResult {
                        success: true,
                        message: check_result.summary.clone(),
                        data: Some(json!({
                            "deliverablesMet": check_result.deliverables_met,
                            "readyToAdvance": check_result.ready_to_advance,
                            "phase": check_result.phase,
                            "nextPhase": check_result.next_phase,
                            "requiredDeliverables": check_result.required_deliverables,
                            "missing": check_result.missing,
                            "summary": check_result.summary,
                            "autoProgressRecommended": check_result.auto_progress_recommended,
                            "autoProgress": {
                                "shouldProgress": auto_progress.should_progress,
                                "nextPhase": auto_progress.next_phase,
                                "reason": auto_progress.reason,
                                "action": format!("{:?}", auto_progress.action),
                            },
                            "autonomousLoop": cwr.contract.autonomous_loop,
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        // =============================================================================
        // Task Derivation Handlers
        // =============================================================================

        ContractToolRequest::DeriveTasksFromFile { file_id } => {
            // First get the file
            match repository::get_file_for_owner(pool, file_id, owner_id).await {
                Ok(Some(file)) => {
                    // Verify file belongs to this contract
                    if file.contract_id != Some(contract_id) {
                        return ContractRequestResult {
                            success: false,
                            message: "File does not belong to this contract".to_string(),
                            data: None,
                        };
                    }

                    // Convert body to markdown for task parsing
                    let markdown = body_to_markdown(&file.body);

                    // Parse tasks from the content
                    let parse_result = parse_tasks_from_breakdown(&markdown);

                    ContractRequestResult {
                        success: true,
                        message: format!("Found {} tasks in file '{}'", parse_result.total, file.name),
                        data: Some(json!({
                            "fileId": file_id,
                            "fileName": file.name,
                            "tasks": parse_result.tasks,
                            "groups": parse_result.groups,
                            "total": parse_result.total,
                            "warnings": parse_result.warnings,
                            "formatted": format_parsed_tasks(&parse_result),
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "File not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::CreateChainedTasks { tasks } => {
            // Get primary repository for tasks
            let repo_url = match get_contract_with_relations(pool, contract_id, owner_id).await {
                Ok(Some(contract)) => {
                    contract
                        .repositories
                        .iter()
                        .find(|r| r.is_primary)
                        .and_then(|r| r.repository_url.clone().or(r.local_path.clone()))
                }
                _ => None,
            };

            let mut created_tasks = Vec::new();
            let mut previous_task_id: Option<Uuid> = None;

            for task_def in &tasks {
                let create_req = CreateTaskRequest {
                    contract_id: Some(contract_id),
                    name: task_def.name.clone(),
                    description: None,
                    plan: task_def.plan.clone(),
                    parent_task_id: None,
                    repository_url: repo_url.clone(),
                    base_branch: None,
                    target_branch: None,
                    merge_mode: None,
                    priority: 0,
                    target_repo_path: None,
                    completion_action: None,
                    continue_from_task_id: previous_task_id,
                    copy_files: None,
                    is_supervisor: false,
                        checkpoint_sha: None,
                    branched_from_task_id: None,
                    conversation_history: None,
                    supervisor_worktree_task_id: None, // Not spawned by supervisor
                };

                match repository::create_task_for_owner(pool, owner_id, create_req).await {
                    Ok(task) => {
                        created_tasks.push(json!({
                            "taskId": task.id,
                            "name": task.name,
                            "status": task.status,
                            "chainedFrom": previous_task_id,
                        }));
                        previous_task_id = Some(task.id);
                    }
                    Err(e) => {
                        return ContractRequestResult {
                            success: false,
                            message: format!("Failed to create task '{}': {}", task_def.name, e),
                            data: Some(json!({
                                "createdSoFar": created_tasks,
                            })),
                        };
                    }
                }
            }

            ContractRequestResult {
                success: true,
                message: format!("Created {} chained tasks", created_tasks.len()),
                data: Some(json!({
                    "tasks": created_tasks,
                    "total": created_tasks.len(),
                })),
            }
        }

        // =============================================================================
        // Task Completion Processing Handlers
        // =============================================================================

        ContractToolRequest::ProcessTaskCompletion { task_id } => {
            // Get the task
            match repository::get_task_for_owner(pool, task_id, owner_id).await {
                Ok(Some(task)) => {
                    // Verify task belongs to this contract
                    if task.contract_id != Some(contract_id) {
                        return ContractRequestResult {
                            success: false,
                            message: "Task does not belong to this contract".to_string(),
                            data: None,
                        };
                    }

                    // Get contract for context
                    let contract = get_contract_with_relations(pool, contract_id, owner_id).await.ok().flatten();

                    let total_tasks = contract.as_ref().map(|c| c.tasks.len()).unwrap_or(0);
                    let completed_tasks = contract.as_ref()
                        .map(|c| c.tasks.iter().filter(|t| t.status == "done").count())
                        .unwrap_or(0);

                    // Note: Finding next chained task would require querying full Task objects
                    // Since TaskSummary doesn't have continue_from_task_id, we skip this for now
                    let next_task: Option<(Uuid, String)> = None;

                    // Find Dev Notes file if exists
                    let dev_notes = if let Some(ref c) = contract {
                        c.files.iter()
                            .find(|f| f.name.to_lowercase().contains("dev") && f.name.to_lowercase().contains("notes"))
                            .map(|f| (f.id, f.name.clone()))
                    } else {
                        None
                    };

                    let contract_phase = contract.as_ref()
                        .map(|c| c.contract.phase.clone())
                        .unwrap_or_else(|| "execute".to_string());

                    // Analyze the task output
                    let analysis = analyze_task_output(
                        task_id,
                        &task.name,
                        task.last_output.as_deref(),
                        task.progress_summary.as_deref(),
                        &contract_phase,
                        total_tasks,
                        completed_tasks,
                        next_task,
                        dev_notes,
                    );

                    ContractRequestResult {
                        success: true,
                        message: format!("Analyzed completion of task '{}'", task.name),
                        data: Some(json!({
                            "taskId": task_id,
                            "taskName": task.name,
                            "taskStatus": task.status,
                            "summary": analysis.summary,
                            "filesAffected": analysis.files_affected,
                            "nextSteps": analysis.next_steps,
                            "phaseImpact": analysis.phase_impact,
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Task not found".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::UpdateFileFromTask { file_id, task_id, section_title } => {
            // Get the task
            let task = match repository::get_task_for_owner(pool, task_id, owner_id).await {
                Ok(Some(t)) => t,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "Task not found".to_string(),
                        data: None,
                    };
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    };
                }
            };

            // Get the file
            let file = match repository::get_file_for_owner(pool, file_id, owner_id).await {
                Ok(Some(f)) => f,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "File not found".to_string(),
                        data: None,
                    };
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    };
                }
            };

            // Verify file belongs to this contract
            if file.contract_id != Some(contract_id) {
                return ContractRequestResult {
                    success: false,
                    message: "File does not belong to this contract".to_string(),
                    data: None,
                };
            }

            // Build the section to add
            let title = section_title.unwrap_or_else(|| format!("Task: {}", task.name));
            let result_text = task.last_output.as_deref().unwrap_or("Task completed");

            // Create new body elements to append
            let mut new_body = file.body.clone();
            new_body.push(crate::db::models::BodyElement::Heading {
                level: 2,
                text: title,
            });
            new_body.push(crate::db::models::BodyElement::Paragraph {
                text: format!("Status: {}", task.status),
            });
            new_body.push(crate::db::models::BodyElement::Paragraph {
                text: result_text.to_string(),
            });

            // Update the file using UpdateFileRequest
            let update_req = UpdateFileRequest {
                name: None,
                description: None,
                transcript: None,
                summary: None,
                body: Some(new_body),
                version: None, // Don't require version for this update
                repo_file_path: None,
            };

            match repository::update_file_for_owner(pool, file_id, owner_id, update_req).await {
                Ok(Some(updated_file)) => {
                    ContractRequestResult {
                        success: true,
                        message: format!("Updated file '{}' with task summary", file.name),
                        data: Some(json!({
                            "fileId": file_id,
                            "fileName": updated_file.name,
                            "taskId": task_id,
                            "taskName": task.name,
                        })),
                    }
                }
                Ok(None) => ContractRequestResult {
                    success: false,
                    message: "Failed to update file".to_string(),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            }
        }

        // =============================================================================
        // Transcript Analysis Handlers
        // =============================================================================

        ContractToolRequest::AnalyzeTranscript { file_id } => {
            // Get the file
            let file = match repository::get_file_for_owner(pool, file_id, owner_id).await {
                Ok(Some(f)) => f,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "File not found".to_string(),
                        data: None,
                    };
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    };
                }
            };

            if file.transcript.is_empty() {
                return ContractRequestResult {
                    success: false,
                    message: "File has no transcript to analyze".to_string(),
                    data: None,
                };
            }

            // Format and analyze
            let transcript_text = format_transcript_for_analysis(&file.transcript);
            let speaker_stats = calculate_speaker_stats(&file.transcript);
            let prompt = build_analysis_prompt(&transcript_text);

            // Call Claude for analysis
            let client = match ClaudeClient::from_env(ClaudeModel::Sonnet) {
                Ok(c) => c,
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Failed to create Claude client: {}", e),
                        data: None,
                    };
                }
            };

            let claude_messages = vec![claude::Message {
                role: "user".to_string(),
                content: claude::MessageContent::Text(prompt),
            }];

            match client.chat_with_tools(claude_messages, &[]).await {
                Ok(result) => {
                    let response_content = result.content.unwrap_or_default();
                    match parse_analysis_response(&response_content, speaker_stats) {
                        Ok(analysis) => {
                            ContractRequestResult {
                                success: true,
                                message: format!(
                                    "Analysis complete: {} requirements, {} decisions, {} action items",
                                    analysis.requirements.len(),
                                    analysis.decisions.len(),
                                    analysis.action_items.len()
                                ),
                                data: Some(json!({
                                    "analysis": analysis
                                })),
                            }
                        }
                        Err(e) => ContractRequestResult {
                            success: false,
                            message: format!("Failed to parse analysis: {}", e),
                            data: None,
                        }
                    }
                }
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Claude API error: {}", e),
                    data: None,
                }
            }
        }

        ContractToolRequest::CreateContractFromTranscript {
            file_id, name, description, include_requirements, include_decisions, include_action_items
        } => {
            // Get file
            let file = match repository::get_file_for_owner(pool, file_id, owner_id).await {
                Ok(Some(f)) => f,
                Ok(None) => {
                    return ContractRequestResult {
                        success: false,
                        message: "File not found".to_string(),
                        data: None,
                    };
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Database error: {}", e),
                        data: None,
                    };
                }
            };

            if file.transcript.is_empty() {
                return ContractRequestResult {
                    success: false,
                    message: "File has no transcript".to_string(),
                    data: None,
                };
            }

            // Analyze transcript
            let transcript_text = format_transcript_for_analysis(&file.transcript);
            let speaker_stats = calculate_speaker_stats(&file.transcript);
            let prompt = build_analysis_prompt(&transcript_text);

            let client = match ClaudeClient::from_env(ClaudeModel::Sonnet) {
                Ok(c) => c,
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Failed to create Claude client: {}", e),
                        data: None,
                    };
                }
            };

            let claude_messages = vec![claude::Message {
                role: "user".to_string(),
                content: claude::MessageContent::Text(prompt),
            }];

            let analysis = match client.chat_with_tools(claude_messages, &[]).await {
                Ok(result) => {
                    let response_content = result.content.unwrap_or_default();
                    match parse_analysis_response(&response_content, speaker_stats) {
                        Ok(a) => a,
                        Err(e) => {
                            return ContractRequestResult {
                                success: false,
                                message: format!("Failed to parse analysis: {}", e),
                                data: None,
                            };
                        }
                    }
                }
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Claude API error: {}", e),
                        data: None,
                    };
                }
            };

            // Create contract
            let contract_name = name
                .or(analysis.suggested_contract_name.clone())
                .unwrap_or_else(|| format!("Contract from {}", file.name));
            let contract_description = description.or(analysis.suggested_description.clone());

            let contract_req = crate::db::models::CreateContractRequest {
                name: contract_name.clone(),
                description: contract_description,
                contract_type: Some("specification".to_string()),
                initial_phase: Some("research".to_string()),
                autonomous_loop: None,
                phase_guard: None,
                local_only: None,
                auto_merge_local: None,
                template_id: None,
            };

            let contract = match repository::create_contract_for_owner(pool, owner_id, contract_req).await {
                Ok(c) => c,
                Err(e) => {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Failed to create contract: {}", e),
                        data: None,
                    };
                }
            };

            let mut files_created = 0;
            let mut tasks_created = 0;

            // Create requirements file if requested and there are requirements
            if include_requirements && !analysis.requirements.is_empty() {
                let requirements_items: Vec<String> = analysis.requirements
                    .iter()
                    .map(|req| format!("[{}] {}", req.speaker, req.text))
                    .collect();

                let body: Vec<crate::db::models::BodyElement> = vec![
                    crate::db::models::BodyElement::Heading {
                        level: 1,
                        text: "Requirements".to_string(),
                    },
                    crate::db::models::BodyElement::Paragraph {
                        text: format!("Extracted {} requirements from transcript analysis.", analysis.requirements.len()),
                    },
                    crate::db::models::BodyElement::Heading {
                        level: 2,
                        text: "Extracted Requirements".to_string(),
                    },
                    crate::db::models::BodyElement::List {
                        ordered: false,
                        items: requirements_items,
                    },
                ];

                let create_req = crate::db::models::CreateFileRequest {
                    contract_id: contract.id,
                    name: Some("Requirements".to_string()),
                    description: Some("Requirements extracted from transcript analysis".to_string()),
                    body,
                    transcript: Vec::new(),
                    location: None,
                    repo_file_path: None,
                    contract_phase: Some("specify".to_string()),
                };

                if repository::create_file_for_owner(pool, owner_id, create_req).await.is_ok() {
                    files_created += 1;
                }
            }

            // Create decisions file if requested and there are decisions
            if include_decisions && !analysis.decisions.is_empty() {
                let decisions_items: Vec<String> = analysis.decisions
                    .iter()
                    .map(|dec| format!("[{}] {}", dec.speaker, dec.text))
                    .collect();

                let body: Vec<crate::db::models::BodyElement> = vec![
                    crate::db::models::BodyElement::Heading {
                        level: 1,
                        text: "Decisions".to_string(),
                    },
                    crate::db::models::BodyElement::Paragraph {
                        text: format!("Extracted {} decisions from transcript analysis.", analysis.decisions.len()),
                    },
                    crate::db::models::BodyElement::Heading {
                        level: 2,
                        text: "Recorded Decisions".to_string(),
                    },
                    crate::db::models::BodyElement::List {
                        ordered: false,
                        items: decisions_items,
                    },
                ];

                let create_req = crate::db::models::CreateFileRequest {
                    contract_id: contract.id,
                    name: Some("Decisions".to_string()),
                    description: Some("Decisions extracted from transcript analysis".to_string()),
                    body,
                    transcript: Vec::new(),
                    location: None,
                    repo_file_path: None,
                    contract_phase: Some("research".to_string()),
                };

                if repository::create_file_for_owner(pool, owner_id, create_req).await.is_ok() {
                    files_created += 1;
                }
            }

            // Create tasks from action items if requested
            if include_action_items && !analysis.action_items.is_empty() {
                for item in &analysis.action_items {
                    let task_req = CreateTaskRequest {
                        contract_id: Some(contract.id),
                        name: item.text.chars().take(100).collect(),
                        description: Some(format!("Action item from: {}", item.speaker)),
                        plan: item.text.clone(),
                        parent_task_id: None,
                        repository_url: None,
                        base_branch: None,
                        target_branch: None,
                        merge_mode: None,
                        priority: match item.priority.as_deref() {
                            Some("high") => 10,
                            Some("medium") => 5,
                            _ => 0,
                        },
                        target_repo_path: None,
                        completion_action: None,
                        continue_from_task_id: None,
                        copy_files: None,
                        is_supervisor: false,
                                checkpoint_sha: None,
                        branched_from_task_id: None,
                        conversation_history: None,
                        supervisor_worktree_task_id: None, // Not spawned by supervisor
                    };

                    if repository::create_task_for_owner(pool, owner_id, task_req).await.is_ok() {
                        tasks_created += 1;
                    }
                }
            }

            ContractRequestResult {
                success: true,
                message: format!(
                    "Created contract '{}' with {} files and {} tasks from transcript analysis",
                    contract_name, files_created, tasks_created
                ),
                data: Some(json!({
                    "contractId": contract.id,
                    "contractName": contract_name,
                    "filesCreated": files_created,
                    "tasksCreated": tasks_created,
                    "analysis": {
                        "requirementsCount": analysis.requirements.len(),
                        "decisionsCount": analysis.decisions.len(),
                        "actionItemsCount": analysis.action_items.len()
                    }
                })),
            }
        }

        // Chain directive tools - for directive contracts to create and manage chains
        ContractToolRequest::CreateChainFromDirective { name, description } => {
            // First, get the current contract to verify it's a directive contract
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            // Check if contract already has a spawned chain
            if contract.spawned_chain_id.is_some() {
                return ContractRequestResult {
                    success: false,
                    message: "This contract already has a chain associated with it".to_string(),
                    data: Some(json!({ "existing_chain_id": contract.spawned_chain_id })),
                };
            }

            // Create the chain
            let chain_req = CreateChainRequest {
                name: name.clone(),
                description: description.clone(),
                repositories: None,
                loop_enabled: None,
                loop_max_iterations: None,
                loop_progress_check: None,
                contracts: None,
            };

            let chain = match repository::create_chain_for_owner(pool, owner_id, chain_req).await {
                Ok(c) => c,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to create chain: {}", e),
                    data: None,
                },
            };

            // Link the chain to this directive contract
            if let Err(e) = sqlx::query(
                r#"
                UPDATE chains SET directive_contract_id = $2, evaluation_enabled = true WHERE id = $1;
                UPDATE contracts SET spawned_chain_id = $1, is_chain_directive = true WHERE id = $2;
                "#,
            )
            .bind(chain.id)
            .bind(contract_id)
            .execute(pool)
            .await {
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to link chain to contract: {}", e),
                    data: None,
                };
            }

            // Create empty directive for the chain
            let directive_req = CreateChainDirectiveRequest {
                requirements: Some(vec![]),
                acceptance_criteria: Some(vec![]),
                constraints: Some(vec![]),
                external_dependencies: Some(vec![]),
                source_type: Some("llm_generated".to_string()),
            };

            if let Err(e) = repository::create_chain_directive(pool, chain.id, directive_req).await {
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to create directive: {}", e),
                    data: None,
                };
            }

            ContractRequestResult {
                success: true,
                message: format!("Created chain '{}' linked to this directive contract", name),
                data: Some(json!({
                    "chain_id": chain.id,
                    "chain_name": name,
                    "description": description
                })),
            }
        }

        ContractToolRequest::AddChainContract { name, description, contract_type, depends_on, requirement_ids } => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain. Use create_chain_from_directive first.".to_string(),
                    data: None,
                },
            };

            // Check for duplicate names
            let existing_defs = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            if existing_defs.iter().any(|d| d.name == name) {
                return ContractRequestResult {
                    success: false,
                    message: format!("A contract definition with name '{}' already exists", name),
                    data: None,
                };
            }

            // Create the contract definition
            let def_req = AddContractDefinitionRequest {
                name: name.clone(),
                description,
                contract_type: contract_type.unwrap_or_else(|| "implementation".to_string()),
                initial_phase: Some("research".to_string()),
                depends_on,
                tasks: None,
                deliverables: None,
                validation: None,
                editor_x: None,
                editor_y: None,
            };

            let definition = match repository::create_chain_contract_definition(pool, chain_id, def_req).await {
                Ok(d) => d,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to create contract definition: {}", e),
                    data: None,
                },
            };

            // Update requirement_ids if provided
            if let Some(req_ids) = requirement_ids {
                if !req_ids.is_empty() {
                    if let Err(e) = sqlx::query(
                        "UPDATE chain_contract_definitions SET requirement_ids = $2 WHERE id = $1"
                    )
                    .bind(definition.id)
                    .bind(&req_ids)
                    .execute(pool)
                    .await {
                        tracing::warn!("Failed to set requirement_ids: {}", e);
                    }
                }
            }

            ContractRequestResult {
                success: true,
                message: format!("Added contract '{}' to chain", name),
                data: Some(json!({
                    "definition_id": definition.id,
                    "name": name,
                    "order_index": definition.order_index
                })),
            }
        }

        ContractToolRequest::SetChainDependencies { contract_name, depends_on } => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Find the definition by name
            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            let definition = match definitions.iter().find(|d| d.name == contract_name) {
                Some(d) => d,
                None => return ContractRequestResult {
                    success: false,
                    message: format!("No contract definition named '{}' found", contract_name),
                    data: None,
                },
            };

            // Validate that all dependencies exist
            for dep_name in &depends_on {
                if !definitions.iter().any(|d| &d.name == dep_name) {
                    return ContractRequestResult {
                        success: false,
                        message: format!("Dependency '{}' does not exist", dep_name),
                        data: None,
                    };
                }
            }

            // Check for circular dependencies (simple check)
            if depends_on.contains(&contract_name) {
                return ContractRequestResult {
                    success: false,
                    message: "A contract cannot depend on itself".to_string(),
                    data: None,
                };
            }

            // Update dependencies
            let update_req = UpdateContractDefinitionRequest {
                name: None,
                description: None,
                contract_type: None,
                initial_phase: None,
                depends_on: Some(depends_on.clone()),
                tasks: None,
                deliverables: None,
                validation: None,
                editor_x: None,
                editor_y: None,
            };

            match repository::update_chain_contract_definition(pool, definition.id, update_req).await {
                Ok(_) => ContractRequestResult {
                    success: true,
                    message: format!("Updated dependencies for '{}'", contract_name),
                    data: Some(json!({
                        "contract_name": contract_name,
                        "depends_on": depends_on
                    })),
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to update dependencies: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::ModifyChainContract { name, new_name, description, add_requirement_ids, remove_requirement_ids } => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Find the definition by name
            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            let definition = match definitions.iter().find(|d| d.name == name) {
                Some(d) => d.clone(),
                None => return ContractRequestResult {
                    success: false,
                    message: format!("No contract definition named '{}' found", name),
                    data: None,
                },
            };

            // Check if new name would conflict
            if let Some(ref nn) = new_name {
                if nn != &name && definitions.iter().any(|d| &d.name == nn) {
                    return ContractRequestResult {
                        success: false,
                        message: format!("A contract definition named '{}' already exists", nn),
                        data: None,
                    };
                }
            }

            // Update the definition
            let update_req = UpdateContractDefinitionRequest {
                name: new_name.clone(),
                description,
                contract_type: None,
                initial_phase: None,
                depends_on: None,
                tasks: None,
                deliverables: None,
                validation: None,
                editor_x: None,
                editor_y: None,
            };

            if let Err(e) = repository::update_chain_contract_definition(pool, definition.id, update_req).await {
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to update definition: {}", e),
                    data: None,
                };
            }

            // Handle requirement_ids modifications
            let mut current_req_ids: Vec<String> = definition.requirement_ids.clone();
            if let Some(add_ids) = add_requirement_ids {
                for id in add_ids {
                    if !current_req_ids.contains(&id) {
                        current_req_ids.push(id);
                    }
                }
            }
            if let Some(remove_ids) = remove_requirement_ids {
                current_req_ids.retain(|id| !remove_ids.contains(id));
            }

            if current_req_ids != definition.requirement_ids {
                if let Err(e) = sqlx::query(
                    "UPDATE chain_contract_definitions SET requirement_ids = $2 WHERE id = $1"
                )
                .bind(definition.id)
                .bind(&current_req_ids)
                .execute(pool)
                .await {
                    tracing::warn!("Failed to update requirement_ids: {}", e);
                }
            }

            ContractRequestResult {
                success: true,
                message: format!("Modified contract definition '{}'", new_name.as_ref().unwrap_or(&name)),
                data: Some(json!({
                    "definition_id": definition.id,
                    "name": new_name.as_ref().unwrap_or(&name),
                    "requirement_ids": current_req_ids
                })),
            }
        }

        ContractToolRequest::RemoveChainContract { name } => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Find the definition by name
            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            let definition = match definitions.iter().find(|d| d.name == name) {
                Some(d) => d,
                None => return ContractRequestResult {
                    success: false,
                    message: format!("No contract definition named '{}' found", name),
                    data: None,
                },
            };

            // Check if other definitions depend on this one
            let dependents: Vec<&str> = definitions.iter()
                .filter(|d| d.depends_on_names.contains(&name))
                .map(|d| d.name.as_str())
                .collect();

            if !dependents.is_empty() {
                return ContractRequestResult {
                    success: false,
                    message: format!("Cannot remove '{}': other contracts depend on it: {}", name, dependents.join(", ")),
                    data: None,
                };
            }

            // Delete the definition
            match repository::delete_chain_contract_definition(pool, definition.id).await {
                Ok(true) => ContractRequestResult {
                    success: true,
                    message: format!("Removed contract definition '{}'", name),
                    data: Some(json!({ "removed": name })),
                },
                Ok(false) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to remove '{}': not found", name),
                    data: None,
                },
                Err(e) => ContractRequestResult {
                    success: false,
                    message: format!("Failed to remove definition: {}", e),
                    data: None,
                },
            }
        }

        ContractToolRequest::PreviewChainDag => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Get chain details and definitions
            let chain = match repository::get_chain_for_owner(pool, chain_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Chain not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            // Build DAG representation
            let nodes: Vec<serde_json::Value> = definitions.iter().map(|d| {
                json!({
                    "name": d.name,
                    "description": d.description,
                    "contract_type": d.contract_type,
                    "depends_on": d.depends_on_names,
                    "requirement_ids": d.requirement_ids
                })
            }).collect();

            // Build ASCII DAG representation
            let mut ascii_dag = String::new();
            ascii_dag.push_str(&format!("Chain: {} ({})\n", chain.name, chain.status));
            ascii_dag.push_str(&format!("Contracts: {}\n\n", definitions.len()));

            // Find root nodes (no dependencies)
            let roots: Vec<&str> = definitions.iter()
                .filter(|d| d.depends_on_names.is_empty())
                .map(|d| d.name.as_str())
                .collect();

            ascii_dag.push_str("Root contracts (no dependencies):\n");
            for root in &roots {
                ascii_dag.push_str(&format!("  [{}]\n", root));
            }

            ascii_dag.push_str("\nDependency relationships:\n");
            for def in &definitions {
                if !def.depends_on_names.is_empty() {
                    ascii_dag.push_str(&format!("  {} <- {}\n", def.name, def.depends_on_names.join(", ")));
                }
            }

            ContractRequestResult {
                success: true,
                message: format!("Chain DAG preview with {} contracts", definitions.len()),
                data: Some(json!({
                    "chain_id": chain_id,
                    "chain_name": chain.name,
                    "chain_status": chain.status,
                    "contract_count": definitions.len(),
                    "nodes": nodes,
                    "ascii_dag": ascii_dag
                })),
            }
        }

        ContractToolRequest::ValidateChainDirective => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            let mut errors: Vec<String> = Vec::new();
            let mut warnings: Vec<String> = Vec::new();

            // Check for empty chain
            if definitions.is_empty() {
                errors.push("Chain has no contract definitions".to_string());
            }

            // Check for circular dependencies
            let def_names: std::collections::HashSet<String> = definitions.iter().map(|d| d.name.clone()).collect();
            for def in &definitions {
                for dep in &def.depends_on_names {
                    if !def_names.contains(dep) {
                        errors.push(format!("'{}' depends on non-existent contract '{}'", def.name, dep));
                    }
                }
            }

            // Simple cycle detection using DFS
            fn has_cycle(
                name: &str,
                definitions: &[crate::db::models::ChainContractDefinition],
                visited: &mut std::collections::HashSet<String>,
                rec_stack: &mut std::collections::HashSet<String>,
            ) -> Option<String> {
                visited.insert(name.to_string());
                rec_stack.insert(name.to_string());

                if let Some(def) = definitions.iter().find(|d| d.name == name) {
                    for dep in &def.depends_on_names {
                        if !visited.contains(dep) {
                            if let Some(cycle) = has_cycle(dep, definitions, visited, rec_stack) {
                                return Some(cycle);
                            }
                        } else if rec_stack.contains(dep) {
                            return Some(format!("{} -> {}", name, dep));
                        }
                    }
                }

                rec_stack.remove(name);
                None
            }

            let mut visited = std::collections::HashSet::new();
            for def in &definitions {
                if !visited.contains(&def.name) {
                    let mut rec_stack = std::collections::HashSet::new();
                    if let Some(cycle) = has_cycle(&def.name, &definitions, &mut visited, &mut rec_stack) {
                        errors.push(format!("Circular dependency detected: {}", cycle));
                        break;
                    }
                }
            }

            // Check for orphan contracts (no one depends on them and they're not root)
            let roots: std::collections::HashSet<&str> = definitions.iter()
                .filter(|d| d.depends_on_names.is_empty())
                .map(|d| d.name.as_str())
                .collect();

            let depended_on: std::collections::HashSet<&str> = definitions.iter()
                .flat_map(|d| d.depends_on_names.iter().map(|s| s.as_str()))
                .collect();

            for def in &definitions {
                if !roots.contains(def.name.as_str()) && !depended_on.contains(def.name.as_str()) {
                    warnings.push(format!("'{}' has dependencies but nothing depends on it (orphan leaf)", def.name));
                }
            }

            // Get directive to check requirement coverage
            if let Ok(Some(directive)) = repository::get_chain_directive(pool, chain_id).await {
                let requirements: Vec<crate::db::models::DirectiveRequirement> =
                    serde_json::from_value(directive.requirements.clone()).unwrap_or_default();

                let covered: std::collections::HashSet<&str> = definitions.iter()
                    .flat_map(|d| d.requirement_ids.iter().map(|s| s.as_str()))
                    .collect();

                for req in &requirements {
                    if !covered.contains(req.id.as_str()) {
                        warnings.push(format!("Requirement '{}' ({}) is not covered by any contract", req.id, req.title));
                    }
                }
            }

            let is_valid = errors.is_empty();

            ContractRequestResult {
                success: is_valid,
                message: if is_valid {
                    format!("Chain is valid with {} contracts", definitions.len())
                } else {
                    format!("Chain validation failed with {} errors", errors.len())
                },
                data: Some(json!({
                    "valid": is_valid,
                    "contract_count": definitions.len(),
                    "errors": errors,
                    "warnings": warnings
                })),
            }
        }

        ContractToolRequest::FinalizeChainDirective { auto_start } => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Get chain
            let chain = match repository::get_chain_for_owner(pool, chain_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Chain not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            if chain.status != "pending" {
                return ContractRequestResult {
                    success: false,
                    message: format!("Chain is already {} - cannot finalize", chain.status),
                    data: None,
                };
            }

            // Update chain status
            let new_status = if auto_start { "active" } else { "pending" };
            if let Err(e) = sqlx::query("UPDATE chains SET status = $2 WHERE id = $1")
                .bind(chain_id)
                .bind(new_status)
                .execute(pool)
                .await {
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to update chain status: {}", e),
                    data: None,
                };
            }

            // If auto_start, trigger chain progression to create root contracts
            if auto_start {
                match repository::progress_chain(pool, chain_id, owner_id).await {
                    Ok(result) => {
                        ContractRequestResult {
                            success: true,
                            message: format!("Chain finalized and started. Created {} root contracts.", result.contracts_created.len()),
                            data: Some(json!({
                                "chain_id": chain_id,
                                "status": "active",
                                "contracts_created": result.contracts_created,
                                "chain_completed": result.chain_completed
                            })),
                        }
                    }
                    Err(e) => ContractRequestResult {
                        success: false,
                        message: format!("Chain finalized but failed to start: {}", e),
                        data: Some(json!({ "chain_id": chain_id, "status": "active" })),
                    },
                }
            } else {
                ContractRequestResult {
                    success: true,
                    message: "Chain finalized but not started. Call finalize_chain_directive with auto_start=true to start.".to_string(),
                    data: Some(json!({
                        "chain_id": chain_id,
                        "status": "pending"
                    })),
                }
            }
        }

        ContractToolRequest::GetChainStatus => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Get chain details
            let chain = match repository::get_chain_for_owner(pool, chain_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Chain not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            // Get definitions
            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            // Get instantiated contracts
            let chain_contracts = match repository::list_chain_contracts(pool, chain_id).await {
                Ok(cc) => cc,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list chain contracts: {}", e),
                    data: None,
                },
            };

            // Build status map
            let contract_statuses: Vec<serde_json::Value> = chain_contracts.iter().map(|cc| {
                json!({
                    "name": cc.contract_name,
                    "contract_id": cc.contract_id,
                    "status": cc.contract_status,
                    "phase": cc.contract_phase,
                    "evaluation_status": cc.evaluation_status,
                    "evaluation_retry_count": cc.evaluation_retry_count
                })
            }).collect();

            let completed = chain_contracts.iter().filter(|cc| cc.contract_status == "completed").count();
            let active = chain_contracts.iter().filter(|cc| cc.contract_status == "active").count();
            let pending = definitions.len() - chain_contracts.len();

            ContractRequestResult {
                success: true,
                message: format!("Chain '{}': {} completed, {} active, {} pending",
                    chain.name, completed, active, pending),
                data: Some(json!({
                    "chain_id": chain_id,
                    "chain_name": chain.name,
                    "chain_status": chain.status,
                    "total_definitions": definitions.len(),
                    "instantiated": chain_contracts.len(),
                    "completed": completed,
                    "active": active,
                    "pending": pending,
                    "contracts": contract_statuses
                })),
            }
        }

        ContractToolRequest::GetUncoveredRequirements => {
            // Get the contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Get directive
            let directive = match repository::get_chain_directive(pool, chain_id).await {
                Ok(Some(d)) => d,
                Ok(None) => return ContractRequestResult {
                    success: true,
                    message: "No directive found for this chain".to_string(),
                    data: Some(json!({ "uncovered": [], "total_requirements": 0 })),
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            // Get definitions
            let definitions = match repository::list_chain_contract_definitions(pool, chain_id).await {
                Ok(defs) => defs,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to list definitions: {}", e),
                    data: None,
                },
            };

            // Parse requirements
            let requirements: Vec<crate::db::models::DirectiveRequirement> =
                serde_json::from_value(directive.requirements.clone()).unwrap_or_default();

            // Find covered requirement IDs
            let covered: std::collections::HashSet<String> = definitions.iter()
                .flat_map(|d| d.requirement_ids.iter().cloned())
                .collect();

            // Find uncovered requirements
            let uncovered: Vec<serde_json::Value> = requirements.iter()
                .filter(|r| !covered.contains(&r.id))
                .map(|r| json!({
                    "id": r.id,
                    "title": r.title,
                    "priority": r.priority
                }))
                .collect();

            ContractRequestResult {
                success: true,
                message: format!("{} of {} requirements are uncovered", uncovered.len(), requirements.len()),
                data: Some(json!({
                    "uncovered": uncovered,
                    "uncovered_count": uncovered.len(),
                    "total_requirements": requirements.len(),
                    "coverage_percent": if requirements.is_empty() { 100.0 } else {
                        ((requirements.len() - uncovered.len()) as f64 / requirements.len() as f64 * 100.0).round()
                    }
                })),
            }
        }

        ContractToolRequest::EvaluateContractCompletion { contract_id: target_contract_id, passed, feedback, rework_instructions } => {
            // Get the directive contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Verify the target contract is part of this chain
            let chain_contract = match repository::get_chain_contract_by_contract_id(pool, target_contract_id).await {
                Ok(Some(cc)) => cc,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: format!("Contract {} is not part of a chain", target_contract_id),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            if chain_contract.chain_id != chain_id {
                return ContractRequestResult {
                    success: false,
                    message: "Contract is not part of this directive's chain".to_string(),
                    data: None,
                };
            }

            // Create evaluation record
            let eval_req = CreateContractEvaluationRequest {
                contract_id: target_contract_id,
                chain_id: Some(chain_id),
                chain_contract_id: Some(chain_contract.id),
                evaluator_model: Some("directive_contract".to_string()),
                passed,
                overall_score: if passed { Some(1.0) } else { Some(0.0) },
                criteria_results: vec![],
                summary_feedback: feedback.clone(),
                rework_instructions: rework_instructions.clone(),
            };

            let evaluation = match repository::create_contract_evaluation(pool, eval_req).await {
                Ok(e) => e,
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Failed to create evaluation: {}", e),
                    data: None,
                },
            };

            // Update chain contract evaluation status
            let new_status = if passed { "passed" } else { "failed" };
            if let Err(e) = repository::update_chain_contract_evaluation_status(
                pool,
                chain_contract.id,
                new_status,
                Some(evaluation.id),
                None, // No rework feedback for passed/failed status
            ).await {
                tracing::warn!("Failed to update chain contract evaluation status: {}", e);
            }

            if passed {
                // Progress the chain to create downstream contracts
                match repository::progress_chain(pool, chain_id, owner_id).await {
                    Ok(result) => ContractRequestResult {
                        success: true,
                        message: format!("Evaluation passed. Created {} downstream contracts.", result.contracts_created.len()),
                        data: Some(json!({
                            "evaluation_id": evaluation.id,
                            "passed": true,
                            "contracts_created": result.contracts_created,
                            "chain_completed": result.chain_completed
                        })),
                    },
                    Err(e) => ContractRequestResult {
                        success: true,
                        message: format!("Evaluation passed but failed to progress chain: {}", e),
                        data: Some(json!({
                            "evaluation_id": evaluation.id,
                            "passed": true
                        })),
                    },
                }
            } else {
                // Mark contract for rework
                if let Err(e) = sqlx::query(
                    r#"
                    UPDATE chain_contracts SET evaluation_status = 'rework', rework_feedback = $2 WHERE id = $1;
                    UPDATE contracts SET status = 'active' WHERE id = (SELECT contract_id FROM chain_contracts WHERE id = $1);
                    "#
                )
                .bind(chain_contract.id)
                .bind(&rework_instructions)
                .execute(pool)
                .await {
                    tracing::warn!("Failed to mark contract for rework: {}", e);
                }

                ContractRequestResult {
                    success: true,
                    message: format!("Evaluation failed. Contract marked for rework."),
                    data: Some(json!({
                        "evaluation_id": evaluation.id,
                        "passed": false,
                        "rework_instructions": rework_instructions,
                        "retry_count": chain_contract.evaluation_retry_count + 1
                    })),
                }
            }
        }

        ContractToolRequest::RequestRework { contract_id: target_contract_id, feedback } => {
            // Get the directive contract's spawned chain
            let contract = match repository::get_contract_for_owner(pool, contract_id, owner_id).await {
                Ok(Some(c)) => c,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: "Contract not found".to_string(),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            let chain_id = match contract.spawned_chain_id {
                Some(id) => id,
                None => return ContractRequestResult {
                    success: false,
                    message: "This contract has no associated chain".to_string(),
                    data: None,
                },
            };

            // Verify the target contract is part of this chain
            let chain_contract = match repository::get_chain_contract_by_contract_id(pool, target_contract_id).await {
                Ok(Some(cc)) => cc,
                Ok(None) => return ContractRequestResult {
                    success: false,
                    message: format!("Contract {} is not part of a chain", target_contract_id),
                    data: None,
                },
                Err(e) => return ContractRequestResult {
                    success: false,
                    message: format!("Database error: {}", e),
                    data: None,
                },
            };

            if chain_contract.chain_id != chain_id {
                return ContractRequestResult {
                    success: false,
                    message: "Contract is not part of this directive's chain".to_string(),
                    data: None,
                };
            }

            // Check retry count
            let max_retries = chain_contract.max_evaluation_retries;
            if chain_contract.evaluation_retry_count >= max_retries {
                return ContractRequestResult {
                    success: false,
                    message: format!("Contract has exceeded max retries ({}/{}). Escalate to user.",
                        chain_contract.evaluation_retry_count, max_retries),
                    data: Some(json!({
                        "retry_count": chain_contract.evaluation_retry_count,
                        "max_retries": max_retries,
                        "escalation_required": true
                    })),
                };
            }

            // Mark contract for rework and increment retry count
            if let Err(e) = sqlx::query(
                r#"
                UPDATE chain_contracts
                SET evaluation_status = 'rework',
                    rework_feedback = $2,
                    evaluation_retry_count = evaluation_retry_count + 1
                WHERE id = $1;
                UPDATE contracts SET status = 'active' WHERE id = (SELECT contract_id FROM chain_contracts WHERE id = $1);
                "#
            )
            .bind(chain_contract.id)
            .bind(&feedback)
            .execute(pool)
            .await {
                return ContractRequestResult {
                    success: false,
                    message: format!("Failed to request rework: {}", e),
                    data: None,
                };
            }

            ContractRequestResult {
                success: true,
                message: format!("Rework requested for contract. Retry {}/{}",
                    chain_contract.evaluation_retry_count + 1, max_retries),
                data: Some(json!({
                    "contract_id": target_contract_id,
                    "retry_count": chain_contract.evaluation_retry_count + 1,
                    "max_retries": max_retries,
                    "feedback": feedback
                })),
            }
        }
    }
}

/// Get description and activities for a phase
fn get_phase_description(phase: &str) -> (String, Vec<String>) {
    match phase {
        "research" => (
            "Gather information, analyze competitors, and understand user needs".to_string(),
            vec![
                "Conduct user research".to_string(),
                "Analyze competitors".to_string(),
                "Document findings".to_string(),
                "Identify opportunities".to_string(),
            ],
        ),
        "specify" => (
            "Define requirements, user stories, and acceptance criteria".to_string(),
            vec![
                "Write requirements".to_string(),
                "Create user stories".to_string(),
                "Define acceptance criteria".to_string(),
                "Document constraints".to_string(),
            ],
        ),
        "plan" => (
            "Design architecture, create task breakdowns, and technical designs".to_string(),
            vec![
                "Design system architecture".to_string(),
                "Create technical specifications".to_string(),
                "Break down into tasks".to_string(),
                "Plan implementation order".to_string(),
            ],
        ),
        "execute" => (
            "Implement features, write code, and run tasks".to_string(),
            vec![
                "Implement features".to_string(),
                "Write tests".to_string(),
                "Track progress".to_string(),
                "Document implementation details".to_string(),
            ],
        ),
        "review" => (
            "Review work, create release notes, and conduct retrospectives".to_string(),
            vec![
                "Review code and features".to_string(),
                "Create release notes".to_string(),
                "Conduct retrospective".to_string(),
                "Document learnings".to_string(),
            ],
        ),
        _ => (
            "Unknown phase".to_string(),
            vec![],
        ),
    }
}

/// Get the next phase in the lifecycle
fn get_next_phase(current: &str) -> Option<String> {
    match current {
        "research" => Some("specify".to_string()),
        "specify" => Some("plan".to_string()),
        "plan" => Some("execute".to_string()),
        "execute" => Some("review".to_string()),
        "review" => None, // Final phase
        _ => None,
    }
}

/// Phase readiness analysis result
struct PhaseReadinessAnalysis {
    ready: bool,
    summary: String,
    reasons: Vec<String>,
    suggestions: Vec<String>,
}

/// Analyze if the contract is ready to transition to the next phase
fn analyze_phase_readiness(contract: &crate::db::models::ContractWithRelations) -> PhaseReadinessAnalysis {
    let mut reasons = Vec::new();
    let mut suggestions = Vec::new();

    match contract.contract.phase.as_str() {
        "research" => {
            // Check for research files
            let research_files = contract.files.iter()
                .filter(|f| f.contract_phase.as_deref() == Some("research"))
                .count();

            if research_files == 0 {
                reasons.push("No research documents created yet".to_string());
                suggestions.push("Create research notes or competitor analysis documents".to_string());
            } else {
                reasons.push(format!("{} research document(s) created", research_files));
            }

            let ready = research_files > 0;
            PhaseReadinessAnalysis {
                ready,
                summary: if ready {
                    "Research phase has documentation. Consider transitioning to Specify phase.".to_string()
                } else {
                    "Research phase needs more documentation before transitioning.".to_string()
                },
                reasons,
                suggestions,
            }
        }
        "specify" => {
            let spec_files = contract.files.iter()
                .filter(|f| f.contract_phase.as_deref() == Some("specify"))
                .count();

            if spec_files == 0 {
                reasons.push("No specification documents created yet".to_string());
                suggestions.push("Create requirements or user stories documents".to_string());
            } else {
                reasons.push(format!("{} specification document(s) created", spec_files));
            }

            let ready = spec_files > 0;
            PhaseReadinessAnalysis {
                ready,
                summary: if ready {
                    "Specification phase has documentation. Consider transitioning to Plan phase.".to_string()
                } else {
                    "Specification phase needs requirements or user stories.".to_string()
                },
                reasons,
                suggestions,
            }
        }
        "plan" => {
            let plan_files = contract.files.iter()
                .filter(|f| f.contract_phase.as_deref() == Some("plan"))
                .count();

            let has_repos = !contract.repositories.is_empty();

            if plan_files == 0 {
                reasons.push("No planning documents created yet".to_string());
                suggestions.push("Create architecture or task breakdown documents".to_string());
            } else {
                reasons.push(format!("{} planning document(s) created", plan_files));
            }

            if !has_repos {
                reasons.push("No repositories configured".to_string());
                suggestions.push("Add a repository for task execution".to_string());
            } else {
                reasons.push(format!("{} repository(ies) configured", contract.repositories.len()));
            }

            let ready = plan_files > 0 && has_repos;
            PhaseReadinessAnalysis {
                ready,
                summary: if ready {
                    "Planning phase complete with documents and repositories. Ready for Execute phase.".to_string()
                } else {
                    "Planning phase needs documentation and/or repository configuration.".to_string()
                },
                reasons,
                suggestions,
            }
        }
        "execute" => {
            let total_tasks = contract.tasks.len();
            let done_tasks = contract.tasks.iter().filter(|t| t.status == "done").count();
            let running_tasks = contract.tasks.iter().filter(|t| t.status == "running").count();

            if total_tasks == 0 {
                reasons.push("No tasks created yet".to_string());
                suggestions.push("Create tasks to implement the planned work".to_string());
            } else {
                reasons.push(format!("{} of {} tasks completed", done_tasks, total_tasks));
            }

            if running_tasks > 0 {
                reasons.push(format!("{} task(s) still running", running_tasks));
                suggestions.push("Wait for running tasks to complete".to_string());
            }

            let ready = total_tasks > 0 && done_tasks == total_tasks;

            // For simple contracts, execute is the terminal phase - suggest completion
            if ready && contract.contract.contract_type == "simple" {
                suggestions.push("Mark the contract as completed".to_string());
            }

            PhaseReadinessAnalysis {
                ready,
                summary: if ready {
                    if contract.contract.contract_type == "simple" {
                        "All tasks completed. Contract can be marked as completed.".to_string()
                    } else {
                        "All tasks completed. Ready for Review phase.".to_string()
                    }
                } else if total_tasks == 0 {
                    "No tasks created yet. Create and complete tasks before reviewing.".to_string()
                } else {
                    format!("{}/{} tasks complete. Finish remaining tasks before review.", done_tasks, total_tasks)
                },
                reasons,
                suggestions,
            }
        }
        "review" => {
            let review_files = contract.files.iter()
                .filter(|f| f.contract_phase.as_deref() == Some("review"))
                .count();

            if review_files == 0 {
                suggestions.push("Create review checklist or release notes".to_string());
            } else {
                // Review documentation exists - suggest completion
                suggestions.push("Mark the contract as completed".to_string());
            }

            PhaseReadinessAnalysis {
                ready: review_files > 0,
                summary: if review_files > 0 {
                    "Review documentation complete. Contract can be marked as completed.".to_string()
                } else {
                    "Review phase needs documentation before completion.".to_string()
                },
                reasons: vec!["Review is the final phase".to_string()],
                suggestions,
            }
        }
        _ => PhaseReadinessAnalysis {
            ready: false,
            summary: "Unknown phase".to_string(),
            reasons: vec!["Phase not recognized".to_string()],
            suggestions: vec![],
        },
    }
}

// =============================================================================
// Contract Chat History Endpoints
// =============================================================================

/// Get contract chat history
#[utoipa::path(
    get,
    path = "/api/v1/contracts/{id}/chat/history",
    responses(
        (status = 200, description = "Chat history retrieved successfully", body = ContractChatHistoryResponse),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Contract not found"),
        (status = 500, description = "Internal server error")
    ),
    params(
        ("id" = Uuid, Path, description = "Contract ID")
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Contracts"
)]
pub async fn get_contract_chat_history(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(contract_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "Database not configured" })),
        )
            .into_response();
    };

    // Verify contract exists and belongs to owner
    match repository::get_contract_for_owner(pool, contract_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "Contract not found" })),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Database error: {}", e) })),
            )
                .into_response();
        }
    }

    // Get or create conversation
    let conversation = match repository::get_or_create_contract_conversation(pool, contract_id, auth.owner_id).await {
        Ok(conv) => conv,
        Err(e) => {
            tracing::error!("Failed to get contract conversation: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Failed to get conversation: {}", e) })),
            )
                .into_response();
        }
    };

    // Get messages
    let messages = match repository::list_contract_chat_messages(pool, conversation.id, Some(100)).await {
        Ok(msgs) => msgs,
        Err(e) => {
            tracing::error!("Failed to list contract chat messages: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Failed to list messages: {}", e) })),
            )
                .into_response();
        }
    };

    (
        StatusCode::OK,
        Json(ContractChatHistoryResponse {
            contract_id,
            conversation_id: conversation.id,
            messages,
        }),
    )
        .into_response()
}

/// Clear contract chat history (creates a new conversation)
#[utoipa::path(
    delete,
    path = "/api/v1/contracts/{id}/chat/history",
    responses(
        (status = 200, description = "Chat history cleared successfully"),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Contract not found"),
        (status = 500, description = "Internal server error")
    ),
    params(
        ("id" = Uuid, Path, description = "Contract ID")
    ),
    security(
        ("bearer_auth" = []),
        ("api_key" = [])
    ),
    tag = "Contracts"
)]
pub async fn clear_contract_chat_history(
    State(state): State<SharedState>,
    Authenticated(auth): Authenticated,
    Path(contract_id): Path<Uuid>,
) -> impl IntoResponse {
    let Some(ref pool) = state.db_pool else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({ "error": "Database not configured" })),
        )
            .into_response();
    };

    // Verify contract exists and belongs to owner
    match repository::get_contract_for_owner(pool, contract_id, auth.owner_id).await {
        Ok(Some(_)) => {}
        Ok(None) => {
            return (
                StatusCode::NOT_FOUND,
                Json(json!({ "error": "Contract not found" })),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Database error: {}", e) })),
            )
                .into_response();
        }
    }

    // Clear conversation (archives existing and creates new)
    match repository::clear_contract_conversation(pool, contract_id, auth.owner_id).await {
        Ok(new_conversation) => {
            (
                StatusCode::OK,
                Json(json!({
                    "message": "Chat history cleared",
                    "newConversationId": new_conversation.id
                })),
            )
                .into_response()
        }
        Err(e) => {
            tracing::error!("Failed to clear contract conversation: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({ "error": format!("Failed to clear history: {}", e) })),
            )
                .into_response()
        }
    }
}