Skip to main content

aither_agent/
working_docs.rs

1//! Working document utilities for long-task execution.
2//!
3//! `tasks.md` is a regular markdown file in the sandbox that the framework
4//! treats specially by loading into context and supervising progress.
5
6use std::path::Path;
7
8use async_fs as fs;
9use similar::{ChangeTag, TextDiff};
10
11/// Snapshot of working documents currently present in the sandbox.
12#[derive(Debug, Clone, Default)]
13pub struct WorkingDocsSnapshot {
14    /// Contents of `tasks.md`, when present.
15    pub tasks_md: Option<String>,
16}
17
18impl WorkingDocsSnapshot {
19    /// Returns true when `tasks.md` has unchecked markdown tasks.
20    #[must_use]
21    pub fn has_unchecked_items(&self) -> bool {
22        self.tasks_md
23            .as_deref()
24            .is_some_and(has_unchecked_markdown_tasks)
25    }
26}
27
28/// Reads `tasks.md` from the given sandbox directory.
29pub async fn read_snapshot(sandbox_dir: &Path) -> WorkingDocsSnapshot {
30    let tasks_path = sandbox_dir.join("tasks.md");
31
32    let tasks_md = read_file_if_exists(&tasks_path).await;
33
34    WorkingDocsSnapshot { tasks_md }
35}
36
37/// Returns a compact changed-line diff for `tasks.md` when it changed.
38#[must_use]
39pub fn tasks_md_diff(
40    previous: &WorkingDocsSnapshot,
41    current: &WorkingDocsSnapshot,
42) -> Option<String> {
43    if previous.tasks_md == current.tasks_md {
44        return None;
45    }
46
47    let diff = TextDiff::from_lines(
48        previous.tasks_md.as_deref().unwrap_or_default(),
49        current.tasks_md.as_deref().unwrap_or_default(),
50    );
51
52    let mut lines = Vec::new();
53    for change in diff.iter_all_changes() {
54        let prefix = match change.tag() {
55            ChangeTag::Delete => "- ",
56            ChangeTag::Insert => "+ ",
57            ChangeTag::Equal => continue,
58        };
59        let value = change.value().trim_end_matches('\n');
60        if value.is_empty() {
61            continue;
62        }
63        let mut line = String::from(prefix);
64        line.push_str(value);
65        lines.push(line);
66        if lines.len() == 48 {
67            lines.push("...".to_string());
68            break;
69        }
70    }
71
72    if lines.is_empty() {
73        return Some("tasks.md changed.".to_string());
74    }
75
76    Some(lines.join("\n"))
77}
78
79/// Detects unfinished markdown checklist items (`- [ ]`).
80#[must_use]
81pub fn has_unchecked_markdown_tasks(content: &str) -> bool {
82    content.lines().any(is_unchecked_todo_line)
83}
84
85fn is_unchecked_todo_line(line: &str) -> bool {
86    let trimmed = line.trim_start();
87    (trimmed.starts_with("- [ ]") || trimmed.starts_with("* [ ]"))
88        || (trimmed.starts_with("- [	]") || trimmed.starts_with("* [	]"))
89}
90
91async fn read_file_if_exists(path: &Path) -> Option<String> {
92    match fs::read_to_string(path).await {
93        Ok(content) => Some(content),
94        Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
95        Err(err) => {
96            tracing::warn!(path = %path.display(), error = %err, "failed to read working doc");
97            None
98        }
99    }
100}