agent-doc 0.32.3

Interactive document sessions with AI agents
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
//! # Module: patch
//!
//! ## Spec
//! - Replaces, appends, or prepends content in a named `<!-- agent:name -->` component within a markdown document.
//! - Patch mode resolution order: inline attribute on the component tag (`patch=`) > `[components.<name>]` entry in `.agent-doc/config.toml` > built-in default (`replace`). `mode=` is accepted as a backward-compatible alias; `patch=` takes precedence when both are present.
//! - `append` mode: concatenates new content after existing; `prepend` mode: inserts new content before existing.
//! - Optional `timestamp: true` in component config prefixes each entry with an ISO-8601 UTC timestamp.
//! - Optional `max_entries` in component config trims to the last N non-empty lines after append/prepend.
//! - `pre_patch` shell hook: content piped to stdin, transformed stdout replaces the replacement string before writing. Receives `COMPONENT` and `FILE` env vars.
//! - `post_patch` shell hook: fire-and-forget after write, receives same env vars. Non-zero exit is logged as a warning only.
//! - After patching, the document is written to disk and a snapshot is saved relative to the project root (`.agent-doc/snapshots/`). Falls back to CWD-relative snapshot if no project root is found.
//! - `run` reads replacement content from the `content` argument or stdin when `None`.
//!
//! ## Agentic Contracts
//! - `run(file, component_name, content)` — returns `Err` if the file is missing, the component is not found, or any hook fails.
//! - Snapshot is always updated after a successful patch; callers can rely on snapshot consistency.
//! - `pre_patch` hook failure (non-zero exit) aborts the patch and returns `Err`; no partial write occurs.
//! - `post_patch` hook failure never aborts the patch; stderr warning only.
//! - `trim_entries(content, max)` trims to the last `max` non-empty lines; returns content unchanged when under the limit.
//!
//! ## Evals
//! - replace_component: existing component + new content → old content replaced, surroundings preserved
//! - preserve_surrounding: content before and after component → unchanged after patch
//! - component_not_found: component name absent from doc → Err containing "not found"
//! - file_not_found: missing file path → Err containing "file not found"
//! - snapshot_updated_after_patch: after replace → snapshot file contains new content, not old
//! - append_mode: `mode = "append"` config + second patch → both entries present in document
//! - prepend_mode: `mode = "prepend"` config + new entry → new entry appears before existing
//! - trim_entries_limits: 5-line content trimmed to 3 → oldest 2 lines removed
//! - pre_patch_hook_transforms: `pre_patch = "tr a-z A-Z"` → content uppercased before write
//! - post_patch_hook_runs: `post_patch = "touch <file>"` → marker file created after write

use anyhow::{bail, Context, Result};
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::process::Command;

use crate::{component, project_config, snapshot};

/// Load component configs from `.agent-doc/config.toml` relative to the document.
/// Walks up from the document's parent directory to find the project root.
fn load_configs(file: &Path) -> Result<HashMap<String, project_config::ComponentConfig>> {
    let start = file.parent().unwrap_or(file);
    let mut current = start;
    loop {
        let candidate = current.join(".agent-doc").join("config.toml");
        if candidate.exists() {
            let cfg = project_config::load_project_from(&candidate);
            return Ok(cfg.components.into_iter().collect());
        }
        match current.parent() {
            Some(p) if p != current => current = p,
            _ => break,
        }
    }
    // Fall back to CWD-based resolution
    let proj_cfg = project_config::load_project();
    Ok(proj_cfg.components.into_iter().collect())
}

