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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Release-debt evaluation — pure comparison logic, no IO.
//!
//! Ports the *patterns* from `asifctl`'s release evaluator (commits-since-tag, tag↔manifest
//! drift) and closes the two gaps that make a literal port insufficient for this program:
//!
//! 1. **Lockfile agreement.** `asifctl`'s `detect_manifest` selects a single manifest and never
//!    reads a lockfile, so it cannot see the class of defect that actually bit this repo: at
//!    commit `eaf8532`, `Cargo.toml` read `1.5.1` while `Cargo.lock` still read `1.5.0`
//!    (corrected one commit later in `e319616`). A `--locked` build fails on that state.
//! 2. **Multi-surface projects.** A repo's version can live on several files at once —
//!    forge-plugin carries five. Agreement across *all* of them is the contract; checking one
//!    manifest passes a repo that is internally inconsistent.
//!
//! Everything here takes values and returns verdicts. Reading files and shelling out to git
//! happens in `cli::doctor`, which injects the results. That split is what lets the tests below
//! exercise every defect class with string literals — no temp dirs, no git checkouts.

use serde::{Deserialize, Serialize};

/// How many commits may accumulate past the latest tag before it is worth flagging.
///
/// Matches the FPL release-discipline threshold: >5 unreleased commits is a P1 signal.
pub const DEFAULT_COMMIT_WARN_THRESHOLD: u32 = 5;

/// A single file that declares the project's version.
///
/// `path` is informational — it is echoed in findings so a human knows which file to open.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionSurface {
    /// Repo-relative path, e.g. `Cargo.toml` or `.claude-plugin/plugin.json`.
    pub path: String,
    /// The version string read from that file, if one was found.
    pub version: Option<String>,
    /// True when this surface is a lockfile (`Cargo.lock`, `package-lock.json`).
    ///
    /// Lockfile disagreement is reported as its own finding because it has a distinct
    /// consequence — a `--locked` / `npm ci` build fails outright, rather than merely shipping
    /// an inconsistent number.
    pub is_lockfile: bool,
}

impl VersionSurface {
    /// A manifest surface (`Cargo.toml`, `package.json`, `plugin.json`, …).
    pub fn manifest(path: impl Into<String>, version: Option<String>) -> Self {
        Self {
            path: path.into(),
            version,
            is_lockfile: false,
        }
    }

    /// A lockfile surface (`Cargo.lock`, `package-lock.json`).
    pub fn lockfile(path: impl Into<String>, version: Option<String>) -> Self {
        Self {
            path: path.into(),
            version,
            is_lockfile: true,
        }
    }
}

/// Everything the evaluator needs, already resolved by the caller.
#[derive(Debug, Clone, Default)]
pub struct ReleaseDebtInput {
    /// Every file that declares this project's version. The first non-lockfile surface is
    /// treated as authoritative when reporting drift.
    pub surfaces: Vec<VersionSurface>,
    /// Latest release tag, e.g. `v1.5.2`. `None` when the repo has never been tagged.
    pub latest_tag: Option<String>,
    /// Commits between `latest_tag` and HEAD.
    pub commits_since_tag: u32,
    /// Threshold above which `commits_since_tag` becomes a WARN.
    pub commit_warn_threshold: u32,
    /// Problems encountered while *inventorying* surfaces — an unreadable file, a directory that
    /// could not be traversed, a malformed manifest.
    ///
    /// These are failures of the gate itself, not of the repo, and they must be **loud**: a gate
    /// that cannot see a surface has not verified it. Discarding them is how a broken checkout
    /// reports OK.
    pub inventory_errors: Vec<String>,
}

/// One problem found. `status` is `WARN` or `FAIL`; `OK` never produces a finding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DebtFinding {
    pub kind: String,
    pub status: String,
    pub detail: String,
}

/// The evaluator's verdict.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseDebtReport {
    /// `OK`, `WARN`, or `FAIL`.
    pub status: String,
    /// The version agreed on by the manifest surfaces, when they agree.
    pub version: Option<String>,
    pub latest_tag: Option<String>,
    pub commits_since_tag: u32,
    pub findings: Vec<DebtFinding>,
}

fn finding(kind: &str, status: &str, detail: String) -> DebtFinding {
    DebtFinding {
        kind: kind.to_string(),
        status: status.to_string(),
        detail,
    }
}

