apm-cli 0.1.22

CLI project manager for running AI coding agents in parallel, isolated by design.
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
use anyhow::{Context, Result};
pub use apm_core::validate::validate_config;
pub use apm_core::validate::validate_depends_on;
pub use apm_core::validate::validate_warnings;
pub use apm_core::validate::verify_tickets;
use apm_core::{config::Config, git, ticket, ticket_fmt};
use serde::Serialize;
use std::collections::HashSet;
use std::path::Path;
use crate::ctx::CmdContext;

/// Rewrites `.apm/config.toml` (or `apm.toml`) to replace legacy
/// `[workers] command/args/model` fields with the agent-wrapper shape.
///
/// Returns `true` when the file was rewritten, `false` when no legacy fields
/// were detected (no-op) or when migration was blocked by a non-Claude command.
pub fn apply_config_migration_fixes(root: &Path) -> Result<bool> {
    use std::fs;

    // 1. Locate config file
    let config_path = {
        let p = root.join(".apm").join("config.toml");
        if p.exists() {
            p
        } else {
            let p = root.join("apm.toml");
            if p.exists() {
                p
            } else {
                return Ok(false);
            }
        }
    };

    // 2. Parse with toml_edit (preserves comments, whitespace, key order)
    let content = fs::read_to_string(&config_path)
        .with_context(|| format!("reading {}", config_path.display()))?;
    let mut doc = content
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("parsing {}", config_path.display()))?;

    // 3. Detect legacy fields.
    // Use .get() throughout: DocumentMut::index panics for missing top-level keys.
    let has_workers_legacy = doc
        .get("workers")
        .and_then(|v| v.as_table())
        .map_or(false, |t| {
            t.contains_key("command") || t.contains_key("args") || t.contains_key("model")
        });

    let profiles_with_legacy: Vec<String> = doc
        .get("worker_profiles")
        .and_then(|v| v.as_table())
        .map(|wp| {
            wp.iter()
                .filter_map(|(name, item)| {
                    item.as_table()
                        .filter(|t| {
                            t.contains_key("command")
                                || t.contains_key("args")
                                || t.contains_key("model")
                        })
                        .map(|_| name.to_string())
                })
                .collect()
        })
        .unwrap_or_default();

    if !has_workers_legacy && profiles_with_legacy.is_empty() {
        return Ok(false);
    }

    // 4. Guard: non-claude command — block migration and warn if any command
    //    is not "claude" (we can't safely choose a wrapper for unknown tools).
    if let Some(cmd) = doc
        .get("workers")
        .and_then(|v| v.as_table())
        .and_then(|t| t.get("command"))
        .and_then(|v| v.as_str())
    {
        if cmd != "claude" {
            #[allow(clippy::print_stderr)]
            {
                eprintln!(
                    "warning: [workers] command = {:?} is not \"claude\" \u{2014} cannot auto-migrate; choose a wrapper manually",
                    cmd
                );
            }
            return Ok(false);
        }
    }

    for name in &profiles_with_legacy {
        if let Some(cmd) = doc
            .get("worker_profiles")
            .and_then(|v| v.as_table())
            .and_then(|wp| wp.get(name.as_str()))
            .and_then(|p| p.as_table())
            .and_then(|t| t.get("command"))
            .and_then(|v| v.as_str())
        {
            if cmd != "claude" {
                #[allow(clippy::print_stderr)]
                {
                    eprintln!(
                        "warning: [worker_profiles.{}] command = {:?} is not \"claude\" \u{2014} cannot auto-migrate; choose a wrapper manually",
                        name, cmd
                    );
                }
                return Ok(false);
            }
        }
    }

    // 5. Migrate [workers]
    if has_workers_legacy {
        let has_command;
        let model_val: Option<String>;
        let has_args;
        {
            let workers = doc
                .get("workers")
                .and_then(|v| v.as_table())
                .expect("workers is a table (checked in step 3)");
            has_command = workers.contains_key("command");
            model_val = workers.get("model").and_then(|v| v.as_str()).map(|s| s.to_string());
            has_args = workers.contains_key("args");
        }

        let workers = doc
            .get_mut("workers")
            .and_then(|v| v.as_table_mut())
            .expect("workers is a table");

        if has_command {
            workers.remove("command");
            workers.insert("agent", toml_edit::value("claude"));
        }
        if has_args {
            workers.remove("args");
        }
        if let Some(ref model) = model_val {
            workers.remove("model");
            if !workers.contains_key("options") {
                workers.insert("options", toml_edit::Item::Table(toml_edit::Table::new()));
            }
            // workers is &mut Table; Table::IndexMut creates keys when missing.
            // options was just inserted as Item::Table, so ["options"] returns &mut Item::Table.
            // ["model"] on Item::Table creates the "model" entry via Item::IndexMut.
            workers["options"]["model"] = toml_edit::value(model.as_str());
        }
    }

    // 6. Migrate each [worker_profiles.<name>]
    for name in &profiles_with_legacy {
        let name = name.as_str();

        let has_command;
        let model_val: Option<String>;
        let has_args;
        {
            let profile = doc
                .get("worker_profiles")
                .and_then(|v| v.as_table())
                .and_then(|wp| wp.get(name))
                .and_then(|v| v.as_table())
                .expect("profile is a table (checked in step 3)");
            has_command = profile.contains_key("command");
            model_val = profile.get("model").and_then(|v| v.as_str()).map(|s| s.to_string());
            has_args = profile.contains_key("args");
        }

        let profile = doc
            .get_mut("worker_profiles")
            .and_then(|v| v.as_table_mut())
            .and_then(|wp| wp.get_mut(name))
            .and_then(|v| v.as_table_mut())
            .expect("profile is a table");

        if has_command {
            // Remove command; do NOT add agent at profile level (inherits from [workers])
            profile.remove("command");
        }
        if has_args {
            profile.remove("args");
        }
        if let Some(ref model) = model_val {
            profile.remove("model");
            if !profile.contains_key("options") {
                profile.insert("options", toml_edit::Item::Table(toml_edit::Table::new()));
            }
            profile["options"]["model"] = toml_edit::value(model.as_str());
        }
    }

    // 7. Write back (toml_edit preserves comments, whitespace, and unrelated sections)
    fs::write(&config_path, doc.to_string())
        .with_context(|| format!("writing {}", config_path.display()))?;

    // 8. Re-validate: confirm the migration did not produce an invalid config.
    let migrated_config = apm_core::config::Config::load(root)
        .context("migration produced an unparseable config (this is a bug)")?;
    let errors = apm_core::validate::validate_config(&migrated_config, root);
    if !errors.is_empty() {
        anyhow::bail!(
            "migration produced an invalid config:\n{}",
            errors.join("\n")
        );
    }

    Ok(true)
}

