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
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! # Module: debounce
//!
//! ## Spec
//! - Provides a shared typing-debounce mechanism used by all editor plugins (JetBrains, VS Code,
//!   Neovim, Zed) so they share identical timing logic via the agent-doc FFI layer.
//! - In-process state: a `Mutex<HashMap<PathBuf, Instant>>` (`LAST_CHANGE`) records the last
//!   edit timestamp per file path.
//! - Cross-process state: each `document_changed` call also writes a millisecond Unix timestamp
//!   to `.agent-doc/typing/<hash>` so CLI invocations running in a separate process can detect
//!   active typing. The hash is derived from the file path string via `DefaultHasher`.
//!   Cross-process writes are best-effort and never block the caller.
//! - `is_idle` / `await_idle` operate on in-process state (same process as the plugin).
//! - `is_typing_via_file` / `await_idle_via_file` operate on the file-based indicator (CLI use).
//! - Files with no recorded `document_changed` call are considered idle by `is_idle`; this
//!   prevents `await_idle` from blocking forever on untracked documents.
//! - `is_tracked` distinguishes "never seen" from "seen and idle" for non-blocking probes.
//! - `await_idle` polls every 100 ms and returns `false` if `timeout_ms` expires before idle.
//!
//! ## Agentic Contracts
//! - `document_changed(file: &str)` — records now as last-change time; writes typing indicator
//!   file (best-effort); never panics.
//! - `is_idle(file, debounce_ms) -> bool` — `true` if elapsed ≥ `debounce_ms` or file untracked.
//! - `is_tracked(file) -> bool` — `true` if at least one `document_changed` was recorded.
//! - `await_idle(file, debounce_ms, timeout_ms) -> bool` — blocks until idle or timeout; 100 ms
//!   poll interval.
//! - `is_typing_via_file(file, debounce_ms) -> bool` — reads indicator file; `false` if absent or
//!   timestamp older than `debounce_ms`.
//! - `await_idle_via_file(file, debounce_ms, timeout_ms) -> bool` — file-based blocking variant.
//!
//! ## Evals
//! - idle_no_changes: file never passed to `document_changed` → `is_idle` returns `true`
//! - not_idle_after_change: immediately after `document_changed` with 1500 ms window → `false`
//! - idle_after_debounce: 50 ms sleep with 10 ms debounce → `is_idle` returns `true`
//! - await_immediate: untracked file, `await_idle` → returns `true` in < 200 ms
//! - await_settle: `document_changed` then `await_idle` with 200 ms debounce → waits ≥ 200 ms
//! - typing_indicator_written: `document_changed` on file with `.agent-doc/typing/` dir →
//!   `is_typing_via_file` returns `true` within 2000 ms window
//! - typing_indicator_expires: 50 ms after change with 10 ms debounce →
//!   `is_typing_via_file` returns `false`
//! - no_indicator_file: nonexistent path → `is_typing_via_file` returns `false`

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::Instant;

/// Global state: last change timestamp per file.
static LAST_CHANGE: Mutex<Option<HashMap<PathBuf, Instant>>> = Mutex::new(None);

fn with_state<R>(f: impl FnOnce(&mut HashMap<PathBuf, Instant>) -> R) -> R {
    let mut guard = LAST_CHANGE.lock().unwrap();
    let map = guard.get_or_insert_with(HashMap::new);
    f(map)
}

/// Record a document change event for the given file.
///
/// Called by editor plugins on every document modification.
/// Also writes a typing indicator file for cross-process visibility.
pub fn document_changed(file: &str) {
    let path = PathBuf::from(file);
    with_state(|map| {
        map.insert(path.clone(), Instant::now());
    });
    // Write cross-process typing indicator (best-effort, never block)
    if let Err(e) = write_typing_indicator(file) {
        eprintln!("[debounce] typing indicator write failed for {:?}: {}", file, e);
    }
}

/// Check if the document has been idle (no changes) for at least `debounce_ms`.
///
/// Returns `true` if no recent changes (safe to run), `false` if still active.
/// For untracked files (no `document_changed` ever called), returns `true` —
/// the blocking `await_idle` relies on this to not wait forever.
pub fn is_idle(file: &str, debounce_ms: u64) -> bool {
    let path = PathBuf::from(file);
    with_state(|map| {
        match map.get(&path) {
            None => true, // No recorded changes — idle
            Some(last) => last.elapsed().as_millis() >= debounce_ms as u128,
        }
    })
}

