forge-orchestrator 1.6.4

Orchestration for Claude Code, with Codex CLI as a task runner, on shared repos — single Rust binary, zero deps. Gemini CLI support is in development (build B1, target 2026-10-27).
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
//! `forge doctor` — the IO shell around the pure aggregation in `core::doctor`.
//!
//! Everything that touches the filesystem, git, or the governance checker happens here; the
//! results are injected into `core::doctor::run_doctor`, which stays pure. Resolution failures
//! degrade to a `SKIP` with a stated reason rather than aborting the run — a doctor that cannot
//! report because one probe failed is worse than one that reports what it could establish.

use std::path::Path;
use std::process::Command;

use colored::Colorize;

use crate::brain::rule_based::RuleBasedBrain;
use crate::core::doctor::{DoctorOptions, DoctorReport, run_doctor};
use crate::core::governance::GovernanceChecker;
use crate::core::release_debt::{
    DEFAULT_COMMIT_WARN_THRESHOLD, MarketplaceParse, ReleaseDebtInput, VersionSurface, evaluate,
    parse_cargo_lock_version, parse_cargo_toml_version, parse_json_version, parse_marketplace,
};

/// Run the doctor and return its fail-closed exit code.
pub fn execute(project_root: &Path, strict: bool, json: bool) -> anyhow::Result<i32> {
    let mut skip_reason = None;

    let release_debt = match collect_release_debt(project_root) {
        Ok(Some(input)) => Some(evaluate(&input)),
        Ok(None) => {
            skip_reason = Some("no recognized version manifest in this project".to_string());
            None
        }
        Err(error) => {
            skip_reason = Some(format!("release debt unresolvable: {error}"));
            None
        }
    };

    // Governance only means something for a forge-INITIALIZED project. `.forge/state.json` is the
    // real signal: a bare `.forge/` directory (or none) means this is simply not a forge project,
    // and reporting "Missing state.json — orchestration state is lost" as a critical health defect
    // would be a category error, not a finding. forge-orchestrator's own repo is exactly this case.
    let initialized = project_root.join(".forge").join("state.json").is_file();
    let governance = if initialized {
        // The rule-based brain is free and offline, so `forge doctor` runs in CI without an API key.
        let checker = GovernanceChecker::new(project_root);
        Some(checker.full_check(&RuleBasedBrain))
    } else {
        None
    };

    let report = run_doctor(&DoctorOptions {
        release_debt,
        governance,
        skip_reason,
        // The rule-based brain cannot measure drift; it returns a neutral score. Claiming that as
        // a drift verdict would be a fabricated green, so the aggregation reports SKIP instead.
        drift_evaluable: false,
    });

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_report(&report);
    }

    Ok(report.exit_code(strict))
}

/// Outcome of the `forge ship` release preflight.
///
/// Shares the evaluator with `forge doctor` rather than reimplementing it, so the two commands
/// can never disagree about whether a repo is shippable.
pub enum Preflight {
    /// No release debt. Carries a one-line summary.
    Clean(String),
    /// WARN-level debt — surfaced, not blocking. Ship is often what discharges it.
    Warned(Vec<String>),
    /// FAIL-level debt — internally inconsistent versions. Blocks the ship.
    Blocked(Vec<String>),
    /// Nothing to evaluate, with the reason.
    Skipped(String),
}

/// Evaluate release debt for `forge ship`'s preflight step.
pub fn release_preflight(project_root: &Path) -> Preflight {
    let input = match collect_release_debt(project_root) {
        Ok(Some(input)) => input,
        Ok(None) => return Preflight::Skipped("no recognized version manifest".to_string()),
        Err(error) => return Preflight::Skipped(format!("release debt unresolvable: {error}")),
    };

    let report = evaluate(&input);
    let details: Vec<String> = report
        .findings
        .iter()
        .map(|f| format!("{}: {}", f.kind, f.detail))
        .collect();

    match report.status.as_str() {
        "FAIL" => Preflight::Blocked(details),
        "WARN" => Preflight::Warned(details),
        _ => Preflight::Clean(format!(
            "version {} agrees across {} surface(s); tag {}",
            report.version.as_deref().unwrap_or("unknown"),
            input.surfaces.len(),
            report.latest_tag.as_deref().unwrap_or("none")
        )),
    }
}

fn print_report(report: &DoctorReport) {
    let header = match report.overall.as_str() {
        "FAIL" => "FORGE DOCTOR: FAIL".red().bold(),
        "WARN" => "FORGE DOCTOR: WARN".yellow().bold(),
        _ => "FORGE DOCTOR: OK".green().bold(),
    };
    println!(
        "{header} | ok={} warn={} fail={} skip={}",
        report.ok, report.warn, report.fail, report.skip
    );

    for check in &report.checks {
        let tag = match check.status.as_str() {
            "FAIL" => "[FAIL]".red().bold(),
            "WARN" => "[WARN]".yellow().bold(),
            "SKIP" => "[SKIP]".dimmed(),
            _ => "[ OK ]".green(),
        };
        println!("  {tag} {} — {}", check.name.bold(), check.detail);
    }
}

