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
//! Ralph types - PRD and state structures

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// A concrete verification step that must pass for a story to be marked complete.
///
/// This complements `quality_checks` (which are repo/toolchain-level gates).
/// Verification steps are story-level and can validate user-visible outcomes
/// like E2E flows, artifacts (e.g. Cypress videos), or deployment endpoints.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum VerificationStep {
    /// Run a shell command and optionally assert on output and/or produced files.
    Shell {
        /// Optional label for UI/logging.
        #[serde(default)]
        name: Option<String>,

        /// Shell command to run.
        command: String,

        /// Optional working directory (relative to repo root / check root).
        #[serde(default)]
        cwd: Option<String>,

        /// Substrings that must be present in stdout+stderr.
        #[serde(default)]
        expect_output_contains: Vec<String>,

        /// File globs that must match at least one file after the command runs.
        /// Example: "cypress/videos/**/*.mp4"
        #[serde(default)]
        expect_files_glob: Vec<String>,
    },

    /// Ensure a file (or glob pattern) exists.
    FileExists {
        #[serde(default)]
        name: Option<String>,
        /// Path or glob pattern.
        path: String,
        /// If true, treat `path` as a glob.
        #[serde(default)]
        glob: bool,
    },

    /// Validate an HTTP endpoint is reachable (useful for “deployment is live”).
    Url {
        #[serde(default)]
        name: Option<String>,
        url: String,
        /// HTTP method (default: GET).
        #[serde(default = "default_http_method")]
        method: String,
        /// Expected status (default: 200).
        #[serde(default = "default_http_status")]
        expect_status: u16,
        /// Substrings that must appear in the response body.
        #[serde(default)]
        expect_body_contains: Vec<String>,
        /// Timeout in seconds (default: 30).
        #[serde(default = "default_http_timeout_secs")]
        timeout_secs: u64,
    },
}

fn default_http_method() -> String {
    "GET".to_string()
}
fn default_http_status() -> u16 {
    200
}
fn default_http_timeout_secs() -> u64 {
    30
}

/// A user story in the PRD
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserStory {
    /// Unique identifier (e.g., "US-001")
    pub id: String,

    /// Short title
    pub title: String,

    /// Full description
    pub description: String,

    /// Acceptance criteria
    #[serde(default)]
    pub acceptance_criteria: Vec<String>,

    /// Explicit verification steps that must pass for this story to be marked complete.
    ///
    /// Example: run Cypress E2E and assert that a video artifact exists.
    #[serde(default)]
    pub verification_steps: Vec<VerificationStep>,

    /// Whether this story passes all tests
    #[serde(default)]
    pub passes: bool,

    /// Story priority (1=highest)
    #[serde(default = "default_priority")]
    pub priority: u8,

    /// Dependencies on other story IDs
    #[serde(default, alias = "dependencies")]
    pub depends_on: Vec<String>,

    /// Estimated complexity (1-5)
    #[serde(default = "default_complexity")]
    pub complexity: u8,
}

fn default_priority() -> u8 {
    1
}
fn default_complexity() -> u8 {
    3
}

/// The full PRD structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Prd {
    /// Project name
    pub project: String,

    /// Feature being implemented
    pub feature: String,

    /// Git branch name for this PRD
    #[serde(default)]
    pub branch_name: String,

    /// Version of the PRD format
    #[serde(default = "default_version")]
    pub version: String,

    /// User stories to implement
    #[serde(default)]
    pub user_stories: Vec<UserStory>,

    /// Technical requirements
    #[serde(default)]
    pub technical_requirements: Vec<String>,

    /// Quality checks to run
    #[serde(default)]
    pub quality_checks: QualityChecks,

    /// Created timestamp
    #[serde(default)]
    pub created_at: String,

    /// Last updated timestamp
    #[serde(default)]
    pub updated_at: String,
}

fn default_version() -> String {
    "1.0".to_string()
}

/// Quality checks configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct QualityChecks {
    /// Command to run type checking
    #[serde(default)]
    pub typecheck: Option<String>,

    /// Command to run tests
    #[serde(default)]
    pub test: Option<String>,

    /// Command to run linting
    #[serde(default)]
    pub lint: Option<String>,

    /// Command to run build
    #[serde(default)]
    pub build: Option<String>,
}