/// Replace content in a named component.
///
/// If `content` is None, reads replacement content from stdin.
/// Applies component config (mode, timestamp, max_entries) and shell hooks.
pub fn run(file: &Path, component_name: &str, content: Option<&str>) -> Result<()> {
    if !file.exists() {
        bail!("file not found: {}", file.display());
    }

    let doc = std::fs::read_to_string(file)
        .with_context(|| format!("failed to read {}", file.display()))?;

    let components = component::parse(&doc)
        .with_context(|| format!("failed to parse components in {}", file.display()))?;

    let comp = components
        .iter()
        .find(|c| c.name == component_name)
        .ok_or_else(|| {
            anyhow::anyhow!(
                "component '{}' not found in {}",
                component_name,
                file.display()
            )
        })?;

    let configs = load_configs(file).unwrap_or_default();
    let config = configs.get(component_name);

    let mut replacement = match content {
        Some(text) => text.to_string(),
        None => {
            let mut buf = String::new();
            std::io::stdin()
                .read_to_string(&mut buf)
                .context("failed to read from stdin")?;
            buf
        }
    };

    // Run pre_patch hook (transforms content)
    if let Some(script) = config.and_then(|c| c.pre_patch.as_ref()) {
        replacement = run_pre_hook(script, component_name, file, &replacement)?;
    }

    // Apply mode: inline attr > config.toml [components.<name>] > default ("replace")
    let mode = comp.patch_mode()
        .or_else(|| config.map(|c| c.patch.as_str()))
        .unwrap_or("replace");
    let timestamp = config.is_some_and(|c| c.timestamp);
    let max_entries = config.map(|c| c.max_entries).unwrap_or(0);

    let final_content = match mode {
        "append" => {
            let existing = comp.content(&doc);
            let entry = if timestamp {
                format!("[{}] {}", iso_now(), replacement)
            } else {
                replacement
            };
            let mut combined = format!("{}{}", existing, entry);
            if max_entries > 0 {
                combined = trim_entries(&combined, max_entries);
            }
            combined
        }
        "prepend" => {
            let existing = comp.content(&doc);
            let entry = if timestamp {
                format!("[{}] {}", iso_now(), replacement)
            } else {
                replacement
            };
            let mut combined = format!("{}{}", entry, existing);
            if max_entries > 0 {
                combined = trim_entries(&combined, max_entries);
            }
            combined
        }
        _ => {
            // "replace" (default)
            if timestamp {
                format!("[{}] {}", iso_now(), replacement)
            } else {
                replacement
            }
        }
    };

    let new_doc = comp.replace_content(&doc, &final_content);

    std::fs::write(file, &new_doc)
        .with_context(|| format!("failed to write {}", file.display()))?;

    // Save snapshot relative to project root (not CWD) for thread safety
    let snap_rel = snapshot::path_for(file)?;
    if let Some(root) = snapshot::find_project_root(file) {
        let snap_abs = root.join(&snap_rel);
        if let Some(parent) = snap_abs.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create snapshot dir for {}", file.display()))?;
        }
        std::fs::write(&snap_abs, &new_doc)
            .with_context(|| format!("failed to update snapshot for {}", file.display()))?;
    } else {
        // Fallback to CWD-relative (original behavior)
        snapshot::save(file, &new_doc)
            .with_context(|| format!("failed to update snapshot for {}", file.display()))?;
    }

    // Run post_patch hook (fire-and-forget)
    if let Some(script) = config.and_then(|c| c.post_patch.as_ref()) {
        run_post_hook(script, component_name, file);
    }

    eprintln!(
        "Patched component '{}' in {} (mode: {})",
        component_name,
        file.display(),
        mode
    );
    Ok(())
}

/// Run a pre_patch hook. Passes content on stdin, returns transformed content from stdout.
fn run_pre_hook(script: &str, component_name: &str, file: &Path, content: &str) -> Result<String> {
    let mut child = Command::new("sh")
        .args(["-c", script])
        .env("COMPONENT", component_name)
        .env("FILE", file.to_string_lossy().as_ref())
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::inherit())
        .spawn()
        .with_context(|| format!("failed to run pre_patch hook: {}", script))?;

    if let Some(mut stdin) = child.stdin.take() {
        use std::io::Write;
        stdin.write_all(content.as_bytes())?;
    }

    let output = child.wait_with_output()?;
    if !output.status.success() {
        bail!(
            "pre_patch hook failed (exit {}): {}",
            output.status.code().unwrap_or(-1),
            script
        );
    }
    String::from_utf8(output.stdout)
        .context("pre_patch hook produced invalid UTF-8")
}

/// Run a post_patch hook (fire-and-forget).
fn run_post_hook(script: &str, component_name: &str, file: &Path) {
    let result = Command::new("sh")
        .args(["-c", script])
        .env("COMPONENT", component_name)
        .env("FILE", file.to_string_lossy().as_ref())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::inherit())
        .stderr(std::process::Stdio::inherit())
        .status();
    if let Err(e) = result {
        eprintln!("Warning: post_patch hook failed: {}", e);
    }
}

/// Trim to the last `max` non-empty lines.
fn trim_entries(content: &str, max: usize) -> String {
    let lines: Vec<&str> = content.lines().filter(|l| !l.is_empty()).collect();
    if lines.len() <= max {
        return content.to_string();
    }
    let trimmed: Vec<&str> = lines[lines.len() - max..].to_vec();
    let mut result = trimmed.join("\n");
    if content.ends_with('\n') {
        result.push('\n');
    }
    result
}