/// Discover this project's version surfaces and git release state.
///
/// Returns `Ok(None)` when the directory holds no recognized manifest — that is a legitimate
/// "nothing to check", distinct from a probe that failed.
fn collect_release_debt(root: &Path) -> anyhow::Result<Option<ReleaseDebtInput>> {
    let (surfaces, inventory_errors) = collect_version_surfaces(root)?;
    // An inventory error with no surfaces still has to be reported: "I could not read anything"
    // is a failure, not a "nothing to check".
    if surfaces.is_empty() && inventory_errors.is_empty() {
        return Ok(None);
    }

    let latest_tag = git_latest_tag(root);
    let commits_since_tag = git_commit_count(root, latest_tag.as_deref());

    Ok(Some(ReleaseDebtInput {
        surfaces,
        latest_tag,
        commits_since_tag,
        commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
        inventory_errors,
    }))
}

/// Directories never descended into when inventorying version surfaces.
///
/// Dependency and build trees contain thousands of `package.json` files belonging to *other*
/// projects. Including them would compare forge's version against every transitive dependency's.
const EXCLUDED_DIRS: &[&str] = &[
    "node_modules",
    "target",
    "dist",
    "dist-ui",
    "build",
    "out",
    "coverage",
    "vendor",
    ".git",
    ".next",
    ".venv",
    "__pycache__",
    ".turbo",
    ".vite",
];

/// How the version is extracted from a given manifest filename.
///
/// Declarative on purpose: adding a manifest shape is one row here, not a new branch in the
/// walker. Each row is a real layout observed in this program's three repos.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SurfaceKind {
    /// `Cargo.toml` — `[package] version`.
    CargoManifest,
    /// `Cargo.lock` — the `[[package]]` block matching the crate name.
    CargoLock,
    /// Top-level `"version"` (`package.json`, `plugin.json`).
    JsonManifest,
    /// Top-level `"version"` in a lockfile (`package-lock.json`).
    JsonLock,
    /// `marketplace.json` — versions live in `plugins[]`, NOT at the top level.
    Marketplace,
}

fn classify(file_name: &str) -> Option<SurfaceKind> {
    match file_name {
        "Cargo.toml" => Some(SurfaceKind::CargoManifest),
        "Cargo.lock" => Some(SurfaceKind::CargoLock),
        "package.json" | "plugin.json" => Some(SurfaceKind::JsonManifest),
        "package-lock.json" => Some(SurfaceKind::JsonLock),
        "marketplace.json" => Some(SurfaceKind::Marketplace),
        _ => None,
    }
}

/// Inventory every file in the repo that declares a version — **at any depth**.
///
/// A root-only scan was the defect Codex round 4 proved in both directions: it missed
/// forge-plugin's nested `servers/governance-mcp/{package.json,package-lock.json}` (so real
/// version drift reported PASS) and it read `marketplace.json` as a top-level manifest (so a clean
/// checkout reported FAIL). Discovery is therefore repo-aware: walk the tree, skip dependency and
/// build directories, and extract per the manifest's actual shape.
fn collect_version_surfaces(root: &Path) -> anyhow::Result<(Vec<VersionSurface>, Vec<String>)> {
    let mut surfaces = Vec::new();
    // Every failure to *see* a surface is recorded and reported. A gate that silently skips what
    // it cannot read has not verified the repo — it has only verified the part that happened to
    // parse. Same cure as the Gate 5 remediation in the MCP layer.
    let mut problems: Vec<String> = Vec::new();

    let walker = walkdir::WalkDir::new(root)
        .max_depth(6)
        .into_iter()
        .filter_entry(|e| {
            if e.depth() == 0 {
                return true;
            }
            let name = e.file_name().to_string_lossy();
            !(e.file_type().is_dir() && EXCLUDED_DIRS.contains(&name.as_ref()))
        });

    for entry in walker {
        let entry = match entry {
            Ok(entry) => entry,
            Err(error) => {
                // A directory we could not traverse may contain a manifest we needed.
                problems.push(format!("could not traverse: {error}"));
                continue;
            }
        };
        if !entry.file_type().is_file() {
            continue;
        }
        let file_name = entry.file_name().to_string_lossy().to_string();
        let Some(kind) = classify(&file_name) else {
            continue;
        };
        let rel = entry
            .path()
            .strip_prefix(root)
            .unwrap_or(entry.path())
            .display()
            .to_string();
        let text = match std::fs::read_to_string(entry.path()) {
            Ok(text) => text,
            Err(error) => {
                problems.push(format!("{rel}: unreadable ({error})"));
                continue;
            }
        };

        match kind {
            SurfaceKind::CargoManifest => {
                surfaces.push(VersionSurface::manifest(
                    rel.clone(),
                    parse_cargo_toml_version(&text),
                ));
            }
            SurfaceKind::CargoLock => {
                // A lockfile lists every dependency; only the block for THIS crate is the repo's
                // own version, so the sibling manifest supplies the package name.
                let manifest = entry.path().with_file_name("Cargo.toml");
                match std::fs::read_to_string(&manifest)
                    .ok()
                    .and_then(|t| parse_cargo_package_name(&t))
                {
                    Some(name) => surfaces.push(VersionSurface::lockfile(
                        rel.clone(),
                        parse_cargo_lock_version(&text, &name),
                    )),
                    // A lockfile whose sibling manifest names no package cannot be checked. Say so
                    // rather than dropping the surface, which would leave a lockfile unverified.
                    None => problems.push(format!(
                        "{rel}: cannot resolve the crate name from its sibling Cargo.toml, so this lockfile was not verified"
                    )),
                }
            }
            SurfaceKind::JsonManifest => {
                surfaces.push(VersionSurface::manifest(
                    rel.clone(),
                    parse_json_version(&text),
                ));
            }
            SurfaceKind::JsonLock => {
                surfaces.push(VersionSurface::lockfile(
                    rel.clone(),
                    parse_json_version(&text),
                ));
            }
            SurfaceKind::Marketplace => match parse_marketplace(&text) {
                // Each plugin entry is its own surface, labelled so a human knows which entry
                // disagrees rather than just "marketplace.json". Entries with NO usable version
                // are surfaced with `None` — the evaluator then reports `version-unreadable`
                // instead of the entry being silently dropped.
                MarketplaceParse::Entries(entries) => {
                    for (name, version) in entries {
                        surfaces.push(VersionSurface::manifest(
                            format!("{rel}#plugins[{name}]"),
                            version,
                        ));
                    }
                }
                MarketplaceParse::Malformed(reason) => {
                    problems.push(format!("{rel}: malformed marketplace manifest — {reason}"));
                }
            },
        }
    }

    // Deterministic order: the findings text is compared in tests and read by humans.
    surfaces.sort_by(|a, b| a.path.cmp(&b.path));
    problems.sort();
    Ok((surfaces, problems))
}