/// Strip a leading `v` so `v1.5.2` and `1.5.2` compare equal.
fn normalize_tag(tag: &str) -> &str {
    tag.strip_prefix('v').unwrap_or(tag)
}

/// Evaluate release debt. Pure: same input always yields the same report.
///
/// Severity rationale — the two failure classes are not equally bad:
///
/// * **FAIL** for internal inconsistency: manifest surfaces disagreeing with each other, or a
///   lockfile disagreeing with its manifest. These are broken *now* — a `--locked` build fails,
///   or the repo ships two different version numbers.
/// * **WARN** for accumulated debt: unreleased commits, or a tag behind the manifest. The repo
///   is coherent; it just has not shipped. `--strict` is what turns that into a blocking exit.
pub fn evaluate(input: &ReleaseDebtInput) -> ReleaseDebtReport {
    let mut findings = Vec::new();

    // Inventory failures first: if the gate could not read something, say so before reporting on
    // what it *could* read. A partial inventory that looks clean is worse than a loud failure.
    for problem in &input.inventory_errors {
        findings.push(finding("inventory-error", "FAIL", problem.clone()));
    }

    let (manifests, lockfiles): (Vec<_>, Vec<_>) =
        input.surfaces.iter().partition(|s| !s.is_lockfile);

    // A surface that exists but has no readable version is a defect in its own right —
    // silently treating it as "agrees" is how a missing version slips through.
    for surface in &input.surfaces {
        if surface.version.is_none() {
            findings.push(finding(
                "version-unreadable",
                "FAIL",
                format!("{}: no version field found", surface.path),
            ));
        }
    }

    // 1. Manifest agreement across every declaring surface (the multi-surface requirement).
    let mut manifest_versions: Vec<(&str, &str)> = manifests
        .iter()
        .filter_map(|s| s.version.as_deref().map(|v| (s.path.as_str(), v)))
        .collect();
    manifest_versions.sort_by(|a, b| a.0.cmp(b.0));

    let mut distinct: Vec<&str> = manifest_versions.iter().map(|(_, v)| *v).collect();
    distinct.sort_unstable();
    distinct.dedup();

    let agreed_version = match distinct.len() {
        0 => None,
        1 => Some(distinct[0].to_string()),
        _ => {
            let detail = manifest_versions
                .iter()
                .map(|(path, version)| format!("{path}={version}"))
                .collect::<Vec<_>>()
                .join(", ");
            findings.push(finding(
                "multi-surface-drift",
                "FAIL",
                format!("version surfaces disagree: {detail}"),
            ));
            None
        }
    };

    // 2. Lockfile agreement. Compared against the agreed manifest version; when the manifests
    //    themselves disagree we skip this rather than emit a cascade of derived findings —
    //    the manifest drift above is the actionable root cause.
    if let Some(expected) = agreed_version.as_deref() {
        for lock in &lockfiles {
            if let Some(actual) = lock.version.as_deref()
                && actual != expected
            {
                findings.push(finding(
                    "lockfile-desync",
                    "FAIL",
                    format!(
                        "{} declares {} but manifest declares {} — a --locked build fails on this state",
                        lock.path, actual, expected
                    ),
                ));
            }
        }
    }

    // 3. Tag ↔ manifest drift.
    match (&input.latest_tag, agreed_version.as_deref()) {
        (Some(tag), Some(version)) if normalize_tag(tag) != version => {
            findings.push(finding(
                "tag-drift",
                "WARN",
                format!("manifest is {version} but latest tag is {tag} — release not cut"),
            ));
        }
        (None, Some(version)) => {
            findings.push(finding(
                "untagged",
                "WARN",
                format!("manifest is {version} but the repo has no release tag"),
            ));
        }
        _ => {}
    }

    // 4. Unreleased commit accumulation.
    if input.commits_since_tag > input.commit_warn_threshold {
        findings.push(finding(
            "unreleased-commits",
            "WARN",
            format!(
                "{} commits since {} (threshold {})",
                input.commits_since_tag,
                input.latest_tag.as_deref().unwrap_or("the initial commit"),
                input.commit_warn_threshold
            ),
        ));
    }

    let status = if findings.iter().any(|f| f.status == "FAIL") {
        "FAIL"
    } else if findings.iter().any(|f| f.status == "WARN") {
        "WARN"
    } else {
        "OK"
    };

    ReleaseDebtReport {
        status: status.to_string(),
        version: agreed_version,
        latest_tag: input.latest_tag.clone(),
        commits_since_tag: input.commits_since_tag,
        findings,
    }
}