/// Simple UTC timestamp.
fn iso_now() -> String {
    let output = Command::new("date")
        .args(["-u", "+%Y-%m-%dT%H:%M:%SZ"])
        .output();
    match output {
        Ok(out) => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        Err(_) => "unknown".to_string(),
    }
}

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

    /// Create a temp dir with `.agent-doc/snapshots/` so `find_project_root` and
    /// `snapshot::save` work without `set_current_dir`.
    fn setup_project() -> TempDir {
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join(".agent-doc/snapshots")).unwrap();
        dir
    }

    fn write_doc(dir: &Path, name: &str, content: &str) -> std::path::PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, content).unwrap();
        path
    }

    fn write_config(dir: &Path, content: &str) {
        // Config lives at .agent-doc/config.toml with [components] section
        let config_path = dir.join(".agent-doc").join("config.toml");
        std::fs::write(config_path, content).unwrap();
    }

    #[test]
    fn replace_component() {
        let dir = setup_project();
        let doc = write_doc(
            dir.path(),
            "test.md",
            "# Dashboard\n\n<!-- agent:status -->\nold content\n<!-- /agent:status -->\n\nFooter\n",
        );

        run(&doc, "status", Some("new content\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        assert!(result.contains("new content"));
        assert!(!result.contains("old content"));
        assert!(result.contains("<!-- agent:status -->"));
        assert!(result.contains("<!-- /agent:status -->"));
        assert!(result.contains("Footer"));
    }

    #[test]
    fn preserve_surrounding() {
        let dir = setup_project();
        let doc = write_doc(
            dir.path(),
            "test.md",
            "BEFORE\n<!-- agent:x -->\nreplace me\n<!-- /agent:x -->\nAFTER\n",
        );

        run(&doc, "x", Some("replaced\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        assert!(result.starts_with("BEFORE\n"));
        assert!(result.ends_with("AFTER\n"));
        assert!(result.contains("replaced"));
    }

    #[test]
    fn component_not_found_error() {
        let dir = setup_project();
        let doc = write_doc(dir.path(), "test.md", "# No components\n");

        let err = run(&doc, "missing", Some("x")).unwrap_err();
        assert!(err.to_string().contains("not found"));
    }

    #[test]
    fn file_not_found_error() {
        let err = run(Path::new("/nonexistent/file.md"), "s", Some("x")).unwrap_err();
        assert!(err.to_string().contains("file not found"));
    }

    #[test]
    fn snapshot_updated_after_patch() {
        let dir = setup_project();
        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:s -->\nold\n<!-- /agent:s -->\n",
        );

        run(&doc, "s", Some("new\n")).unwrap();

        // Snapshot should be readable from the project's .agent-doc/snapshots/
        let snap_path = dir.path().join(snapshot::path_for(&doc).unwrap());
        let snap = std::fs::read_to_string(snap_path).unwrap();
        assert!(snap.contains("new"));
        assert!(!snap.contains("old"));
    }

    #[test]
    fn append_mode() {
        let dir = setup_project();
        write_config(dir.path(), "[components.log]\npatch = \"append\"\n");

        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:log -->\nentry1\n<!-- /agent:log -->\n",
        );

        run(&doc, "log", Some("entry2\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        assert!(result.contains("entry1"));
        assert!(result.contains("entry2"));
    }

    #[test]
    fn prepend_mode() {
        let dir = setup_project();
        write_config(dir.path(), "[components.log]\npatch = \"prepend\"\n");

        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:log -->\nold\n<!-- /agent:log -->\n",
        );

        run(&doc, "log", Some("new\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        let new_pos = result.find("new").unwrap();
        let old_pos = result.find("old").unwrap();
        assert!(new_pos < old_pos);
    }

    #[test]
    fn trim_entries_limits() {
        let content = "line1\nline2\nline3\nline4\nline5\n";
        let trimmed = trim_entries(content, 3);
        assert!(!trimmed.contains("line1"));
        assert!(!trimmed.contains("line2"));
        assert!(trimmed.contains("line3"));
        assert!(trimmed.contains("line4"));
        assert!(trimmed.contains("line5"));
    }

    #[test]
    fn trim_entries_noop_when_under_limit() {
        let content = "line1\nline2\n";
        assert_eq!(trim_entries(content, 5), content);
    }

    #[test]
    fn no_config_defaults_to_replace() {
        let dir = setup_project();
        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:x -->\nold\n<!-- /agent:x -->\n",
        );

        run(&doc, "x", Some("new\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        assert!(result.contains("new"));
        assert!(!result.contains("old"));
    }

    #[test]
    fn pre_patch_hook_transforms_content() {
        let dir = setup_project();
        write_config(dir.path(), "[components.x]\npre_patch = \"tr a-z A-Z\"\n");

        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:x -->\nold\n<!-- /agent:x -->\n",
        );

        run(&doc, "x", Some("hello world\n")).unwrap();

        let result = std::fs::read_to_string(&doc).unwrap();
        assert!(result.contains("HELLO WORLD"));
    }

    #[test]
    fn post_patch_hook_runs() {
        let dir = setup_project();
        let marker = dir.path().join("hook-ran");
        write_config(
            dir.path(),
            &format!(
                "[components.x]\npost_patch = \"touch {}\"\n",
                marker.to_string_lossy()
            ),
        );

        let doc = write_doc(
            dir.path(),
            "test.md",
            "<!-- agent:x -->\nold\n<!-- /agent:x -->\n",
        );

        run(&doc, "x", Some("new\n")).unwrap();

        assert!(marker.exists(), "post_patch hook should have created marker file");
    }
}