aca 0.3.1

A Rust-based agentic tool that automates coding tasks using Claude Code and OpenAI Codex CLI integrations
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
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use uuid::Uuid;

/// Unique identifier for tasks
pub type TaskId = Uuid;

/// Unique identifier for Claude Code sessions
pub type ClaudeSessionId = Uuid;

/// Core task structure with comprehensive metadata and state tracking
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Task {
    pub id: TaskId,
    pub title: String,
    pub description: String,
    pub status: TaskStatus,
    pub parent_id: Option<TaskId>,
    pub children: Vec<TaskId>,
    pub dependencies: Vec<TaskId>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub metadata: TaskMetadata,
    pub execution_history: Vec<ExecutionRecord>,
}

/// Task status with detailed state information
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TaskStatus {
    /// Task is ready to be executed but hasn't started
    Pending,
    /// Task is currently being processed
    InProgress {
        started_at: DateTime<Utc>,
        estimated_completion: Option<DateTime<Utc>>,
    },
    /// Task is temporarily blocked by external factors
    Blocked {
        reason: String,
        blocked_at: DateTime<Utc>,
        retry_after: Option<DateTime<Utc>>,
    },
    /// Task completed successfully
    Completed {
        completed_at: DateTime<Utc>,
        result: TaskResult,
    },
    /// Task failed and cannot be recovered automatically
    Failed {
        failed_at: DateTime<Utc>,
        error: TaskError,
        retry_count: u32,
    },
    /// Task was deliberately skipped
    Skipped {
        reason: String,
        skipped_at: DateTime<Utc>,
    },
}

/// Rich metadata for task management and scheduling
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TaskMetadata {
    pub priority: TaskPriority,
    pub estimated_complexity: Option<ComplexityLevel>,
    pub estimated_duration: Option<Duration>,
    pub repository_refs: Vec<RepositoryRef>,
    pub file_refs: Vec<FileRef>,
    pub tags: Vec<String>,
    pub context_requirements: ContextRequirements,
}

/// Task priority levels with numeric values for scoring
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TaskPriority {
    Critical = 10,
    High = 8,
    Normal = 5,
    Low = 3,
    Background = 1,
}

/// Complexity estimation for resource planning
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ComplexityLevel {
    Trivial,  // < 5 minutes
    Simple,   // 5-15 minutes
    Moderate, // 15-60 minutes
    Complex,  // 1-4 hours
    Epic,     // > 4 hours
}

/// Repository reference for VCS operations
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RepositoryRef {
    pub name: String,
    pub url: String,
    pub branch: Option<String>,
    pub commit: Option<String>,
}

/// File reference for context and change tracking
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct FileRef {
    pub path: PathBuf,
    pub repository: String,
    pub line_range: Option<(u32, u32)>,
    pub importance: FileImportance,
}

/// Importance level for file references
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum FileImportance {
    Critical, // Core implementation files
    High,     // Important supporting files
    Medium,   // Related files
    Low,      // Reference files
}

/// Context requirements for task execution
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ContextRequirements {
    pub required_files: Vec<PathBuf>,
    pub required_repositories: Vec<String>,
    pub build_dependencies: Vec<String>,
    pub environment_vars: HashMap<String, String>,
    pub claude_context_keys: Vec<String>,
}

/// Task dependency relationship
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TaskDependency {
    pub task_id: TaskId,
    pub dependency_type: DependencyType,
    pub required_status: Vec<TaskStatus>,
}

/// Types of task dependencies
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum DependencyType {
    /// Must complete before this task can start
    Prerequisite,
    /// Should complete before this task starts (soft dependency)
    Preferred,
    /// Must be running concurrently
    Concurrent,
    /// Must not run at the same time
    Exclusive,
}

/// Execution record for task history tracking
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ExecutionRecord {
    pub started_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
    pub status: TaskStatus,
    pub claude_session_id: Option<ClaudeSessionId>,
    pub resources_used: ResourceUsage,
    pub files_modified: Vec<PathBuf>,
    pub errors: Vec<String>,
}

/// Resource usage tracking
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ResourceUsage {
    pub max_memory_mb: u64,
    pub cpu_time_seconds: f64,
    pub disk_io_mb: u64,
    pub network_requests: u32,
}

