codetether-agent 4.0.0

A2A-native AI coding agent for the CodeTether ecosystem
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
//! OKR (Objectives and Key Results) domain models
//!
//! This module provides first-class OKR entities for operational control:
//! - `Okr` - An objective with measurable key results
//! - `KeyResult` - Quantifiable outcomes tied to objectives
//! - `OkrRun` - An execution instance of an OKR
//! - `ApprovalDecision` - Approve/deny gate decisions
//! - `KrOutcome` - Evidence-backed outcomes for key results
//! - `OkrRepository` - File-based persistence with CRUD operations

pub mod persistence;

pub use persistence::OkrRepository;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

/// A high-level objective with associated key results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Okr {
    /// Unique identifier for this OKR
    pub id: Uuid,

    /// Human-readable title of the objective
    pub title: String,

    /// Detailed description of what this objective aims to achieve
    pub description: String,

    /// Current status of the OKR
    #[serde(default)]
    pub status: OkrStatus,

    /// Key results that measure success
    #[serde(default)]
    pub key_results: Vec<KeyResult>,

    /// Owner of this OKR (user ID or team)
    #[serde(default)]
    pub owner: Option<String>,

    /// Tenant ID for multi-tenant isolation
    #[serde(default)]
    pub tenant_id: Option<String>,

    /// Tags for categorization
    #[serde(default)]
    pub tags: Vec<String>,

    /// Creation timestamp
    #[serde(default = "utc_now")]
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    #[serde(default = "utc_now")]
    pub updated_at: DateTime<Utc>,

    /// Target completion date
    #[serde(default)]
    pub target_date: Option<DateTime<Utc>>,
}

impl Okr {
    /// Create a new OKR with a generated UUID
    pub fn new(title: impl Into<String>, description: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            title: title.into(),
            description: description.into(),
            status: OkrStatus::Draft,
            key_results: Vec::new(),
            owner: None,
            tenant_id: None,
            tags: Vec::new(),
            created_at: now,
            updated_at: now,
            target_date: None,
        }
    }

    /// Validate the OKR structure
    pub fn validate(&self) -> Result<(), OkrValidationError> {
        if self.title.trim().is_empty() {
            return Err(OkrValidationError::EmptyTitle);
        }
        if self.key_results.is_empty() {
            return Err(OkrValidationError::NoKeyResults);
        }
        for kr in &self.key_results {
            kr.validate()?;
        }
        Ok(())
    }

    /// Calculate overall progress (0.0 to 1.0) across all key results
    pub fn progress(&self) -> f64 {
        if self.key_results.is_empty() {
            return 0.0;
        }
        let total: f64 = self.key_results.iter().map(|kr| kr.progress()).sum();
        total / self.key_results.len() as f64
    }

    /// Check if all key results are complete
    pub fn is_complete(&self) -> bool {
        self.key_results.iter().all(|kr| kr.is_complete())
    }

    /// Add a key result to this OKR
    pub fn add_key_result(&mut self, kr: KeyResult) {
        self.key_results.push(kr);
        self.updated_at = Utc::now();
    }
}

/// OKR status enum
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OkrStatus {
    /// Draft - not yet approved
    Draft,

    /// Active - approved and in progress
    Active,

    /// Completed - all key results achieved
    Completed,

    /// Cancelled - abandoned before completion
    Cancelled,

    /// OnHold - temporarily paused
    OnHold,
}

impl Default for OkrStatus {
    fn default() -> Self {
        OkrStatus::Draft
    }
}

/// A measurable key result within an OKR
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyResult {
    /// Unique identifier for this key result
    pub id: Uuid,

    /// Parent OKR ID
    pub okr_id: Uuid,

    /// Human-readable title
    pub title: String,

    /// Detailed description
    pub description: String,

    /// Target value (numeric for percentage/count metrics)
    pub target_value: f64,

    /// Current value (progress)
    #[serde(default)]
    pub current_value: f64,

    /// Unit of measurement (e.g., "%", "count", "files", "tests")
    #[serde(default = "default_unit")]
    pub unit: String,

    /// Type of metric
    #[serde(default)]
    pub metric_type: KrMetricType,

    /// Current status
    #[serde(default)]
    pub status: KeyResultStatus,

    /// Evidence/outcomes linked to this KR
    #[serde(default)]
    pub outcomes: Vec<KrOutcome>,

    /// Creation timestamp
    #[serde(default = "utc_now")]
    pub created_at: DateTime<Utc>,

    /// Last update timestamp
    #[serde(default = "utc_now")]
    pub updated_at: DateTime<Utc>,
}

