pitboss 0.3.0

CLI that orchestrates coding agents (Claude Code and others) through a phased implementation plan, with automatic test/commit loops and a TUI dashboard
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
//! `pitboss status` — print a summary of the current run.
//!
//! Loads `.pitboss/play/state.json`, `.pitboss/play/plan.md`, and
//! `.pitboss/play/deferred.md` and renders a multi-line report covering the
//! run id and branch, the active phase against the plan's phase count,
//! completed phases, deferred work, accumulated token usage, and the last
//! commit on the run branch.
//!
//! `status` is read-only: it never mutates state, never creates branches, and
//! is safe to invoke at any time. A workspace with no started run prints a
//! single line indicating that fact (and the seed plan's current phase) so
//! `pitboss init && pitboss status` is meaningful.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, Result};

use crate::config::{self, Config};
use crate::deferred::{self, DeferredDoc};
use crate::plan::{self, Plan};
use crate::runner::{self, sweep::unchecked_count};
use crate::state::{self, RunState};
use crate::util::paths;

// Maximum number of stale items to render in `pitboss status`. Shared with
// the TUI stale panel via [`crate::runner::STALE_ITEMS_DISPLAY_CAP`] so the
// two operator surfaces stay in lockstep.
use crate::runner::STALE_ITEMS_DISPLAY_CAP as STALE_DISPLAY_CAP;

/// Top-level entry point for the `status` subcommand. Prints to stdout.
pub fn run(workspace: PathBuf) -> Result<()> {
    let plan = load_plan(&workspace)?;
    let deferred = load_deferred(&workspace)?;
    let state = state::load(&workspace)
        .with_context(|| format!("status: loading state in {:?}", workspace))?;
    let config = config::load(&workspace)
        .with_context(|| format!("status: loading config in {:?}", workspace))?;

    let report = render_report(
        &workspace,
        &plan,
        &deferred,
        state.as_ref(),
        &config,
        crate::style::use_color_stdout(),
    );
    print!("{}", report);
    Ok(())
}

/// Build the human-readable status report. Pure function over the loaded
/// state so tests can exercise it without shelling out to git for the
/// last-commit lookup; the workspace is only used to query git, and the
/// internal `last_commit_subject` helper swallows errors so a non-git
/// workspace still produces a useful report. `color` controls ANSI styling
/// so callers (and tests) decide rather than probing terminal state here.
pub fn render_report(
    workspace: &Path,
    plan: &Plan,
    deferred: &DeferredDoc,
    state: Option<&RunState>,
    config: &Config,
    color: bool,
) -> String {
    use crate::style::{self, col};
    let c = color;

    // Label in cyan, muted parenthetical text.
    let lbl = |key: &str| col(c, style::CYAN, key);
    let dim = |v: &str| col(c, style::DIM, v);

    let mut out = String::new();

    let total_phases = plan.phases.len();
    let current_phase_index = plan
        .phases
        .iter()
        .position(|p| p.id == plan.current_phase)
        .map(|i| i + 1);
    let current_phase_title = plan
        .phase(&plan.current_phase)
        .map(|p| p.title.as_str())
        .unwrap_or("(unknown)");

    match state {
        None => {
            out.push_str(&format!(
                "{}: {}\n",
                lbl("run"),
                col(
                    c,
                    style::YELLOW,
                    "not started (no .pitboss/play/state.json)"
                )
            ));
        }
        Some(s) if s.aborted => {
            out.push_str(&format!(
                "{}: {} {}\n",
                lbl("run"),
                col(c, style::BOLD_RED, &s.run_id),
                dim(&format!("(folded, started {})", s.started_at.to_rfc3339()))
            ));
            out.push_str(&format!("{}: {}\n", lbl("branch"), s.branch));
            if let Some(orig) = &s.original_branch {
                out.push_str(&format!("{}: {}\n", lbl("original branch"), orig));
            }
        }
        Some(s) => {
            out.push_str(&format!(
                "{}: {} {}\n",
                lbl("run"),
                col(c, style::BOLD_WHITE, &s.run_id),
                dim(&format!("(started {})", s.started_at.to_rfc3339()))
            ));
            out.push_str(&format!("{}: {}\n", lbl("branch"), s.branch));
            if let Some(orig) = &s.original_branch {
                out.push_str(&format!("{}: {}\n", lbl("original branch"), orig));
            }
        }
    }

    out.push_str(&match current_phase_index {
        Some(i) => format!(
            "{}: phase {} of {}{} {}\n",
            lbl("plan"),
            col(c, style::BOLD_WHITE, &plan.current_phase.to_string()),
            total_phases,
            current_phase_title,
            dim(&format!("({i})")),
        ),
        None => format!(
            "{}: current phase {} not found in plan ({} phases total)\n",
            lbl("plan"),
            plan.current_phase,
            total_phases
        ),
    });

    if let Some(s) = state {
        if s.completed.is_empty() {
            out.push_str(&format!("{}: {}\n", lbl("completed"), dim("(none)")));
        } else {
            let joined: Vec<&str> = s.completed.iter().map(|p| p.as_str()).collect();
            out.push_str(&format!(
                "{}: {}\n",
                lbl("completed"),
                col(c, style::GREEN, &joined.join(", "))
            ));
        }
    }

    let unchecked = deferred.items.iter().filter(|i| !i.done).count();
    let checked = deferred.items.len() - unchecked;
    out.push_str(&format!(
        "{}: {} {}\n",
        lbl("deferred items"),
        deferred.items.len(),
        dim(&format!("({unchecked} unchecked, {checked} checked)"))
    ));
    out.push_str(&format!(
        "{}: {}\n",
        lbl("deferred phases"),
        deferred.phases.len()
    ));

    out.push_str(&render_sweep_block(deferred, state, config, c));

    if let Some(s) = state {
        let usage = &s.token_usage;
        out.push_str(&format!(
            "{}: input={} output={}\n",
            lbl("tokens"),
            usage.input,
            usage.output
        ));
        if !usage.by_role.is_empty() {
            let mut roles: Vec<(&String, &state::RoleUsage)> = usage.by_role.iter().collect();
            roles.sort_by(|a, b| a.0.cmp(b.0));
            for (role, ru) in roles {
                out.push_str(&format!(
                    "  {}: input={} output={}\n",
                    dim(role),
                    ru.input,
                    ru.output
                ));
            }
        }
        out.push_str(&render_budgets(config, usage, c));
    }

    if let Some(s) = state {
        match last_commit_subject(workspace, &s.branch) {
            Some(line) => out.push_str(&format!("{}: {}\n", lbl("last commit"), line)),
            None => out.push_str(&format!("{}: {}\n", lbl("last commit"), dim("(none)"))),
        }
    }

    out
}