/// Extract `version` from a `[package]` section without a TOML parser.
///
/// The no-new-runtime-deps constraint rules out the `toml` crate, so this is deliberately
/// narrow: it finds the `[package]` table and returns the first `version = "..."` inside it,
/// stopping at the next section header. It is not a general TOML reader and does not try to be.
pub fn parse_cargo_toml_version(text: &str) -> Option<String> {
    let mut in_package = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            // Any new section ends [package]; `[package.metadata]` is a subtable, not the end.
            in_package = trimmed == "[package]" || trimmed.starts_with("[package.");
            if trimmed == "[package]" {
                in_package = true;
                continue;
            }
        }
        if in_package && let Some(value) = parse_toml_string_value(trimmed, "version") {
            return Some(value);
        }
    }
    None
}

/// Extract a package's version from `Cargo.lock`.
///
/// Locates the `[[package]]` block whose `name` matches, then reads *that block's* `version`.
/// Scanning for the first `version` after the name would be wrong: `Cargo.lock` blocks may
/// carry `source`/`checksum`/`dependencies` lines, and a `dependencies` list runs into the next
/// block — so a naive scan silently returns a different package's version.
pub fn parse_cargo_lock_version(text: &str, package_name: &str) -> Option<String> {
    let mut in_target_block = false;
    let mut block_version: Option<String> = None;

    for line in text.lines() {
        let trimmed = line.trim();

        if trimmed == "[[package]]" {
            // Entering a new block: whatever we were tracking is finished.
            if in_target_block {
                return block_version;
            }
            in_target_block = false;
            block_version = None;
            continue;
        }

        if let Some(name) = parse_toml_string_value(trimmed, "name") {
            in_target_block = name == package_name;
            continue;
        }

        if in_target_block && let Some(version) = parse_toml_string_value(trimmed, "version") {
            block_version = Some(version);
        }
    }

    if in_target_block { block_version } else { None }
}

/// Parse `key = "value"` from a single trimmed TOML line.
fn parse_toml_string_value(line: &str, key: &str) -> Option<String> {
    let rest = line.strip_prefix(key)?.trim_start();
    let rest = rest.strip_prefix('=')?.trim();
    let rest = rest.strip_prefix('"')?;
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

/// Extract a top-level `"version"` from JSON (`package.json`, `plugin.json`, `package-lock.json`).
pub fn parse_json_version(text: &str) -> Option<String> {
    let value: serde_json::Value = serde_json::from_str(text).ok()?;
    value
        .get("version")
        .and_then(|v| v.as_str())
        .map(|v| v.to_string())
}

/// Outcome of reading a Claude Code `marketplace.json`.
///
/// The distinction is the whole point: **"no plugins declared" and "this file is broken" are not
/// the same answer**, and collapsing them into an empty list is how a malformed manifest passes a
/// gate. See [`parse_marketplace`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarketplaceParse {
    /// Readable. Every entry is reported, **including entries with no usable version** — those
    /// carry `None` so the evaluator reports them rather than dropping them.
    Entries(Vec<(String, Option<String>)>),
    /// Not usable as a marketplace manifest, with the reason.
    Malformed(String),
}

