fallow-output 3.25.0

Output contract types for fallow reports
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
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Audit brief output contracts.

use crate::root_envelopes::{RootEnvelopeMode, attach_telemetry_meta, serialize_named_json_output};
use fallow_types::envelope::{ElapsedMs, Meta, ToolVersion};
use serde::Serialize;
use serde_json::Value;

/// Wire version for the `fallow audit --brief --format json` envelope.
pub const REVIEW_BRIEF_SCHEMA_VERSION: u32 = 10;

/// Maximum number of affected-but-not-in-diff paths sampled into
/// [`ImpactClosureFacts::affected_not_shown`].
///
/// The full count is preserved in [`ImpactClosureFacts::affected_count`]
/// (aggregate-before-truncate), so capping the sample never distorts the count,
/// and the SHAPE of the reach is carried by
/// [`ImpactClosureFacts::affected_by_dir`] rather than by which files landed in
/// the sample. Nothing that ranks or gates reads this list: the decision surface
/// takes its blast metric from the uncapped engine closure.
pub const AFFECTED_SAMPLE_CAP: usize = 10;

/// Maximum number of directories reported in
/// [`ImpactClosureFacts::affected_by_dir`]. Directories beyond the cap are the
/// lightest ones and are counted in
/// [`ImpactClosureFacts::affected_by_dir_omitted`].
pub const AFFECTED_DIR_CAP: usize = 25;

/// Independently-versioned wire-version newtype for the brief envelope.
/// Serializes as the integer `REVIEW_BRIEF_SCHEMA_VERSION`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(extend("const" = REVIEW_BRIEF_SCHEMA_VERSION))
)]
pub struct ReviewBriefSchemaVersion(pub u32);

impl Default for ReviewBriefSchemaVersion {
    fn default() -> Self {
        Self(REVIEW_BRIEF_SCHEMA_VERSION)
    }
}

/// Coarse risk classification for a changeset, a pure function of the change
/// size (file count plus, once threaded, net lines).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum RiskClass {
    /// Small, contained change.
    Low,
    /// Moderately sized change.
    Medium,
    /// Large change spanning many files or lines.
    High,
}

/// Suggested reviewer effort, a pure function of [`RiskClass`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum ReviewEffort {
    /// A quick scan is enough.
    Glance,
    /// A normal line-by-line review.
    Review,
    /// A careful, deep review is warranted.
    DeepDive,
}

/// Stage 0 of the brief: triage facts derived purely from the diff size.
///
/// `hunks` and `net_lines` are populated when the caller supplies parsed diff
/// evidence. They remain absent when no diff is available.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DiffTriage {
    /// Number of changed files in the audit scope.
    pub files: usize,
    /// Number of diff hunks, or `None` when no diff evidence was supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hunks: Option<usize>,
    /// Net added-minus-removed lines, or `None` without diff evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub net_lines: Option<i64>,
    /// Coarse risk class derived from the change size.
    pub risk_class: RiskClass,
    /// Suggested reviewer effort derived from `risk_class`.
    pub review_effort: ReviewEffort,
}

/// Stage 1 of the brief: graph-derived orientation facts.
///
/// `boundaries_touched` is derived from the run's boundary-violation zones.
/// `exports_added` and `api_width_delta` both report the exports-aware public
/// API widening count. Removed exports are not represented in this
/// widening-only signal. The set of modules the changed code reaches is Stage
/// 3's `impact_closure`, which owns both its magnitude and its paths.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct GraphFacts {
    /// Number of public API exports added by the changeset. Zero means the
    /// changeset adds no public API exports.
    pub exports_added: usize,
    /// Widening-only public API delta, currently equal to `exports_added`.
    /// Removed exports are not represented, so zero means no public API exports
    /// were added.
    pub api_width_delta: i64,
    /// Architecture boundary zones touched by the changeset, deduped and sorted.
    /// Derived from the run's boundary-violation findings.
    pub boundaries_touched: Vec<String>,
}

