riglr-core 0.3.0

Core abstractions and job execution engine for riglr - building resilient AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
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
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
//! Job data structures and types for task execution.
//!
//! This module defines the core data structures used for representing work units
//! and their execution results in the riglr system. Jobs are queued for execution
//! by the [`ToolWorker`](crate::ToolWorker) and can include retry logic, idempotency
//! keys, and structured result handling.
//!
//! ## Core Types
//!
//! - **[`Job`]** - A unit of work to be executed, with retry and idempotency support
//! - **[`JobResult`]** - The outcome of job execution with success/failure classification
//!
//! ## Job Lifecycle
//!
//! 1. **Creation** - Jobs are created with tool name, parameters, and retry limits
//! 2. **Queueing** - Jobs are enqueued for processing by workers
//! 3. **Execution** - Workers execute the corresponding tool with job parameters
//! 4. **Result** - Execution produces a [`JobResult`] indicating success or failure
//! 5. **Retry** - Failed jobs may be retried based on failure type and retry limits
//!
//! ## Examples
//!
//! ### Creating and Processing Jobs
//!
//! ```rust
//! use riglr_core::{Job, JobResult};
//! use serde_json::json;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a simple job
//! let job = Job::new(
//!     "weather_check",
//!     &json!({"city": "San Francisco"}),
//!     3 // max retries
//! )?;
//!
//! // Create an idempotent job
//! let idempotent_job = Job::new_idempotent(
//!     "account_balance",
//!     &json!({"address": "0x123..."}),
//!     2, // max retries
//!     "balance_check_user_123" // idempotency key
//! )?;
//!
//! // Check retry status
//! assert!(job.can_retry());
//! assert_eq!(job.retry_count, 0);
//! # Ok(())
//! # }
//! ```
//!
//! ### Working with Job Results
//!
//! ```rust
//! use riglr_core::{JobResult, ToolError};
//! use serde_json::json;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Successful result
//! let success = JobResult::success(&json!({
//!     "temperature": 72,
//!     "condition": "sunny"
//! }))?;
//! assert!(success.is_success());
//!
//! // Successful transaction result
//! let tx_result = JobResult::success_with_tx(
//!     &json!({"amount": 100, "recipient": "0xabc..."}),
//!     "0x789def..."
//! )?;
//!
//! // Retriable failure using new ToolError structure
//! let retriable = JobResult::Failure {
//!     error: ToolError::retriable_string("Network timeout")
//! };
//! assert!(retriable.is_retriable());
//! assert!(!retriable.is_success());
//!
//! // Permanent failure using new ToolError structure
//! let permanent = JobResult::Failure {
//!     error: ToolError::permanent_string("Invalid address format")
//! };
//! assert!(!permanent.is_retriable());
//! assert!(!permanent.is_success());
//! # Ok(())
//! # }
//! ```
//!
//! ## Error Handling Strategy
//!
//! The system distinguishes between two types of failures:
//!
//! ### Retriable Failures
//! These represent temporary issues that may resolve on retry:
//! - Network connectivity problems
//! - Rate limiting from external APIs
//! - Temporary service unavailability
//! - Resource contention
//!
//! ### Permanent Failures
//! These represent issues that won't be resolved by retrying:
//! - Invalid parameters or malformed requests
//! - Authentication or authorization failures
//! - Insufficient funds or resources
//! - Business logic violations
//!
//! ## Idempotency
//!
//! Jobs can include idempotency keys to ensure safe retry behavior:
//!
//! ```rust
//! use riglr_core::Job;
//! use serde_json::json;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let job = Job::new_idempotent(
//!     "transfer",
//!     &json!({
//!         "from": "user123",
//!         "to": "user456",
//!         "amount": 100
//!     }),
//!     3, // max retries
//!     "transfer_user123_to_user456_100_20241201" // unique key
//! )?;
//!
//! // Subsequent executions with the same key return cached results
//! # Ok(())
//! # }
//! ```