#[derive(Debug, Serialize)]
struct Issue {
    kind: String,
    subject: String,
    message: String,
}

pub fn run(root: &Path, fix: bool, json: bool, config_only: bool, no_aggressive: bool, verbose: bool) -> Result<()> {
    // Config migration runs first so the freshly-written config is loaded below.
    if fix && apply_config_migration_fixes(root)? {
        println!("migrated [workers] config to agent-driven shape; legacy command/args/model removed");
    }

    let config_errors;
    let config_warnings;
    let mut ticket_issues: Vec<Issue> = Vec::new();
    let mut tickets_checked = 0usize;
    let config: Config;

    if config_only {
        config = CmdContext::load_config_only(root)?;
        let pair = apm_core::validate::validate_all(&config, root);
        config_errors = pair.0;
        config_warnings = pair.1;
    } else {
        let ctx = CmdContext::load(root, no_aggressive)?;
        config = ctx.config;
        let pair = apm_core::validate::validate_all(&config, root);
        config_errors = pair.0;
        config_warnings = pair.1;
        tickets_checked = ctx.tickets.len();

        let tickets = ctx.tickets;

        let merged = apm_core::git::merged_into_main(root, &config.project.default_branch).unwrap_or_default();
        let merged_set: HashSet<String> = merged.into_iter().collect();

        let state_ids: HashSet<&str> = config.workflow.states.iter()
            .map(|s| s.id.as_str())
            .collect();

        let mut branch_fixes: Vec<(ticket::Ticket, String, String)> = Vec::new();

        for t in &tickets {
            let fm = &t.frontmatter;
            let ticket_subject = format!("#{}", fm.id);

            if !state_ids.is_empty() && fm.state != "closed" && !state_ids.contains(fm.state.as_str()) {
                ticket_issues.push(Issue {
                    kind: "ticket".into(),
                    subject: ticket_subject.clone(),
                    message: format!(
                        "ticket #{} has unknown state '{}'",
                        fm.id, fm.state
                    ),
                });
            }

            if let Some(branch) = &fm.branch {
                let canonical = ticket_fmt::branch_name_from_path(&t.path);
                if let Some(expected) = canonical {
                    if branch != &expected {
                        ticket_issues.push(Issue {
                            kind: "ticket".into(),
                            subject: ticket_subject.clone(),
                            message: format!(
                                "ticket #{} branch field '{}' does not match expected '{}'",
                                fm.id, branch, expected
                            ),
                        });
                        if fix {
                            branch_fixes.push((t.clone(), expected, branch.clone()));
                        }
                    }
                }
            }
        }

        for (subject, message) in validate_depends_on(&config, &tickets) {
            ticket_issues.push(Issue {
                kind: "depends_on".into(),
                subject,
                message,
            });
        }

        for issue in verify_tickets(root, &config, &tickets, &merged_set) {
            ticket_issues.push(Issue {
                kind: "integrity".into(),
                subject: String::new(),
                message: issue,
            });
        }

        if fix {
            apply_branch_fixes(root, &config, branch_fixes)?;
            let merged_refs: HashSet<&str> = merged_set.iter().map(|s| s.as_str()).collect();
            apply_merged_fixes(root, &config, &tickets, &merged_refs)?;
        }
    }

    if fix {
        apply_on_failure_fixes(root, &config)?;
        let pattern = apm_core::init::worktree_gitignore_pattern(&config.worktrees.dir);
        if let Some(p) = pattern {
            let mut msgs = Vec::new();
            apm_core::init::ensure_gitignore(&root.join(".gitignore"), Some(&p), &mut msgs)?;
            for m in &msgs {
                println!("  fixed: {m}");
            }
        }
    }

    let has_errors = !config_errors.is_empty() || !ticket_issues.is_empty();

    let audit = if verbose {
        Some(apm_core::validate::audit_agent_resolution(&config, root))
    } else {
        None
    };

    if json {
        let mut out = serde_json::json!({
            "tickets_checked": tickets_checked,
            "config_errors": config_errors,
            "warnings": config_warnings,
            "errors": ticket_issues,
        });
        if let Some(ref ar) = audit {
            out["agent_resolution"] = serde_json::to_value(ar)?;
        }
        println!("{}", serde_json::to_string_pretty(&out)?);
    } else {
        for e in &config_errors {
            eprintln!("{e}");
        }
        for w in &config_warnings {
            eprintln!("warning: {w}");
        }
        for e in &ticket_issues {
            println!("error [{}] {}: {}", e.kind, e.subject, e.message);
        }
        println!(
            "{} tickets checked, {} config errors, {} warnings, {} ticket errors",
            tickets_checked,
            config_errors.len(),
            config_warnings.len(),
            ticket_issues.len(),
        );
        if let Some(ref ar) = audit {
            print_agent_resolution_audit(ar);
        }
    }

    if config_errors.is_empty() && ticket_issues.is_empty() {
        if let Ok(hash) = apm_core::hash_stamp::config_hash(root) {
            let _ = apm_core::hash_stamp::write_stamp(root, &hash);
        }
    }

    if has_errors {
        anyhow::bail!(
            "{} config errors, {} ticket errors",
            config_errors.len(),
            ticket_issues.len()
        );
    }

    Ok(())
}