/// Stage 3 of the brief: the impact closure. The transitive
/// affected-but-not-in-diff set plus the coordination gap. The differentiator a
/// diff tool fundamentally cannot do, because it has no graph.
///
/// Honest scope (ADR-001, syntactic): the coordination gap is an attention
/// pointer at the exact inter-module failure mode, NOT a correctness proof.
#[derive(Debug, Clone, Default, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ImpactClosureFacts {
    /// The FULL number of files transitively affected by the changeset
    /// (reverse-deps + re-export chains) that are NOT in the diff. Computed
    /// BEFORE [`affected_not_shown`](Self::affected_not_shown) is capped to a
    /// sample, so it is always the true magnitude of the blast radius.
    pub affected_count: usize,
    /// A capped, path-sorted sample of the affected root-relative paths (at most
    /// [`AFFECTED_SAMPLE_CAP`]), deduped. The full count lives in
    /// [`affected_count`](Self::affected_count) and the distribution in
    /// [`affected_by_dir`](Self::affected_by_dir); use this list to jump to
    /// representative files, NEVER to enumerate the blast radius or to infer its
    /// shape. Because it is a prefix of the sorted set, it clusters in whichever
    /// directory sorts first. To reconstruct the full set, run
    /// `fallow check --impact-closure <path>` once per changed file and union the
    /// results: that flag seeds from a single file, so no single command
    /// reproduces this changeset-wide union.
    pub affected_not_shown: Vec<String>,
    /// The blast radius rolled up by parent directory: how the affected files
    /// distribute, heaviest directory first, ties broken by directory path so the
    /// order is deterministic. This is the SHAPE signal, and unlike
    /// [`affected_not_shown`](Self::affected_not_shown) its counts are exact for
    /// every directory it lists. At most [`AFFECTED_DIR_CAP`] entries.
    pub affected_by_dir: Vec<AffectedDirectory>,
    /// How many directories did not fit within [`AFFECTED_DIR_CAP`] and are
    /// absent from [`affected_by_dir`](Self::affected_by_dir). They are the
    /// lightest ones; their files are still counted in
    /// [`affected_count`](Self::affected_count). Zero when nothing was omitted.
    /// Add this to `affected_by_dir.len()` for the true number of directories
    /// the change reaches.
    pub affected_by_dir_omitted: usize,
    /// Coordination gaps: a changed file exports a contract consumed by a module
    /// absent from the diff. One entry per (changed file, consumer) pair. NOT a
    /// subset of [`affected_not_shown`](Self::affected_not_shown): the gap
    /// deliberately skips story and test consumers that the affected set counts.
    pub coordination_gap: Vec<CoordinationGapFact>,
}

impl ImpactClosureFacts {
    /// Build the facts from the full closure, capping the file sample and the
    /// directory rollup while preserving the exact total.
    ///
    /// `affected` must arrive deduped and path-sorted (the engine closure
    /// guarantees both); the sample is its prefix.
    #[must_use]
    pub fn new(affected: &[String], coordination_gap: Vec<CoordinationGapFact>) -> Self {
        let (affected_by_dir, affected_by_dir_omitted) = roll_up_by_directory(affected);
        Self {
            affected_count: affected.len(),
            affected_not_shown: affected.iter().take(AFFECTED_SAMPLE_CAP).cloned().collect(),
            affected_by_dir,
            affected_by_dir_omitted,
            coordination_gap,
        }
    }
}

/// One directory of the blast radius and how many affected files it holds.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AffectedDirectory {
    /// Root-relative parent directory, forward-slashed. The empty string is the
    /// repository root.
    pub dir: String,
    /// How many affected-but-not-in-diff files live directly in `dir`. Exact,
    /// never sampled.
    pub count: usize,
}

/// Roll the affected paths up by parent directory, heaviest first, capped at
/// [`AFFECTED_DIR_CAP`]. Returns the kept rows and how many directories were
/// dropped.
///
/// Sorting by count descending keeps the heaviest directories, which is the
/// question a reviewer is actually asking ("did this leak somewhere new, or is
/// it all inside the module I already changed?"). The directory path breaks
/// ties so the order is total and stable across runs.
fn roll_up_by_directory(affected: &[String]) -> (Vec<AffectedDirectory>, usize) {
    let mut counts: rustc_hash::FxHashMap<&str, usize> = rustc_hash::FxHashMap::default();
    for path in affected {
        let dir = path.rsplit_once('/').map_or("", |(head, _)| head);
        *counts.entry(dir).or_default() += 1;
    }
    let mut rows: Vec<AffectedDirectory> = counts
        .into_iter()
        .map(|(dir, count)| AffectedDirectory {
            dir: dir.to_string(),
            count,
        })
        .collect();
    rows.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.dir.cmp(&b.dir)));
    let omitted = rows.len().saturating_sub(AFFECTED_DIR_CAP);
    rows.truncate(AFFECTED_DIR_CAP);
    (rows, omitted)
}