/// Render the "Sweep" block of the status report.
///
/// Always prints the pending / consecutive / item count fields so a fresh
/// repo with no sweep activity still shows zeros (matches the spec). Stale
/// items only render when at least one item's sweep-attempt counter has
/// hit `[sweep] escalate_after`; the list is capped at
/// [`STALE_DISPLAY_CAP`] entries with a footer line that points the
/// operator at the recommended remediation paths.
fn render_sweep_block(
    deferred: &DeferredDoc,
    state: Option<&RunState>,
    config: &Config,
    c: bool,
) -> String {
    use crate::style::{self, col};
    let lbl = |key: &str| col(c, style::CYAN, key);
    let dim = |v: &str| col(c, style::DIM, v);

    let pending = state.map(|s| s.pending_sweep).unwrap_or(false);
    let consecutive = state.map(|s| s.consecutive_sweeps).unwrap_or(0);
    let unchecked = unchecked_count(deferred);
    let total_items = deferred.items.len();

    let mut out = String::new();
    out.push_str(&format!("{}:\n", lbl("Sweep")));
    out.push_str(&format!(
        "  {}: {}\n",
        dim("pending"),
        if pending {
            col(c, style::BOLD_YELLOW, "true")
        } else {
            "false".to_string()
        }
    ));
    out.push_str(&format!("  {}: {}\n", dim("consecutive"), consecutive));
    out.push_str(&format!(
        "  {}: {} unchecked / {} total\n",
        dim("deferred items"),
        unchecked,
        total_items,
    ));

    let stale = collect_stale_items(state, config);
    if !stale.is_empty() {
        let total_stale = state
            .map(|s| {
                let escalate = config.sweep.escalate_after.max(1);
                s.deferred_item_attempts
                    .values()
                    .filter(|&&n| n >= escalate)
                    .count()
            })
            .unwrap_or(0);
        out.push_str(&format!(
            "  {}: {} {}\n",
            dim("stale items"),
            col(c, style::BOLD_YELLOW, &total_stale.to_string()),
            dim("(need attention)"),
        ));
        for (text, attempts) in stale.iter().take(STALE_DISPLAY_CAP) {
            out.push_str(&format!(
                "    - \"{}\" {}\n",
                text,
                dim(&format!("(tried {attempts} times)")),
            ));
        }
        if stale.len() > STALE_DISPLAY_CAP {
            out.push_str(&format!(
                "    {}\n",
                dim(&format!("… +{} more", stale.len() - STALE_DISPLAY_CAP)),
            ));
        }
        out.push_str(&format!(
            "    {}\n",
            dim(
                "Promote a stale item to a `## Deferred phase` H3 block, rewrite the text, or check it off if obsolete."
            )
        ));
    }

    out
}