fn truncate_role_prefix(s: &str) -> String {
    if s.chars().count() > 60 {
        let truncated: String = s.chars().take(57).collect();
        format!("{truncated}...")
    } else {
        s.to_string()
    }
}

fn print_agent_resolution_audit(audit: &[apm_core::validate::TransitionAudit]) {
    let n = audit.len();
    println!("\nAgent resolution audit -- {n} spawn transition{}:", if n == 1 { "" } else { "s" });

    for ta in audit {
        let profile_str = match &ta.profile {
            Some(p) => format!("  [profile: {p}]"),
            None => String::new(),
        };
        println!("\n  {} -> {}{}", ta.from_state, ta.to_state, profile_str);

        let role_prefix_display = truncate_role_prefix(&ta.role_prefix.value);

        // Compute max value width across the 3 sourced fields for alignment.
        let max_val = [
            ta.agent.value.len(),
            ta.instructions.value.len(),
            role_prefix_display.len(),
        ]
        .into_iter()
        .max()
        .unwrap_or(0);

        // Label column is 14 chars wide (matches "instructions: ").
        println!(
            "    {:<14}{:<max_val$}  ({})",
            "agent:",
            ta.agent.value,
            ta.agent.source,
        );
        println!(
            "    {:<14}{:<max_val$}  ({})",
            "instructions:",
            ta.instructions.value,
            ta.instructions.source,
        );
        println!(
            "    {:<14}{:<max_val$}  ({})",
            "role prefix:",
            role_prefix_display,
            ta.role_prefix.source,
        );
        println!("    {:<14}{}", "wrapper:", ta.wrapper);
    }
}