/// Read the plugin entries from a Claude Code `marketplace.json`.
///
/// A marketplace manifest has **no top-level `version`** — each entry in `plugins[]` carries its
/// own. Reading it with [`parse_json_version`] yields `None`, which the evaluator would report as
/// `version-unreadable`: a false FAIL on a clean checkout (Codex round 4).
///
/// Every discovered entry becomes a surface *with an optional version*. An earlier revision used
/// `filter_map` to skip entries whose version was missing or non-string, which silently dropped
/// them — so a required plugin entry with no version at all passed `--strict` with exit 0
/// (Codex round 5). That is the same silent-swallow class this repo removed from the MCP layer in
/// Gate 5, and the cure is the same: surface the unreadable thing instead of discarding it.
pub fn parse_marketplace(text: &str) -> MarketplaceParse {
    let value: serde_json::Value = match serde_json::from_str(text) {
        Ok(value) => value,
        Err(e) => return MarketplaceParse::Malformed(format!("not valid JSON: {e}")),
    };
    if !value.is_object() {
        return MarketplaceParse::Malformed("document is not a JSON object".to_string());
    }
    let Some(plugins) = value.get("plugins") else {
        return MarketplaceParse::Malformed("no `plugins` array".to_string());
    };
    let Some(plugins) = plugins.as_array() else {
        return MarketplaceParse::Malformed("`plugins` is not an array".to_string());
    };

    let mut entries = Vec::new();
    for (i, entry) in plugins.iter().enumerate() {
        if !entry.is_object() {
            return MarketplaceParse::Malformed(format!("plugins[{i}] is not an object"));
        }
        let name = entry
            .get("name")
            .and_then(|n| n.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("<unnamed #{i}>"));
        // A missing or non-string version yields None — reported, never dropped.
        let version = entry
            .get("version")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        entries.push((name, version));
    }
    MarketplaceParse::Entries(entries)
}

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

    fn input(surfaces: Vec<VersionSurface>) -> ReleaseDebtInput {
        ReleaseDebtInput {
            surfaces,
            latest_tag: Some("v1.5.2".into()),
            commits_since_tag: 0,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        }
    }

    #[test]
    fn clean_repo_is_ok() {
        let report = evaluate(&input(vec![
            VersionSurface::manifest("Cargo.toml", Some("1.5.2".into())),
            VersionSurface::lockfile("Cargo.lock", Some("1.5.2".into())),
        ]));
        assert_eq!(report.status, "OK");
        assert!(report.findings.is_empty());
        assert_eq!(report.version.as_deref(), Some("1.5.2"));
    }

    /// The real incident: at `eaf8532` the bump landed in Cargo.toml but Cargo.lock still
    /// carried the previous version; `e319616` fixed it one commit later. Verified against
    /// this repo's history with `git show <sha>:Cargo.toml` / `:Cargo.lock`.
    #[test]
    fn v1_5_1_cargo_lock_desync_is_detected() {
        let report = evaluate(&ReleaseDebtInput {
            surfaces: vec![
                VersionSurface::manifest("Cargo.toml", Some("1.5.1".into())),
                VersionSurface::lockfile("Cargo.lock", Some("1.5.0".into())),
            ],
            latest_tag: Some("v1.5.0".into()),
            commits_since_tag: 2,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        });

        assert_eq!(report.status, "FAIL");
        let desync = report
            .findings
            .iter()
            .find(|f| f.kind == "lockfile-desync")
            .expect("lockfile desync must be reported");
        assert_eq!(desync.status, "FAIL");
        assert!(desync.detail.contains("1.5.0"), "{}", desync.detail);
        assert!(desync.detail.contains("1.5.1"), "{}", desync.detail);
    }

    #[test]
    fn multi_surface_disagreement_fails() {
        // The forge-plugin shape: five surfaces, one of them stale.
        let report = evaluate(&input(vec![
            VersionSurface::manifest(".claude-plugin/plugin.json", Some("3.10.2".into())),
            VersionSurface::manifest(".claude-plugin/marketplace.json", Some("3.10.2".into())),
            VersionSurface::manifest(
                "plugins/nxtg-forge/.claude-plugin/plugin.json",
                Some("3.10.2".into()),
            ),
            VersionSurface::manifest(
                "plugins/nxtg-forge/servers/governance-mcp/package.json",
                Some("3.7.0".into()),
            ),
            VersionSurface::lockfile(
                "plugins/nxtg-forge/servers/governance-mcp/package-lock.json",
                Some("3.10.2".into()),
            ),
        ]));

        assert_eq!(report.status, "FAIL");
        let drift = report
            .findings
            .iter()
            .find(|f| f.kind == "multi-surface-drift")
            .expect("multi-surface drift must be reported");
        assert!(drift.detail.contains("3.7.0"), "{}", drift.detail);
        assert!(drift.detail.contains("package.json"), "{}", drift.detail);
        // Manifests disagree, so no single expected version exists to judge the lockfile by.
        assert!(report.version.is_none());
    }

    #[test]
    fn single_manifest_port_would_pass_the_plugin_case() {
        // Guards Codex finding 5: checking only the first manifest sees 3.10.2 and reports OK,
        // which is exactly the false pass this evaluator exists to prevent.
        let surfaces = vec![
            VersionSurface::manifest(".claude-plugin/plugin.json", Some("3.10.2".into())),
            VersionSurface::manifest("governance-mcp/package.json", Some("3.7.0".into())),
        ];
        let single_surface_only = evaluate(&ReleaseDebtInput {
            surfaces: vec![surfaces[0].clone()],
            latest_tag: Some("v3.10.2".into()),
            commits_since_tag: 0,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        });
        assert_eq!(single_surface_only.status, "OK");

        let all_surfaces = evaluate(&ReleaseDebtInput {
            surfaces,
            latest_tag: Some("v3.10.2".into()),
            commits_since_tag: 0,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        });
        assert_eq!(all_surfaces.status, "FAIL");
    }

    #[test]
    fn tag_drift_warns() {
        let report = evaluate(&ReleaseDebtInput {
            surfaces: vec![VersionSurface::manifest("Cargo.toml", Some("1.6.0".into()))],
            latest_tag: Some("v1.5.2".into()),
            commits_since_tag: 1,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        });
        assert_eq!(report.status, "WARN");
        assert!(report.findings.iter().any(|f| f.kind == "tag-drift"));
    }

    #[test]
    fn unreleased_commits_warn_above_threshold() {
        let mut base = input(vec![VersionSurface::manifest(
            "Cargo.toml",
            Some("1.5.2".into()),
        )]);
        base.commits_since_tag = 6;
        let report = evaluate(&base);
        assert_eq!(report.status, "WARN");
        let f = report
            .findings
            .iter()
            .find(|f| f.kind == "unreleased-commits")
            .expect("unreleased commits must be reported");
        assert!(f.detail.contains('6'), "{}", f.detail);

        base.commits_since_tag = 5;
        assert_eq!(evaluate(&base).status, "OK", "threshold is exclusive");
    }

    #[test]
    fn untagged_repo_warns() {
        let report = evaluate(&ReleaseDebtInput {
            surfaces: vec![VersionSurface::manifest("Cargo.toml", Some("0.1.0".into()))],
            latest_tag: None,
            commits_since_tag: 3,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: Vec::new(),
        });
        assert_eq!(report.status, "WARN");
        assert!(report.findings.iter().any(|f| f.kind == "untagged"));
    }

    #[test]
    fn unreadable_version_fails() {
        let report = evaluate(&input(vec![
            VersionSurface::manifest("Cargo.toml", Some("1.5.2".into())),
            VersionSurface::manifest("plugin.json", None),
        ]));
        assert_eq!(report.status, "FAIL");
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "version-unreadable")
        );
    }

    #[test]
    fn tag_v_prefix_is_normalized() {
        let report = evaluate(&input(vec![VersionSurface::manifest(
            "Cargo.toml",
            Some("1.5.2".into()),
        )]));
        assert_eq!(report.status, "OK", "v1.5.2 must equal 1.5.2");
    }

    #[test]
    fn parses_cargo_toml_package_version() {
        let text = r#"
[package]
name = "forge-orchestrator"
version = "1.5.2"
edition = "2024"

[dependencies]
clap = { version = "4", features = ["derive"] }
"#;
        assert_eq!(parse_cargo_toml_version(text).as_deref(), Some("1.5.2"));
    }

    #[test]
    fn cargo_toml_parser_ignores_dependency_versions() {
        // A dependency version appearing before [package] must not be mistaken for the crate's.
        let text = r#"
[workspace]

[dependencies]
serde = { version = "9.9.9" }

[package]
name = "forge-orchestrator"
version = "1.5.2"
"#;
        assert_eq!(parse_cargo_toml_version(text).as_deref(), Some("1.5.2"));
    }

    #[test]
    fn parses_cargo_lock_block_for_the_named_package() {
        let text = r#"
[[package]]
name = "clap"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
 "clap_builder",
]