/// Task execution result
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TaskResult {
    Success {
        output: serde_json::Value,
        files_created: Vec<PathBuf>,
        files_modified: Vec<PathBuf>,
        build_artifacts: Vec<PathBuf>,
    },
    Partial {
        completed_work: serde_json::Value,
        remaining_work: Vec<TaskSpec>,
        files_modified: Vec<PathBuf>,
    },
}

/// Task execution errors
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum TaskError {
    /// Claude Code API errors
    ClaudeError {
        message: String,
        error_code: Option<String>,
        retry_possible: bool,
    },
    /// Build or compilation errors
    BuildError {
        exit_code: i32,
        stdout: String,
        stderr: String,
        affected_files: Vec<PathBuf>,
    },
    /// File system errors
    FileSystemError {
        message: String,
        path: Option<PathBuf>,
        operation: String,
    },
    /// Resource exhaustion
    ResourceError {
        resource_type: String,
        limit_exceeded: String,
        current_usage: String,
    },
    /// Dependency errors
    DependencyError {
        message: String,
        missing_dependencies: Vec<String>,
        conflict_dependencies: Vec<String>,
    },
    /// Timeout errors
    TimeoutError {
        operation: String,
        timeout_duration: Duration,
        elapsed_time: Duration,
    },
    /// Generic errors
    Other {
        message: String,
        source: Option<String>,
    },
}

/// Task specification for creating new tasks
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct TaskSpec {
    pub title: String,
    pub description: String,
    pub metadata: TaskMetadata,
    pub dependencies: Vec<TaskId>,
}

impl Task {
    /// Create a new task with the given specification
    pub fn new(spec: TaskSpec, parent_id: Option<TaskId>) -> Self {
        let now = Utc::now();
        Self {
            id: Uuid::new_v4(),
            title: spec.title,
            description: spec.description,
            status: TaskStatus::Pending,
            parent_id,
            children: Vec::new(),
            dependencies: spec.dependencies,
            created_at: now,
            updated_at: now,
            metadata: spec.metadata,
            execution_history: Vec::new(),
        }
    }

    /// Check if task is in a terminal state
    pub fn is_terminal(&self) -> bool {
        matches!(
            self.status,
            TaskStatus::Completed { .. } | TaskStatus::Failed { .. } | TaskStatus::Skipped { .. }
        )
    }

    /// Check if task is currently runnable
    pub fn is_runnable(&self) -> bool {
        matches!(self.status, TaskStatus::Pending)
    }

    /// Check if task is currently running
    pub fn is_running(&self) -> bool {
        matches!(self.status, TaskStatus::InProgress { .. })
    }

    /// Check if task is blocked
    pub fn is_blocked(&self) -> bool {
        matches!(self.status, TaskStatus::Blocked { .. })
    }

    /// Get task age since creation
    pub fn age(&self) -> Duration {
        Utc::now().signed_duration_since(self.created_at)
    }

    /// Get task runtime if currently running
    pub fn runtime(&self) -> Option<Duration> {
        if let TaskStatus::InProgress { started_at, .. } = self.status {
            Some(Utc::now().signed_duration_since(started_at))
        } else {
            None
        }
    }

    /// Update task status and timestamp
    pub fn update_status(&mut self, status: TaskStatus) {
        self.status = status;
        self.updated_at = Utc::now();
    }

    /// Add execution record
    pub fn add_execution_record(&mut self, record: ExecutionRecord) {
        self.execution_history.push(record);
        self.updated_at = Utc::now();
    }

    /// Get priority as numeric value for scoring
    pub fn priority_value(&self) -> u8 {
        self.metadata.priority.clone() as u8
    }
}

impl ContextRequirements {
    /// Create empty context requirements
    pub fn new() -> Self {
        Self {
            required_files: Vec::new(),
            required_repositories: Vec::new(),
            build_dependencies: Vec::new(),
            environment_vars: HashMap::new(),
            claude_context_keys: Vec::new(),
        }
    }