fn apply_branch_fixes(
    root: &Path,
    config: &Config,
    fixes: Vec<(ticket::Ticket, String, String)>,
) -> Result<()> {
    for (mut t, expected_branch, _old_branch) in fixes {
        let id = t.frontmatter.id.clone();
        t.frontmatter.branch = Some(expected_branch.clone());
        let content = t.serialize()?;
        let filename = t.path.file_name().unwrap().to_string_lossy().to_string();
        let rel_path = format!("{}/{filename}", config.tickets.dir.to_string_lossy());
        match git::commit_to_branch(
            root,
            &expected_branch,
            &rel_path,
            &content,
            &format!("ticket({id}): fix branch field (validate --fix)"),
        ) {
            Ok(_) => println!("  fixed {id}: branch -> {expected_branch}"),
            Err(e) => eprintln!("  warning: could not fix {id}: {e:#}"),
        }
    }
    Ok(())
}

/// Returns `true` when `workflow.toml` was modified.
/// Repairs in a single write pass:
/// (a) inserts a missing `on_failure` field after each `completion` line
///     for Merge/PrOrEpicMerge transitions, porting the value from the
///     default template's matching transition.
/// (b) appends any state block referenced by `on_failure` that is absent
///     from the project's workflow.
fn apply_on_failure_fixes(root: &Path, config: &Config) -> Result<bool> {
    let workflow_path = root.join(".apm").join("workflow.toml");
    if !workflow_path.exists() {
        return Ok(false);
    }

    let default_on_failure = apm_core::init::default_on_failure_map();
    let default_toml = apm_core::init::default_workflow_toml();

    let declared_states: std::collections::HashSet<&str> = config.workflow.states.iter()
        .map(|s| s.id.as_str())
        .collect();

    // Collect (from_state, to) pairs where on_failure is absent and we know the default value.
    let mut needs_field_patch: Vec<(String, String)> = Vec::new();
    // Collect state names that are referenced by on_failure but not declared.
    let mut needs_state_append: std::collections::HashSet<String> = std::collections::HashSet::new();

    for state in &config.workflow.states {
        for tr in &state.transitions {
            if matches!(
                tr.completion,
                apm_core::config::CompletionStrategy::Merge
                    | apm_core::config::CompletionStrategy::PrOrEpicMerge
            ) {
                if tr.on_failure.is_none() {
                    if default_on_failure.contains_key(&tr.to) {
                        needs_field_patch.push((state.id.clone(), tr.to.clone()));
                        let of_name = &default_on_failure[&tr.to];
                        if !declared_states.contains(of_name.as_str()) {
                            needs_state_append.insert(of_name.clone());
                        }
                    }
                } else if let Some(ref name) = tr.on_failure {
                    if !declared_states.contains(name.as_str()) {
                        needs_state_append.insert(name.clone());
                    }
                }
            }
        }
    }

    if needs_field_patch.is_empty() && needs_state_append.is_empty() {
        return Ok(false);
    }

    let raw = std::fs::read_to_string(&workflow_path)
        .context("reading .apm/workflow.toml")?;
    let mut result = raw.clone();

    // 5a: Insert missing on_failure fields.
    if !needs_field_patch.is_empty() {
        result = patch_on_failure_fields(&result, &needs_field_patch, &default_on_failure);
    }

    // 5b: Append missing state blocks.
    for name in &needs_state_append {
        if let Some(block) = extract_state_block_from_default(default_toml, name) {
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push('\n');
            result.push_str(&block);
            result.push('\n');
            println!("  fixed: appended state '{name}' from default template");
        } else {
            eprintln!("  warning: state '{name}' not found in default template — add it manually");
        }
    }

    if result == raw {
        return Ok(false);
    }

    std::fs::write(&workflow_path, &result).context("writing .apm/workflow.toml")?;
    Ok(true)
}