impl KeyResult {
    /// Create a new key result
    pub fn new(
        okr_id: Uuid,
        title: impl Into<String>,
        target_value: f64,
        unit: impl Into<String>,
    ) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            okr_id,
            title: title.into(),
            description: String::new(),
            target_value,
            current_value: 0.0,
            unit: unit.into(),
            metric_type: KrMetricType::Progress,
            status: KeyResultStatus::Pending,
            outcomes: Vec::new(),
            created_at: now,
            updated_at: now,
        }
    }

    /// Validate the key result
    pub fn validate(&self) -> Result<(), OkrValidationError> {
        if self.title.trim().is_empty() {
            return Err(OkrValidationError::EmptyKeyResultTitle);
        }
        if self.target_value < 0.0 {
            return Err(OkrValidationError::InvalidTargetValue);
        }
        Ok(())
    }

    /// Calculate progress as a ratio (0.0 to 1.0)
    pub fn progress(&self) -> f64 {
        if self.target_value == 0.0 {
            return 0.0;
        }
        (self.current_value / self.target_value).clamp(0.0, 1.0)
    }

    /// Check if the key result is complete
    pub fn is_complete(&self) -> bool {
        self.status == KeyResultStatus::Completed || self.current_value >= self.target_value
    }

    /// Add an outcome to this key result
    pub fn add_outcome(&mut self, outcome: KrOutcome) {
        self.outcomes.push(outcome);
        self.updated_at = Utc::now();
    }

    /// Update current value and recalculate status
    pub fn update_progress(&mut self, value: f64) {
        self.current_value = value;
        self.updated_at = Utc::now();
        if self.is_complete() {
            self.status = KeyResultStatus::Completed;
        } else if self.current_value > 0.0 {
            self.status = KeyResultStatus::InProgress;
        }
    }
}

/// Type of metric for a key result
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KrMetricType {
    /// Progress percentage (0-100)
    Progress,

    /// Count of items
    Count,

    /// Boolean completion
    Binary,

    /// Latency/duration (lower is better)
    Latency,

    /// Quality score (0-1 or 0-100)
    Quality,
}

impl Default for KrMetricType {
    fn default() -> Self {
        KrMetricType::Progress
    }
}

/// Status of a key result
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KeyResultStatus {
    /// Not yet started
    Pending,

    /// Actively being worked on
    InProgress,

    /// Achieved the target
    Completed,

    /// At risk of missing target
    AtRisk,

    /// Failed to achieve target
    Failed,
}

impl Default for KeyResultStatus {
    fn default() -> Self {
        KeyResultStatus::Pending
    }
}

/// An execution run of an OKR (multiple runs per OKR are allowed)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OkrRun {
    /// Unique identifier for this run
    pub id: Uuid,

    /// Parent OKR ID
    pub okr_id: Uuid,

    /// Human-readable name for this run
    pub name: String,

    /// Current status of the run
    #[serde(default)]
    pub status: OkrRunStatus,

    /// Correlation ID linking to relay/session
    #[serde(default)]
    pub correlation_id: Option<String>,

    /// Relay checkpoint ID for resume capability
    #[serde(default)]
    pub relay_checkpoint_id: Option<String>,

    /// Session ID if applicable
    #[serde(default)]
    pub session_id: Option<String>,

    /// Progress per key result (kr_id -> progress)
    #[serde(default)]
    pub kr_progress: std::collections::HashMap<String, f64>,

    /// Approval decision for this run
    #[serde(default)]
    pub approval: Option<ApprovalDecision>,

    /// List of outcomes achieved in this run
    #[serde(default)]
    pub outcomes: Vec<KrOutcome>,

    /// Iteration count for this run
    #[serde(default)]
    pub iterations: u32,

    /// Started timestamp
    #[serde(default = "utc_now")]
    pub started_at: DateTime<Utc>,

    /// Completed timestamp (if finished)
    #[serde(default)]
    pub completed_at: Option<DateTime<Utc>>,

    /// Last update timestamp
    #[serde(default = "utc_now")]
    pub updated_at: DateTime<Utc>,
}