impl Prd {
    /// Load a PRD from a JSON file
    pub async fn load(path: &PathBuf) -> anyhow::Result<Self> {
        let content = tokio::fs::read_to_string(path).await?;
        let prd: Prd = serde_json::from_str(&content)?;
        Ok(prd)
    }

    /// Save the PRD to a JSON file
    pub async fn save(&self, path: &PathBuf) -> anyhow::Result<()> {
        let content = serde_json::to_string_pretty(self)?;
        tokio::fs::write(path, content).await?;
        Ok(())
    }

    /// Get the next story to work on (not passed, dependencies met)
    pub fn next_story(&self) -> Option<&UserStory> {
        self.user_stories
            .iter()
            .filter(|s| !s.passes)
            .filter(|s| self.dependencies_met(&s.depends_on))
            .min_by_key(|s| (s.priority, s.complexity))
    }

    /// Check if all dependencies are met (all passed)
    fn dependencies_met(&self, deps: &[String]) -> bool {
        deps.iter().all(|dep_id| {
            self.user_stories
                .iter()
                .find(|s| s.id == *dep_id)
                .map(|s| s.passes)
                .unwrap_or(true)
        })
    }

    /// Get count of passed stories
    pub fn passed_count(&self) -> usize {
        self.user_stories.iter().filter(|s| s.passes).count()
    }

    /// Check if all stories are complete
    pub fn is_complete(&self) -> bool {
        self.user_stories.iter().all(|s| s.passes)
    }

    /// Mark a story as passed
    pub fn mark_passed(&mut self, story_id: &str) {
        if let Some(story) = self.user_stories.iter_mut().find(|s| s.id == *story_id) {
            story.passes = true;
        }
    }

    /// Get all stories ready to be worked on (not passed, dependencies met)
    pub fn ready_stories(&self) -> Vec<&UserStory> {
        self.user_stories
            .iter()
            .filter(|s| !s.passes)
            .filter(|s| self.dependencies_met(&s.depends_on))
            .collect()
    }

    /// Group stories into parallel execution stages based on dependencies
    /// Returns a Vec of stages, where each stage is a Vec of stories that can run in parallel
    pub fn stages(&self) -> Vec<Vec<&UserStory>> {
        let mut stages: Vec<Vec<&UserStory>> = Vec::new();
        let mut completed: std::collections::HashSet<String> = self
            .user_stories
            .iter()
            .filter(|s| s.passes)
            .map(|s| s.id.clone())
            .collect();

        let mut remaining: Vec<&UserStory> =
            self.user_stories.iter().filter(|s| !s.passes).collect();

        while !remaining.is_empty() {
            // Find all stories whose dependencies are met
            let (ready, not_ready): (Vec<_>, Vec<_>) = remaining
                .into_iter()
                .partition(|s| s.depends_on.iter().all(|dep| completed.contains(dep)));

            if ready.is_empty() {
                // Circular dependency or missing deps - just take remaining
                if !not_ready.is_empty() {
                    stages.push(not_ready);
                }
                break;
            }

            // Mark these as "will be completed" for next iteration
            for story in &ready {
                completed.insert(story.id.clone());
            }

            stages.push(ready);
            remaining = not_ready;
        }

        stages
    }
}

/// Ralph execution state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RalphState {
    /// The PRD being worked on
    pub prd: Prd,

    /// Current iteration number
    pub current_iteration: usize,

    /// Maximum allowed iterations
    pub max_iterations: usize,

    /// Current status
    pub status: RalphStatus,

    /// Progress log entries
    #[serde(default)]
    pub progress_log: Vec<ProgressEntry>,

    /// Path to the PRD file
    pub prd_path: PathBuf,

    /// Working directory
    pub working_dir: PathBuf,
}

/// Ralph execution status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RalphStatus {
    Pending,
    Running,
    Completed,
    MaxIterations,
    Stopped,
    QualityFailed,
}