[[package]]
name = "forge-orchestrator"
version = "1.5.2"
dependencies = [
 "anyhow",
 "clap",
]

[[package]]
name = "serde"
version = "1.0.200"
"#;
        assert_eq!(
            parse_cargo_lock_version(text, "forge-orchestrator").as_deref(),
            Some("1.5.2")
        );
        assert_eq!(
            parse_cargo_lock_version(text, "clap").as_deref(),
            Some("4.5.0")
        );
        assert_eq!(
            parse_cargo_lock_version(text, "serde").as_deref(),
            Some("1.0.200")
        );
        assert_eq!(parse_cargo_lock_version(text, "absent"), None);
    }

    #[test]
    fn cargo_lock_parser_does_not_leak_into_the_next_block() {
        // The naive "first version line after the name" approach returns 9.9.9 here, because
        // the target block has no version of its own. It must return None instead.
        let text = r#"
[[package]]
name = "forge-orchestrator"
dependencies = [
 "anyhow",
]

[[package]]
name = "other"
version = "9.9.9"
"#;
        assert_eq!(parse_cargo_lock_version(text, "forge-orchestrator"), None);
    }

    #[test]
    fn marketplace_entry_without_a_version_is_surfaced_not_dropped() {
        // Codex round 5: filter_map silently dropped entries whose version was missing, so a
        // required plugin entry with no version passed --strict with exit 0.
        let parsed = parse_marketplace(
            r#"{"plugins":[
                {"name":"a","version":"1.0.0"},
                {"name":"b","source":"./b"}
            ]}"#,
        );
        let MarketplaceParse::Entries(entries) = parsed else {
            panic!("readable manifest must parse: {parsed:?}");
        };
        assert_eq!(entries.len(), 2, "every entry is reported: {entries:?}");
        assert_eq!(entries[1], ("b".to_string(), None));
    }

    #[test]
    fn marketplace_entry_version_is_surfaced_and_fails_the_evaluator() {
        // End-to-end through the evaluator: a None version must FAIL, not be treated as agreeing.
        let report = evaluate(&input(vec![
            VersionSurface::manifest("marketplace.json#plugins[a]", Some("1.0.0".into())),
            VersionSurface::manifest("marketplace.json#plugins[b]", None),
        ]));
        assert_eq!(report.status, "FAIL");
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "version-unreadable" && f.detail.contains("plugins[b]")),
            "{:?}",
            report.findings
        );
    }

    #[test]
    fn valid_empty_marketplace_is_not_malformed() {
        // "No plugins declared" is a legitimate answer and must not be confused with "broken".
        assert_eq!(
            parse_marketplace(r#"{"name":"m","plugins":[]}"#),
            MarketplaceParse::Entries(vec![])
        );
    }

    #[test]
    fn malformed_marketplace_shapes_are_reported_not_emptied() {
        // Each of these previously yielded an empty Vec — indistinguishable from "no plugins",
        // which is exactly the fail-open.
        for (text, needle) in [
            ("not json at all", "not valid JSON"),
            ("[]", "not a JSON object"),
            (r#"{"name":"m"}"#, "no `plugins` array"),
            (r#"{"plugins":{}}"#, "not an array"),
            (r#"{"plugins":["a string"]}"#, "plugins[0] is not an object"),
        ] {
            match parse_marketplace(text) {
                MarketplaceParse::Malformed(reason) => {
                    assert!(reason.contains(needle), "{text} -> {reason}");
                }
                other => panic!("{text} must be malformed, got {other:?}"),
            }
        }
    }

    #[test]
    fn a_non_string_entry_version_is_treated_as_missing() {
        let MarketplaceParse::Entries(entries) =
            parse_marketplace(r#"{"plugins":[{"name":"a","version":3}]}"#)
        else {
            panic!("structurally fine, just a bad version type");
        };
        assert_eq!(entries[0], ("a".to_string(), None));
    }

    #[test]
    fn inventory_errors_fail_the_evaluation_loudly() {
        // A gate that could not READ a surface has not verified it. Reporting OK because the
        // readable half agreed is the silent-swallow class Gate 5 removed from the MCP layer.
        let report = evaluate(&ReleaseDebtInput {
            surfaces: vec![VersionSurface::manifest("Cargo.toml", Some("1.5.2".into()))],
            latest_tag: Some("v1.5.2".into()),
            commits_since_tag: 0,
            commit_warn_threshold: DEFAULT_COMMIT_WARN_THRESHOLD,
            inventory_errors: vec!["plugin.json: unreadable (permission denied)".into()],
        });
        assert_eq!(
            report.status, "FAIL",
            "an unreadable surface cannot yield a passing verdict"
        );
        let f = report
            .findings
            .iter()
            .find(|f| f.kind == "inventory-error")
            .expect("inventory error must be reported");
        assert!(f.detail.contains("permission denied"), "{}", f.detail);
    }

    #[test]
    fn parses_json_version() {
        assert_eq!(
            parse_json_version(r#"{"name":"nxtg-forge","version":"3.10.2"}"#).as_deref(),
            Some("3.10.2")
        );
        assert_eq!(parse_json_version(r#"{"name":"x"}"#), None);
        assert_eq!(parse_json_version("not json"), None);
    }
}