impl OkrRun {
    /// Create a new OKR run
    pub fn new(okr_id: Uuid, name: impl Into<String>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            okr_id,
            name: name.into(),
            status: OkrRunStatus::Draft,
            correlation_id: None,
            relay_checkpoint_id: None,
            session_id: None,
            kr_progress: std::collections::HashMap::new(),
            approval: None,
            outcomes: Vec::new(),
            iterations: 0,
            started_at: now,
            completed_at: None,
            updated_at: now,
        }
    }

    /// Validate the run
    pub fn validate(&self) -> Result<(), OkrValidationError> {
        if self.name.trim().is_empty() {
            return Err(OkrValidationError::EmptyRunName);
        }
        Ok(())
    }

    /// Submit for approval
    pub fn submit_for_approval(&mut self) -> Result<(), OkrValidationError> {
        if self.status != OkrRunStatus::Draft {
            return Err(OkrValidationError::InvalidStatusTransition);
        }
        self.status = OkrRunStatus::PendingApproval;
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Record an approval decision
    pub fn record_decision(&mut self, decision: ApprovalDecision) {
        self.approval = Some(decision.clone());
        self.updated_at = Utc::now();
        match decision.decision {
            ApprovalChoice::Approved => {
                self.status = OkrRunStatus::Approved;
            }
            ApprovalChoice::Denied => {
                self.status = OkrRunStatus::Denied;
            }
        }
    }

    /// Start execution
    pub fn start(&mut self) -> Result<(), OkrValidationError> {
        if self.status != OkrRunStatus::Approved {
            return Err(OkrValidationError::NotApproved);
        }
        self.status = OkrRunStatus::Running;
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Mark as complete
    pub fn complete(&mut self) {
        self.status = OkrRunStatus::Completed;
        self.completed_at = Some(Utc::now());
        self.updated_at = Utc::now();
    }

    /// Update key result progress
    pub fn update_kr_progress(&mut self, kr_id: &str, progress: f64) {
        self.kr_progress.insert(kr_id.to_string(), progress);
        self.updated_at = Utc::now();
    }

    /// Check if run can be resumed
    pub fn is_resumable(&self) -> bool {
        matches!(
            self.status,
            OkrRunStatus::Running | OkrRunStatus::Paused | OkrRunStatus::WaitingApproval
        )
    }
}

/// Status of an OKR run
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OkrRunStatus {
    /// Draft - not yet submitted
    Draft,

    /// Pending approval
    PendingApproval,

    /// Approved to run
    Approved,

    /// Actively running
    Running,

    /// Paused (can resume)
    Paused,

    /// Waiting for something
    WaitingApproval,

    /// Successfully completed
    Completed,

    /// Failed to complete
    Failed,

    /// Denied approval
    Denied,

    /// Cancelled
    Cancelled,
}

impl Default for OkrRunStatus {
    fn default() -> Self {
        OkrRunStatus::Draft
    }
}

/// Approval decision for an OKR run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalDecision {
    /// Unique identifier for this decision
    pub id: Uuid,

    /// ID of the run this decision applies to
    pub run_id: Uuid,

    /// The actual decision
    pub decision: ApprovalChoice,

    /// Reason for the decision
    #[serde(default)]
    pub reason: String,

    /// Who made the decision
    #[serde(default)]
    pub approver: Option<String>,

    /// Additional context/metadata
    #[serde(default)]
    pub metadata: std::collections::HashMap<String, String>,

    /// Timestamp of the decision
    #[serde(default = "utc_now")]
    pub decided_at: DateTime<Utc>,
}

impl ApprovalDecision {
    /// Create an approval
    pub fn approve(run_id: Uuid, reason: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4(),
            run_id,
            decision: ApprovalChoice::Approved,
            reason: reason.into(),
            approver: None,
            metadata: std::collections::HashMap::new(),
            decided_at: Utc::now(),
        }
    }

    /// Create a denial
    pub fn deny(run_id: Uuid, reason: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4(),
            run_id,
            decision: ApprovalChoice::Denied,
            reason: reason.into(),
            approver: None,
            metadata: std::collections::HashMap::new(),
            decided_at: Utc::now(),
        }
    }
}

/// Approval choice enum
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalChoice {
    /// Approved to proceed
    Approved,

    /// Denied
    Denied,
}

/// Evidence-backed outcome for a key result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KrOutcome {
    /// Unique identifier for this outcome
    pub id: Uuid,

    /// Key result this outcome belongs to
    pub kr_id: Uuid,

    /// OKR run this outcome is part of
    #[serde(default)]
    pub run_id: Option<Uuid>,

    /// Description of the outcome/evidence
    pub description: String,

    /// Type of outcome
    #[serde(default)]
    pub outcome_type: KrOutcomeType,

    /// Numeric value contributed (if applicable)
    #[serde(default)]
    pub value: Option<f64>,

    /// Evidence links (URLs, file paths, etc.)
    #[serde(default)]
    pub evidence: Vec<String>,

    /// Who/what generated this outcome
    #[serde(default)]
    pub source: String,

    /// Timestamp
    #[serde(default = "utc_now")]
    pub created_at: DateTime<Utc>,
}