    /// Merge with another context requirements
    pub fn merge_with(&mut self, other: &ContextRequirements) {
        self.required_files
            .extend(other.required_files.iter().cloned());
        self.required_repositories
            .extend(other.required_repositories.iter().cloned());
        self.build_dependencies
            .extend(other.build_dependencies.iter().cloned());
        self.environment_vars.extend(
            other
                .environment_vars
                .iter()
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        self.claude_context_keys
            .extend(other.claude_context_keys.iter().cloned());

        // Remove duplicates
        self.required_files.sort();
        self.required_files.dedup();
        self.required_repositories.sort();
        self.required_repositories.dedup();
        self.build_dependencies.sort();
        self.build_dependencies.dedup();
        self.claude_context_keys.sort();
        self.claude_context_keys.dedup();
    }

    /// Check if context is empty
    pub fn is_empty(&self) -> bool {
        self.required_files.is_empty()
            && self.required_repositories.is_empty()
            && self.build_dependencies.is_empty()
            && self.environment_vars.is_empty()
            && self.claude_context_keys.is_empty()
    }
}

impl Default for ContextRequirements {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskPriority {
    /// Get numeric value for calculations
    pub fn value(&self) -> u8 {
        self.clone() as u8
    }
}

impl ComplexityLevel {
    /// Get estimated duration for this complexity level
    pub fn estimated_duration(&self) -> Duration {
        match self {
            ComplexityLevel::Trivial => Duration::minutes(5),
            ComplexityLevel::Simple => Duration::minutes(15),
            ComplexityLevel::Moderate => Duration::minutes(60),
            ComplexityLevel::Complex => Duration::hours(4),
            ComplexityLevel::Epic => Duration::hours(8),
        }
    }

    /// Get numeric value for calculations (0-4)
    pub fn value(&self) -> u8 {
        match self {
            ComplexityLevel::Trivial => 0,
            ComplexityLevel::Simple => 1,
            ComplexityLevel::Moderate => 2,
            ComplexityLevel::Complex => 3,
            ComplexityLevel::Epic => 4,
        }
    }
}

impl std::fmt::Display for TaskError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TaskError::ClaudeError {
                message,
                error_code,
                retry_possible,
            } => {
                if let Some(code) = error_code {
                    write!(
                        f,
                        "Claude API error [{}]: {} (retry: {})",
                        code, message, retry_possible
                    )
                } else {
                    write!(
                        f,
                        "Claude API error: {} (retry: {})",
                        message, retry_possible
                    )
                }
            }
            TaskError::BuildError {
                exit_code, stderr, ..
            } => {
                write!(
                    f,
                    "Build failed with exit code {}: {}",
                    exit_code,
                    stderr.lines().next().unwrap_or("No error details")
                )
            }
            TaskError::FileSystemError {
                message,
                path,
                operation,
            } => {
                if let Some(path) = path {
                    write!(
                        f,
                        "File system error during {}: {} (path: {})",
                        operation,
                        message,
                        path.display()
                    )
                } else {
                    write!(f, "File system error during {}: {}", operation, message)
                }
            }
            TaskError::ResourceError {
                resource_type,
                limit_exceeded,
                ..
            } => {
                write!(
                    f,
                    "Resource exhausted: {} limit exceeded ({})",
                    resource_type, limit_exceeded
                )
            }
            TaskError::DependencyError {
                message,
                missing_dependencies,
                ..
            } => {
                if missing_dependencies.is_empty() {
                    write!(f, "Dependency error: {}", message)
                } else {
                    write!(
                        f,
                        "Dependency error: {} (missing: {})",
                        message,
                        missing_dependencies.join(", ")
                    )
                }
            }
            TaskError::TimeoutError {
                operation,
                timeout_duration,
                elapsed_time,
            } => {
                write!(
                    f,
                    "Timeout during {}: {}s exceeded (elapsed: {}s)",
                    operation,
                    timeout_duration.num_seconds(),
                    elapsed_time.num_seconds()
                )
            }
            TaskError::Other { message, source } => {
                if let Some(source) = source {
                    write!(f, "{} (source: {})", message, source)
                } else {
                    write!(f, "{}", message)
                }
            }
        }
    }
}

// ============================================================================
// Setup Commands and Error Handling
// ============================================================================

/// Setup command to run before the main instruction loop
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SetupCommand {
    pub id: Uuid,
    pub name: String,
    pub command: String,                     // Shell command to execute
    pub args: Vec<String>,                   // Command arguments
    pub working_dir: Option<PathBuf>,        // Optional working directory
    pub timeout: Option<Duration>,           // Command timeout
    pub required: bool,                      // If false, failure won't stop initialization
    pub error_handler: Option<ErrorHandler>, // Optional error handling strategy
}