/// Read `name` from a `Cargo.toml` `[package]` section, so the right lock block is selected.
fn parse_cargo_package_name(text: &str) -> Option<String> {
    let mut in_package = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            in_package = trimmed == "[package]";
            continue;
        }
        if in_package
            && let Some(rest) = trimmed.strip_prefix("name")
            && let Some(rest) = rest.trim_start().strip_prefix('=')
            && let Some(rest) = rest.trim().strip_prefix('"')
            && let Some(end) = rest.find('"')
        {
            return Some(rest[..end].to_string());
        }
    }
    None
}

fn git_latest_tag(root: &Path) -> Option<String> {
    run_git(root, &["describe", "--tags", "--abbrev=0"])
}

fn git_commit_count(root: &Path, tag: Option<&str>) -> u32 {
    let range = match tag {
        Some(tag) => format!("{tag}..HEAD"),
        None => "HEAD".to_string(),
    };
    run_git(root, &["rev-list", &range, "--count"])
        .and_then(|out| out.parse().ok())
        .unwrap_or(0)
}

/// Run a git command, returning trimmed stdout on success.
///
/// Any failure — git absent, not a repo, no tags yet — yields `None`. The caller turns that into
/// a visible `SKIP`/`untagged` finding rather than an error, so `forge doctor` still works in a
/// freshly-created directory.
fn run_git(root: &Path, args: &[&str]) -> Option<String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(root)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if text.is_empty() { None } else { Some(text) }
}

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

    #[test]
    fn reads_cargo_package_name() {
        let text = "[package]\nname = \"forge-orchestrator\"\nversion = \"1.5.2\"\n";
        assert_eq!(
            parse_cargo_package_name(text).as_deref(),
            Some("forge-orchestrator")
        );
    }

    #[test]
    fn package_name_ignores_dependency_names() {
        let text = "[dependencies]\nname = \"wrong\"\n\n[package]\nname = \"right\"\n";
        assert_eq!(parse_cargo_package_name(text).as_deref(), Some("right"));
    }

    #[test]
    fn empty_directory_yields_no_surfaces() {
        let dir = std::env::temp_dir().join(format!("forge-doctor-empty-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let (surfaces, problems) = collect_version_surfaces(&dir).unwrap();
        assert!(surfaces.is_empty());
        assert!(
            problems.is_empty(),
            "an empty dir is not a failure: {problems:?}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn this_repo_reports_agreeing_cargo_surfaces() {
        // Runs against the real repo: Cargo.toml and Cargo.lock must agree, which is exactly
        // the invariant the v1.5.1 incident violated.
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let (surfaces, problems) = collect_version_surfaces(root).unwrap();
        assert!(
            problems.is_empty(),
            "this repo must inventory cleanly: {problems:?}"
        );
        let manifest = surfaces
            .iter()
            .find(|s| s.path == "Cargo.toml")
            .expect("Cargo.toml surface");
        let lock = surfaces
            .iter()
            .find(|s| s.path == "Cargo.lock")
            .expect("Cargo.lock surface");
        assert!(manifest.version.is_some(), "Cargo.toml version must parse");
        assert_eq!(
            manifest.version, lock.version,
            "Cargo.toml and Cargo.lock must agree — this is the v1.5.1 desync guard"
        );
    }
}