/// One coordination-gap entry: a changed file exports symbols consumed by a
/// `consumer_file` that is NOT in the diff. Deduped per (changed, consumer) pair
/// (firing-precision rule R2).
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CoordinationGapFact {
    /// Root-relative path of the changed file whose contract is consumed elsewhere.
    pub changed_file: String,
    /// Root-relative path of the consumer module that is NOT in the diff.
    pub consumer_file: String,
    /// The exported symbol names the consumer references, sorted.
    pub consumed_symbols: Vec<String>,
    /// Honest scope note: this is a syntactic attention pointer, not a proof.
    pub note: String,
}

/// Stage 2 of the brief: the partition + order. The changed files split into
/// coherent BY-MODULE units (the only byte-identical-deterministic clustering
/// definition straight from the graph), plus a dependency-sensible review ORDER
/// over those units (definitions before consumers, mechanical/leaf units last,
/// ties broken by the path sort). Stage 2 sits UNDER the decision surface as a
/// drill-down; it is the backbone the directed-review loop hands the agent.
///
/// Feature-cluster and concern partitioning are deferred (they need scoring
/// heuristics whose tie-breaks are a fresh nondeterminism surface).
#[derive(Debug, Clone, Default, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PartitionFacts {
    /// The by-module units, sorted by module directory. Empty when no graph was
    /// retained or no changed file maps to a known module.
    pub units: Vec<ReviewUnitFact>,
    /// The dependency-sensible review order: module-directory strings,
    /// definitions before consumers, mechanical/leaf units last. A permutation of
    /// the `units` module directories.
    pub order: Vec<String>,
    /// Connected components of the inter-unit dependency graph: groups of
    /// module directories that share no import edge with any unit outside the
    /// group. Present only when there are two or more; a single slice is just
    /// `order`. A slice proves the absence of import edges to the rest of the
    /// change, nothing more: whether it can land on its own is still a
    /// judgment (generated files and lockstep contracts share no edge and
    /// still belong together). An orientation fact, never a demand to split.
    #[serde(default, skip_serializing_if = "fewer_than_two_slices")]
    pub independent_slices: Vec<Vec<String>>,
}

fn fewer_than_two_slices(slices: &[Vec<String>]) -> bool {
    slices.len() < 2
}

/// One review unit: a coherent by-module cluster of the changed set.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReviewUnitFact {
    /// The module directory the unit covers (root-relative, forward-slashed).
    /// The empty string is the repository-root group.
    pub module_dir: String,
    /// The changed files in this unit, path-sorted.
    pub files: Vec<String>,
}

/// Diff-aware deterministic deltas (6.A), framed new-vs-pre-existing against
/// the audit base snapshot. Each entry is a brief summary/verdict line.
///
/// `public_api` is batch-consolidated to ONE decision per change (rule R1):
/// the `added` list carries the introduced public-export keys as evidence, but a
/// reviewer reads "the public surface widened by N", never one decision per
/// symbol.
#[derive(Debug, Clone, Default, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReviewDeltas {
    /// Cross-zone boundary EDGES introduced vs base (R2 first-edge-only: one per
    /// `<from_zone>-><to_zone>` pair, never per import). New-vs-pre-existing.
    pub boundary_introduced: Vec<String>,
    /// Circular dependencies introduced vs base (canonical file-set keys).
    pub cycle_introduced: Vec<String>,
    /// Exports-aware public-API surface delta: the public-export keys
    /// (`<rel_path>::<name>`) added vs base, resolved through `package.json`
    /// `exports` + re-export reachability. A symbol re-exported only through an
    /// internal barrel NOT in `exports` is absent here (zero delta); one
    /// reachable through an `exports` path is present (exactly one).
    pub public_api_added: Vec<String>,
    /// Third-party dependencies a changed `package.json` declares that the base
    /// manifest did not, as `<manifest>::<name>` keys. Every dependency section
    /// participates. Always present, empty when no manifest changed.
    pub dependency_added: Vec<String>,
    /// Declared dependencies whose range moved across a major version (or a
    /// `0.x` minor) vs base, as `<manifest>::<name>@<from>-><to>` keys. Minor
    /// and patch moves are not candidates; a non-numeric range is skipped.
    /// Always present, empty when nothing crossed a major version.
    pub dependency_major_bumped: Vec<String>,
}

