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
# 1.3 Session Persistence System

**Deliverable**: Comprehensive state management, persistence formats, and recovery mechanisms
**Status**: ✅ Implemented - Full checkpoint/resume functionality with atomic persistence and recovery

## Overview

The session persistence system ensures complete recoverability and continuity of agent operations across interruptions, restarts, and system failures. It maintains atomic consistency while optimizing for performance and storage efficiency.

## State Architecture

### Core State Components

The system maintains four primary state categories with distinct persistence requirements:

```rust
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SessionState {
    pub session_id: SessionId,
    pub created_at: DateTime<Utc>,
    pub last_checkpoint: DateTime<Utc>,
    pub configuration: SessionConfiguration,
    pub task_tree: TaskTreeState,
    pub claude_context: ClaudeContextState,
    pub file_system: FileSystemState,
    pub execution_logs: ExecutionLogState,
    pub resource_usage: ResourceUsageState,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct TaskTreeState {
    pub tasks: HashMap<TaskId, Task>,
    pub root_tasks: Vec<TaskId>,
    pub active_task: Option<TaskId>,
    pub task_counter: u64,
    pub dependency_graph: DependencyGraph,
    pub scheduling_state: SchedulingState,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ClaudeContextState {
    pub session_id: String,
    pub conversation_history: ConversationHistory,
    pub context_windows: Vec<ContextWindow>,
    pub rate_limit_state: RateLimitState,
    pub model_configuration: ModelConfiguration,
    pub usage_tracking: UsageTracking,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct FileSystemState {
    pub workspace_snapshot: WorkspaceSnapshot,
    pub file_modifications: Vec<FileModification>,
    pub build_artifacts: HashMap<String, BuildArtifact>,
    pub dependency_resolution: DependencyResolution,
    pub git_state: GitState,
}
```

## Persistence Architecture

### Storage Layout

The session data is organized in a structured directory layout optimized for atomic updates and efficient access. Session data is stored in a hidden `.aca` directory within the workspace root to maintain a clean development environment:

```
.aca/
└── sessions/{session_id}/
├── meta/
│   ├── session.json              # Session metadata and configuration
│   ├── checkpoint_manifest.json  # Checkpoint history and validation
│   └── recovery_info.json        # Recovery instructions and state
│
├── state/
│   ├── task_tree.json           # Complete task hierarchy and status
│   ├── scheduling_state.json    # Task scheduler state and queues
│   └── dependency_graph.json    # Task dependencies and relationships
│
├── claude/
│   ├── session_config.json      # Claude Code session configuration
│   ├── conversation/            # Conversation history in chunks
│   │   ├── messages_001.json
│   │   ├── messages_002.json
│   │   └── current.json
│   ├── context_windows/         # Maintained context windows
│   │   ├── window_001.json
│   │   └── window_002.json
│   └── rate_limit/
│       ├── usage_history.json
│       └── current_limits.json
│
├── filesystem/
│   ├── workspace_snapshot.json  # File system state tracking
│   ├── modifications/           # Change tracking and history
│   │   ├── changes_001.json
│   │   └── changes_002.json
│   ├── build_artifacts/         # Build results and artifacts
│   │   ├── compilation_results.json
│   │   └── test_results.json
│   └── git_state.json          # Git repository state
│
├── logs/
│   ├── execution/              # Task execution logs
│   │   ├── task_{task_id}.json
│   │   └── system_events.json
│   ├── claude_interactions/    # Claude Code API interactions
│   │   ├── requests_001.json
│   │   └── responses_001.json
│   └── errors/                # Error logs and stack traces
│       ├── error_001.json
│       └── recovery_actions.json
│
└── checkpoints/               # Point-in-time snapshots
    ├── checkpoint_001/
    │   ├── state_snapshot.json
    │   └── manifest.json
    └── checkpoint_002/
        ├── state_snapshot.json
        └── manifest.json
```

### Benefits of `.aca` Directory Structure

The hidden `.aca` directory provides several advantages:

- **Clean Workspace**: Keeps development files separate from session metadata
- **Standards Compliance**: Follows established conventions (like `.git`, `.vscode`, `.cargo`)
- **Multi-Session Support**: Multiple sessions can coexist without conflicts
- **Easy Maintenance**: Centralized location for all session-related data
- **Version Control Friendly**: Can be easily added to `.gitignore` if desired
- **Backup/Restore**: Simple to backup entire session history

### Atomic Persistence Operations

All state updates use atomic write operations to prevent corruption:

```rust
pub struct AtomicPersistence {
    session_dir: PathBuf,
    write_lock: Arc<Mutex<()>>,
    compression_enabled: bool,
}

impl AtomicPersistence {
    pub async fn persist_state<T: Serialize>(
        &self,
        component: StateComponent,
        data: &T,
    ) -> Result<()> {
        let _lock = self.write_lock.lock().await;

        // Write to temporary file first
        let temp_path = self.get_temp_path(&component);
        let target_path = self.get_component_path(&component);

        // Serialize data
        let serialized = if self.compression_enabled {
            self.serialize_compressed(data)?
        } else {
            serde_json::to_vec_pretty(data)?
        };

        // Atomic write operation
        fs::write(&temp_path, serialized).await?;
        fs::rename(&temp_path, &target_path).await?;

        // Update checkpoint manifest
        self.update_checkpoint_manifest(&component).await?;

        Ok(())
    }

    pub async fn load_state<T: DeserializeOwned>(
        &self,
        component: StateComponent,
    ) -> Result<T> {
        let path = self.get_component_path(&component);

        if !path.exists() {
            return Err(PersistenceError::ComponentNotFound(component));
        }

        let data = fs::read(&path).await?;

        let deserialized = if self.compression_enabled {
            self.deserialize_compressed(&data)?
        } else {
            serde_json::from_slice(&data)?
        };

        Ok(deserialized)
    }
}
```

### Incremental State Updates

For large state components, the system uses incremental updates to minimize I/O:

```rust
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct StateUpdate {
    pub timestamp: DateTime<Utc>,
    pub component: StateComponent,
    pub operation: UpdateOperation,
    pub sequence_number: u64,
    pub checksum: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum UpdateOperation {
    TaskCreated { task: Task },
    TaskStatusChanged { task_id: TaskId, old_status: TaskStatus, new_status: TaskStatus },
    TaskModified { task_id: TaskId, changes: TaskChanges },
    FileModified { path: PathBuf, modification: FileModification },
    ConversationExtended { messages: Vec<ClaudeMessage> },
    DependencyAdded { from: TaskId, to: TaskId, dep_type: DependencyType },
}

impl SessionState {
    pub async fn apply_incremental_update(&mut self, update: StateUpdate) -> Result<()> {
        match update.operation {
            UpdateOperation::TaskCreated { task } => {
                self.task_tree.tasks.insert(task.id, task);
                self.task_tree.task_counter += 1;
            }

            UpdateOperation::TaskStatusChanged { task_id, new_status, .. } => {
                if let Some(task) = self.task_tree.tasks.get_mut(&task_id) {
                    task.status = new_status;
                    task.updated_at = update.timestamp;
                }
            }

            UpdateOperation::FileModified { path, modification } => {
                self.file_system.file_modifications.push(modification);
                self.file_system.workspace_snapshot.update_file(&path).await?;
            }

            UpdateOperation::ConversationExtended { messages } => {
                self.claude_context.conversation_history.extend(messages);
            }

            _ => {} // Handle other operations
        }

        self.last_checkpoint = update.timestamp;
        Ok(())
    }
}
```

## Recovery Mechanisms

### Checkpoint System

The system creates periodic checkpoints with configurable intervals:

```rust
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Checkpoint {
    pub id: CheckpointId,
    pub created_at: DateTime<Utc>,
    pub session_id: SessionId,
    pub state_snapshot: CompressedStateSnapshot,
    pub manifest: CheckpointManifest,
    pub validation_hash: String,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct CheckpointManifest {
    pub total_tasks: u32,
    pub completed_tasks: u32,
    pub active_tasks: Vec<TaskId>,
    pub file_modifications_count: u32,
    pub conversation_messages_count: u32,
    pub storage_size_bytes: u64,
    pub dependencies: Vec<String>,
}

pub struct CheckpointManager {
    session_dir: PathBuf,
    retention_policy: CheckpointRetentionPolicy,
    compression_level: u32,
}

impl CheckpointManager {
    pub async fn create_checkpoint(&self, session: &SessionState) -> Result<CheckpointId> {
        let checkpoint_id = self.generate_checkpoint_id();
        let checkpoint_dir = self.session_dir.join("checkpoints").join(&checkpoint_id);

        fs::create_dir_all(&checkpoint_dir).await?;

        // Create compressed state snapshot
        let snapshot = self.create_state_snapshot(session).await?;
        let manifest = self.generate_manifest(session).await?;

        let checkpoint = Checkpoint {
            id: checkpoint_id.clone(),
            created_at: Utc::now(),
            session_id: session.session_id.clone(),
            state_snapshot: snapshot,
            manifest,
            validation_hash: self.calculate_validation_hash(session).await?,
        };

        // Write checkpoint atomically
        self.write_checkpoint(&checkpoint_dir, &checkpoint).await?;

        // Update retention policy
        self.apply_retention_policy().await?;

        Ok(checkpoint_id)
    }

    pub async fn restore_from_checkpoint(
        &self,
        checkpoint_id: &CheckpointId,
    ) -> Result<SessionState> {
        let checkpoint_path = self.get_checkpoint_path(checkpoint_id);
        let checkpoint = self.load_checkpoint(&checkpoint_path).await?;

        // Validate checkpoint integrity
        self.validate_checkpoint(&checkpoint).await?;

        // Decompress and restore state
        let session_state = self.decompress_state_snapshot(&checkpoint.state_snapshot).await?;

        // Apply any incremental updates since checkpoint
        let updates = self.load_incremental_updates_since(&checkpoint.created_at).await?;
        let mut restored_state = session_state;

        for update in updates {
            restored_state.apply_incremental_update(update).await?;
        }

        Ok(restored_state)
    }
}
```