/// Insert `on_failure = "..."` after each `completion = "..."` line for the
/// transitions listed in `needs_patch`.
fn patch_on_failure_fields(
    raw: &str,
    needs_patch: &[(String, String)],
    default_on_failure: &std::collections::HashMap<String, String>,
) -> String {
    enum Scope { TopLevel, InState, InTransition }

    let mut scope = Scope::TopLevel;
    let mut current_state_id: Option<String> = None;
    let mut current_to: Option<String> = None;
    let mut out: Vec<String> = Vec::new();

    for line in raw.lines() {
        let trimmed = line.trim();
        if trimmed == "[[workflow.states]]" {
            scope = Scope::InState;
            current_state_id = None;
            current_to = None;
            out.push(line.to_string());
            continue;
        }
        if trimmed == "[[workflow.states.transitions]]" {
            scope = Scope::InTransition;
            current_to = None;
            out.push(line.to_string());
            continue;
        }
        match scope {
            Scope::InState => {
                if let Some(v) = toml_str_val(trimmed, "id") {
                    current_state_id = Some(v);
                }
            }
            Scope::InTransition => {
                if let Some(v) = toml_str_val(trimmed, "to") {
                    current_to = Some(v);
                }
                if let Some(comp) = toml_str_val(trimmed, "completion") {
                    if comp == "merge" || comp == "pr_or_epic_merge" {
                        if let (Some(ref from), Some(ref to)) =
                            (&current_state_id, &current_to)
                        {
                            let want = needs_patch.iter().any(|(f, t)| f == from && t == to);
                            if want {
                                if let Some(of_val) = default_on_failure.get(to) {
                                    let indent: String = line
                                        .chars()
                                        .take_while(|c| c.is_whitespace())
                                        .collect();
                                    out.push(line.to_string());
                                    out.push(format!("{indent}on_failure = \"{of_val}\""));
                                    println!(
                                        "  fixed: added on_failure = \"{of_val}\" to \
                                         transition '{from}' → '{to}'"
                                    );
                                    continue;
                                }
                            }
                        }
                    }
                }
            }
            Scope::TopLevel => {}
        }
        out.push(line.to_string());
    }

    let mut s = out.join("\n");
    if raw.ends_with('\n') && !s.ends_with('\n') {
        s.push('\n');
    }
    s
}

/// Scan the default workflow template and return the full TOML block for the
/// state with `id = state_id`, including its transition sub-tables.
/// Returns `None` when the state is not found in the template.
fn extract_state_block_from_default(default_toml: &str, state_id: &str) -> Option<String> {
    let mut in_block = false;
    let mut block: Vec<&str> = Vec::new();

    for line in default_toml.lines() {
        let trimmed = line.trim();
        if trimmed == "[[workflow.states]]" {
            if in_block {
                break; // reached the next state, done
            }
            // Start collecting a candidate block.
            block.clear();
            block.push(line);
            // in_block stays false until we confirm the id.
        } else if !block.is_empty() || in_block {
            block.push(line);
            if !in_block {
                if let Some(v) = toml_str_val(trimmed, "id") {
                    if v == state_id {
                        in_block = true;
                    } else {
                        block.clear(); // wrong state
                    }
                }
            }
        }
    }

    if !in_block || block.is_empty() {
        return None;
    }

    // Strip trailing blank lines.
    while block.last().map(|l| l.trim().is_empty()).unwrap_or(false) {
        block.pop();
    }

    Some(block.join("\n"))
}

/// Parse `key = "value"` (with optional whitespace) from a trimmed TOML line.
fn toml_str_val(line: &str, key: &str) -> Option<String> {
    if !line.starts_with(key) {
        return None;
    }
    let rest = line[key.len()..].trim_start();
    if !rest.starts_with('=') {
        return None;
    }
    let after_eq = rest[1..].trim_start();
    if !after_eq.starts_with('"') {
        return None;
    }
    let inner = &after_eq[1..];
    let end = inner.find('"')?;
    Some(inner[..end].to_string())
}

fn apply_merged_fixes(
    root: &Path,
    config: &Config,
    tickets: &[ticket::Ticket],
    merged_set: &HashSet<&str>,
) -> Result<()> {
    for t in tickets {
        let fm = &t.frontmatter;
        let Some(branch) = &fm.branch else { continue };
        if (fm.state == "in_progress" || fm.state == "implemented")
            && merged_set.contains(branch.as_str())
        {
            let id = fm.id.clone();
            let old_state = fm.state.clone();
            match apm_core::ticket::close(root, config, &id, None, "validate --fix", false) {
                Ok(msgs) => {
                    for msg in &msgs {
                        println!("{msg}");
                    }
                    println!("  fixed {id}: {old_state} → closed");
                }
                Err(e) => eprintln!("  warning: could not fix {id}: {e:#}"),
            }
        }
    }
    Ok(())
}