use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// A job represents a unit of work to be executed by a [`ToolWorker`](crate::ToolWorker).
///
/// Jobs encapsulate all the information needed to execute a tool, including
/// the tool name, parameters, retry configuration, and optional idempotency key.
/// They are the primary unit of work in the riglr job processing system.
///
/// ## Job Lifecycle
///
/// 1. **Creation** - Job is created with tool name and parameters
/// 2. **Queuing** - Job is submitted to a job queue for processing
/// 3. **Execution** - Worker picks up job and executes the corresponding tool
/// 4. **Retry** - If execution fails with a retriable error, job may be retried
/// 5. **Completion** - Job succeeds or fails permanently after exhausting retries
///
/// ## Examples
///
/// ### Basic Job Creation
///
/// ```rust
/// use riglr_core::Job;
/// use serde_json::json;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let job = Job::new(
///     "price_checker",
///     &json!({
///         "symbol": "BTC",
///         "currency": "USD"
///     }),
///     3 // max retries
/// )?;
///
/// println!("Job ID: {}", job.job_id);
/// println!("Tool: {}", job.tool_name);
/// println!("Can retry: {}", job.can_retry());
/// # Ok(())
/// # }
/// ```
///
/// ### Idempotent Job Creation
///
/// ```rust
/// use riglr_core::Job;
/// use serde_json::json;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let job = Job::new_idempotent(
///     "bank_transfer",
///     &json!({
///         "from_account": "123",
///         "to_account": "456",
///         "amount": 100.00,
///         "currency": "USD"
///     }),
///     2, // max retries
///     "transfer_123_456_100_20241201" // idempotency key
/// )?;
///
/// assert!(job.idempotency_key.is_some());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
    /// Unique identifier for this job instance.
    ///
    /// Generated automatically when the job is created. This ID is used
    /// for tracking and logging purposes throughout the job's lifecycle.
    pub job_id: Uuid,

    /// Name of the tool to execute.
    ///
    /// This must match the name of a tool registered with the [`ToolWorker`](crate::ToolWorker).
    /// Tool names also influence resource pool assignment (e.g., "solana_*" tools
    /// use the "solana_rpc" resource pool).
    pub tool_name: String,

    /// Parameters to pass to the tool, serialized as JSON.
    ///
    /// These parameters will be passed to the tool's [`execute`](crate::Tool::execute)
    /// method. Tools are responsible for validating and extracting the required
    /// parameters from this JSON value.
    pub params: serde_json::Value,

    /// Optional idempotency key to prevent duplicate execution.
    ///
    /// When an idempotency key is provided and an idempotency store is configured,
    /// the worker will cache successful results. Subsequent jobs with the same
    /// idempotency key will return the cached result instead of re-executing.
    ///
    /// Idempotency keys should be unique per logical operation and include
    /// relevant parameters to ensure uniqueness.
    pub idempotency_key: Option<String>,

    /// Maximum number of retry attempts allowed for this job.
    ///
    /// If a tool execution fails with a retriable error, the job will be
    /// retried up to this many times. The total execution attempts will
    /// be `max_retries + 1`.
    ///
    /// Only retriable failures trigger retries - permanent failures will
    /// not be retried regardless of this setting.
    pub max_retries: u32,

    /// Current retry count for this job.
    ///
    /// This tracks how many retry attempts have been made. It starts at 0
    /// for new jobs and is incremented after each failed execution attempt.
    /// The job stops retrying when `retry_count >= max_retries`.
    #[serde(default)]
    pub retry_count: u32,
}

impl Job {
    /// Create a new job without an idempotency key.
    ///
    /// This creates a standard job that will be executed normally without
    /// result caching. If the job fails with a retriable error, it may be
    /// retried up to `max_retries` times.
    ///
    /// # Parameters
    /// * `tool_name` - Name of the tool to execute (must match a registered tool)
    /// * `params` - Parameters to pass to the tool (will be JSON-serialized)
    /// * `max_retries` - Maximum number of retry attempts (0 = no retries)
    ///
    /// # Returns
    /// * `Ok(Job)` - Successfully created job
    /// * `Err(serde_json::Error)` - If parameters cannot be serialized to JSON
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::Job;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Simple job with basic parameters
    /// let job = Job::new(
    ///     "weather_check",
    ///     &json!({
    ///         "city": "San Francisco",
    ///         "units": "metric"
    ///     }),
    ///     3 // allow up to 3 retries
    /// )?;
    ///
    /// assert_eq!(job.tool_name, "weather_check");
    /// assert_eq!(job.max_retries, 3);
    /// assert_eq!(job.retry_count, 0);
    /// assert!(job.idempotency_key.is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new<T: Serialize>(
        tool_name: impl Into<String>,
        params: &T,
        max_retries: u32,
    ) -> Result<Self, serde_json::Error> {
        Ok(Self {
            job_id: Uuid::new_v4(),
            tool_name: tool_name.into(),
            params: serde_json::to_value(params)?,
            idempotency_key: None,
            max_retries,
            retry_count: 0,
        })
    }

    /// Create a new job with an idempotency key for safe retry behavior.
    ///
    /// When an idempotency store is configured, successful results for jobs
    /// with idempotency keys are cached. Subsequent jobs with the same key
    /// will return the cached result instead of re-executing the tool.
    ///
    /// # Parameters
    /// * `tool_name` - Name of the tool to execute (must match a registered tool)
    /// * `params` - Parameters to pass to the tool (will be JSON-serialized)
    /// * `max_retries` - Maximum number of retry attempts (0 = no retries)
    /// * `idempotency_key` - Unique key for this operation (should include relevant parameters)
    ///
    /// # Returns
    /// * `Ok(Job)` - Successfully created job
    /// * `Err(serde_json::Error)` - If parameters cannot be serialized to JSON
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::Job;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Idempotent job for a financial transaction
    /// let job = Job::new_idempotent(
    ///     "transfer_funds",
    ///     &json!({
    ///         "from": "account_123",
    ///         "to": "account_456",
    ///         "amount": 100.50,
    ///         "currency": "USD"
    ///     }),
    ///     2, // allow up to 2 retries
    ///     "transfer_123_456_100.50_USD_20241201_001" // unique operation ID
    /// )?;
    ///
    /// assert_eq!(job.tool_name, "transfer_funds");
    /// assert_eq!(job.max_retries, 2);
    /// assert!(job.idempotency_key.is_some());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Idempotency Key Best Practices
    ///
    /// Idempotency keys should:
    /// - Be unique per logical operation
    /// - Include relevant parameters that affect the result
    /// - Include timestamp or sequence numbers for time-sensitive operations
    /// - Be deterministic for the same logical operation
    ///
    /// Example patterns:
    /// - `"transfer_{from}_{to}_{amount}_{currency}_{date}_{sequence}"`
    /// - `"price_check_{symbol}_{currency}_{timestamp}"`
    /// - `"user_action_{user_id}_{action}_{target}_{date}"`
    pub fn new_idempotent<T: Serialize>(
        tool_name: impl Into<String>,
        params: &T,
        max_retries: u32,
        idempotency_key: impl Into<String>,
    ) -> Result<Self, serde_json::Error> {
        Ok(Self {
            job_id: Uuid::new_v4(),
            tool_name: tool_name.into(),
            params: serde_json::to_value(params)?,
            idempotency_key: Some(idempotency_key.into()),
            max_retries,
            retry_count: 0,
        })
    }

    /// Check if this job has retries remaining.
    ///
    /// Returns `true` if the job can be retried after a failure,
    /// `false` if all retry attempts have been exhausted.
    ///
    /// # Returns
    /// * `true` - Job can be retried (`retry_count < max_retries`)
    /// * `false` - No retries remaining (`retry_count >= max_retries`)
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::Job;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut job = Job::new("test_tool", &json!({}), 2)?;
    ///
    /// assert!(job.can_retry());  // 0 < 2, can retry
    /// job.increment_retry();
    /// assert!(job.can_retry());  // 1 < 2, can retry
    /// job.increment_retry();
    /// assert!(!job.can_retry()); // 2 >= 2, cannot retry
    /// # Ok(())
    /// # }
    /// ```
    pub fn can_retry(&self) -> bool {
        self.retry_count < self.max_retries
    }

    /// Increment the retry count for this job.
    ///
    /// This should be called by the job processing system after each
    /// failed execution attempt. The retry count is used to determine
    /// whether the job can be retried again.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::Job;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut job = Job::new("test_tool", &json!({}), 3)?;
    ///
    /// assert_eq!(job.retry_count, 0);
    /// job.increment_retry();
    /// assert_eq!(job.retry_count, 1);
    /// job.increment_retry();
    /// assert_eq!(job.retry_count, 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn increment_retry(&mut self) {
        self.retry_count += 1;
    }
}