### Crash Recovery

The system implements comprehensive crash recovery with multiple fallback strategies:

```rust
#[derive(Debug, Clone)]
pub enum RecoveryStrategy {
    /// Restore from latest checkpoint
    LatestCheckpoint,
    /// Restore from specific checkpoint
    SpecificCheckpoint(CheckpointId),
    /// Reconstruct from incremental updates
    IncrementalReconstruction,
    /// Partial recovery with user intervention
    PartialRecovery,
}

pub struct CrashRecoveryManager {
    session_dir: PathBuf,
    checkpoint_manager: Arc<CheckpointManager>,
    validation_rules: Vec<ValidationRule>,
}

impl CrashRecoveryManager {
    pub async fn detect_crash_state(&self) -> Result<Option<CrashState>> {
        // Check for incomplete write operations
        let incomplete_writes = self.find_incomplete_writes().await?;

        // Check for corrupted state files
        let corrupted_files = self.validate_state_files().await?;

        // Check for orphaned processes or resources
        let orphaned_resources = self.find_orphaned_resources().await?;

        if incomplete_writes.is_empty() && corrupted_files.is_empty() && orphaned_resources.is_empty() {
            return Ok(None);
        }

        Ok(Some(CrashState {
            incomplete_writes,
            corrupted_files,
            orphaned_resources,
            detected_at: Utc::now(),
        }))
    }

    pub async fn recover_session(
        &self,
        crash_state: CrashState,
        strategy: RecoveryStrategy,
    ) -> Result<SessionState> {
        match strategy {
            RecoveryStrategy::LatestCheckpoint => {
                self.recover_from_latest_checkpoint().await
            }

            RecoveryStrategy::SpecificCheckpoint(checkpoint_id) => {
                self.checkpoint_manager.restore_from_checkpoint(&checkpoint_id).await
            }

            RecoveryStrategy::IncrementalReconstruction => {
                self.reconstruct_from_incremental_updates().await
            }

            RecoveryStrategy::PartialRecovery => {
                self.perform_partial_recovery(crash_state).await
            }
        }
    }

    async fn perform_partial_recovery(&self, crash_state: CrashState) -> Result<SessionState> {
        // Start with empty session state
        let mut session = SessionState::new_empty();

        // Recover task tree from available data
        if let Ok(task_data) = self.recover_task_tree_partial().await {
            session.task_tree = task_data;
        }

        // Recover Claude context if possible
        if let Ok(claude_data) = self.recover_claude_context_partial().await {
            session.claude_context = claude_data;
        }

        // Mark session as requiring validation
        session.configuration.requires_validation = true;

        Ok(session)
    }
}
```

## Performance Optimizations

### Lazy Loading

Large state components are loaded on-demand to minimize memory usage:

```rust
pub struct LazyStateManager {
    session_dir: PathBuf,
    loaded_components: Arc<Mutex<HashMap<StateComponent, Arc<dyn Any + Send + Sync>>>>,
    access_patterns: Arc<Mutex<HashMap<StateComponent, AccessPattern>>>,
}

impl LazyStateManager {
    pub async fn get_component<T: DeserializeOwned + Clone + Send + Sync + 'static>(
        &self,
        component: StateComponent,
    ) -> Result<Arc<T>> {
        let mut loaded = self.loaded_components.lock().await;

        if let Some(cached) = loaded.get(&component) {
            if let Some(typed) = cached.downcast_ref::<T>() {
                self.record_access(component).await;
                return Ok(Arc::new(typed.clone()));
            }
        }

        // Load component from disk
        let data: T = self.load_from_disk(component).await?;
        let arc_data = Arc::new(data.clone());

        loaded.insert(component, arc_data.clone());
        self.record_access(component).await;

        Ok(Arc::new(data))
    }

    pub async fn invalidate_component(&self, component: StateComponent) {
        let mut loaded = self.loaded_components.lock().await;
        loaded.remove(&component);
    }
}
```

### State Compression

Large state files are compressed to reduce storage requirements:

```rust
pub struct StateCompression {
    compression_algorithm: CompressionAlgorithm,
    compression_level: u32,
    size_threshold: u64,
}

#[derive(Clone, Debug)]
pub enum CompressionAlgorithm {
    None,
    Gzip,
    Zstd,
    Lz4,
}

impl StateCompression {
    pub fn compress_data(&self, data: &[u8]) -> Result<Vec<u8>> {
        if data.len() < self.size_threshold as usize {
            return Ok(data.to_vec());
        }

        match self.compression_algorithm {
            CompressionAlgorithm::None => Ok(data.to_vec()),
            CompressionAlgorithm::Gzip => {
                use flate2::{Compression, write::GzEncoder};
                use std::io::Write;

                let mut encoder = GzEncoder::new(Vec::new(), Compression::new(self.compression_level));
                encoder.write_all(data)?;
                Ok(encoder.finish()?)
            }
            CompressionAlgorithm::Zstd => {
                Ok(zstd::encode_all(data, self.compression_level as i32)?)
            }
            CompressionAlgorithm::Lz4 => {
                Ok(lz4_flex::compress(data))
            }
        }
    }
}
```

## Data Integrity

### Validation System

The system implements comprehensive validation to ensure data integrity:

```rust
#[derive(Debug, Clone)]
pub struct ValidationRule {
    pub name: String,
    pub component: StateComponent,
    pub rule_type: ValidationRuleType,
    pub severity: ValidationSeverity,
}

#[derive(Debug, Clone)]
pub enum ValidationRuleType {
    StructuralConsistency,
    ReferentialIntegrity,
    BusinessLogic,
    ChecksumValidation,
}

#[derive(Debug, Clone)]
pub enum ValidationSeverity {
    Warning,
    Error,
    Critical,
}

pub struct StateValidator {
    rules: Vec<ValidationRule>,
    repair_strategies: HashMap<ValidationRuleType, RepairStrategy>,
}

impl StateValidator {
    pub async fn validate_session_state(&self, state: &SessionState) -> ValidationResult {
        let mut issues = Vec::new();

        for rule in &self.rules {
            match self.apply_validation_rule(rule, state).await {
                Ok(_) => continue,
                Err(validation_error) => {
                    issues.push(ValidationIssue {
                        rule: rule.clone(),
                        error: validation_error,
                        suggested_repair: self.suggest_repair(rule).await,
                    });
                }
            }
        }

        ValidationResult {
            is_valid: issues.iter().all(|i| i.rule.severity != ValidationSeverity::Critical),
            issues,
            repair_suggestions: self.generate_repair_plan(&issues).await,
        }
    }

    async fn validate_task_tree_consistency(&self, task_tree: &TaskTreeState) -> Result<()> {
        // Validate parent-child relationships
        for (task_id, task) in &task_tree.tasks {
            if let Some(parent_id) = task.parent_id {
                let parent = task_tree.tasks.get(&parent_id)
                    .ok_or(ValidationError::OrphanedTask(*task_id))?;

                if !parent.children.contains(task_id) {
                    return Err(ValidationError::InconsistentParentChild {
                        parent: parent_id,
                        child: *task_id,
                    });
                }
            }

            // Validate dependencies exist
            for &dep_id in &task.dependencies {
                if !task_tree.tasks.contains_key(&dep_id) {
                    return Err(ValidationError::MissingDependency {
                        task: *task_id,
                        dependency: dep_id,
                    });
                }
            }
        }

        // Validate no circular dependencies
        self.check_circular_dependencies(&task_tree.dependency_graph).await?;

        Ok(())
    }
}
```

This comprehensive persistence system ensures robust state management with efficient storage, reliable recovery, and strong data integrity guarantees for long-running development workflows.