git-paw 0.7.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
//! Git-status polling watcher.
//!
//! Each `WatchTarget` spawns one async task that runs `git status --porcelain`
//! in the worktree every [`POLL_INTERVAL`]. When the set of reported paths
//! differs from the previous tick, the watcher publishes `agent.status` with
//! the current paths in `modified_files`.
//!
//! The watcher inherits git's exclusion rules (`.gitignore`, `.git/` internals)
//! instead of maintaining a hand-rolled filter list.

use std::path::Path;
use std::sync::Arc;
use std::time::Duration;

use super::messages::{BrokerMessage, StatusPayload};
use super::{BrokerState, WatchTarget, delivery};

/// Interval between `git status --porcelain` polls.
pub const POLL_INTERVAL: Duration = Duration::from_secs(2);

/// Decides whether the watcher should publish `working` for an observed
/// git-status change, given the agent's current broker status, the time since
/// its last `committed` event (if any), and the configured post-commit
/// re-entry TTL (bug 8).
///
/// - When the agent is **not** in the `committed` state, the watcher publishes
///   `working` exactly as in v0.5.0.
/// - When the agent **is** `committed`:
///   - `ttl == 0` suppresses the publish (committed stays terminal — the
///     v0.5.0 opt-out model).
///   - otherwise the publish fires only when the elapsed time since the
///     committed event is within `ttl`; past the window the agent is
///     considered settled and the watcher suppresses the publish.
#[must_use]
pub fn should_republish_working(
    status: &str,
    since_committed: Option<Duration>,
    ttl: Duration,
) -> bool {
    if status != "committed" {
        return true;
    }
    if ttl.is_zero() {
        return false;
    }
    match since_committed {
        Some(elapsed) => elapsed <= ttl,
        None => false,
    }
}

/// Parses `git status --porcelain` output into a sorted, deduplicated list of paths.
///
/// Each porcelain line looks like `XY PATH` or `XY PATH1 -> PATH2` for renames.
/// For renames, both the source and destination paths are reported.
fn parse_porcelain(stdout: &str) -> Vec<String> {
    let mut paths: Vec<String> = Vec::new();
    for line in stdout.lines() {
        if line.len() < 4 {
            continue;
        }
        // Skip the two-character status prefix and the separating space.
        let rest = &line[3..];
        if let Some((from, to)) = rest.split_once(" -> ") {
            paths.push(from.trim().to_string());
            paths.push(to.trim().to_string());
        } else {
            paths.push(rest.trim().to_string());
        }
    }
    paths.sort();
    paths.dedup();
    paths
}

/// Runs `git status --porcelain` in `worktree` and returns the parsed path list.
///
/// Returns `None` when git is unavailable or the command fails — callers treat
/// that as "no change detected this tick" and retry on the next interval.
async fn run_git_status(worktree: &Path) -> Option<Vec<String>> {
    let output = tokio::process::Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .current_dir(worktree)
        .output()
        .await
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    Some(parse_porcelain(&stdout))
}