/// Collect stale `## Deferred items` for the status block. Returns
/// `(text, attempts)` pairs sorted by descending attempts (text ascending
/// as a deterministic tiebreaker).
fn collect_stale_items(state: Option<&RunState>, config: &Config) -> Vec<(String, u32)> {
    let Some(state) = state else {
        return Vec::new();
    };
    let escalate = config.sweep.escalate_after.max(1);
    let mut items: Vec<(String, u32)> = state
        .deferred_item_attempts
        .iter()
        .filter(|(_, &n)| n >= escalate)
        .map(|(text, &n)| (text.clone(), n))
        .collect();
    items.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    items
}

/// Render the budget block of the status report.
///
/// Always prints the running USD cost (computed from
/// [`crate::runner::budget_totals`]) so users can see spend at a glance even
/// without budgets configured. When either budget cap is set, an extra line
/// per cap reports usage against that cap.
fn render_budgets(config: &Config, usage: &crate::state::TokenUsage, c: bool) -> String {
    use crate::style::{self, col};
    let lbl = |key: &str| col(c, style::CYAN, key);
    let dim = |v: &str| col(c, style::DIM, v);

    let (total_tokens, total_usd) = runner::budget_totals(config, usage);
    let mut out = format!(
        "{}: {} {}\n",
        lbl("cost"),
        col(c, style::BOLD_YELLOW, &format!("${:.4}", total_usd)),
        dim(&format!("({total_tokens} tokens)"))
    );
    if let Some(cap) = config.budgets.max_total_tokens {
        let remaining = cap.saturating_sub(total_tokens);
        out.push_str(&format!(
            "  {}: {}/{} used, {} remaining\n",
            dim("token budget"),
            total_tokens,
            cap,
            remaining
        ));
    }
    if let Some(cap) = config.budgets.max_total_usd {
        let remaining = (cap - total_usd).max(0.0);
        out.push_str(&format!(
            "  {}: ${:.4}/${:.4} used, ${:.4} remaining\n",
            dim("USD budget"),
            total_usd,
            cap,
            remaining
        ));
    }
    out
}

fn load_plan(workspace: &Path) -> Result<Plan> {
    let path = paths::plan_path(workspace);
    let text = fs::read_to_string(&path).with_context(|| format!("status: reading {:?}", path))?;
    plan::parse(&text).with_context(|| format!("status: parsing {:?}", path))
}