/// A progress log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgressEntry {
    /// Story ID being worked on
    pub story_id: String,

    /// Iteration number
    pub iteration: usize,

    /// Status of this attempt
    pub status: String,

    /// What was learned
    #[serde(default)]
    pub learnings: Vec<String>,

    /// Files changed
    #[serde(default)]
    pub files_changed: Vec<String>,

    /// Timestamp
    pub timestamp: String,
}

/// Ralph configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RalphConfig {
    /// Path to prd.json
    #[serde(default = "default_prd_path")]
    pub prd_path: String,

    /// Maximum iterations
    #[serde(default = "default_max_iterations")]
    pub max_iterations: usize,

    /// Path to progress.txt
    #[serde(default = "default_progress_path")]
    pub progress_path: String,

    /// Whether to auto-commit changes
    #[serde(default = "default_auto_commit")]
    pub auto_commit: bool,

    /// Whether to run quality checks
    #[serde(default = "default_quality_checks_enabled")]
    pub quality_checks_enabled: bool,

    /// Model to use for iterations
    #[serde(default)]
    pub model: Option<String>,

    /// Whether to use RLM for progress compression
    #[serde(default)]
    pub use_rlm: bool,

    /// Enable parallel story execution
    #[serde(default = "default_parallel_enabled")]
    pub parallel_enabled: bool,

    /// Maximum concurrent stories to execute
    #[serde(default = "default_max_concurrent_stories")]
    pub max_concurrent_stories: usize,

    /// Use worktree isolation for parallel execution
    #[serde(default = "default_worktree_enabled")]
    pub worktree_enabled: bool,

    /// Timeout in seconds per step for story sub-agents (resets on each step)
    #[serde(default = "default_story_timeout_secs")]
    pub story_timeout_secs: u64,

    /// Maximum tool call steps per story sub-agent
    /// Increase this for complex stories that need more iterations
    #[serde(default = "default_max_steps_per_story")]
    pub max_steps_per_story: usize,

    /// Timeout in seconds per step for conflict resolution sub-agents
    #[serde(default = "default_conflict_timeout_secs")]
    pub conflict_timeout_secs: u64,

    /// Enable per-story relay teams (multi-agent collaboration per story)
    #[serde(default)]
    pub relay_enabled: bool,

    /// Maximum agents per relay team (2-8)
    #[serde(default = "default_relay_max_agents")]
    pub relay_max_agents: usize,

    /// Maximum relay rounds per story
    #[serde(default = "default_relay_max_rounds")]
    pub relay_max_rounds: usize,
}

fn default_prd_path() -> String {
    "prd.json".to_string()
}
fn default_max_iterations() -> usize {
    10
}
fn default_progress_path() -> String {
    "progress.txt".to_string()
}
fn default_auto_commit() -> bool {
    false
}
fn default_quality_checks_enabled() -> bool {
    true
}
fn default_parallel_enabled() -> bool {
    true
}
fn default_max_concurrent_stories() -> usize {
    100
}
fn default_worktree_enabled() -> bool {
    true
}
fn default_story_timeout_secs() -> u64 {
    300
}
fn default_max_steps_per_story() -> usize {
    50
}
fn default_conflict_timeout_secs() -> u64 {
    120
}
fn default_relay_max_agents() -> usize {
    8
}
fn default_relay_max_rounds() -> usize {
    3
}

impl Default for RalphConfig {
    fn default() -> Self {
        Self {
            prd_path: default_prd_path(),
            max_iterations: default_max_iterations(),
            progress_path: default_progress_path(),
            auto_commit: default_auto_commit(),
            quality_checks_enabled: default_quality_checks_enabled(),
            model: None,
            use_rlm: true,
            parallel_enabled: default_parallel_enabled(),
            max_concurrent_stories: default_max_concurrent_stories(),
            worktree_enabled: default_worktree_enabled(),
            story_timeout_secs: default_story_timeout_secs(),
            max_steps_per_story: default_max_steps_per_story(),
            conflict_timeout_secs: default_conflict_timeout_secs(),
            relay_enabled: true,
            relay_max_agents: default_relay_max_agents(),
            relay_max_rounds: default_relay_max_rounds(),
        }
    }
}