/// Result of executing a job, indicating success or failure with classification.
///
/// The `JobResult` enum provides structured representation of job execution outcomes,
/// enabling the system to make intelligent decisions about error handling and retry logic.
///
/// ## Success vs Failure
///
/// - **Success**: The tool executed successfully and produced a result
/// - **Failure**: The tool execution failed, with classification for retry behavior
///
/// ## Failure Classification
///
/// Failed executions are classified as either retriable or permanent:
///
/// - **Retriable failures**: Temporary issues that may resolve on retry
///   - Network timeouts, connection errors
///   - Rate limiting from external APIs
///   - Temporary service unavailability
///   - Resource contention
///
/// - **Permanent failures**: Issues that won't be resolved by retrying
///   - Invalid parameters or malformed requests
///   - Authentication/authorization failures
///   - Insufficient funds or resources
///   - Business logic violations
///
/// ## Examples
///
/// ### Creating Success Results
///
/// ```rust
/// use riglr_core::JobResult;
/// use serde_json::json;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Simple success result
/// let result = JobResult::success(&json!({
///     "temperature": 72,
///     "humidity": 65,
///     "condition": "sunny"
/// }))?;
/// assert!(result.is_success());
///
/// // Success result with transaction hash
/// let tx_result = JobResult::success_with_tx(
///     &json!({
///         "recipient": "0x123...",
///         "amount": "1.5",
///         "status": "confirmed"
///     }),
///     "0xabc123def456..."
/// )?;
/// assert!(tx_result.is_success());
/// # Ok(())
/// # }
/// ```
///
/// ### Creating Failure Results
///
/// ```rust
/// use riglr_core::{JobResult, ToolError};
///
/// // Retriable failure using new ToolError structure
/// let network_error = JobResult::Failure {
///     error: ToolError::retriable_string("Connection timeout after 30 seconds")
/// };
/// assert!(network_error.is_retriable());
/// assert!(!network_error.is_success());
///
/// // Permanent failure using new ToolError structure
/// let validation_error = JobResult::Failure {
///     error: ToolError::permanent_string("Invalid email address format")
/// };
/// assert!(!validation_error.is_retriable());
/// assert!(!validation_error.is_success());
/// ```
///
/// ### Pattern Matching
///
/// ```rust
/// use riglr_core::JobResult;
///
/// fn handle_result(result: JobResult) {
///     match result {
///         JobResult::Success { value, tx_hash } => {
///             println!("Success: {:?}", value);
///             if let Some(hash) = tx_hash {
///                 println!("Transaction: {}", hash);
///             }
///         }
///         JobResult::Failure { error } => {
///             if error.is_retriable() {
///                 println!("Temporary failure (will retry): {}", error);
///                 if let Some(delay) = error.retry_after() {
///                     println!("Retry after: {:?}", delay);
///                 }
///             } else {
///                 println!("Permanent failure (won't retry): {}", error);
///             }
///         }
///     }
/// }
/// ```
#[derive(Debug, Serialize, Deserialize)]
pub enum JobResult {
    /// Job executed successfully and produced a result.
    ///
    /// This variant indicates that the tool completed its work successfully
    /// and returned data. The result may optionally include a transaction
    /// hash for blockchain operations.
    Success {
        /// The result data produced by the tool execution.
        ///
        /// This contains the actual output of the tool, serialized as JSON.
        /// The structure of this value depends on the specific tool that
        /// was executed.
        value: serde_json::Value,

        /// Optional transaction hash for blockchain operations.
        ///
        /// When the tool performs a blockchain transaction (transfer, swap, etc.),
        /// this field should contain the transaction hash for tracking and
        /// verification purposes. For non-blockchain operations, this is typically `None`.
        tx_hash: Option<String>,
    },

    /// Job execution failed with error details and retry classification.
    ///
    /// This variant indicates that the tool execution failed. The ToolError
    /// contains the error details and determines whether it's retriable.
    Failure {
        /// The structured error from tool execution.
        ///
        /// ToolError provides rich error classification including retriability,
        /// rate limiting, and error context.
        error: crate::error::ToolError,
    },
}

