loopflow 0.10.0

Run steps and flows with coding 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
use std::collections::HashSet;
use std::path::Path;
use std::process::Command;

use chrono::{DateTime, Local, NaiveDate, TimeZone, Utc};
use serde::Serialize;

use crate::engine::config::load_config;
use crate::engine::git::{
    current_branch, delete_remote_branch, get_default_branch, is_squash_merged,
};
use crate::engine::naming::wave_name_from_branch;
use crate::ops::error::{OpsError, OpsResult};
use crate::ops::progress::Progress;

#[derive(Debug, Clone)]
pub struct BranchListOptions {
    pub filters: BranchFilterOptions,
    pub default_user_if_empty: bool,
}

#[derive(Debug, Clone)]
pub struct BranchPruneOptions {
    pub filters: BranchFilterOptions,
    pub dry_run: bool,
    pub yes: bool,
}

#[derive(Debug, Clone, Default)]
pub struct BranchFilterOptions {
    pub user: Option<String>,
    pub wave: Option<String>,
    pub stale: Option<String>,
    pub created_before: Option<String>,
    pub merged: bool,
    pub include_open_prs: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BranchCandidate {
    pub branch: String,
    pub author: String,
    pub last_commit_date: String,
    pub age_days: i64,
    pub wave: Option<String>,
    pub merged: bool,
    pub open_pr: bool,
    pub protected: bool,
    pub protect_reason: Option<String>,
}

#[derive(Debug, Clone)]
struct BranchFilters {
    user: Option<String>,
    wave: Option<String>,
    stale_days: Option<i64>,
    created_before: Option<NaiveDate>,
    merged: bool,
    include_open_prs: bool,
}

#[derive(Debug, Clone)]
struct RemoteBranchRef {
    branch: String,
    author: String,
    committer_timestamp: i64,
}

pub fn list_branch_candidates(
    repo: &Path,
    options: &BranchListOptions,
) -> OpsResult<Vec<BranchCandidate>> {
    let filters =
        BranchFilters::from_options(repo, &options.filters, options.default_user_if_empty)?;
    collect_branch_candidates(repo, &filters)
}

pub fn prune_branches(
    repo: &Path,
    options: &BranchPruneOptions,
    progress: &impl Progress,
) -> OpsResult<Vec<BranchCandidate>> {
    if !options.has_filter() {
        return Err(OpsError::Message(
            "refusing to prune remote branches without at least one filter".to_string(),
        ));
    }

    let filters = BranchFilters::from_options(repo, &options.filters, false)?;
    let candidates = collect_branch_candidates(repo, &filters)?;
    let targets = candidates
        .into_iter()
        .filter(|branch| !branch.protected)
        .collect::<Vec<_>>();

    if targets.is_empty() {
        progress.status("No deletable remote branches match.");
        return Ok(Vec::new());
    }

    if options.dry_run {
        return Ok(targets);
    }

    let summary = targets
        .iter()
        .map(|candidate| format!("  {}", candidate.branch))
        .collect::<Vec<_>>()
        .join("\n");
    if !options.yes && !progress.confirm(&format!("Delete these remote branches?\n{summary}")) {
        return Err(OpsError::Message("aborted".to_string()));
    }

    for candidate in &targets {
        progress.status(&format!("Deleting origin/{}...", candidate.branch));
        delete_remote_branch(repo, "origin", &candidate.branch)?;
    }

    Ok(targets)
}

impl BranchPruneOptions {
    fn has_filter(&self) -> bool {
        self.filters.has_filter()
    }
}

impl BranchFilterOptions {
    fn has_filter(&self) -> bool {
        self.user.is_some()
            || self.wave.is_some()
            || self.stale.is_some()
            || self.created_before.is_some()
            || self.merged
    }
}

impl BranchFilters {
    fn from_options(
        repo: &Path,
        options: &BranchFilterOptions,
        default_user_if_empty: bool,
    ) -> OpsResult<Self> {
        let user = if !options.has_filter() && default_user_if_empty {
            Some(resolve_user(repo, "@me")?)
        } else {
            options
                .user
                .as_deref()
                .map(|user| resolve_user(repo, user))
                .transpose()?
        };
        Self::new(
            user,
            options.wave.clone(),
            options.stale.as_deref(),
            options.created_before.as_deref(),
            options.merged,
            options.include_open_prs,
        )
    }