/// The full `fallow audit --brief --format json` envelope. Carries the
/// informational verdict, the triage and graph-facts orientation stages, plus
/// the reused "subtract" section (the same dead-code / duplication / complexity
/// payload `fallow audit --format json` emits).
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(title = "fallow audit --brief --format json")
)]
pub struct ReviewBriefOutput<Focus, Weakening, Routing, Decisions> {
    /// Independently-versioned brief schema version.
    pub schema_version: ReviewBriefSchemaVersion,
    /// Fallow CLI version that produced this output.
    pub version: String,
    /// Command discriminator singleton: always `"audit-brief"`.
    pub command: String,
    /// Stage 0: change-size triage (file/hunk/line counts, risk class, effort).
    pub triage: DiffTriage,
    /// Stage 1: graph orientation facts.
    pub graph_facts: GraphFacts,
    /// Stage 2: the partition + order (by-module units + dependency-sensible
    /// review order). The backbone the directed-review loop hands the agent.
    pub partition: PartitionFacts,
    /// Stage 3: the impact closure (affected-not-shown + coordination gap).
    pub impact_closure: ImpactClosureFacts,
    /// Stage 4: the weighted focus map. A composite attention score per
    /// changed-file unit (fan-in/out + security taint + risk zone + change shape),
    /// with `review-here` / `not-prioritized` labels (NEVER `skip` in free mode),
    /// a per-unit confidence flag, and the FULL `deprioritized` escape-hatch list
    /// so every de-prioritized piece is reachable. Stage 4 sits UNDER the decision
    /// surface as drill-down.
    pub focus: Focus,
    /// 6.A: diff-aware deterministic deltas (boundary/cycle introduced +
    /// exports-aware public-API surface delta), new-vs-pre-existing.
    pub deltas: ReviewDeltas,
    /// 6.F, headline: reviewer-private weakening signals (tests
    /// removed/skipped, thresholds lowered, suppressions added, security steps
    /// removed). Advisory, never gates, never auto-posted.
    pub weakening: Vec<Weakening>,
    /// 6.D: ownership-aware reviewer routing (per-file expert + bus-factor).
    pub routing: Routing,
    /// 6.G, the APEX: the decision surface. The ranked, capped,
    /// signal_id-anchored set of consequential structural decisions, each framed
    /// as a judgment question with its routed expert. This is the only thing the
    /// brief visibly leads with; the stages above are its drill-down derivation.
    pub decisions: Decisions,
    /// Branching conservation across the changeset: total branching against
    /// the number of functions now holding it. Absent when no base comparison
    /// ran, which keeps the wire shape byte-identical for a consumer that
    /// never had a base snapshot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branching: Option<crate::BranchingReport>,
}

/// The standard audit brief payload shape used by the CLI, schema emitter,
/// API, and agent-facing review surfaces.
pub type StandardReviewBriefOutput = ReviewBriefOutput<
    crate::audit_focus::FocusMap,
    crate::audit_weakening::WeakeningSignal,
    crate::audit_routing::RoutingFacts,
    crate::audit_decision_surface::DecisionSurface,
>;

/// Informational audit metadata carried by the review brief wire envelope.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReviewBriefHeader<Verdict, Summary, Attribution> {
    /// Fallow CLI version that produced this output.
    pub version: ToolVersion,
    /// Audit verdict, informational only on the brief path.
    pub verdict: Verdict,
    /// Number of changed files in the audit scope.
    pub changed_files_count: u32,
    /// Base ref used to determine the changeset.
    pub base_ref: String,
    /// Human-readable description of the resolved base, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_description: Option<String>,
    /// Head commit SHA, when the audit ran against a committed head.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head_sha: Option<String>,
    /// Analysis duration in milliseconds.
    pub elapsed_ms: ElapsedMs,
    /// Whether base-snapshot analysis was skipped for this run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_snapshot_skipped: Option<bool>,
    /// Per-category audit summary.
    pub summary: Summary,
    /// Introduced-versus-inherited issue attribution.
    pub attribution: Attribution,
}

/// Complete `fallow audit --brief --format json` wire envelope.
///
/// This is distinct from [`ReviewBriefOutput`], which is the reusable review
/// digest embedded in walkthrough output. The wire envelope also carries audit
/// metadata, optional telemetry, and the subtract-style analysis subreports.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(title = "fallow audit --brief --format json")
)]
pub struct ReviewBriefWireOutput<
    Focus,
    Weakening,
    Routing,
    Decisions,
    Verdict,
    Summary,
    Attribution,
    DeadCode,
    Duplication,
    Complexity,