/// Manual Clone implementation for JobResult
///
/// # Why Manual Implementation Is Necessary
///
/// A manual Clone implementation is required because `ToolError` contains a
/// `source: Option<Arc<dyn Error + Send + Sync>>` field. The `dyn Error` trait object
/// doesn't automatically implement Clone, which prevents the compiler from deriving
/// Clone automatically for types containing it.
///
/// # Performance Characteristics
///
/// This implementation is extremely efficient:
/// - For `Success` variants: Clones the JSON value and optional string (standard clones)
/// - For `Failure` variants: Uses `Arc::clone` on the error's source field
///   
/// The use of `Arc::clone` is critical - it's a cheap, pointer-copying operation that
/// increments the reference count, NOT a deep clone of the error itself. This means
/// cloning a JobResult with an error is as fast as cloning a pointer, regardless of
/// the error's complexity.
///
/// # Maintenance Warning
///
/// If you modify the `ToolError` enum (adding new variants or fields), you MUST ensure
/// the Clone implementation remains correct. There is an exhaustive "canary" test in
/// `riglr-core/tests/arc_error_cloning_test.rs` that will fail to compile if the
/// ToolError enum is modified without corresponding updates to its Clone logic.
///
/// Always run `cargo test --package riglr-core arc_error_cloning_test` after modifying
/// ToolError to ensure your changes are properly handled.
impl Clone for JobResult {
    fn clone(&self) -> Self {
        match self {
            Self::Success { value, tx_hash } => Self::Success {
                value: value.clone(),
                tx_hash: tx_hash.clone(),
            },
            Self::Failure { error } => {
                // Clone the ToolError - now cheap with Arc
                let cloned_error = error.clone();
                Self::Failure {
                    error: cloned_error,
                }
            }
        }
    }
}

impl JobResult {
    /// Create a successful result without a transaction hash.
    ///
    /// This is the standard way to create success results for operations
    /// that don't involve blockchain transactions.
    ///
    /// # Parameters
    /// * `value` - The result data to serialize as JSON
    ///
    /// # Returns
    /// * `Ok(JobResult::Success)` - Successfully created result
    /// * `Err(serde_json::Error)` - If value cannot be serialized to JSON
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::JobResult;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // API response result
    /// let api_result = JobResult::success(&json!({
    ///     "data": {
    ///         "price": 45000.50,
    ///         "currency": "USD",
    ///         "timestamp": 1638360000
    ///     },
    ///     "status": "success"
    /// }))?;
    ///
    /// assert!(api_result.is_success());
    /// # Ok(())
    /// # }
    /// ```
    pub fn success<T: Serialize>(value: &T) -> Result<Self, serde_json::Error> {
        Ok(JobResult::Success {
            value: serde_json::to_value(value)?,
            tx_hash: None,
        })
    }

    /// Create a successful result with a blockchain transaction hash.
    ///
    /// Use this for operations that involve blockchain transactions,
    /// such as transfers, swaps, or contract interactions. The transaction
    /// hash enables tracking and verification of the operation.
    ///
    /// # Parameters
    /// * `value` - The result data to serialize as JSON
    /// * `tx_hash` - The blockchain transaction hash
    ///
    /// # Returns
    /// * `Ok(JobResult::Success)` - Successfully created result
    /// * `Err(serde_json::Error)` - If value cannot be serialized to JSON
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::JobResult;
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Solana transfer result
    /// let transfer_result = JobResult::success_with_tx(
    ///     &json!({
    ///         "from": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
    ///         "to": "7XjBz3VSM8Y6kXoHdXFRvLV8Fn6dQJgj9AJhCFJZ9L2x",
    ///         "amount": 1.5,
    ///         "currency": "SOL",
    ///         "status": "confirmed"
    ///     }),
    ///     "2Z8h8K6wF5L9X3mE4u1nV7yQ9H5pG3rD1M2cB6x8Wq7N"
    /// )?;
    ///
    /// // Ethereum swap result
    /// let swap_result = JobResult::success_with_tx(
    ///     &json!({
    ///         "input_token": "USDC",
    ///         "output_token": "WETH",
    ///         "input_amount": "1000.00",
    ///         "output_amount": "0.42",
    ///         "slippage": "0.5%"
    ///     }),
    ///     "0x1234567890abcdef1234567890abcdef12345678"
    /// )?;
    ///
    /// assert!(transfer_result.is_success());
    /// assert!(swap_result.is_success());
    /// # Ok(())
    /// # }
    /// ```
    pub fn success_with_tx<T: Serialize>(
        value: &T,
        tx_hash: impl Into<String>,
    ) -> Result<Self, serde_json::Error> {
        Ok(JobResult::Success {
            value: serde_json::to_value(value)?,
            tx_hash: Some(tx_hash.into()),
        })
    }