/// Check if the document has been tracked (at least one `document_changed` call recorded).
///
/// Used by non-blocking probes to distinguish "never tracked" from "tracked and idle".
/// If a file is untracked, the probe should be conservative (assume not idle).
pub fn is_tracked(file: &str) -> bool {
    let path = PathBuf::from(file);
    with_state(|map| map.contains_key(&path))
}

/// Return the number of tracked files in the debounce state.
pub fn tracked_count() -> usize {
    with_state(|map| map.len())
}

/// Block until the document has been idle for `debounce_ms`, or `timeout_ms` expires.
///
/// Returns `true` if idle was reached, `false` if timed out.
///
/// Poll interval: 100ms (responsive without busy-waiting).
pub fn await_idle(file: &str, debounce_ms: u64, timeout_ms: u64) -> bool {
    let start = Instant::now();
    let timeout = std::time::Duration::from_millis(timeout_ms);
    let poll_interval = std::time::Duration::from_millis(100);

    loop {
        if is_idle(file, debounce_ms) {
            return true;
        }
        if start.elapsed() >= timeout {
            return false;
        }
        std::thread::sleep(poll_interval);
    }
}

// ── Cross-process typing bridge ──

/// Directory for typing indicator files, relative to project root.
const TYPING_DIR: &str = ".agent-doc/typing";

/// Write a typing indicator file for the given document path.
/// The file contains a Unix timestamp (milliseconds) of the last edit.
fn write_typing_indicator(file: &str) -> std::io::Result<()> {
    let typing_path = typing_indicator_path(file);
    if let Some(parent) = typing_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    std::fs::write(&typing_path, now.to_string())
}

/// Compute the typing indicator file path for a document.
fn typing_indicator_path(file: &str) -> PathBuf {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    file.hash(&mut hasher);
    let hash = hasher.finish();
    // Walk up to find .agent-doc/ directory (one pop per level, no skip)
    let mut dir = PathBuf::from(file);
    dir.pop(); // Start from file's parent
    loop {
        if dir.join(".agent-doc").is_dir() {
            return dir.join(TYPING_DIR).join(format!("{:016x}", hash));
        }
        if !dir.pop() {
            // Fallback: use file's parent directory
            let parent = PathBuf::from(file).parent().unwrap_or(std::path::Path::new(".")).to_path_buf();
            return parent.join(TYPING_DIR).join(format!("{:016x}", hash));
        }
    }
}

/// Check if the document has a recent typing indicator (cross-process).
///
/// Returns `true` if the typing indicator exists and was updated within
/// `debounce_ms` milliseconds. Used by CLI preflight to detect active typing
/// from a plugin running in a different process.
pub fn is_typing_via_file(file: &str, debounce_ms: u64) -> bool {
    let path = typing_indicator_path(file);
    match std::fs::read_to_string(&path) {
        Ok(content) => {
            if let Ok(ts_ms) = content.trim().parse::<u128>() {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis();
                now.saturating_sub(ts_ms) < debounce_ms as u128
            } else {
                false
            }
        }
        Err(_) => false, // No indicator file — not typing
    }
}

/// Block until the typing indicator shows idle, or timeout.
///
/// Used by CLI preflight to wait for plugin-side typing to settle.
/// Returns `true` if idle was reached, `false` if timed out.
pub fn await_idle_via_file(file: &str, debounce_ms: u64, timeout_ms: u64) -> bool {
    let start = Instant::now();
    let timeout = std::time::Duration::from_millis(timeout_ms);
    let poll_interval = std::time::Duration::from_millis(100);

    loop {
        if !is_typing_via_file(file, debounce_ms) {
            return true;
        }
        if start.elapsed() >= timeout {
            return false;
        }
        std::thread::sleep(poll_interval);
    }
}

// ── Response status signal (A: file, B: FFI) ──

/// Status directory for cross-process signals (Option A).
const STATUS_DIR: &str = ".agent-doc/status";

/// In-process status (Option B: FFI).
static STATUS: Mutex<Option<HashMap<PathBuf, String>>> = Mutex::new(None);

fn with_status<R>(f: impl FnOnce(&mut HashMap<PathBuf, String>) -> R) -> R {
    let mut guard = STATUS.lock().unwrap();
    let map = guard.get_or_insert_with(HashMap::new);
    f(map)
}