> {
    /// Independently-versioned brief schema version.
    pub schema_version: ReviewBriefSchemaVersion,
    /// Fallow CLI version that produced this output.
    pub version: ToolVersion,
    /// Command discriminator singleton: always `"audit-brief"`.
    pub command: String,
    /// Audit verdict, informational only on the brief path.
    pub verdict: Verdict,
    /// Number of changed files in the audit scope.
    pub changed_files_count: u32,
    /// Base ref used to determine the changeset.
    pub base_ref: String,
    /// Human-readable description of the resolved base, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_description: Option<String>,
    /// Head commit SHA, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub head_sha: Option<String>,
    /// Analysis duration in milliseconds.
    pub elapsed_ms: ElapsedMs,
    /// Whether base-snapshot analysis was skipped for this run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_snapshot_skipped: Option<bool>,
    /// Per-category audit summary.
    pub summary: Summary,
    /// Introduced-versus-inherited issue attribution.
    pub attribution: Attribution,
    /// Optional metric definitions and local telemetry correlation metadata.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    /// Ranked, capped review decisions.
    pub decisions: Decisions,
    /// Diff-size triage facts.
    pub triage: DiffTriage,
    /// Graph-derived orientation facts.
    pub graph_facts: GraphFacts,
    /// Changed-file partition and review order.
    pub partition: PartitionFacts,
    /// Transitive impact closure outside the diff.
    pub impact_closure: ImpactClosureFacts,
    /// Weighted focus map for changed-file units.
    pub focus: Focus,
    /// Deterministic introduced deltas against the base snapshot.
    pub deltas: ReviewDeltas,
    /// Reviewer-private weakening signals.
    pub weakening: Vec<Weakening>,
    /// Ownership-aware reviewer routing.
    pub routing: Routing,
    /// Dead-code findings scoped to the audit changeset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dead_code: Option<DeadCode>,
    /// Duplication findings scoped to the audit changeset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duplication: Option<Duplication>,
    /// Complexity findings scoped to the audit changeset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub complexity: Option<Complexity>,
    /// Branching conservation across the changeset. Absent when no base
    /// comparison ran.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branching: Option<crate::BranchingReport>,
}

/// CLI-built audit subreports that are embedded in the audit brief envelope.
///
/// The brief envelope and field ordering belong to `fallow-output`; the
/// underlying subreport payloads are still supplied by the CLI until their
/// builders are fully command-neutral.
#[derive(Debug, Clone, Default)]
pub struct ReviewBriefSubtractSections<DeadCode = Value, Duplication = Value, Complexity = Value> {
    /// Dead-code subreport, when the CLI produced one for this changeset.
    pub dead_code: Option<DeadCode>,
    /// Duplication subreport, when the CLI produced one for this changeset.
    pub duplication: Option<Duplication>,
    /// Complexity subreport, when the CLI produced one for this changeset.
    pub complexity: Option<Complexity>,
}

/// Build the complete `fallow audit --brief --format json` value.
///
/// `header` carries informational audit scope fields such as verdict, base ref,
/// summary, and attribution. The independent brief schema and command always
/// come from the typed brief payload.
pub fn build_review_brief_json_output<
    Focus,
    Weakening,
    Routing,
    Decisions,
    Verdict,
    Summary,
    Attribution,
    DeadCode,
    Duplication,
    Complexity,
>(
    brief: ReviewBriefOutput<Focus, Weakening, Routing, Decisions>,
    header: ReviewBriefHeader<Verdict, Summary, Attribution>,
    subtract: ReviewBriefSubtractSections<DeadCode, Duplication, Complexity>,
) -> Result<Value, serde_json::Error>
where
    Focus: Serialize,
    Weakening: Serialize,
    Routing: Serialize,
    Decisions: Serialize,
    Verdict: Serialize,
    Summary: Serialize,
    Attribution: Serialize,
    DeadCode: Serialize,
    Duplication: Serialize,
    Complexity: Serialize,
{
    serde_json::to_value(ReviewBriefWireOutput {
        schema_version: brief.schema_version,
        version: header.version,
        command: brief.command,
        verdict: header.verdict,
        changed_files_count: header.changed_files_count,
        base_ref: header.base_ref,
        base_description: header.base_description,
        head_sha: header.head_sha,
        elapsed_ms: header.elapsed_ms,
        base_snapshot_skipped: header.base_snapshot_skipped,
        summary: header.summary,
        attribution: header.attribution,
        meta: None,
        decisions: brief.decisions,
        triage: brief.triage,
        graph_facts: brief.graph_facts,
        partition: brief.partition,
        impact_closure: brief.impact_closure,
        focus: brief.focus,
        deltas: brief.deltas,
        weakening: brief.weakening,
        routing: brief.routing,
        dead_code: subtract.dead_code,
        duplication: subtract.duplication,
        complexity: subtract.complexity,
        branching: brief.branching,
    })
}

