ralph-agent-loop 0.4.0

A Rust CLI for managing AI agent loops with a structured JSON task queue
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
//! Markdown section merging utilities for AGENTS.md updates.
//!
//! Responsibilities:
//! - Parse markdown content into structured sections while preserving formatting.
//! - Merge new content into existing sections, preserving footers and structure.
//! - Support both interactive and file-based update workflows.
//!
//! Not handled here:
//! - File I/O (callers read/write files).
//! - User interaction (handled by the wizard module).
//!
//! Invariants/assumptions:
//! - Sections are defined by `## ` headings.
//! - The footer is detected by `---` followed by "Generated by" or "Template version".
//! - Section order is preserved; new sections are appended after existing ones.

/// Parsed markdown document with sections.
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedDocument {
    /// Content before the first section heading (preamble).
    pub preamble: String,
    /// Sections in order: (title, content).
    pub sections: Vec<(String, String)>,
    /// Footer block (typically "Generated by..."), if present.
    pub footer: Option<String>,
}

impl ParsedDocument {
    /// Create an empty parsed document.
    pub fn empty() -> Self {
        Self {
            preamble: String::new(),
            sections: Vec::new(),
            footer: None,
        }
    }

    /// Reconstruct the full markdown content.
    pub fn to_content(&self) -> String {
        let mut result = self.preamble.clone();

        for (title, content) in &self.sections {
            result.push_str(&format!("## {}\n", title));
            // Ensure content ends with newline if not empty
            if !content.is_empty() {
                result.push_str(content);
                if !content.ends_with('\n') {
                    result.push('\n');
                }
            }
            // Add blank line between sections
            result.push('\n');
        }

        if let Some(footer) = &self.footer {
            result.push_str(footer);
            if !footer.ends_with('\n') {
                result.push('\n');
            }
        }

        result
    }

    /// Get section titles in order.
    pub fn section_titles(&self) -> Vec<&str> {
        self.sections.iter().map(|(t, _)| t.as_str()).collect()
    }

    /// Get mutable reference to a section's content by title.
    pub fn get_section_mut(&mut self, title: &str) -> Option<&mut String> {
        self.sections
            .iter_mut()
            .find(|(t, _)| t.eq_ignore_ascii_case(title))
            .map(|(_, content)| content)
    }

    /// Add a new section at the end.
    pub fn add_section(&mut self, title: String, content: String) {
        self.sections.push((title, content));
    }
}

/// Parse markdown content into structured sections.
///
/// Recognizes:
/// - Preamble: everything before the first `## ` heading.
/// - Sections: content under `## ` headings.
/// - Footer: content starting with `---` followed by "Generated by" or "Template version".
pub fn parse_markdown_document(content: &str) -> ParsedDocument {
    let mut preamble_lines = Vec::new();
    let mut sections: Vec<(String, Vec<String>)> = Vec::new();
    let mut footer_lines = Vec::new();
    let mut in_footer = false;
    let mut current_section_lines: Vec<String> = Vec::new();

    let lines: Vec<&str> = content.lines().collect();
    let mut i = 0;

    while i < lines.len() {
        let line = lines[i];

        // Check for footer marker (--- followed by Generated by/Template version)
        if line.trim() == "---" && i + 1 < lines.len() {
            let next_line = lines[i + 1];
            if next_line.contains("Generated by") || next_line.contains("Template version") {
                in_footer = true;
                footer_lines.push(line.to_string());
                i += 1;
                continue;
            }
        }

        if in_footer {
            footer_lines.push(line.to_string());
            i += 1;
            continue;
        }

        // Check for section heading
        if let Some(title) = line.strip_prefix("## ") {
            // Save previous section if exists
            if let Some((_, content_lines)) = sections.last_mut() {
                *content_lines = std::mem::take(&mut current_section_lines);
            }
            // Start new section
            sections.push((title.trim().to_string(), Vec::new()));
        } else if sections.is_empty() {
            // Still in preamble
            preamble_lines.push(line.to_string());
        } else {
            // In section content
            current_section_lines.push(line.to_string());
        }

        i += 1;
    }

    // Save last section's content
    if let Some((_, content_lines)) = sections.last_mut() {
        *content_lines = current_section_lines;
    }

    // Convert section content from Vec<String> to String
    let sections: Vec<(String, String)> = sections
        .into_iter()
        .map(|(title, lines)| {
            let content = lines.join("\n");
            // Trim trailing whitespace but preserve internal formatting
            let content = content.trim_end().to_string();
            (title, content)
        })
        .collect();

    let preamble = preamble_lines.join("\n");
    let preamble = preamble.trim_end().to_string();

    let footer = if footer_lines.is_empty() {
        None
    } else {
        Some(footer_lines.join("\n"))
    };

    ParsedDocument {
        preamble,
        sections,
        footer,
    }
}

/// Merge updates into an existing document.
///
/// For each update:
/// - If the section exists, append the new content to it.
/// - If the section doesn't exist, create it at the end.
///
/// Returns the merged document and a list of section names that were updated.
pub fn merge_section_updates(
    existing: &ParsedDocument,
    updates: &[(String, String)],
) -> (ParsedDocument, Vec<String>) {
    let mut result = existing.clone();
    let mut sections_updated = Vec::new();

    for (section_name, new_content) in updates {
        if let Some(existing_content) = result.get_section_mut(section_name) {
            // Section exists - append content
            if !existing_content.is_empty() && !existing_content.ends_with('\n') {
                existing_content.push('\n');
            }
            existing_content.push_str(new_content);
            sections_updated.push(section_name.clone());
        } else {
            // Section doesn't exist - create it
            result.add_section(section_name.clone(), new_content.clone());
            sections_updated.push(section_name.clone());
        }
    }

    (result, sections_updated)
}

