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
//! `pitboss init` — scaffold a workspace.
//!
//! Idempotent and never destructive: every artifact is created only when
//! missing; pre-existing files are left byte-for-byte alone with a warning on
//! stderr. The summary printed to stdout reports `created` / `skipped` /
//! `updated` for each path so a re-run shows at a glance what changed.

use std::fs;
use std::io::Write;
use std::path::Path;

use anyhow::{Context, Result};

use crate::state;
use crate::util::write_atomic;

/// One-phase template seed for `plan.md`. Designed to round-trip through
/// [`crate::plan::parse`] so a freshly scaffolded plan parses cleanly without
/// edits.
///
/// `pub(crate)` so `cli::plan` can recognize an unmodified seed and silently
/// overwrite it without `--force` (the canonical `init` → `plan` flow).
pub(crate) const PLAN_TEMPLATE: &str = "\
---
current_phase: \"01\"
---

# Pitboss Plan

Replace this preamble with a description of the work pitboss will orchestrate.

# Phase 01: First phase

**Scope.** Describe what this phase delivers.

**Deliverables.**
- Item

**Acceptance.**
- Criterion
";

/// Empty scaffold for `deferred.md`. Both H2 sections are present so users see
/// the structure agents will write into; both are empty, which the parser
/// accepts.
const DEFERRED_TEMPLATE: &str = "\
## Deferred items

## Deferred phases
";

/// Default `.pitboss/config.toml`. The values here mirror
/// [`crate::config::Config`]'s `Default` impl exactly — a freshly initialized
/// workspace round-trips through `config::load` to `Config::default()`. Edit
/// both together.
const CONFIG_TOML_TEMPLATE: &str = "\
# pitboss configuration

[models]
planner = \"claude-opus-4-7\"
implementer = \"claude-opus-4-7\"
auditor = \"claude-opus-4-7\"
fixer = \"claude-opus-4-7\"

[retries]
fixer_max_attempts = 2
max_phase_attempts = 3

[audit]
enabled = true
small_fix_line_limit = 30

[git]
branch_prefix = \"pitboss/play/\"
create_pr = false

# Caveman mode: opt-in terse-output directive prepended to every agent
# dispatch's system prompt. Cuts output tokens at the cost of slightly
# terser plan/audit/fix prose. Intensity: \"lite\" | \"full\" | \"ultra\".
[caveman]
enabled = false
intensity = \"full\"

# Grind mode: rotating prompt runner.
# - Drop prompt files in .pitboss/grind/prompts/<name>.md (pitboss prompts new
#   <name> scaffolds one).
# - Drop rotation files in .pitboss/grind/rotations/<name>.toml; select with
#   `pitboss grind --rotation <name>` or set `default_rotation` below.
[grind]
# default_rotation = \"nightly\"
max_parallel = 1
consecutive_failure_limit = 3
";

/// Marker line appended to `.gitignore`. Matched verbatim against trimmed
/// existing lines; only `".pitboss"` and `".pitboss/"` are recognized as
/// already-present.
const GITIGNORE_ENTRY: &str = ".pitboss/";

/// What `init` did (or didn't do) to a single path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// File or directory was newly created.
    Created,
    /// Path already existed; left untouched.
    Skipped,
    /// File existed but was modified (currently only `.gitignore`).
    Updated,
}

/// One row of the per-file summary printed by [`run`].
#[derive(Debug, Clone)]
pub struct ReportEntry {
    /// Workspace-relative display path.
    pub path: String,
    /// Action taken.
    pub action: Action,
}