/// Set the response status for a file.
///
/// Status values: "generating", "writing", "routing", "idle"
/// Sets both in-process state (B) and file signal (A).
pub fn set_status(file: &str, status: &str) {
    let path = PathBuf::from(file);
    with_status(|map| {
        if status == "idle" {
            map.remove(&path);
        } else {
            map.insert(path, status.to_string());
        }
    });
    let _ = write_status_file(file, status);
}

/// Get the response status for a file (in-process, Option B).
///
/// Returns "idle" if no status is set.
pub fn get_status(file: &str) -> String {
    let path = PathBuf::from(file);
    with_status(|map| {
        map.get(&path).cloned().unwrap_or_else(|| "idle".to_string())
    })
}

/// Check if any operation is in progress for a file (in-process, Option B).
///
/// Returns `true` if status is NOT "idle". Used by plugins to avoid
/// triggering routes during active operations.
pub fn is_busy(file: &str) -> bool {
    get_status(file) != "idle"
}

/// Get status from file signal (cross-process, Option A).
///
/// Returns "idle" if no status file exists or it's stale (>30s).
pub fn get_status_via_file(file: &str) -> String {
    let path = status_file_path(file);
    match std::fs::read_to_string(&path) {
        Ok(content) => {
            // Format: "status:timestamp_ms"
            let parts: Vec<&str> = content.trim().splitn(2, ':').collect();
            if parts.len() == 2 && let Ok(ts) = parts[1].parse::<u128>() {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_millis();
                // Stale after 30s — operation probably crashed
                if now.saturating_sub(ts) < 30_000 {
                    return parts[0].to_string();
                }
            }
            "idle".to_string()
        }
        Err(_) => "idle".to_string(),
    }
}