    /// Create a retriable failure result.
    ///
    /// Use this for temporary failures that may resolve on retry, such as
    /// network timeouts, rate limits, or temporary service unavailability.
    /// The worker will attempt to retry jobs that fail with retriable errors.
    ///
    /// # Parameters
    /// * `error` - Human-readable error message describing the failure
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::{JobResult, ToolError};
    ///
    /// // Network connectivity issues
    /// let network_error = JobResult::Failure {
    ///     error: ToolError::retriable_string("Connection timeout after 30 seconds")
    /// };
    ///
    /// // Rate limiting with retry delay
    /// let rate_limit = JobResult::Failure {
    ///     error: ToolError::rate_limited_string("API rate limit exceeded")
    /// };
    ///
    /// // Service unavailability
    /// let service_down = JobResult::Failure {
    ///     error: ToolError::retriable_string("Service temporarily unavailable (HTTP 503)")
    /// };
    ///
    /// assert!(network_error.is_retriable());
    /// assert!(rate_limit.is_retriable());
    /// assert!(service_down.is_retriable());
    /// ```
    /// Check if this result represents a successful execution.
    ///
    /// # Returns
    /// * `true` - If this is a `JobResult::Success`
    /// * `false` - If this is a `JobResult::Failure`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::{JobResult, ToolError};
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let success = JobResult::success(&json!({"data": "ok"}))?;
    /// let failure = JobResult::Failure {
    ///     error: ToolError::permanent_string("Error occurred")
    /// };
    ///
    /// assert!(success.is_success());
    /// assert!(!failure.is_success());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_success(&self) -> bool {
        matches!(self, JobResult::Success { .. })
    }

    /// Check if this result represents a retriable failure.
    ///
    /// This method returns `true` only for `JobResult::Failure` variants
    /// where `retriable` is `true`. Success results always return `false`.
    ///
    /// # Returns
    /// * `true` - If this is a retriable failure
    /// * `false` - If this is a success or permanent failure
    ///
    /// # Examples
    ///
    /// ```rust
    /// use riglr_core::{JobResult, ToolError};
    /// use serde_json::json;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let success = JobResult::success(&json!({"data": "ok"}))?;
    /// let retriable = JobResult::Failure {
    ///     error: ToolError::retriable_string("Network timeout")
    /// };
    /// let permanent = JobResult::Failure {
    ///     error: ToolError::permanent_string("Invalid input")
    /// };
    ///
    /// assert!(!success.is_retriable());     // Success is not retriable
    /// assert!(retriable.is_retriable());    // Retriable failure
    /// assert!(!permanent.is_retriable());   // Permanent failure is not retriable
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_retriable(&self) -> bool {
        match self {
            JobResult::Failure { error } => error.is_retriable(),
            _ => false,
        }
    }
}

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

    /// Compile-time test to ensure JobResult remains cloneable.
    /// This test will fail to compile if JobResult or any of its fields
    /// don't implement Clone, preventing the maintenance risk of manual
    /// Clone implementations getting out of sync.
    #[test]
    fn test_job_result_clone_trait_bound() {
        fn assert_clone<T: Clone>() {}

        // Assert that JobResult implements Clone
        assert_clone::<JobResult>();

        // Assert that all field types implement Clone
        assert_clone::<serde_json::Value>();
        assert_clone::<Option<String>>();
        assert_clone::<crate::error::ToolError>();

        // Test actual cloning to ensure it works at runtime
        let success = JobResult::Success {
            value: serde_json::json!({"test": "data"}),
            tx_hash: Some("0x123".to_string()),
        };
        let _cloned_success = success.clone();

        let failure = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("test error"),
        };
        let _cloned_failure = failure.clone();
    }

    /// Test that cloning JobResult preserves error sources with Arc.
    /// This ensures that error chains are preserved efficiently.
    #[test]
    fn test_job_result_clone_preserves_error_source() {
        use std::error::Error;

        // Create a source error
        #[derive(Debug)]
        struct SourceError(String);
        impl std::fmt::Display for SourceError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.0)
            }
        }
        impl Error for SourceError {}

        // Create a JobResult with an error containing a source
        let error_with_source = crate::error::ToolError::retriable_with_source(
            SourceError("original error".to_string()),
            "operation failed",
        );

        let result = JobResult::Failure {
            error: error_with_source,
        };

        // Clone the result
        let cloned = result.clone();

        // Verify the clone has the same error source
        match (&result, &cloned) {
            (JobResult::Failure { error: original }, JobResult::Failure { error: cloned_err }) => {
                assert!(original.source().is_some());
                assert!(cloned_err.source().is_some());
                assert_eq!(
                    original.source().unwrap().to_string(),
                    cloned_err.source().unwrap().to_string()
                );
            }
            _ => panic!("Expected both to be Failure variants"),
        }
    }

    #[test]
    fn test_job_creation() {
        let params = serde_json::json!({"key": "value"});
        let job = Job::new("test_tool", &params, 3).unwrap();

        assert_eq!(job.tool_name, "test_tool");
        assert_eq!(job.params, params);
        assert_eq!(job.max_retries, 3);
        assert_eq!(job.retry_count, 0);
        assert!(job.idempotency_key.is_none());
        assert!(job.can_retry());
    }

    #[test]
    fn test_job_new_when_valid_params_should_succeed() {
        // Test with various parameter types
        let string_params = "test string";
        let job = Job::new("string_tool", &string_params, 5).unwrap();
        assert_eq!(job.tool_name, "string_tool");
        assert_eq!(job.max_retries, 5);
        assert_eq!(job.retry_count, 0);
        assert!(job.idempotency_key.is_none());
        assert!(job.job_id != Uuid::nil());

        // Test with complex JSON object
        let complex_params = serde_json::json!({
            "nested": {
                "array": [1, 2, 3],
                "string": "test",
                "bool": true,
                "null": null
            }
        });
        let job = Job::new("complex_tool", &complex_params, 0).unwrap();
        assert_eq!(job.params, complex_params);
        assert_eq!(job.max_retries, 0);
    }

    #[test]
    fn test_job_new_when_zero_retries_should_not_allow_retry() {
        let job = Job::new("test_tool", &serde_json::json!({}), 0).unwrap();
        assert_eq!(job.max_retries, 0);
        assert!(!job.can_retry()); // 0 < 0 is false
    }

    #[test]
    fn test_job_new_when_tool_name_is_string_slice_should_convert() {
        let job = Job::new("slice_tool", &serde_json::json!({}), 1).unwrap();
        assert_eq!(job.tool_name, "slice_tool");
    }

    #[test]
    fn test_job_new_when_tool_name_is_string_should_convert() {
        let tool_name = String::from("owned_tool");
        let job = Job::new(tool_name, &serde_json::json!({}), 1).unwrap();
        assert_eq!(job.tool_name, "owned_tool");
    }

    #[test]
    fn test_job_with_idempotency() {
        let params = serde_json::json!({"key": "value"});
        let job = Job::new_idempotent("test_tool", &params, 3, "test_key").unwrap();

        assert_eq!(job.idempotency_key, Some("test_key".to_string()));
    }

    #[test]
    fn test_job_new_idempotent_when_valid_params_should_succeed() {
        let params = serde_json::json!({"transfer": "data"});
        let job = Job::new_idempotent("idempotent_tool", &params, 2, "unique_key_123").unwrap();

        assert_eq!(job.tool_name, "idempotent_tool");
        assert_eq!(job.params, params);
        assert_eq!(job.max_retries, 2);
        assert_eq!(job.retry_count, 0);
        assert_eq!(job.idempotency_key, Some("unique_key_123".to_string()));
        assert!(job.job_id != Uuid::nil());
        assert!(job.can_retry());
    }

    #[test]
    fn test_job_new_idempotent_when_key_is_string_slice_should_convert() {
        let job = Job::new_idempotent("test_tool", &serde_json::json!({}), 1, "slice_key").unwrap();
        assert_eq!(job.idempotency_key, Some("slice_key".to_string()));
    }

    #[test]
    fn test_job_new_idempotent_when_key_is_string_should_convert() {
        let key = String::from("owned_key");
        let job = Job::new_idempotent("test_tool", &serde_json::json!({}), 1, key).unwrap();
        assert_eq!(job.idempotency_key, Some("owned_key".to_string()));
    }

    #[test]
    fn test_job_retry_logic() {
        let params = serde_json::json!({"key": "value"});
        let mut job = Job::new("test_tool", &params, 2).unwrap();

        assert!(job.can_retry());
        job.increment_retry();
        assert!(job.can_retry());
        job.increment_retry();
        assert!(!job.can_retry());
    }

    #[test]
    fn test_job_can_retry_when_retry_count_equals_max_retries_should_return_false() {
        let mut job = Job::new("test_tool", &serde_json::json!({}), 1).unwrap();
        job.retry_count = 1; // Set equal to max_retries
        assert!(!job.can_retry());
    }

    #[test]
    fn test_job_can_retry_when_retry_count_exceeds_max_retries_should_return_false() {
        let mut job = Job::new("test_tool", &serde_json::json!({}), 1).unwrap();
        job.retry_count = 2; // Set greater than max_retries
        assert!(!job.can_retry());
    }

    #[test]
    fn test_job_increment_retry_when_called_multiple_times_should_increment() {
        let mut job = Job::new("test_tool", &serde_json::json!({}), 5).unwrap();

        assert_eq!(job.retry_count, 0);
        job.increment_retry();
        assert_eq!(job.retry_count, 1);
        job.increment_retry();
        assert_eq!(job.retry_count, 2);
        job.increment_retry();
        assert_eq!(job.retry_count, 3);
    }

    #[test]
    fn test_job_increment_retry_when_already_at_max_should_still_increment() {
        let mut job = Job::new("test_tool", &serde_json::json!({}), 1).unwrap();
        job.retry_count = 1;

        job.increment_retry();
        assert_eq!(job.retry_count, 2); // Should still increment even if past max
    }

    #[test]
    fn test_job_result_creation() {
        let success = JobResult::success(&"test_value").unwrap();
        assert!(success.is_success());

        let success_with_tx = JobResult::success_with_tx(&"test_value", "tx_hash").unwrap();
        assert!(success_with_tx.is_success());

        let retriable_failure = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("test error"),
        };
        assert!(retriable_failure.is_retriable());
        assert!(!retriable_failure.is_success());

        let permanent_failure = JobResult::Failure {
            error: crate::error::ToolError::permanent_string("test error"),
        };
        assert!(!permanent_failure.is_retriable());
        assert!(!permanent_failure.is_success());
    }

    #[test]
    fn test_job_result_success_when_valid_value_should_create_success() {
        // Test with simple value
        let result = JobResult::success(&42).unwrap();
        match result {
            JobResult::Success {
                ref value,
                ref tx_hash,
            } => {
                assert_eq!(*value, serde_json::json!(42));
                assert!(tx_hash.is_none());
            }
            _ => panic!("Expected Success variant"),
        }
        assert!(result.is_success());
        assert!(!result.is_retriable());

        // Test with complex object
        let complex_data = serde_json::json!({
            "status": "completed",
            "data": {
                "items": [1, 2, 3],
                "metadata": {
                    "count": 3,
                    "timestamp": "2024-01-01"
                }
            }
        });
        let result = JobResult::success(&complex_data).unwrap();
        match result {
            JobResult::Success { value, tx_hash } => {
                assert_eq!(value, complex_data);
                assert!(tx_hash.is_none());
            }
            _ => panic!("Expected Success variant"),
        }
    }

    #[test]
    fn test_job_result_success_with_tx_when_valid_params_should_create_success() {
        let data = serde_json::json!({"amount": 100, "recipient": "0xabc"});
        let tx_hash = "0x123456789abcdef";

        let result = JobResult::success_with_tx(&data, tx_hash).unwrap();

        match result {
            JobResult::Success {
                ref value,
                tx_hash: ref hash,
            } => {
                assert_eq!(*value, data);
                assert_eq!(*hash, Some("0x123456789abcdef".to_string()));
            }
            _ => panic!("Expected Success variant"),
        }
        assert!(result.is_success());
        assert!(!result.is_retriable());
    }

    #[test]
    fn test_job_result_success_with_tx_when_tx_hash_is_string_slice_should_convert() {
        let result = JobResult::success_with_tx(&"test", "slice_hash").unwrap();
        match result {
            JobResult::Success { tx_hash, .. } => {
                assert_eq!(tx_hash, Some("slice_hash".to_string()));
            }
            _ => panic!("Expected Success variant"),
        }
    }

    #[test]
    fn test_job_result_success_with_tx_when_tx_hash_is_string_should_convert() {
        let hash = String::from("owned_hash");
        let result = JobResult::success_with_tx(&"test", hash).unwrap();
        match result {
            JobResult::Success { tx_hash, .. } => {
                assert_eq!(tx_hash, Some("owned_hash".to_string()));
            }
            _ => panic!("Expected Success variant"),
        }
    }

    #[test]
    fn test_job_result_retriable_failure_when_error_message_should_create_retriable() {
        let error_msg = "Connection timeout occurred";
        let result = JobResult::Failure {
            error: crate::error::ToolError::retriable_string(error_msg),
        };

        match result {
            JobResult::Failure { ref error } => {
                assert!(error.contains("Connection timeout occurred"));
                assert!(result.is_retriable());
            }
            _ => panic!("Expected Failure variant"),
        }
        assert!(!result.is_success());
        assert!(result.is_retriable());
    }

    #[test]
    fn test_job_result_retriable_failure_when_error_is_string_slice_should_convert() {
        let result = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("slice error"),
        };
        match result {
            JobResult::Failure { error } => {
                assert_eq!(
                    error.to_string(),
                    "Operation can be retried: slice error - slice error"
                );
            }
            _ => panic!("Expected Failure variant"),
        }
    }

    #[test]
    fn test_job_result_retriable_failure_when_error_is_string_should_convert() {
        let error = String::from("owned error");
        let result = JobResult::Failure {
            error: crate::error::ToolError::retriable_string(error),
        };
        match result {
            JobResult::Failure { error } => {
                assert_eq!(
                    error.to_string(),
                    "Operation can be retried: owned error - owned error"
                );
            }
            _ => panic!("Expected Failure variant"),
        }
    }

    #[test]
    fn test_job_result_permanent_failure_when_error_message_should_create_permanent() {
        let error_msg = "Invalid input parameters";
        let result = JobResult::Failure {
            error: crate::error::ToolError::permanent_string(error_msg),
        };

        match result {
            JobResult::Failure { ref error } => {
                assert!(error.contains("Invalid input parameters"));
                assert!(!result.is_retriable());
            }
            _ => panic!("Expected Failure variant"),
        }
        assert!(!result.is_success());
        assert!(!result.is_retriable());
    }

    #[test]
    fn test_job_result_permanent_failure_when_error_is_string_slice_should_convert() {
        let result = JobResult::Failure {
            error: crate::error::ToolError::permanent_string("slice error"),
        };
        match result {
            JobResult::Failure { error } => {
                assert_eq!(
                    error.to_string(),
                    "Permanent error: slice error - slice error"
                );
            }
            _ => panic!("Expected Failure variant"),
        }
    }

    #[test]
    fn test_job_result_permanent_failure_when_error_is_string_should_convert() {
        let error = String::from("owned error");
        let result = JobResult::Failure {
            error: crate::error::ToolError::permanent_string(error),
        };
        match result {
            JobResult::Failure { error } => {
                assert_eq!(
                    error.to_string(),
                    "Permanent error: owned error - owned error"
                );
            }
            _ => panic!("Expected Failure variant"),
        }
    }

    #[test]
    fn test_job_result_is_success_when_success_variant_should_return_true() {
        let success = JobResult::success(&"test").unwrap();
        assert!(success.is_success());

        let success_with_tx = JobResult::success_with_tx(&"test", "hash").unwrap();
        assert!(success_with_tx.is_success());
    }

    #[test]
    fn test_job_result_is_success_when_failure_variant_should_return_false() {
        let retriable_failure = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("error"),
        };
        assert!(!retriable_failure.is_success());

        let permanent_failure = JobResult::Failure {
            error: crate::error::ToolError::permanent_string("error"),
        };
        assert!(!permanent_failure.is_success());
    }

    #[test]
    fn test_job_result_is_retriable_when_retriable_failure_should_return_true() {
        let result = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("Network error"),
        };
        assert!(result.is_retriable());
    }

    #[test]
    fn test_job_result_is_retriable_when_permanent_failure_should_return_false() {
        let result = JobResult::Failure {
            error: crate::error::ToolError::permanent_string("Invalid input"),
        };
        assert!(!result.is_retriable());
    }

    #[test]
    fn test_job_result_is_retriable_when_success_should_return_false() {
        let result = JobResult::success(&"test").unwrap();
        assert!(!result.is_retriable());

        let result_with_tx = JobResult::success_with_tx(&"test", "hash").unwrap();
        assert!(!result_with_tx.is_retriable());
    }

    #[test]
    fn test_job_clone_should_create_identical_copy() {
        let original = Job::new_idempotent(
            "clone_tool",
            &serde_json::json!({"test": true}),
            3,
            "clone_key",
        )
        .unwrap();
        let cloned = original.clone();

        assert_eq!(original.job_id, cloned.job_id);
        assert_eq!(original.tool_name, cloned.tool_name);
        assert_eq!(original.params, cloned.params);
        assert_eq!(original.idempotency_key, cloned.idempotency_key);
        assert_eq!(original.max_retries, cloned.max_retries);
        assert_eq!(original.retry_count, cloned.retry_count);
    }

    #[test]
    fn test_job_result_clone_should_create_identical_copy() {
        let original_success =
            JobResult::success_with_tx(&serde_json::json!({"data": "test"}), "tx123").unwrap();
        let cloned_success = original_success.clone();

        match (&original_success, &cloned_success) {
            (
                JobResult::Success {
                    value: v1,
                    tx_hash: h1,
                },
                JobResult::Success {
                    value: v2,
                    tx_hash: h2,
                },
            ) => {
                assert_eq!(v1, v2);
                assert_eq!(h1, h2);
            }
            _ => panic!("Expected Success variants"),
        }

        let original_failure = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("test error"),
        };
        let cloned_failure = original_failure.clone();

        match (&original_failure, &cloned_failure) {
            (JobResult::Failure { error: e1 }, JobResult::Failure { error: e2 }) => {
                assert_eq!(e1, e2);
            }
            _ => panic!("Expected Failure variants"),
        }
    }

    #[test]
    fn test_job_serialization_and_deserialization_should_preserve_data() {
        let original = Job::new_idempotent(
            "serialize_tool",
            &serde_json::json!({"key": "value"}),
            5,
            "serialize_key",
        )
        .unwrap();

        // Serialize to JSON
        let serialized = serde_json::to_string(&original).unwrap();

        // Deserialize back
        let deserialized: Job = serde_json::from_str(&serialized).unwrap();

        assert_eq!(original.job_id, deserialized.job_id);
        assert_eq!(original.tool_name, deserialized.tool_name);
        assert_eq!(original.params, deserialized.params);
        assert_eq!(original.idempotency_key, deserialized.idempotency_key);
        assert_eq!(original.max_retries, deserialized.max_retries);
        assert_eq!(original.retry_count, deserialized.retry_count);
    }

    #[test]
    fn test_job_result_serialization_and_deserialization_should_preserve_data() {
        // Test Success variant
        let original_success =
            JobResult::success_with_tx(&serde_json::json!({"amount": 100}), "hash123").unwrap();
        let serialized = serde_json::to_string(&original_success).unwrap();
        let deserialized: JobResult = serde_json::from_str(&serialized).unwrap();

        match (&original_success, &deserialized) {
            (
                JobResult::Success {
                    value: v1,
                    tx_hash: h1,
                },
                JobResult::Success {
                    value: v2,
                    tx_hash: h2,
                },
            ) => {
                assert_eq!(v1, v2);
                assert_eq!(h1, h2);
            }
            _ => panic!("Expected Success variants"),
        }

        // Test Failure variant
        let original_failure = JobResult::Failure {
            error: crate::error::ToolError::retriable_string("Network timeout"),
        };
        let serialized = serde_json::to_string(&original_failure).unwrap();
        let deserialized: JobResult = serde_json::from_str(&serialized).unwrap();

        match (&original_failure, &deserialized) {
            (JobResult::Failure { error: e1 }, JobResult::Failure { error: e2 }) => {
                assert_eq!(e1, e2);
            }
            _ => panic!("Expected Failure variants"),
        }
    }

    #[test]
    fn test_job_default_retry_count_when_deserializing_without_field_should_be_zero() {
        // Create JSON without retry_count field to test #[serde(default)]
        let json = r#"{
            "job_id": "550e8400-e29b-41d4-a716-446655440000",
            "tool_name": "test_tool",
            "params": {"key": "value"},
            "idempotency_key": null,
            "max_retries": 3
        }"#;

        let job: Job = serde_json::from_str(json).unwrap();
        assert_eq!(job.retry_count, 0); // Should default to 0
    }

    #[test]
    fn test_job_debug_format_should_include_all_fields() {
        let job = Job::new_idempotent(
            "debug_tool",
            &serde_json::json!({"test": "data"}),
            2,
            "debug_key",
        )
        .unwrap();
        let debug_output = format!("{:?}", job);

        // Should contain all major field information
        assert!(debug_output.contains("job_id"));
        assert!(debug_output.contains("debug_tool"));
        assert!(debug_output.contains("test"));
        assert!(debug_output.contains("debug_key"));
        assert!(debug_output.contains("2")); // max_retries
    }

    #[test]
    fn test_job_result_debug_format_should_include_variant_info() {
        let success =
            JobResult::success_with_tx(&serde_json::json!({"data": "test"}), "tx456").unwrap();
        let success_debug = format!("{:?}", success);
        assert!(success_debug.contains("Success"));
        assert!(success_debug.contains("tx456"));

        let failure = JobResult::Failure {
            error: crate::error::ToolError::permanent_string("Debug error message"),
        };
        let failure_debug = format!("{:?}", failure);
        assert!(failure_debug.contains("Failure"));
        assert!(failure_debug.contains("Debug error message"));
        assert!(failure_debug.contains("Permanent")); // Permanent error variant
    }
}

/// Transaction status tracking for job lifecycle
///
/// This enum represents the various states a transaction can be in during
/// its execution lifecycle, from initial submission through final confirmation.
#[derive(Debug, Clone)]
pub enum TransactionStatus {
    /// Transaction is pending submission
    Pending,
    /// Transaction has been submitted to the network
    Submitted {
        /// Transaction hash from the network
        hash: String,
    },
    /// Transaction is being confirmed
    Confirming {
        /// Transaction hash from the network
        hash: String,
        /// Current number of confirmations received
        confirmations: u64,
    },
    /// Transaction has been confirmed
    Confirmed {
        /// Transaction hash from the network
        hash: String,
        /// Block number where the transaction was included
        block: u64,
    },
    /// Transaction failed
    Failed {
        /// Reason why the transaction failed
        reason: String,
    },
}