/// Parse markdown sections from content (legacy compatibility).
/// Returns vector of (section_name, section_content) pairs.
pub fn parse_markdown_sections(content: &str) -> Vec<(String, String)> {
    let doc = parse_markdown_document(content);
    doc.sections
}

/// Extract section titles from markdown content (legacy compatibility).
pub fn extract_section_titles(content: &str) -> Vec<String> {
    let doc = parse_markdown_document(content);
    doc.section_titles().into_iter().map(String::from).collect()
}

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

    #[test]
    fn parse_empty_content() {
        let doc = parse_markdown_document("");
        assert!(doc.preamble.is_empty());
        assert!(doc.sections.is_empty());
        assert!(doc.footer.is_none());
    }

    #[test]
    fn parse_preamble_only() {
        let content = "# Title\n\nSome description here.";
        let doc = parse_markdown_document(content);
        assert_eq!(doc.preamble, "# Title\n\nSome description here.");
        assert!(doc.sections.is_empty());
    }

    #[test]
    fn parse_sections() {
        let content = r#"# Title

## Section One

Content one.

More content.

## Section Two

Content two.
"#;
        let doc = parse_markdown_document(content);
        assert_eq!(doc.preamble, "# Title");
        assert_eq!(doc.sections.len(), 2);
        assert_eq!(doc.sections[0].0, "Section One");
        assert!(doc.sections[0].1.contains("Content one."));
        assert_eq!(doc.sections[1].0, "Section Two");
    }

    #[test]
    fn parse_with_footer() {
        let content = r#"# Title

## Section One

Content.

---
*Generated by Ralph v1.0.0*
*Template version: 1*
"#;
        let doc = parse_markdown_document(content);
        assert_eq!(doc.sections.len(), 1);
        assert!(doc.footer.is_some());
        let footer = doc.footer.unwrap();
        assert!(footer.contains("Generated by Ralph"));
        assert!(footer.contains("Template version"));
    }

    #[test]
    fn merge_updates_existing_section() {
        let existing = parse_markdown_document(
            r#"# Title

## Section One

Original content.
"#,
        );
        let updates = vec![("Section One".to_string(), "Appended content.".to_string())];

        let (merged, updated) = merge_section_updates(&existing, &updates);

        assert_eq!(updated, vec!["Section One"]);
        assert!(merged.sections[0].1.contains("Original content."));
        assert!(merged.sections[0].1.contains("Appended content."));
    }

    #[test]
    fn merge_creates_new_section() {
        let existing = parse_markdown_document(
            r#"# Title

## Section One

Content.
"#,
        );
        let updates = vec![("Section Two".to_string(), "New content.".to_string())];

        let (merged, updated) = merge_section_updates(&existing, &updates);

        assert_eq!(updated, vec!["Section Two"]);
        assert_eq!(merged.sections.len(), 2);
        assert_eq!(merged.sections[1].0, "Section Two");
        assert!(merged.sections[1].1.contains("New content."));
    }

    #[test]
    fn merge_preserves_footer() {
        let existing = parse_markdown_document(
            r#"# Title

## Section One

Content.

---
*Generated by Ralph v1.0.0*
"#,
        );
        let updates = vec![("Section One".to_string(), "More content.".to_string())];

        let (merged, _) = merge_section_updates(&existing, &updates);

        assert!(merged.footer.is_some());
        assert!(merged.footer.unwrap().contains("Generated by Ralph"));
    }

    #[test]
    fn to_content_reconstructs_document() {
        let original = r#"# Title

## Section One

Content one.

## Section Two

Content two.

---
*Generated by Ralph*
"#;
        let doc = parse_markdown_document(original);
        let reconstructed = doc.to_content();

        // Check that reconstructed content has all parts
        assert!(reconstructed.contains("# Title"));
        assert!(reconstructed.contains("## Section One"));
        assert!(reconstructed.contains("Content one."));
        assert!(reconstructed.contains("## Section Two"));
        assert!(reconstructed.contains("---"));
        assert!(reconstructed.contains("Generated by Ralph"));
    }

    #[test]
    fn extract_section_titles_finds_all_sections() {
        let content = r#"# Title

## Section One

Content one.

## Section Two

Content two.

### Subsection

More content.
"#;
        let titles = extract_section_titles(content);
        assert_eq!(titles, vec!["Section One", "Section Two"]);
    }

    #[test]
    fn merge_multiple_updates() {
        let existing = parse_markdown_document(
            r#"# Title

## Section One

Content one.
"#,
        );
        let updates = vec![
            ("Section One".to_string(), "Updated one.".to_string()),
            (
                "Section Two".to_string(),
                "New section content.".to_string(),
            ),
        ];

        let (merged, updated) = merge_section_updates(&existing, &updates);

        assert_eq!(updated.len(), 2);
        assert!(updated.contains(&"Section One".to_string()));
        assert!(updated.contains(&"Section Two".to_string()));
        assert_eq!(merged.sections.len(), 2);
    }
}