/// Scaffold a pitboss workspace under `workspace`. Idempotent.
///
/// Stdout receives one line per artifact ("created .pitboss/play/plan.md",
/// "skipped .pitboss/play/plan.md (already exists)", etc.). Stderr receives a
/// warning for each pre-existing file we left alone, so users notice when init
/// found a populated workspace.
pub fn run(workspace: impl AsRef<Path>) -> Result<()> {
    let workspace = workspace.as_ref();
    let mut report: Vec<ReportEntry> = Vec::new();

    fs::create_dir_all(workspace)
        .with_context(|| format!("init: creating workspace {:?}", workspace))?;

    // Reject early if `.pitboss` exists as a non-directory. Without this
    // check, write_if_missing would surface a low-level "Not a directory" OS
    // error trying to mkdir-p its parent — clear on close inspection but
    // confusing in a stderr scroll.
    let pitboss_root = workspace.join(".pitboss");
    if pitboss_root.exists() && !pitboss_root.is_dir() {
        anyhow::bail!(
            "init: {:?} exists but is not a directory; refusing to overwrite",
            pitboss_root
        );
    }

    write_if_missing(
        workspace,
        ".pitboss/play/plan.md",
        PLAN_TEMPLATE.as_bytes(),
        &mut report,
    )?;
    write_if_missing(
        workspace,
        ".pitboss/play/deferred.md",
        DEFERRED_TEMPLATE.as_bytes(),
        &mut report,
    )?;
    write_if_missing(
        workspace,
        ".pitboss/config.toml",
        CONFIG_TOML_TEMPLATE.as_bytes(),
        &mut report,
    )?;

    ensure_dir(workspace, ".pitboss/play/snapshots", &mut report)?;
    ensure_dir(workspace, ".pitboss/play/logs", &mut report)?;

    ensure_dir(workspace, ".pitboss/grind/prompts", &mut report)?;
    ensure_dir(workspace, ".pitboss/grind/rotations", &mut report)?;
    ensure_dir(workspace, ".pitboss/grind/runs", &mut report)?;

    init_state_file(workspace, &mut report)?;
    update_gitignore(workspace, &mut report)?;

    print_summary(&report);
    Ok(())
}

fn write_if_missing(
    workspace: &Path,
    rel: &str,
    contents: &[u8],
    report: &mut Vec<ReportEntry>,
) -> Result<()> {
    let path = workspace.join(rel);
    if path.exists() {
        warn_skipped(rel);
        report.push(ReportEntry {
            path: rel.to_string(),
            action: Action::Skipped,
        });
        return Ok(());
    }
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("init: creating parent of {:?}", path))?;
    }
    write_atomic(&path, contents)?;
    report.push(ReportEntry {
        path: rel.to_string(),
        action: Action::Created,
    });
    Ok(())
}

fn ensure_dir(workspace: &Path, rel: &str, report: &mut Vec<ReportEntry>) -> Result<()> {
    let path = workspace.join(rel);
    let display = format!("{}/", rel);
    if path.is_dir() {
        report.push(ReportEntry {
            path: display,
            action: Action::Skipped,
        });
        return Ok(());
    }
    if path.exists() {
        // Path exists but isn't a directory — refuse rather than clobber.
        anyhow::bail!(
            "init: {:?} exists but is not a directory; refusing to overwrite",
            path
        );
    }
    fs::create_dir_all(&path).with_context(|| format!("init: creating {:?}", path))?;
    report.push(ReportEntry {
        path: display,
        action: Action::Created,
    });
    Ok(())
}

fn init_state_file(workspace: &Path, report: &mut Vec<ReportEntry>) -> Result<()> {
    let path = state::state_path(workspace);
    let rel = ".pitboss/play/state.json".to_string();
    if path.exists() {
        warn_skipped(&rel);
        report.push(ReportEntry {
            path: rel,
            action: Action::Skipped,
        });
        return Ok(());
    }
    state::save(workspace, None)?;
    report.push(ReportEntry {
        path: rel,
        action: Action::Created,
    });
    Ok(())
}

fn update_gitignore(workspace: &Path, report: &mut Vec<ReportEntry>) -> Result<()> {
    let path = workspace.join(".gitignore");
    let rel = ".gitignore".to_string();

    let existing = match fs::read_to_string(&path) {
        Ok(s) => Some(s),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(anyhow::Error::new(e).context(format!("init: reading {:?}", path))),
    };

    if let Some(ref text) = existing {
        if has_pitboss_entry(text) {
            report.push(ReportEntry {
                path: rel,
                action: Action::Skipped,
            });
            return Ok(());
        }
    }

    let new_contents = append_entry(existing.as_deref());
    write_atomic(&path, new_contents.as_bytes())?;
    report.push(ReportEntry {
        path: rel,
        action: if existing.is_some() {
            Action::Updated
        } else {
            Action::Created
        },
    });
    Ok(())
}