fn write_status_file(file: &str, status: &str) -> std::io::Result<()> {
    let path = status_file_path(file);
    if status == "idle" {
        let _ = std::fs::remove_file(&path);
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    std::fs::write(&path, format!("{}:{}", status, now))
}

fn status_file_path(file: &str) -> PathBuf {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    file.hash(&mut hasher);
    let hash = hasher.finish();
    let mut dir = PathBuf::from(file);
    dir.pop(); // Start from file's parent
    loop {
        if dir.join(".agent-doc").is_dir() {
            return dir.join(STATUS_DIR).join(format!("{:016x}", hash));
        }
        if !dir.pop() {
            let parent = PathBuf::from(file).parent().unwrap_or(std::path::Path::new(".")).to_path_buf();
            return parent.join(STATUS_DIR).join(format!("{:016x}", hash));
        }
    }
}

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

    #[test]
    fn idle_when_no_changes() {
        assert!(is_idle("/tmp/test-no-changes.md", 1500));
    }

    #[test]
    fn not_idle_after_change() {
        document_changed("/tmp/test-just-changed.md");
        assert!(!is_idle("/tmp/test-just-changed.md", 1500));
    }

    #[test]
    fn idle_after_debounce_period() {
        document_changed("/tmp/test-debounce.md");
        // Use a very short debounce for testing
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert!(is_idle("/tmp/test-debounce.md", 10));
    }

    #[test]
    fn await_idle_returns_immediately_when_idle() {
        let start = Instant::now();
        assert!(await_idle("/tmp/test-await-idle.md", 100, 5000));
        assert!(start.elapsed().as_millis() < 200);
    }

    #[test]
    fn await_idle_waits_for_settle() {
        document_changed("/tmp/test-await-settle.md");
        let start = Instant::now();
        assert!(await_idle("/tmp/test-await-settle.md", 200, 5000));
        assert!(start.elapsed().as_millis() >= 200);
    }

    #[test]
    fn typing_indicator_written_on_change() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-typing.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);

        // Should detect typing within 2000ms window
        assert!(is_typing_via_file(&doc_str, 2000));
    }

    #[test]
    fn typing_indicator_expires() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-typing-expire.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);
        std::thread::sleep(std::time::Duration::from_millis(50));

        // With a 10ms debounce, 50ms ago should NOT be typing
        assert!(!is_typing_via_file(&doc_str, 10));
    }

    #[test]
    fn no_typing_indicator_means_not_typing() {
        assert!(!is_typing_via_file("/tmp/nonexistent-file-xyz.md", 2000));
    }

    // ── GAP 1: Mtime Granularity ──
    // Route path relies on filesystem mtime which may have coarse resolution (100ms-1s).
    // Can miss rapid successive edits if they occur within mtime granularity window.

    #[test]
    fn rapid_edits_within_mtime_granularity() {
        let tmp = tempfile::TempDir::new().unwrap();
        let doc = tmp.path().join("test-rapid-edits.md");
        std::fs::write(&doc, "initial").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        // Simulate rapid edits: write → is_idle check → write again
        // All within filesystem mtime granularity (e.g., 1s on some systems)
        document_changed(&doc_str);
        // This may not detect the second change on coarse-grained filesystems
        document_changed(&doc_str);

        // Should be not idle, but mtime-based detection may fail
        assert!(!is_idle(&doc_str, 500));
    }

    // ── GAP 2: Untracked File Edge Case ──
    // Untracked files return idle=true immediately, preventing await_idle from blocking forever.
    // But is_tracked() should distinguish "never-tracked" from "tracked and idle".

    #[test]
    fn is_tracked_distinguishes_untracked_from_idle() {
        let file_never_tracked = "/tmp/never-tracked.md";
        let file_tracked_idle = "/tmp/tracked-idle.md";

        // Never-tracked file
        assert!(!is_tracked(file_never_tracked));
        assert!(is_idle(file_never_tracked, 1500)); // idle=true for untracked

        // Tracked file that is now idle
        document_changed(file_tracked_idle);
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert!(is_tracked(file_tracked_idle)); // is_tracked=true
        assert!(is_idle(file_tracked_idle, 10)); // also idle=true after debounce
    }

    #[test]
    fn await_idle_on_untracked_file_returns_immediately() {
        let start = Instant::now();
        // Untracked file should return immediately, not wait
        assert!(await_idle("/tmp/untracked-await.md", 1500, 5000));
        assert!(start.elapsed().as_millis() < 500);
    }

    #[test]
    fn await_idle_respects_tracked_state() {
        let tracked_file = "/tmp/tracked-await.md";
        document_changed(tracked_file);
        assert!(is_tracked(tracked_file));

        // await_idle should wait for debounce even though tracked
        let start = Instant::now();
        assert!(await_idle(tracked_file, 200, 5000));
        assert!(start.elapsed().as_millis() >= 200);
    }

    // ── GAP 3: Hash Collision Risk ──
    // DefaultHasher is non-cryptographic; collision risk is low but possible.
    // Need to verify collision handling in typing indicator files.

    #[test]
    fn hash_collision_handling() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();

        let doc1 = tmp.path().join("doc1.md");
        let doc2 = tmp.path().join("doc2.md");
        std::fs::write(&doc1, "test").unwrap();
        std::fs::write(&doc2, "test").unwrap();

        let doc1_str = doc1.to_string_lossy().to_string();
        let doc2_str = doc2.to_string_lossy().to_string();

        document_changed(&doc1_str);
        let path1 = typing_indicator_path(&doc1_str);

        document_changed(&doc2_str);
        let path2 = typing_indicator_path(&doc2_str);

        // If hashes collide, paths are identical
        // This is a low-probability event but should be documented
        if path1 == path2 {
            // Collision detected: last write wins, earlier timestamp is overwritten
            // is_typing_via_file for both returns true for the more recent change only
            assert!(is_typing_via_file(&doc2_str, 2000)); // Most recent
        } else {
            // No collision: separate files, both typing
            assert!(is_typing_via_file(&doc1_str, 2000));
            assert!(is_typing_via_file(&doc2_str, 2000));
        }
    }

    // ── GAP 4: Reactive Mode CRDT Assumption ──
    // Watch daemon reactive path (zero debounce) assumes CRDT merge always converges.
    // If CRDT merge fails or produces unexpected state, reactive mode could cause issues.
    // Note: This is tested at watch.rs level; debounce.rs cannot test CRDT semantics.

    #[test]
    fn reactive_mode_requires_zero_debounce() {
        // Reactive mode relies on zero debounce (instant idle check).
        // With debounce_ms=0, elapsed >= 0 is always true.
        let reactive_file = "/tmp/reactive.md";
        document_changed(reactive_file);

        // With zero debounce, even freshly changed files return idle=true
        // because elapsed (even nanoseconds) >= 0
        assert!(is_idle(reactive_file, 0));

        // This means reactive mode responds instantly but assumes CRDT merge
        // will handle concurrent edits correctly (see Gap 4 in SPEC.md)
    }

    // ── GAP 5: Status File Staleness (30s timeout) ──
    // Response status files expire after 30s with assumption operation crashed.
    // No recovery for long-running operations or delayed writes.

    #[test]
    fn status_file_staleness_timeout() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("status");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-status.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        set_status(&doc_str, "generating");
        assert_eq!(get_status(&doc_str), "generating");

        // Status should remain until explicitly cleared
        assert_eq!(get_status_via_file(&doc_str), "generating");

        // After 30s, get_status_via_file returns "idle" (assumes operation crashed)
        // This test documents the 30s assumption but cannot test actual passage of time
        // in unit tests without mocking SystemTime.
    }

    #[test]
    fn status_file_cleared_on_idle() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("status");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-status-clear.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        set_status(&doc_str, "writing");
        assert!(is_busy(&doc_str));

        set_status(&doc_str, "idle");
        assert!(!is_busy(&doc_str));
        assert_eq!(get_status(&doc_str), "idle");
    }

    // ── GAP 6: Hardcoded Timing Constants ──
    // Preflight hardcodes 1500ms for typing indicator debounce (vs 500ms poll debounce).
    // Not configurable; one-size-fits-all fails for slow CI or fast typists.

    #[test]
    fn timing_constants_are_configurable() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-timing.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);

        // is_typing_via_file accepts debounce_ms as parameter — good
        assert!(is_typing_via_file(&doc_str, 2000));
        assert!(is_typing_via_file(&doc_str, 100));

        // await_idle_via_file also accepts debounce_ms — configurable
        let start = Instant::now();
        let result = await_idle_via_file(&doc_str, 10, 1000);
        let elapsed = start.elapsed();

        // With 10ms debounce, should wait ~10ms then return true
        assert!(result);
        assert!(elapsed.as_millis() >= 10);

        // preflight.rs hardcodes 1500ms in is_typing_via_file call
        // This is a documentation test: ideally 1500ms should be configurable
    }

    #[test]
    fn await_idle_via_file_respects_poll_interval() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let doc = tmp.path().join("test-poll-interval.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);

        let start = Instant::now();
        // With 100ms debounce, poll should check ~every 100ms
        assert!(await_idle_via_file(&doc_str, 100, 5000));
        let elapsed = start.elapsed().as_millis();

        // Should wait at least the debounce time (allowing some jitter)
        assert!(elapsed >= 100);
    }

    // ── GAP 7: Directory-walk bug (depth-1) ──
    // typing_indicator_path and status_file_path had a double-pop bug:
    // each loop iteration popped twice, skipping every other directory level.
    // Files at depth 1 from the project root (e.g. tasks/file.md) failed to
    // find .agent-doc/ and fell back to the wrong path.

    #[test]
    fn typing_indicator_found_for_file_one_level_deep() {
        let tmp = tempfile::TempDir::new().unwrap();
        // .agent-doc at project root
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        // File one level deep (tasks/file.md pattern)
        let subdir = tmp.path().join("tasks");
        std::fs::create_dir_all(&subdir).unwrap();
        let doc = subdir.join("test-depth1.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);

        // Should find .agent-doc/ at project root, not fall back to wrong path
        assert!(is_typing_via_file(&doc_str, 2000));
    }

    #[test]
    fn typing_indicator_found_for_file_two_levels_deep() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("typing");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        // File two levels deep (tasks/software/file.md pattern)
        let subdir = tmp.path().join("tasks").join("software");
        std::fs::create_dir_all(&subdir).unwrap();
        let doc = subdir.join("test-depth2.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        document_changed(&doc_str);

        assert!(is_typing_via_file(&doc_str, 2000));
    }

    #[test]
    fn status_found_for_file_one_level_deep() {
        let tmp = tempfile::TempDir::new().unwrap();
        let agent_doc_dir = tmp.path().join(".agent-doc").join("status");
        std::fs::create_dir_all(&agent_doc_dir).unwrap();
        let subdir = tmp.path().join("tasks");
        std::fs::create_dir_all(&subdir).unwrap();
        let doc = subdir.join("test-status-depth1.md");
        std::fs::write(&doc, "test").unwrap();
        let doc_str = doc.to_string_lossy().to_string();

        set_status(&doc_str, "generating");

        // get_status uses in-process map (always works), but cross-process file check
        // must find .agent-doc at project root
        assert_eq!(get_status_via_file(&doc_str), "generating");
    }
}