fn load_deferred(workspace: &Path) -> Result<DeferredDoc> {
    let path = paths::deferred_path(workspace);
    match fs::read_to_string(&path) {
        Ok(text) => {
            if text.trim().is_empty() {
                Ok(DeferredDoc::empty())
            } else {
                deferred::parse(&text).with_context(|| format!("status: parsing {:?}", path))
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(DeferredDoc::empty()),
        Err(e) => Err(anyhow::Error::new(e).context(format!("status: reading {:?}", path))),
    }
}

/// Best-effort lookup of `<short hash> <subject>` for the tip of `branch`.
/// Returns `None` if the workspace isn't a git repo, the branch doesn't
/// exist, or git is otherwise unhappy. Status is informational so we
/// degrade silently rather than failing the whole command.
fn last_commit_subject(workspace: &Path, branch: &str) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(workspace)
        .args(["log", "-1", "--pretty=format:%h %s", branch])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let line = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if line.is_empty() {
        None
    } else {
        Some(line)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::deferred::{DeferredItem, DeferredPhase};
    use crate::plan::{Phase, PhaseId};
    use crate::state::{RoleUsage, TokenUsage};
    use chrono::{DateTime, Utc};
    use std::collections::HashMap;
    use tempfile::tempdir;

    fn pid(s: &str) -> PhaseId {
        PhaseId::parse(s).unwrap()
    }

    fn three_phase_plan() -> Plan {
        Plan::new(
            pid("02"),
            vec![
                Phase {
                    id: pid("01"),
                    title: "First".into(),
                    body: String::new(),
                },
                Phase {
                    id: pid("02"),
                    title: "Second".into(),
                    body: String::new(),
                },
                Phase {
                    id: pid("03"),
                    title: "Third".into(),
                    body: String::new(),
                },
            ],
        )
    }

    fn sample_state() -> RunState {
        let mut by_role = HashMap::new();
        by_role.insert(
            "implementer".to_string(),
            RoleUsage {
                input: 100,
                output: 50,
            },
        );
        RunState {
            run_id: "20260429T143022Z".into(),
            branch: "pitboss/run-20260429T143022Z".into(),
            original_branch: Some("main".into()),
            started_at: DateTime::parse_from_rfc3339("2026-04-29T14:30:22Z")
                .unwrap()
                .with_timezone(&Utc),
            started_phase: pid("01"),
            completed: vec![pid("01")],
            attempts: HashMap::new(),
            token_usage: TokenUsage {
                input: 100,
                output: 50,
                by_role,
            },
            aborted: false,
            pending_sweep: false,
            consecutive_sweeps: 0,
            deferred_item_attempts: HashMap::new(),
            post_final_phase: false,
        }
    }

    #[test]
    fn report_for_no_run_says_not_started() {
        let dir = tempdir().unwrap();
        let plan = three_phase_plan();
        let deferred = DeferredDoc::empty();
        let config = Config::default();
        let report = render_report(dir.path(), &plan, &deferred, None, &config, false);
        assert!(report.contains("run: not started"), "report: {report}");
        // Plan header still rendered so users see what the seed plan looks like.
        assert!(report.contains("plan: phase 02 of 3"), "report: {report}");
        // No tokens / completed / cost lines when no state.
        assert!(!report.contains("tokens"), "report: {report}");
        assert!(!report.contains("completed:"), "report: {report}");
        assert!(!report.contains("cost:"), "report: {report}");
    }

    #[test]
    fn report_for_active_run_includes_branch_completed_and_tokens() {
        let dir = tempdir().unwrap();
        let plan = three_phase_plan();
        let deferred = DeferredDoc {
            items: vec![
                DeferredItem {
                    text: "open".into(),
                    done: false,
                },
                DeferredItem {
                    text: "done".into(),
                    done: true,
                },
            ],
            phases: vec![DeferredPhase {
                source_phase: pid("01"),
                title: "rework".into(),
                body: String::new(),
            }],
        };
        let state = sample_state();
        let config = Config::default();
        let report = render_report(dir.path(), &plan, &deferred, Some(&state), &config, false);

        assert!(report.contains("run: 20260429T143022Z"), "report: {report}");
        assert!(
            report.contains("branch: pitboss/run-20260429T143022Z"),
            "report: {report}"
        );
        assert!(report.contains("original branch: main"), "report: {report}");
        assert!(
            report.contains("plan: phase 02 of 3 — Second"),
            "report: {report}"
        );
        assert!(report.contains("completed: 01"), "report: {report}");
        assert!(
            report.contains("deferred items: 2 (1 unchecked, 1 checked)"),
            "report: {report}"
        );
        assert!(report.contains("deferred phases: 1"), "report: {report}");
        assert!(
            report.contains("tokens: input=100 output=50"),
            "report: {report}"
        );
        assert!(
            report.contains("implementer: input=100 output=50"),
            "report: {report}"
        );
        // 100 input + 50 output at default opus rate ($15/M in, $75/M out)
        // == 100*15/1e6 + 50*75/1e6 = 0.0015 + 0.00375 = 0.00525.
        // Rust's `{:.4}` rounds-half-to-even, so 0.00525 → 0.0052.
        assert!(report.contains("cost: $0.0052"), "report: {report}");
        // No budget caps configured → no per-cap line.
        assert!(!report.contains("token budget"), "report: {report}");
        assert!(!report.contains("USD budget"), "report: {report}");
        // No git in tempdir → last commit is "(none)".
        assert!(report.contains("last commit: (none)"), "report: {report}");
    }

    #[test]
    fn report_marks_folded_run() {
        let dir = tempdir().unwrap();
        let plan = three_phase_plan();
        let deferred = DeferredDoc::empty();
        let mut state = sample_state();
        state.aborted = true;
        let config = Config::default();
        let report = render_report(dir.path(), &plan, &deferred, Some(&state), &config, false);
        assert!(report.contains("folded"), "report: {report}");
    }

    #[test]
    fn report_with_empty_completed_says_none() {
        let dir = tempdir().unwrap();
        let plan = three_phase_plan();
        let deferred = DeferredDoc::empty();
        let mut state = sample_state();
        state.completed.clear();
        let config = Config::default();
        let report = render_report(dir.path(), &plan, &deferred, Some(&state), &config, false);
        assert!(report.contains("completed: (none)"), "report: {report}");
    }

    #[test]
    fn report_includes_budget_remaining_when_configured() {
        let dir = tempdir().unwrap();
        let plan = three_phase_plan();
        let deferred = DeferredDoc::empty();
        let state = sample_state();
        let mut config = Config::default();
        config.budgets.max_total_tokens = Some(10_000);
        config.budgets.max_total_usd = Some(1.00);
        let report = render_report(dir.path(), &plan, &deferred, Some(&state), &config, false);
        // 100 input + 50 output = 150 tokens used; cap 10000; 9850 remaining.
        assert!(
            report.contains("token budget: 150/10000 used, 9850 remaining"),
            "report: {report}"
        );
        // Cost is the same $0.0052 figure as the prior test; cap $1.0000.
        assert!(
            report.contains("USD budget: $0.0052/$1.0000 used, $0.9948 remaining"),
            "report: {report}"
        );
    }
}