fn has_pitboss_entry(text: &str) -> bool {
    text.lines().any(|line| {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            return false;
        }
        // Strip an optional leading slash so `/.pitboss/` and `.pitboss/` both
        // count as the same entry. Trailing slash is also optional.
        let canonical = trimmed.trim_start_matches('/').trim_end_matches('/');
        canonical == ".pitboss"
    })
}

fn append_entry(existing: Option<&str>) -> String {
    let mut out = match existing {
        Some(s) => s.to_string(),
        None => String::new(),
    };
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    out.push_str(GITIGNORE_ENTRY);
    out.push('\n');
    out
}

fn warn_skipped(rel: &str) {
    use crate::style::{self, col};
    let c = style::use_color_stderr();
    let stderr = std::io::stderr();
    let mut handle = stderr.lock();
    // Best-effort: warning output is informational and we don't want a write
    // error to fail the whole init.
    let _ = writeln!(
        handle,
        "{} {} already exists, leaving it alone",
        col(c, style::BOLD_YELLOW, "warning:"),
        rel
    );
}

fn print_summary(report: &[ReportEntry]) {
    use crate::style::{self, col};
    let c = style::use_color_stdout();
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    for entry in report {
        let line = match entry.action {
            Action::Created => format!("{} {}", col(c, style::GREEN, "created"), entry.path),
            Action::Skipped => format!(
                "{} {} {}",
                col(c, style::DARK_GRAY, "skipped"),
                entry.path,
                col(c, style::DIM, "(already exists)")
            ),
            Action::Updated => format!("{} {}", col(c, style::YELLOW, "updated"), entry.path),
        };
        let _ = writeln!(handle, "{}", line);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn paths_with(report: &[ReportEntry], action: Action) -> Vec<&str> {
        report
            .iter()
            .filter(|e| e.action == action)
            .map(|e| e.path.as_str())
            .collect()
    }

    #[test]
    fn fresh_workspace_creates_every_artifact() {
        let dir = tempdir().unwrap();
        run(dir.path()).unwrap();

        for rel in [
            ".pitboss",
            ".pitboss/config.toml",
            ".pitboss/play",
            ".pitboss/play/plan.md",
            ".pitboss/play/deferred.md",
            ".pitboss/play/state.json",
            ".pitboss/play/snapshots",
            ".pitboss/play/logs",
            ".pitboss/grind",
            ".pitboss/grind/prompts",
            ".pitboss/grind/rotations",
            ".pitboss/grind/runs",
            ".gitignore",
        ] {
            assert!(
                dir.path().join(rel).exists(),
                "expected {:?} to be created",
                rel
            );
        }

        // plan.md template parses cleanly.
        let plan_text = fs::read_to_string(dir.path().join(".pitboss/play/plan.md")).unwrap();
        let plan = crate::plan::parse(&plan_text).expect("seed plan.md must parse");
        assert_eq!(plan.current_phase.as_str(), "01");

        // deferred.md template parses cleanly.
        let deferred_text =
            fs::read_to_string(dir.path().join(".pitboss/play/deferred.md")).unwrap();
        crate::deferred::parse(&deferred_text).expect("seed deferred.md must parse");

        // state.json is JSON null (no run started).
        assert!(state::load(dir.path()).unwrap().is_none());
    }

    #[test]
    fn rerun_is_idempotent_and_skips_everything() {
        let dir = tempdir().unwrap();
        run(dir.path()).unwrap();

        let snapshot_paths = [
            ".pitboss/config.toml",
            ".pitboss/play/plan.md",
            ".pitboss/play/deferred.md",
            ".pitboss/play/state.json",
            ".gitignore",
        ];
        let before: Vec<Vec<u8>> = snapshot_paths
            .iter()
            .map(|p| fs::read(dir.path().join(p)).unwrap())
            .collect();

        run(dir.path()).unwrap();

        let after: Vec<Vec<u8>> = snapshot_paths
            .iter()
            .map(|p| fs::read(dir.path().join(p)).unwrap())
            .collect();
        assert_eq!(before, after, "rerun must not modify any artifact");
    }

    #[test]
    fn preexisting_plan_md_survives_byte_for_byte() {
        let dir = tempdir().unwrap();
        let custom = "---\ncurrent_phase: \"05\"\n---\n\n# Phase 05: Custom\n\nbody.\n";
        let plan_path = dir.path().join(".pitboss/play/plan.md");
        fs::create_dir_all(plan_path.parent().unwrap()).unwrap();
        fs::write(&plan_path, custom).unwrap();

        run(dir.path()).unwrap();

        let after = fs::read_to_string(&plan_path).unwrap();
        assert_eq!(after, custom);
    }

    #[test]
    fn gitignore_is_created_with_pitboss_entry() {
        let dir = tempdir().unwrap();
        run(dir.path()).unwrap();
        let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(gi.contains(".pitboss/"));
    }

    #[test]
    fn gitignore_is_appended_when_entry_missing() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join(".gitignore"), "/target\n").unwrap();
        run(dir.path()).unwrap();
        let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        assert!(gi.starts_with("/target\n"));
        assert!(gi.contains(".pitboss/"));
    }

    #[test]
    fn gitignore_entry_recognized_in_several_forms() {
        for line in [".pitboss", ".pitboss/", "/.pitboss", "/.pitboss/"] {
            let dir = tempdir().unwrap();
            fs::write(
                dir.path().join(".gitignore"),
                format!("/target\n{}\n", line),
            )
            .unwrap();
            run(dir.path()).unwrap();
            let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
            // No duplicate appended.
            let occurrences = gi
                .lines()
                .filter(|l| {
                    let t = l.trim().trim_start_matches('/').trim_end_matches('/');
                    t == ".pitboss"
                })
                .count();
            assert_eq!(occurrences, 1, "input form {:?}, full file: {:?}", line, gi);
        }
    }

    #[test]
    fn gitignore_idempotent_across_many_runs() {
        let dir = tempdir().unwrap();
        for _ in 0..3 {
            run(dir.path()).unwrap();
        }
        let gi = fs::read_to_string(dir.path().join(".gitignore")).unwrap();
        let occurrences = gi
            .lines()
            .filter(|l| l.trim().trim_start_matches('/').trim_end_matches('/') == ".pitboss")
            .count();
        assert_eq!(occurrences, 1);
    }

    #[test]
    fn rejects_non_directory_at_dot_pitboss() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join(".pitboss"), b"oops").unwrap();
        let err = run(dir.path()).unwrap_err();
        assert!(err.to_string().contains("is not a directory"));
    }

    #[test]
    fn report_describes_skipped_files() {
        // We can't observe `run`'s report directly (it's printed), but we can
        // exercise the lower-level helpers to ensure the Action variants are
        // produced as expected.
        let dir = tempdir().unwrap();
        let plan_path = dir.path().join(".pitboss/play/plan.md");
        fs::create_dir_all(plan_path.parent().unwrap()).unwrap();
        fs::write(&plan_path, "preexisting\n").unwrap();

        let mut report = Vec::new();
        write_if_missing(
            dir.path(),
            ".pitboss/play/plan.md",
            PLAN_TEMPLATE.as_bytes(),
            &mut report,
        )
        .unwrap();
        write_if_missing(
            dir.path(),
            ".pitboss/play/deferred.md",
            DEFERRED_TEMPLATE.as_bytes(),
            &mut report,
        )
        .unwrap();

        assert_eq!(
            paths_with(&report, Action::Skipped),
            vec![".pitboss/play/plan.md"]
        );
        assert_eq!(
            paths_with(&report, Action::Created),
            vec![".pitboss/play/deferred.md"]
        );
    }
}