fn serialize_agent_contract_json_output<T: Serialize>(
    output: T,
    kind: &'static str,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut value = serialize_named_json_output(output, kind, mode)?;
    attach_telemetry_meta(&mut value, analysis_run_id);
    Ok(value)
}

/// Serialize the `fallow audit --brief --format json` envelope.
///
/// # Errors
///
/// Returns a serde error when the brief output cannot be converted to JSON.
pub fn serialize_review_brief_json_output<T: Serialize>(
    output: T,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    serialize_agent_contract_json_output(output, "audit-brief", mode, analysis_run_id)
}

/// Serialize the standalone decision-surface envelope.
///
/// # Errors
///
/// Returns a serde error when the decision-surface output cannot be converted
/// to JSON.
pub fn serialize_decision_surface_json_output<T: Serialize>(
    output: T,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    serialize_agent_contract_json_output(output, "decision-surface", mode, analysis_run_id)
}

/// Serialize the review walkthrough guide envelope.
///
/// # Errors
///
/// Returns a serde error when the walkthrough guide cannot be converted to
/// JSON.
pub fn serialize_walkthrough_guide_json_output<T: Serialize>(
    output: T,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    serialize_agent_contract_json_output(output, "review-walkthrough-guide", mode, analysis_run_id)
}

/// Serialize the review walkthrough validation envelope.
///
/// # Errors
///
/// Returns a serde error when the walkthrough validation cannot be converted
/// to JSON.
pub fn serialize_walkthrough_validation_json_output<T: Serialize>(
    output: T,
    mode: RootEnvelopeMode,
    analysis_run_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    serialize_agent_contract_json_output(
        output,
        "review-walkthrough-validation",
        mode,
        analysis_run_id,
    )
}

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

    /// Serialize a minimal brief through the real wire mapping.
    fn brief_wire_value(branching: Option<crate::BranchingReport>) -> Value {
        let brief = ReviewBriefOutput {
            branching,
            schema_version: ReviewBriefSchemaVersion::default(),
            version: "1.2.3".to_string(),
            command: "audit-brief".to_string(),
            triage: DiffTriage {
                files: 1,
                hunks: None,
                net_lines: None,
                risk_class: RiskClass::Low,
                review_effort: ReviewEffort::Glance,
            },
            graph_facts: GraphFacts {
                exports_added: 0,
                api_width_delta: 0,
                boundaries_touched: Vec::new(),
            },
            partition: PartitionFacts::default(),
            impact_closure: ImpactClosureFacts::default(),
            focus: json!({"units": []}),
            deltas: ReviewDeltas::default(),
            weakening: Vec::<Value>::new(),
            routing: json!({"units": []}),
            decisions: json!({"decisions": []}),
        };
        let header = ReviewBriefHeader {
            version: ToolVersion("1.2.3".to_string()),
            verdict: json!("fail"),
            changed_files_count: 1,
            base_ref: "main".to_string(),
            base_description: Some("merge base".to_string()),
            head_sha: Some("abc123".to_string()),
            elapsed_ms: ElapsedMs(12),
            base_snapshot_skipped: Some(false),
            summary: json!({"dead_code_issues": 0}),
            attribution: json!({"gate": "new_only"}),
        };

        build_review_brief_json_output(
            brief,
            header,
            ReviewBriefSubtractSections::<Value, Value, Value> {
                dead_code: Some(json!({"issues": []})),
                duplication: None,
                complexity: None,
            },
        )
        .expect("brief output should serialize")
    }

    #[test]
    fn review_brief_json_output_assembles_typed_wire_contract() {
        let value = brief_wire_value(None);

        assert_eq!(value["schema_version"], REVIEW_BRIEF_SCHEMA_VERSION);
        assert_eq!(value["command"], "audit-brief");
        assert_eq!(value["verdict"], "fail");
        assert_eq!(value["base_ref"], "main");
        assert_eq!(value["summary"]["dead_code_issues"], 0);
        assert_eq!(value["attribution"]["gate"], "new_only");
        assert_eq!(value["dead_code"]["issues"], json!([]));
        assert!(
            value.get("branching").is_none(),
            "absent when no base comparison ran, so the wire shape is unchanged              for a consumer that never had a base snapshot"
        );
    }

    #[test]
    fn review_brief_json_output_carries_the_branching_block() {
        // Widening `ReviewBriefOutput` alone would land the block in the
        // walkthrough digest and leave it out of the brief JSON, because the
        // wire struct is mapped field by field.
        let base: crate::BranchingSnapshot = std::iter::once((
            "src/a.ts".to_string(),
            fallow_types::extract::FileBranching {
                branch_points: 12,
                functions: 1,
                peak_cyclomatic: 13,
                cognitive: 12,
                cognitive_nesting_weight: 6,
                has_module_unit: false,
                has_synthetic_units: false,
            },
        ))
        .collect();
        let head: crate::BranchingSnapshot = std::iter::once((
            "src/a.ts".to_string(),
            fallow_types::extract::FileBranching {
                branch_points: 12,
                functions: 5,
                peak_cyclomatic: 4,
                cognitive: 6,
                cognitive_nesting_weight: 0,
                has_module_unit: false,
                has_synthetic_units: false,
            },
        ))
        .collect();
        let report = crate::BranchingReport::compare(
            &base,
            &head,
            crate::DEFAULT_BRANCHING_TOLERANCE,
            &|_| false,
        );

        let value = brief_wire_value(Some(report));

        assert_eq!(
            value["branching"]["split_in_place"][0]["path"], "src/a.ts",
            "the local claim reaches the wire, not only the digest"
        );
        assert_eq!(
            value["branching"]["split_in_place"][0]["functions_after"],
            5
        );
        assert!(
            !value["branching"]
                .as_object()
                .expect("branching is an object")
                .contains_key("verdict"),
            "there is no changeset-level verdict to publish"
        );
        assert_eq!(value["branching"]["branch_points"]["delta"], 0);
        assert_eq!(value["branching"]["functions"]["delta"], 4);
        assert_eq!(value["branching"]["peak_unit_cyclomatic"]["delta"], -9);
        assert_eq!(
            value["branching"]["cognitive"]["attributed_to"],
            "nesting-reset"
        );
        assert_eq!(value["branching"]["tolerance"], 2);
        assert_eq!(value["branching"]["by_file"][0]["path"], "src/a.ts");
    }

    #[test]
    fn review_brief_serializer_owns_root_contract() {
        let value = serialize_review_brief_json_output(
            json!({"command": "audit-brief"}),
            RootEnvelopeMode::Tagged,
            Some("run-brief"),
        )
        .expect("brief output should serialize");

        assert_eq!(value["kind"], "audit-brief");
        assert_eq!(value["_meta"]["telemetry"]["analysis_run_id"], "run-brief");
    }

    #[test]
    fn decision_surface_serializer_owns_root_contract() {
        let value = serialize_decision_surface_json_output(
            json!({"decisions": []}),
            RootEnvelopeMode::Tagged,
            Some("run-decision"),
        )
        .expect("decision surface should serialize");

        assert_eq!(value["kind"], "decision-surface");
        assert_eq!(
            value["_meta"]["telemetry"]["analysis_run_id"],
            "run-decision"
        );
    }

    /// `<dirs>` directories holding `<per_dir>` files each, path-sorted the way
    /// the engine closure hands them over.
    fn affected(dirs: usize, per_dir: usize) -> Vec<String> {
        let mut paths: Vec<String> = (0..dirs)
            .flat_map(|d| (0..per_dir).map(move |f| format!("src/zone{d:03}/file{f:03}.ts")))
            .collect();
        paths.sort();
        paths
    }

    #[test]
    fn a_closure_within_the_caps_is_reported_whole() {
        let paths = affected(2, 3);
        let facts = ImpactClosureFacts::new(&paths, Vec::new());

        assert_eq!(facts.affected_count, 6);
        assert_eq!(facts.affected_not_shown, paths);
        assert_eq!(facts.affected_by_dir_omitted, 0);
        assert_eq!(
            facts
                .affected_by_dir
                .iter()
                .map(|row| (row.dir.as_str(), row.count))
                .collect::<Vec<_>>(),
            vec![("src/zone000", 3), ("src/zone001", 3)]
        );
    }

    #[test]
    fn the_count_survives_capping_the_sample() {
        let paths = affected(4, 40);
        let facts = ImpactClosureFacts::new(&paths, Vec::new());

        assert_eq!(
            facts.affected_count, 160,
            "the magnitude is computed before the sample is capped"
        );
        assert_eq!(facts.affected_not_shown.len(), AFFECTED_SAMPLE_CAP);
        assert_eq!(
            facts
                .affected_by_dir
                .iter()
                .map(|row| row.count)
                .sum::<usize>(),
            facts.affected_count,
            "an uncapped rollup accounts for every affected file"
        );
    }

    #[test]
    fn the_rollup_carries_weight_the_sample_cannot() {
        // A prefix sample lands entirely in the directory that sorts first, so
        // the rollup is the only thing that can say where the reach actually is.
        let mut paths = affected(1, 12);
        paths.extend((0..90).map(|f| format!("src/zzz_heavy/file{f:03}.ts")));
        paths.sort();
        let facts = ImpactClosureFacts::new(&paths, Vec::new());

        assert!(
            facts
                .affected_not_shown
                .iter()
                .all(|path| path.starts_with("src/zone000/")),
            "the fixture must produce a one-directory sample: {:?}",
            facts.affected_not_shown
        );
        let heaviest = facts.affected_by_dir.first().expect("a rollup row");
        assert_eq!(
            (heaviest.dir.as_str(), heaviest.count),
            ("src/zzz_heavy", 90)
        );
    }

    #[test]
    fn rollup_rows_beyond_the_cap_are_counted_not_dropped_silently() {
        let paths = affected(AFFECTED_DIR_CAP + 7, 1);
        let facts = ImpactClosureFacts::new(&paths, Vec::new());

        assert_eq!(facts.affected_by_dir.len(), AFFECTED_DIR_CAP);
        assert_eq!(facts.affected_by_dir_omitted, 7);
        assert_eq!(facts.affected_count, AFFECTED_DIR_CAP + 7);
    }

    #[test]
    fn equal_weight_directories_are_ordered_by_path() {
        let facts = ImpactClosureFacts::new(&affected(3, 2), Vec::new());
        let dirs: Vec<&str> = facts
            .affected_by_dir
            .iter()
            .map(|row| row.dir.as_str())
            .collect();
        assert_eq!(
            dirs,
            vec!["src/zone000", "src/zone001", "src/zone002"],
            "the path is the tie-break, so the order is total across runs"
        );
    }

    #[test]
    fn the_coordination_gap_is_never_capped() {
        // The human brief routes a reader to `--format json` for the gaps and
        // their symbols. That promise holds only while this constructor stores
        // both whole, alongside two fields it does deliberately cap.
        let symbols: Vec<String> = (0..40).map(|i| format!("symbol{i:02}")).collect();
        let gaps: Vec<CoordinationGapFact> = (0..60)
            .map(|i| CoordinationGapFact {
                changed_file: "src/core.ts".to_string(),
                consumer_file: format!("src/consumer{i:02}.ts"),
                consumed_symbols: symbols.clone(),
                note: String::new(),
            })
            .collect();
        let facts = ImpactClosureFacts::new(&affected(40, 3), gaps);

        assert_eq!(facts.coordination_gap.len(), 60);
        assert!(
            facts
                .coordination_gap
                .iter()
                .all(|gap| gap.consumed_symbols.len() == 40),
            "every consumed symbol survives, or the brief's json route is a lie"
        );
        assert!(
            facts.affected_not_shown.len() < facts.affected_count
                && facts.affected_by_dir_omitted > 0,
            "the fixture must show the sibling fields really are capped"
        );
    }

    #[test]
    fn root_level_files_roll_up_under_the_empty_directory() {
        let facts =
            ImpactClosureFacts::new(&["play.ts".to_string(), "setup.ts".to_string()], Vec::new());
        assert_eq!(facts.affected_by_dir.len(), 1);
        assert_eq!(facts.affected_by_dir[0].dir, "");
        assert_eq!(facts.affected_by_dir[0].count, 2);
    }
}