impl KrOutcome {
    /// Create a new outcome
    pub fn new(kr_id: Uuid, description: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4(),
            kr_id,
            run_id: None,
            description: description.into(),
            outcome_type: KrOutcomeType::Evidence,
            value: None,
            evidence: Vec::new(),
            source: String::new(),
            created_at: Utc::now(),
        }
    }

    /// Create a metric outcome with a value
    pub fn with_value(mut self, value: f64) -> Self {
        self.value = Some(value);
        self
    }

    /// Add evidence link
    pub fn add_evidence(mut self, evidence: impl Into<String>) -> Self {
        self.evidence.push(evidence.into());
        self
    }
}

/// Type of key result outcome
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KrOutcomeType {
    /// Evidence/documentation
    Evidence,

    /// Test pass
    TestPass,

    /// Code change
    CodeChange,

    /// Bug fix
    BugFix,

    /// Feature delivered
    FeatureDelivered,

    /// Metric achievement
    MetricAchievement,

    /// Review passed
    ReviewPassed,

    /// Deployment
    Deployment,
}

impl Default for KrOutcomeType {
    fn default() -> Self {
        KrOutcomeType::Evidence
    }
}

/// Validation errors for OKR entities
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OkrValidationError {
    /// Objective title is empty
    EmptyTitle,

    /// No key results defined
    NoKeyResults,

    /// Key result title is empty
    EmptyKeyResultTitle,

    /// Target value is invalid
    InvalidTargetValue,

    /// Run name is empty
    EmptyRunName,

    /// Invalid status transition
    InvalidStatusTransition,

    /// Run not approved
    NotApproved,
}

impl std::fmt::Display for OkrValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OkrValidationError::EmptyTitle => write!(f, "objective title cannot be empty"),
            OkrValidationError::NoKeyResults => write!(f, "at least one key result is required"),
            OkrValidationError::EmptyKeyResultTitle => {
                write!(f, "key result title cannot be empty")
            }
            OkrValidationError::InvalidTargetValue => {
                write!(f, "target value must be non-negative")
            }
            OkrValidationError::EmptyRunName => write!(f, "run name cannot be empty"),
            OkrValidationError::InvalidStatusTransition => {
                write!(f, "invalid status transition")
            }
            OkrValidationError::NotApproved => write!(f, "run must be approved before starting"),
        }
    }
}

impl std::error::Error for OkrValidationError {}

/// Helper to get current UTC time
fn utc_now() -> DateTime<Utc> {
    Utc::now()
}

/// Default unit value
fn default_unit() -> String {
    "%".to_string()
}

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

    #[test]
    fn test_okr_creation() {
        let okr = Okr::new("Test Objective", "Description");
        assert_eq!(okr.title, "Test Objective");
        assert_eq!(okr.status, OkrStatus::Draft);
        assert!(okr.validate().is_err()); // No key results
    }

    #[test]
    fn test_okr_with_key_results() {
        let mut okr = Okr::new("Test Objective", "Description");
        let kr = KeyResult::new(okr.id, "KR1", 100.0, "%");
        okr.add_key_result(kr);
        assert!(okr.validate().is_ok());
    }

    #[test]
    fn test_key_result_progress() {
        let kr = KeyResult::new(Uuid::new_v4(), "Test KR", 100.0, "%");
        assert_eq!(kr.progress(), 0.0);

        let mut kr = kr;
        kr.update_progress(50.0);
        assert!((kr.progress() - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_okr_run_workflow() {
        let okr_id = Uuid::new_v4();
        let mut run = OkrRun::new(okr_id, "Q1 2024 Run");

        // Submit for approval
        run.submit_for_approval().unwrap();
        assert_eq!(run.status, OkrRunStatus::PendingApproval);

        // Record approval
        run.record_decision(ApprovalDecision::approve(run.id, "Looks good"));
        assert_eq!(run.status, OkrRunStatus::Approved);

        // Start execution
        run.start().unwrap();
        assert_eq!(run.status, OkrRunStatus::Running);

        // Update progress
        run.update_kr_progress("kr-1", 0.5);

        // Complete
        run.complete();
        assert_eq!(run.status, OkrRunStatus::Completed);
    }

    #[test]
    fn test_outcome_creation() {
        let outcome = KrOutcome::new(Uuid::new_v4(), "Fixed bug in auth")
            .with_value(1.0)
            .add_evidence("commit:abc123");

        assert_eq!(outcome.value, Some(1.0));
        assert!(outcome.evidence.contains(&"commit:abc123".to_string()));
    }
}