    fn new(
        user: Option<String>,
        wave: Option<String>,
        stale: Option<&str>,
        created_before: Option<&str>,
        merged: bool,
        include_open_prs: bool,
    ) -> OpsResult<Self> {
        Ok(Self {
            user,
            wave,
            stale_days: stale.map(parse_duration_days).transpose()?,
            created_before: created_before.map(parse_date).transpose()?,
            merged,
            include_open_prs,
        })
    }
}

fn collect_branch_candidates(
    repo: &Path,
    filters: &BranchFilters,
) -> OpsResult<Vec<BranchCandidate>> {
    let default_branch = get_default_branch(repo)?;
    let _ = fetch_origin_prune(repo);
    let refs = remote_branch_refs(repo)?;
    let open_prs = open_pr_branches(repo);
    let current = current_branch(repo)?.unwrap_or_default();
    let branch_config = load_config(Some(repo))
        .ok()
        .flatten()
        .and_then(|config| config.branch_names);

    let mut candidates = Vec::new();
    for item in refs {
        if item.branch == "HEAD"
            || item.branch == default_branch
            || item.branch == "main"
            || item.branch == "master"
        {
            continue;
        }

        let parsed_wave = wave_name_from_branch(&item.branch, branch_config.as_ref());
        if let Some(user) = filters.user.as_deref() {
            if !matches_user(&item.author, user) {
                continue;
            }
        }
        if let Some(wave) = filters.wave.as_deref() {
            if !branch_matches_wave(&item.branch, parsed_wave.as_deref(), wave) {
                continue;
            }
        }
        if let Some(stale_days) = filters.stale_days {
            if age_days(item.committer_timestamp) < stale_days {
                continue;
            }
        }
        if let Some(cutoff) = filters.created_before {
            let created =
                first_unique_commit_date(repo, &item.branch)?.unwrap_or(item.committer_timestamp);
            let created_date = Utc
                .timestamp_opt(created, 0)
                .single()
                .ok_or_else(|| OpsError::Parse(format!("invalid commit timestamp: {created}")))?
                .date_naive();
            if created_date >= cutoff {
                continue;
            }
        }

        let merged = branch_is_merged(repo, &item.branch, &default_branch);
        if filters.merged && !merged {
            continue;
        }

        let open_pr = open_prs.contains(&item.branch);
        let (protected, protect_reason) =
            protected_reason(&item.branch, &current, open_pr, filters.include_open_prs);
        candidates.push(BranchCandidate {
            branch: item.branch,
            author: item.author,
            last_commit_date: format_date(item.committer_timestamp)?,
            age_days: age_days(item.committer_timestamp),
            wave: parsed_wave,
            merged,
            open_pr,
            protected,
            protect_reason,
        });
    }

    candidates.sort_by(|a, b| b.age_days.cmp(&a.age_days).then(a.branch.cmp(&b.branch)));
    Ok(candidates)
}

fn fetch_origin_prune(repo: &Path) -> OpsResult<()> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["fetch", "origin", "--prune"])
        .output()?;
    if output.status.success() {
        Ok(())
    } else {
        Err(OpsError::CommandFailed {
            command: "git fetch origin --prune".to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        })
    }
}

fn remote_branch_refs(repo: &Path) -> OpsResult<Vec<RemoteBranchRef>> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args([
            "for-each-ref",
            "refs/remotes/origin/",
            "--format=%(refname:short)%00%(authorname)%00%(committerdate:unix)",
        ])
        .output()?;
    if !output.status.success() {
        return Err(OpsError::CommandFailed {
            command: "git for-each-ref refs/remotes/origin/".to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        });
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut refs = Vec::new();
    for line in stdout.lines() {
        let mut parts = line.split('\0');
        let Some(ref_name) = parts.next() else {
            continue;
        };
        let Some(author) = parts.next() else { continue };
        let Some(timestamp) = parts.next() else {
            continue;
        };
        let Some(branch) = ref_name.strip_prefix("origin/") else {
            continue;
        };
        let committer_timestamp = timestamp
            .parse::<i64>()
            .map_err(|_| OpsError::Parse(format!("invalid commit timestamp: {timestamp}")))?;
        refs.push(RemoteBranchRef {
            branch: branch.to_string(),
            author: author.to_string(),
            committer_timestamp,
        });
    }
    Ok(refs)
}

fn open_pr_branches(repo: &Path) -> HashSet<String> {
    let output = Command::new("gh")
        .current_dir(repo)
        .args([
            "pr",
            "list",
            "--state",
            "open",
            "--json",
            "headRefName",
            "--limit",
            "1000",
            "--jq",
            ".[] | .headRefName",
        ])
        .output();

    match output {
        Ok(output) if output.status.success() => String::from_utf8_lossy(&output.stdout)
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| line.trim().to_string())
            .collect(),
        _ => HashSet::new(),
    }
}