/// Watches a single worktree, publishing `agent.status` when git-status output changes.
///
/// The task runs until the broker's shutdown signal fires. Each iteration waits
/// [`POLL_INTERVAL`] and then checks `git status --porcelain`. If the result
/// differs from the previous tick, it publishes a status message.
pub async fn watch_worktree(
    state: Arc<BrokerState>,
    target: WatchTarget,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    let mut previous: Option<Vec<String>> = None;
    let mut ticker = tokio::time::interval(POLL_INTERVAL);
    // Skip the immediate first tick so we wait one interval before the first poll.
    ticker.tick().await;
    loop {
        tokio::select! {
            _ = ticker.tick() => {}
            _ = shutdown.changed() => {
                if *shutdown.borrow() {
                    break;
                }
            }
        }

        let Some(current) = run_git_status(&target.worktree_path).await else {
            // `git status` failed. Distinguish a transient failure (retry next
            // tick) from a vanished worktree: when the worktree no longer
            // exists on disk, deregister it and stop this task. This is the
            // prune path for `git paw remove` — a later re-registration of the
            // same path spawns a fresh watcher.
            if !target.worktree_path.exists() {
                state.forget_watch_target(&target.worktree_path);
                break;
            }
            continue;
        };

        if previous.as_ref() == Some(&current) {
            continue;
        }

        // Skip the very first baseline when the worktree is clean. We only
        // want to announce the agent once it has actual dirty state; otherwise
        // a quiet worktree would publish an empty status on startup with no
        // useful information.
        if previous.is_none() && current.is_empty() {
            previous = Some(current);
            continue;
        }

        // Bug 8: gate the `working` publish against the post-commit re-entry
        // TTL. Read the agent's status, time-since-committed, and the
        // configured TTL under a short read lock (never held across an await).
        let (status, since_committed, ttl) = {
            let inner = state.read();
            let ttl = inner.republish_working_ttl;
            let rec = inner.agents.get(&target.agent_id);
            let status = rec.map(|r| r.status.clone()).unwrap_or_default();
            let since = rec.and_then(|r| r.last_committed_at).map(|t| t.elapsed());
            (status, since, ttl)
        };
        if !should_republish_working(&status, since_committed, ttl) {
            // Agent is settled at `committed`; absorb the change as the new
            // baseline without re-publishing `working`.
            previous = Some(current);
            continue;
        }

        let msg = BrokerMessage::Status {
            agent_id: target.agent_id.clone(),
            payload: StatusPayload {
                status: "working".to_string(),
                modified_files: current.clone(),
                message: None,
                ..Default::default()
            },
        };
        delivery::publish_message(&state, &msg);
        previous = Some(current);
    }
}

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

    // === Bug 8: post-commit re-entry decision (should_republish_working) ===

    #[test]
    fn non_committed_status_always_publishes() {
        // Normal operation: a working agent publishes regardless of TTL.
        assert!(should_republish_working(
            "working",
            None,
            Duration::from_secs(45)
        ));
        assert!(should_republish_working("idle", None, Duration::ZERO));
    }

    #[test]
    fn committed_within_ttl_republishes() {
        assert!(should_republish_working(
            "committed",
            Some(Duration::from_secs(10)),
            Duration::from_secs(45)
        ));
    }

    #[test]
    fn committed_past_ttl_does_not_republish() {
        assert!(!should_republish_working(
            "committed",
            Some(Duration::from_secs(290)),
            Duration::from_secs(45)
        ));
    }

    #[test]
    fn committed_with_zero_ttl_does_not_republish() {
        // Opt-out: TTL=0 keeps committed terminal even within "0 seconds".
        assert!(!should_republish_working(
            "committed",
            Some(Duration::from_secs(0)),
            Duration::ZERO
        ));
    }

    #[test]
    fn committed_without_timestamp_does_not_republish() {
        assert!(!should_republish_working(
            "committed",
            None,
            Duration::from_secs(45)
        ));
    }

    #[test]
    fn parse_porcelain_handles_modified_and_untracked() {
        let input = " M src/main.rs\n?? new_file.txt\nM  src/lib.rs\n";
        let parsed = parse_porcelain(input);
        assert_eq!(
            parsed,
            vec![
                "new_file.txt".to_string(),
                "src/lib.rs".to_string(),
                "src/main.rs".to_string(),
            ]
        );
    }

    #[test]
    fn parse_porcelain_handles_renames() {
        let input = "R  old.rs -> new.rs\n";
        let parsed = parse_porcelain(input);
        assert_eq!(parsed, vec!["new.rs".to_string(), "old.rs".to_string()]);
    }

    #[test]
    fn parse_porcelain_empty_is_empty_vec() {
        assert!(parse_porcelain("").is_empty());
    }

    #[test]
    fn parse_porcelain_dedupes() {
        let input = " M a.rs\n M a.rs\n";
        let parsed = parse_porcelain(input);
        assert_eq!(parsed, vec!["a.rs".to_string()]);
    }

    fn init_test_repo(dir: &std::path::Path) {
        use std::process::Command;
        let run = |args: &[&str]| {
            Command::new("git")
                .args(args)
                .current_dir(dir)
                .output()
                .expect("git command failed");
        };
        run(&["init", "-q", "-b", "main"]);
        run(&["config", "user.email", "test@example.com"]);
        run(&["config", "user.name", "test"]);
        run(&["commit", "--allow-empty", "-m", "root", "-q"]);
    }

    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn run_git_status_detects_new_file() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());
        std::fs::write(tmp.path().join("hello.txt"), "hi").unwrap();
        let result = run_git_status(tmp.path()).await.unwrap();
        assert!(
            result.iter().any(|p| p == "hello.txt"),
            "expected hello.txt in {result:?}"
        );
    }

    /// Spec scenario: multiple writes within the TTL republish `working`
    /// exactly once (the 2s poll coalesces a burst into one tick).
    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_burst_republishes_working_once() {
        use crate::broker::BrokerState;
        use crate::broker::messages::{ArtifactPayload, BrokerMessage};

        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let state = Arc::new(BrokerState::new(None));
        super::delivery::publish_message(
            &state,
            &BrokerMessage::Artifact {
                agent_id: "feat-b".to_string(),
                payload: ArtifactPayload {
                    status: "committed".to_string(),
                    exports: vec![],
                    modified_files: vec![],
                },
            },
        );

        let (tx, rx) = tokio::sync::watch::channel(false);
        let target = WatchTarget {
            agent_id: "feat-b".to_string(),
            cli: "claude".to_string(),
            worktree_path: tmp.path().to_path_buf(),
        };
        let handle = tokio::spawn(watch_worktree(Arc::clone(&state), target, rx));

        // Burst: ten files written well within one poll interval.
        tokio::time::sleep(Duration::from_millis(300)).await;
        for i in 0..10 {
            std::fs::write(tmp.path().join(format!("f{i}.rs")), "x").unwrap();
        }

        tokio::time::sleep(POLL_INTERVAL + Duration::from_millis(800)).await;

        let working_count = {
            let inner = state.read();
            inner
                .message_log
                .iter()
                .filter(|(_, _, m)| {
                    matches!(m, BrokerMessage::Status { agent_id, payload }
                        if agent_id == "feat-b" && payload.status == "working")
                })
                .count()
        };
        assert_eq!(
            working_count, 1,
            "a burst of writes within one poll interval must republish working exactly once"
        );

        let _ = tx.send(true);
        let _ = tokio::time::timeout(Duration::from_secs(3), handle).await;
    }

    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn run_git_status_respects_gitignore() {
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());
        std::fs::write(tmp.path().join(".gitignore"), "target/\n").unwrap();
        std::fs::create_dir(tmp.path().join("target")).unwrap();
        std::fs::write(tmp.path().join("target").join("build.o"), "x").unwrap();
        let result = run_git_status(tmp.path()).await.unwrap();
        assert!(
            !result.iter().any(|p| p.starts_with("target/")),
            "target/ should be filtered by gitignore, got {result:?}"
        );
    }

    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_publishes_on_change() {
        use crate::broker::BrokerState;
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let state = Arc::new(BrokerState::new(None));
        let (tx, rx) = tokio::sync::watch::channel(false);
        let target = WatchTarget {
            agent_id: "feat-x".to_string(),
            cli: "claude".to_string(),
            worktree_path: tmp.path().to_path_buf(),
        };
        let state_clone = Arc::clone(&state);
        let handle = tokio::spawn(watch_worktree(state_clone, target, rx));

        // Give the first tick a chance, then create a file.
        tokio::time::sleep(Duration::from_millis(300)).await;
        std::fs::write(tmp.path().join("change.txt"), "hello").unwrap();

        // Wait long enough for at least two poll intervals.
        tokio::time::sleep(POLL_INTERVAL + Duration::from_millis(800)).await;

        let msg = {
            let inner = state.read();
            let record = inner
                .agents
                .get("feat-x")
                .expect("watcher should register the agent");
            record
                .last_message
                .clone()
                .expect("watcher should publish a message")
        };
        match msg {
            BrokerMessage::Status { agent_id, payload } => {
                assert_eq!(agent_id, "feat-x");
                assert!(payload.modified_files.iter().any(|p| p == "change.txt"));
            }
            other => panic!("expected Status message, got {other:?}"),
        }

        let _ = tx.send(true);
        let _ = tokio::time::timeout(Duration::from_secs(3), handle).await;
    }

    /// Spec scenario (task 5.5): an agent commits, the broker records
    /// `committed`, then the agent keeps editing — the watcher re-publishes
    /// `working`, so the record transitions `committed` -> `working`.
    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_reenters_working_after_commit() {
        use crate::broker::BrokerState;
        use crate::broker::messages::{ArtifactPayload, BrokerMessage};

        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let state = Arc::new(BrokerState::new(None));
        // Record a committed artifact so the agent is in the committed state
        // with a fresh last_committed_at (default TTL is 60s).
        super::delivery::publish_message(
            &state,
            &BrokerMessage::Artifact {
                agent_id: "feat-x".to_string(),
                payload: ArtifactPayload {
                    status: "committed".to_string(),
                    exports: vec![],
                    modified_files: vec![],
                },
            },
        );
        assert_eq!(state.read().agents["feat-x"].status, "committed");

        let (tx, rx) = tokio::sync::watch::channel(false);
        let target = WatchTarget {
            agent_id: "feat-x".to_string(),
            cli: "claude".to_string(),
            worktree_path: tmp.path().to_path_buf(),
        };
        let handle = tokio::spawn(watch_worktree(Arc::clone(&state), target, rx));

        // Agent keeps editing after the commit.
        tokio::time::sleep(Duration::from_millis(300)).await;
        std::fs::write(tmp.path().join("more_work.rs"), "fn extra() {}").unwrap();

        tokio::time::sleep(POLL_INTERVAL + Duration::from_millis(800)).await;

        assert_eq!(
            state.read().agents["feat-x"].status,
            "working",
            "watcher must re-enter working after a post-commit edit within TTL"
        );

        let _ = tx.send(true);
        let _ = tokio::time::timeout(Duration::from_secs(3), handle).await;
    }

    /// With TTL=0 the post-commit edit must NOT re-publish `working` — the
    /// dashboard keeps showing `committed` (v0.5.0 opt-out).
    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_does_not_reenter_when_ttl_zero() {
        use crate::broker::BrokerState;
        use crate::broker::messages::{ArtifactPayload, BrokerMessage};

        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let state = Arc::new(BrokerState::new(None));
        state.set_republish_working_ttl(Duration::ZERO);
        super::delivery::publish_message(
            &state,
            &BrokerMessage::Artifact {
                agent_id: "feat-z".to_string(),
                payload: ArtifactPayload {
                    status: "committed".to_string(),
                    exports: vec![],
                    modified_files: vec![],
                },
            },
        );

        let (tx, rx) = tokio::sync::watch::channel(false);
        let target = WatchTarget {
            agent_id: "feat-z".to_string(),
            cli: "claude".to_string(),
            worktree_path: tmp.path().to_path_buf(),
        };
        let handle = tokio::spawn(watch_worktree(Arc::clone(&state), target, rx));

        tokio::time::sleep(Duration::from_millis(300)).await;
        std::fs::write(tmp.path().join("more_work.rs"), "fn extra() {}").unwrap();
        tokio::time::sleep(POLL_INTERVAL + Duration::from_millis(800)).await;

        assert_eq!(
            state.read().agents["feat-z"].status,
            "committed",
            "with TTL=0 the watcher must not re-enter working after commit"
        );

        let _ = tx.send(true);
        let _ = tokio::time::timeout(Duration::from_secs(3), handle).await;
    }

    /// Spec scenario (task 3.2): when a watched worktree disappears (the
    /// `git paw remove` prune path), the watcher deregisters it from the live
    /// target set and exits, so a later re-add of the same path spawns a fresh
    /// watcher.
    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_prunes_vanished_worktree() {
        use crate::broker::BrokerState;
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());
        let path = tmp.path().to_path_buf();

        let state = Arc::new(BrokerState::new(None));
        let target = WatchTarget {
            agent_id: "feat-gone".to_string(),
            cli: "claude".to_string(),
            worktree_path: path.clone(),
        };
        assert!(state.register_watch_target(&target));

        let (tx, rx) = tokio::sync::watch::channel(false);
        let handle = tokio::spawn(watch_worktree(Arc::clone(&state), target, rx));

        // Let the watcher settle on a baseline, then delete the worktree.
        tokio::time::sleep(Duration::from_millis(300)).await;
        tmp.close().unwrap();

        // Within a couple poll intervals the watcher detects the vanished
        // worktree, prunes it, and exits.
        let joined = tokio::time::timeout(POLL_INTERVAL * 2 + Duration::from_secs(1), handle).await;
        assert!(
            joined.is_ok(),
            "watcher task must exit after its worktree disappears"
        );
        assert!(
            !state.read().watched_paths.contains(&path),
            "the vanished worktree must be pruned from the live target set"
        );

        let _ = tx.send(true);
    }

    #[tokio::test(flavor = "current_thread")]
    #[serial_test::serial]
    async fn watch_worktree_does_not_publish_when_unchanged() {
        use crate::broker::BrokerState;
        let tmp = tempfile::tempdir().unwrap();
        init_test_repo(tmp.path());

        let state = Arc::new(BrokerState::new(None));
        let (tx, rx) = tokio::sync::watch::channel(false);
        let target = WatchTarget {
            agent_id: "feat-y".to_string(),
            cli: "claude".to_string(),
            worktree_path: tmp.path().to_path_buf(),
        };
        let state_clone = Arc::clone(&state);
        let handle = tokio::spawn(watch_worktree(state_clone, target, rx));

        // Let several ticks elapse with no changes.
        tokio::time::sleep(POLL_INTERVAL * 2 + Duration::from_millis(200)).await;

        let has_entry = {
            let inner = state.read();
            inner.agents.contains_key("feat-y")
        };
        assert!(
            !has_entry,
            "no publish expected when git status is unchanged"
        );

        let _ = tx.send(true);
        let _ = tokio::time::timeout(Duration::from_secs(3), handle).await;
    }
}