/// Result of executing a setup command
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SetupResult {
    pub command_id: Uuid,
    pub success: bool,
    pub exit_code: i32,
    pub stdout: String,
    pub stderr: String,
    pub duration: Duration,
}

/// Error handler for setup commands
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ErrorHandler {
    pub name: String,
    pub strategy: ErrorStrategy,
}

/// Strategy for handling setup command errors
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum ErrorStrategy {
    /// Continue despite failure
    Skip,
    /// Retry the command with delay
    Retry { max_attempts: u32, delay: Duration },
    /// Run backup command based on output analysis
    Backup {
        condition: OutputCondition,
        backup_command: String,
        backup_args: Vec<String>,
    },
}

/// Condition for determining when to run backup commands
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct OutputCondition {
    pub check_stdout: bool,                  // Analyze stdout
    pub check_stderr: bool,                  // Analyze stderr
    pub contains: Option<String>,            // Text that must be present
    pub not_contains: Option<String>,        // Text that must NOT be present
    pub exit_code_range: Option<(i32, i32)>, // Acceptable exit code range
}

impl Default for SetupCommand {
    fn default() -> Self {
        Self {
            id: Uuid::new_v4(),
            name: String::new(),
            command: String::new(),
            args: Vec::new(),
            working_dir: None,
            timeout: Some(Duration::seconds(30)), // Default 30 second timeout
            required: true,
            error_handler: None,
        }
    }
}

impl Default for OutputCondition {
    fn default() -> Self {
        Self {
            check_stdout: false,
            check_stderr: true, // Default to checking stderr
            contains: None,
            not_contains: None,
            exit_code_range: None,
        }
    }
}

impl SetupCommand {
    /// Create a new setup command
    pub fn new(name: &str, command: &str) -> Self {
        Self {
            name: name.to_string(),
            command: command.to_string(),
            ..Default::default()
        }
    }

    /// Add arguments to the command
    pub fn with_args(mut self, args: Vec<String>) -> Self {
        self.args = args;
        self
    }

    /// Set working directory
    pub fn with_working_dir(mut self, dir: PathBuf) -> Self {
        self.working_dir = Some(dir);
        self
    }

    /// Set timeout
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Mark as optional (not required)
    pub fn optional(mut self) -> Self {
        self.required = false;
        self
    }

    /// Add error handler
    pub fn with_error_handler(mut self, handler: ErrorHandler) -> Self {
        self.error_handler = Some(handler);
        self
    }
}

impl ErrorHandler {
    /// Create a skip error handler
    pub fn skip(name: &str) -> Self {
        Self {
            name: name.to_string(),
            strategy: ErrorStrategy::Skip,
        }
    }

    /// Create a retry error handler
    pub fn retry(name: &str, max_attempts: u32, delay: Duration) -> Self {
        Self {
            name: name.to_string(),
            strategy: ErrorStrategy::Retry {
                max_attempts,
                delay,
            },
        }
    }

    /// Create a backup error handler
    pub fn backup(
        name: &str,
        condition: OutputCondition,
        backup_command: &str,
        backup_args: Vec<String>,
    ) -> Self {
        Self {
            name: name.to_string(),
            strategy: ErrorStrategy::Backup {
                condition,
                backup_command: backup_command.to_string(),
                backup_args,
            },
        }
    }
}

impl OutputCondition {
    /// Check if stderr contains a specific string
    pub fn stderr_contains(text: &str) -> Self {
        Self {
            check_stdout: false,
            check_stderr: true,
            contains: Some(text.to_string()),
            not_contains: None,
            exit_code_range: None,
        }
    }

    /// Check if stdout contains a specific string
    pub fn stdout_contains(text: &str) -> Self {
        Self {
            check_stdout: true,
            check_stderr: false,
            contains: Some(text.to_string()),
            not_contains: None,
            exit_code_range: None,
        }
    }

    /// Check exit code is within range
    pub fn exit_code_range(min: i32, max: i32) -> Self {
        Self {
            exit_code_range: Some((min, max)),
            ..Default::default()
        }
    }
}

impl Default for TaskMetadata {
    fn default() -> Self {
        Self {
            priority: TaskPriority::Normal,
            estimated_complexity: None,
            estimated_duration: None,
            repository_refs: Vec::new(),
            file_refs: Vec::new(),
            tags: Vec::new(),
            context_requirements: ContextRequirements::default(),
        }
    }
}