fn branch_is_merged(repo: &Path, branch: &str, default_branch: &str) -> bool {
    let remote_branch = format!("origin/{branch}");
    let target = format!("origin/{default_branch}");
    let ancestor = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["merge-base", "--is-ancestor", &remote_branch, &target])
        .status()
        .map(|status| status.success())
        .unwrap_or(false);
    ancestor || is_squash_merged(repo, &remote_branch, &target).unwrap_or(false)
}

fn first_unique_commit_date(repo: &Path, branch: &str) -> OpsResult<Option<i64>> {
    let default_branch = get_default_branch(repo)?;
    let range = format!("origin/{default_branch}..origin/{branch}");
    let output = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["log", "--reverse", "--format=%ct", &range])
        .output()?;
    if !output.status.success() {
        return Ok(None);
    }
    let first = String::from_utf8_lossy(&output.stdout)
        .lines()
        .find(|line| !line.trim().is_empty())
        .map(str::to_string);
    first
        .map(|value| {
            value
                .parse::<i64>()
                .map_err(|_| OpsError::Parse(format!("invalid commit timestamp: {value}")))
        })
        .transpose()
}

fn protected_reason(
    branch: &str,
    current: &str,
    open_pr: bool,
    include_open_prs: bool,
) -> (bool, Option<String>) {
    let reason = if branch == "main" || branch == "master" {
        Some("base branch".to_string())
    } else if !current.is_empty() && branch == current {
        Some("current branch".to_string())
    } else if open_pr && !include_open_prs {
        Some("open PR".to_string())
    } else {
        None
    };
    (reason.is_some(), reason)
}

fn parse_duration_days(value: &str) -> OpsResult<i64> {
    let trimmed = value.trim();
    let split = trimmed
        .find(|ch: char| !ch.is_ascii_digit())
        .unwrap_or(trimmed.len());
    let (digits, unit) = trimmed.split_at(split);
    if digits.is_empty() {
        return Err(OpsError::Parse(format!("invalid duration: {value}")));
    }
    let amount = digits
        .parse::<i64>()
        .map_err(|_| OpsError::Parse(format!("invalid duration: {value}")))?;
    let multiplier = match unit.trim() {
        "" | "d" | "day" | "days" => 1,
        "w" | "week" | "weeks" => 7,
        "m" | "mo" | "month" | "months" => 30,
        _ => return Err(OpsError::Parse(format!("invalid duration unit: {value}"))),
    };
    Ok(amount * multiplier)
}

fn parse_date(value: &str) -> OpsResult<NaiveDate> {
    NaiveDate::parse_from_str(value, "%Y-%m-%d")
        .map_err(|_| OpsError::Parse(format!("invalid date: {value}")))
}

fn age_days(timestamp: i64) -> i64 {
    let now = Utc::now().timestamp();
    ((now - timestamp).max(0)) / 86_400
}

fn format_date(timestamp: i64) -> OpsResult<String> {
    let utc = Utc
        .timestamp_opt(timestamp, 0)
        .single()
        .ok_or_else(|| OpsError::Parse(format!("invalid commit timestamp: {timestamp}")))?;
    let local: DateTime<Local> = DateTime::from(utc);
    Ok(local.format("%Y-%m-%d").to_string())
}

fn resolve_user(repo: &Path, user: &str) -> OpsResult<String> {
    if user != "@me" {
        return Ok(user.to_string());
    }

    let output = Command::new("git")
        .arg("-C")
        .arg(repo)
        .args(["config", "user.name"])
        .output()?;
    if output.status.success() {
        let value = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if !value.is_empty() {
            return Ok(value);
        }
    }

    Ok(std::env::var("USER").unwrap_or_else(|_| "user".to_string()))
}

fn matches_user(author: &str, user: &str) -> bool {
    author.eq_ignore_ascii_case(user)
}

fn branch_matches_wave(branch: &str, parsed_wave: Option<&str>, wave: &str) -> bool {
    if parsed_wave.is_some_and(|name| name == wave) {
        return true;
    }
    branch.split(['.', '/', '_', '-']).any(|part| part == wave)
}

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

    #[test]
    fn parse_duration_accepts_days_weeks_months() {
        assert_eq!(parse_duration_days("30d").unwrap(), 30);
        assert_eq!(parse_duration_days("2w").unwrap(), 14);
        assert_eq!(parse_duration_days("1month").unwrap(), 30);
    }

    #[test]
    fn branch_wave_match_uses_schema_or_segments() {
        assert!(branch_matches_wave(
            "jack.redesign.20260401_1200",
            Some("redesign"),
            "redesign"
        ));
        assert!(branch_matches_wave(
            "feature/redesign-cleanup",
            None,
            "redesign"
        ));
        assert!(!branch_matches_wave("feature/predesign", None, "redesign"));
    }
}