Skip to main content

fallow_api/
decision_surface.rs

1//! Decision-surface extractor (stage 6 / 6.G): THE product.
2//!
3//! The apex of the review brief. A change embeds many decisions; almost all are
4//! mechanical and a few are consequential enough to need human taste. This
5//! extractor lifts the consequential STRUCTURAL decisions out of the scattered
6//! diff, frames each as a judgment question, ranks by consequence (blast x
7//! reversibility), caps the surface to a working-memory-sized handful (4 plus or
8//! minus 1), collapses the mechanical remainder, and pairs each decision with the
9//! routed expert ("who to ask").
10//!
11//! ## The SOLID-3 (the ONLY categories that ship)
12//!
13//! Per the verdict (`.plans/agentic-review-e0-verdict.md`) the decision
14//! categories are NOT uniformly reliable on a syntactic engine (ADR-001). Exactly
15//! three are validated and shippable, each backed by a deterministic signal
16//! fallow already emits:
17//!
18//! 1. **coupling/boundary** (`boundary_introduced`): a new cross-zone edge.
19//! 2. **public-API/contract** (`public_api_added` + coordination gaps): a
20//!    new exports-aware public surface, or a changed contract consumed by modules
21//!    outside the diff.
22//! 3. **dependency**: a changed `package.json` that adds third-party entries or
23//!    moves one across a major version (`dependency_added` /
24//!    `dependency_major_bumped`), batch-consolidated per manifest per kind and
25//!    weighted by the graph's in-repo importers of the affected packages.
26//!
27//! The four CUT categories (abstraction-with-1-implementor, deletion-still-
28//! reachable, convention-divergence, irreversibility/migration) are CONFIRMED
29//! NOISE and MUST NOT ship. `DecisionCategory` has exactly three discriminants,
30//! so a cut category is not even representable: the type system is the guarantee.
31//!
32//! ## The trust mechanism (anti-hallucination)
33//!
34//! Post-validation closes on EXTRACTION, not on framing. Every decision carries a
35//! `signal_id` deterministically derived from the fallow-emitted candidate key it
36//! frames (a delta key or a coordination-gap key). The deterministic layer keeps
37//! the SET of signal_ids it emitted; `DecisionSurface::accept_signal_id` returns
38//! true iff an id is in that set. An agent-proposed decision whose `signal_id` was
39//! never emitted is REJECTED. The agent proposes; the graph disposes.
40
41pub use fallow_output::{
42    Decision, DecisionCategory, DecisionSurface, TruncationNote, build_decision_surface_output,
43};
44use xxhash_rust::xxh3::xxh3_64;
45
46use fallow_output::{ReviewDeltas, RoutingFacts};
47
48/// Default decision-surface cap (the working-memory limit). The surface holds at
49/// most this many ranked decisions; the rest collapse into a truncation note.
50pub const DEFAULT_DECISION_CAP: usize = 4;
51/// Lower bound on the configurable cap (4 minus 1).
52pub const MIN_DECISION_CAP: usize = 3;
53/// Upper bound on the configurable cap (4 plus 1).
54pub const MAX_DECISION_CAP: usize = 5;
55
56/// Derive a deterministic, content-addressed `signal_id` from a category tag plus
57/// the fallow-emitted candidate key. The tag namespaces the key so a boundary key
58/// and a public-API key sharing text never collide. Pure: same inputs always
59/// yield the same id (byte-identical across runs).
60#[must_use]
61pub fn derive_signal_id(category: DecisionCategory, candidate_key: &str) -> String {
62    let mut bytes = Vec::with_capacity(category.tag().len() + 1 + candidate_key.len());
63    bytes.extend_from_slice(category.tag().as_bytes());
64    bytes.push(0);
65    bytes.extend_from_slice(candidate_key.as_bytes());
66    format!("sig:{:016x}", xxh3_64(&bytes))
67}
68
69/// A representative boundary violation used to anchor a coupling/boundary
70/// decision to a file + line. Decoupled from the `fallow_types` finding type so
71/// the extractor unit-tests without constructing full findings.
72#[derive(Debug, Clone)]
73pub struct BoundaryAnchor {
74    /// The R2 zone-pair key (`"<from_zone>->-<to_zone>"`), matching
75    /// `ReviewDeltas::boundary_introduced`.
76    pub zone_pair_key: String,
77    /// Root-relative path of the importing file (the decision anchor).
78    pub from_file: String,
79    /// The `from_zone` of the edge (for the framed question).
80    pub from_zone: String,
81    /// The `to_zone` of the edge (for the framed question).
82    pub to_zone: String,
83    /// 1-based line of the offending import (the suppression anchor).
84    pub line: u32,
85}
86
87/// A coordination gap projected onto the public-API/contract decision shape: a
88/// changed contract consumed by a module outside the diff.
89#[derive(Debug, Clone)]
90pub struct CoordinationAnchor {
91    /// Root-relative path of the changed file whose contract is consumed elsewhere.
92    pub changed_file: String,
93    /// The consumed symbol names (the contract).
94    pub consumed_symbols: Vec<String>,
95    /// Count of distinct non-diff consumers of this changed file's contract.
96    pub consumer_count: u64,
97    /// 1-based line of the contract symbol's declaration in `changed_file`, so the
98    /// decision deep-links / inline-anchors to the exact export. `0` when the line
99    /// could not be resolved (graph not retained or file unreadable).
100    pub line: u32,
101}
102
103/// Which manifest change a dependency decision frames.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum DependencyChangeKind {
106    /// Entries the base manifest did not declare.
107    Added,
108    /// Entries whose range crossed a major version.
109    MajorBump,
110}
111
112/// One declared dependency entry inside a dependency decision.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct DependencyEntry {
115    /// The package name.
116    pub name: String,
117    /// The manifest section the entry lives in at head (`dependencies`,
118    /// `devDependencies`, `optionalDependencies`, `peerDependencies`).
119    pub section: String,
120    /// The base range; `None` for an added entry.
121    pub from: Option<String>,
122    /// The head range.
123    pub to: String,
124}
125
126/// A changed manifest's dependency candidates of one kind, batch-consolidated
127/// per manifest (rule R1): a reviewer reads "3 new dependencies", never one
128/// decision per package. The importer counts come from the graph's package
129/// usage, so the decision carries the modules the change actually reaches.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct DependencyAnchor {
132    /// Root-relative path of the `package.json` (the decision anchor).
133    pub manifest: String,
134    /// Added entries or major bumps.
135    pub kind: DependencyChangeKind,
136    /// The entries, name-sorted.
137    pub entries: Vec<DependencyEntry>,
138    /// In-repo modules importing any of the entries (the blast).
139    pub importers: u64,
140    /// The subset of `importers` outside the diff (the display number).
141    pub out_of_diff_importers: u64,
142    /// 1-based line of the first entry in the head manifest, `0` when unresolved.
143    pub line: u32,
144}
145
146/// All inputs the extractor needs, gathered from the assembled brief data.
147pub struct DecisionInputs<'a> {
148    /// Diff-aware deltas (boundary + public-API). The candidate source.
149    pub deltas: &'a ReviewDeltas,
150    /// Boundary anchors keyed by zone-pair, one representative per introduced edge.
151    pub boundary_anchors: &'a [BoundaryAnchor],
152    /// Coordination gaps projected to the contract decision shape.
153    pub coordination: &'a [CoordinationAnchor],
154    /// Dependency candidates per changed manifest, one per kind.
155    pub dependency_anchors: &'a [DependencyAnchor],
156    /// 1-based line of the first widened public-API export's declaration, so the
157    /// public-API-surface decision anchors to a real line. `0` when unresolved.
158    pub public_api_anchor_line: u32,
159    /// Project-wide fan-in beyond the diff (impact-closure `affected_not_shown`).
160    /// Used as the blast magnitude for boundary + public-API-surface decisions.
161    pub affected_not_shown: u64,
162    /// Ownership routing (routed expert per file).
163    pub routing: &'a RoutingFacts,
164    /// Per-anchor-file head source, for suppression checks. `None` for a file
165    /// whose head content could not be read (the decision is then not suppressed).
166    pub head_source: &'a dyn Fn(&str) -> Option<String>,
167    /// Resolve a head (post-rename) root-relative path to its pre-rename path, from
168    /// the diff's rename pairs. `None` when the file was not renamed. Lets each
169    /// decision carry a `previous_signal_id` so review memory survives a `git mv`.
170    pub rename_old_path: &'a dyn Fn(&str) -> Option<String>,
171    /// Honest per-anchor in-repo out-of-diff consumer count, precomputed from the
172    /// retained graph's reverse-deps before it was dropped. `0` for an anchor with
173    /// no recorded importers (a genuinely new file). The display number; distinct
174    /// from `affected_not_shown` (the project-wide ranking proxy).
175    pub internal_consumers: &'a dyn Fn(&str) -> u64,
176    /// The decision cap (default 4, clamped to [3, 5] by the caller).
177    pub cap: usize,
178}
179
180/// Resolve the routed expert(s) + bus-factor flag for a decision's anchor file.
181fn route_for(routing: &RoutingFacts, anchor_file: &str) -> (Vec<String>, bool) {
182    routing
183        .units
184        .iter()
185        .find(|unit| unit.file == anchor_file)
186        .map_or((Vec::new(), false), |unit| {
187            (unit.expert.clone(), unit.bus_factor_one)
188        })
189}
190
191/// Whether the head source of `anchor_file` suppresses a decision of `category`
192/// at (1-based) `line`. Honors a file-level `fallow-ignore-file` and a
193/// line-level `fallow-ignore-next-line` immediately above the anchor line, in
194/// both the category-scoped (`decision-surface` / category tag) and bare forms.
195fn is_decision_suppressed(
196    head_source: Option<&str>,
197    category: DecisionCategory,
198    line: u32,
199) -> bool {
200    let Some(source) = head_source else {
201        return false;
202    };
203    let lines: Vec<&str> = source.lines().collect();
204    let token_matches = |comment: &str| {
205        if !comment.contains("fallow-ignore") {
206            return false;
207        }
208        // A bare ignore (no kind) suppresses; a kinded ignore must name the
209        // decision-surface family or this decision's category tag.
210        let after = comment
211            .split_once("fallow-ignore-file")
212            .or_else(|| comment.split_once("fallow-ignore-next-line"))
213            .map(|(_, rest)| rest.trim());
214        match after {
215            None => false,
216            Some("") => true,
217            Some(rest) => {
218                rest.contains("decision-surface")
219                    || rest.contains("decision-surfaces")
220                    || rest.contains(category.tag())
221            }
222        }
223    };
224
225    // File-level: any line carrying a file-level ignore.
226    if lines
227        .iter()
228        .any(|l| l.contains("fallow-ignore-file") && token_matches(l))
229    {
230        return true;
231    }
232    // Line-level: the comment sits immediately above the 1-based anchor line.
233    if line >= 2
234        && let Some(prev) = lines.get((line - 2) as usize)
235        && prev.contains("fallow-ignore-next-line")
236        && token_matches(prev)
237    {
238        return true;
239    }
240    false
241}
242
243/// Frame a coupling/boundary decision as a judgment question.
244fn boundary_question(from_zone: &str, to_zone: &str) -> String {
245    format!(
246        "`{from_zone}` now imports `{to_zone}` for the first time. Intended coupling, or should this edge not exist?"
247    )
248}
249
250/// Frame the (batch-consolidated, R1) public-API-surface decision.
251fn public_api_question(count: usize) -> String {
252    format!(
253        "This change adds {count} export{} to the public API surface. Intended as maintained contracts, or should they stay internal?",
254        if count == 1 { "" } else { "s" }
255    )
256}
257
258/// Frame a coordination-gap (contract consumed outside the diff) decision.
259fn coordination_question(changed_file: &str, symbols: &[String], consumers: u64) -> String {
260    format!(
261        "`{changed_file}` changes {} ({}) imported by {consumers} {} outside this PR. Does this change break or alter what those callers expect?",
262        if symbols.len() == 1 {
263            "export"
264        } else {
265            "exports"
266        },
267        symbols.join(", "),
268        if consumers == 1 { "file" } else { "files" }
269    )
270}
271
272/// Pluralize "module" against a count.
273fn modules_word(n: u64) -> &'static str {
274    if n == 1 { "module" } else { "modules" }
275}
276
277/// Subject-verb agreement for the per-clause count: a singular subject takes the
278/// "-s" verb form ("1 module depends"), plural drops it ("2 modules depend").
279fn agrees(verb_plural: &str, n: u64) -> String {
280    if n == 1 {
281        format!("{verb_plural}s")
282    } else {
283        verb_plural.to_string()
284    }
285}
286
287/// The named structural sacrifice for a coupling/boundary decision, as a FACT.
288/// `consumers` is the honest in-repo out-of-diff count for the anchor.
289fn boundary_tradeoff(from_zone: &str, to_zone: &str, consumers: u64) -> String {
290    format!(
291        "Couples `{from_zone}` to `{to_zone}`; {consumers} in-repo {} already {} on this anchor.",
292        modules_word(consumers),
293        agrees("depend", consumers)
294    )
295}
296
297/// The named structural sacrifice for the public-API-surface decision, as a FACT.
298/// The internal count is internal-only, so the clause also names the external
299/// contract risk in prose (it cannot count a published library's downstream).
300fn public_api_tradeoff(count: usize, consumers: u64) -> String {
301    format!(
302        "Adds {count} maintained contract{}; {consumers} in-repo {} already {} this surface, and any external consumers become a contract you cannot remove without a breaking change.",
303        if count == 1 { "" } else { "s" },
304        modules_word(consumers),
305        agrees("consume", consumers)
306    )
307}
308
309/// The named structural sacrifice for a coordination-gap decision, as a FACT.
310fn coordination_tradeoff(consumers: u64) -> String {
311    format!(
312        "{consumers} {} outside the diff {} this contract; changing its shape requires coordinating them.",
313        modules_word(consumers),
314        agrees("consume", consumers)
315    )
316}
317
318/// The per-decision fields for [`build_decision`], distinct from the shared
319/// run context carried in [`DecisionInputs`].
320struct DecisionSpec {
321    category: DecisionCategory,
322    candidate_key: String,
323    question: String,
324    anchor_file: String,
325    anchor_line: u32,
326    blast: u64,
327    /// Honest per-decision in-repo out-of-diff consumer count (display number).
328    internal_consumer_count: u64,
329    /// The named-sacrifice clause, stated as a fact.
330    tradeoff: String,
331    /// Per-decision override of the category's reversibility weight. A
332    /// dependency ADDED is a permanent new surface (the category weight); a
333    /// MAJOR BUMP reverts with two files and a lockfile, so it ranks with a
334    /// public-API change rather than above it.
335    reversibility_weight: Option<u64>,
336}
337
338/// The reversibility weight a major bump carries: the public-API weight, not
339/// the added-dependency weight.
340const MAJOR_BUMP_REVERSIBILITY_WEIGHT: u64 = 3;
341
342/// Build one decision, resolving its routed expert and suppression state.
343fn build_decision(spec: DecisionSpec, inputs: &DecisionInputs<'_>) -> Decision {
344    let DecisionSpec {
345        category,
346        candidate_key,
347        question,
348        anchor_file,
349        anchor_line,
350        blast,
351        internal_consumer_count,
352        reversibility_weight,
353        tradeoff,
354    } = spec;
355    let signal_id = derive_signal_id(category, &candidate_key);
356    // Rename-durable review memory: if any path embedded in the candidate key was
357    // renamed, derive the signal_id this decision WOULD have had under the old
358    // path so the cloud can carry a prior dismissal across the move.
359    let previous_signal_id = remap_key_paths(&candidate_key, inputs.rename_old_path)
360        .map(|old_key| derive_signal_id(category, &old_key));
361    let (expert, bus_factor_one) = route_for(inputs.routing, &anchor_file);
362    let consequence = blast
363        .saturating_mul(reversibility_weight.unwrap_or_else(|| category.reversibility_weight()));
364    Decision {
365        signal_id,
366        category,
367        question,
368        anchor_file,
369        anchor_line,
370        signal_key: candidate_key,
371        previous_signal_id,
372        blast,
373        consequence,
374        expert,
375        bus_factor_one,
376        internal_consumer_count,
377        tradeoff,
378    }
379}
380
381/// Rebuild a candidate key with every embedded rel path swapped to its pre-rename
382/// form via `rename_old_path`. The key embeds paths as `contract:<path>` or as
383/// `|`-joined `<path>::<name>` components (boundary zone-pair keys carry no path).
384/// Returns the rebuilt, re-sorted key iff at least one path moved, else `None`.
385fn remap_key_paths(key: &str, rename_old_path: &dyn Fn(&str) -> Option<String>) -> Option<String> {
386    let mut moved = false;
387    let mut parts: Vec<String> = key
388        .split('|')
389        .map(|segment| {
390            if let Some(path) = segment.strip_prefix("contract:")
391                && let Some(old) = rename_old_path(path)
392            {
393                moved = true;
394                return format!("contract:{old}");
395            } else if let Some((path, name)) = segment.split_once("::")
396                && let Some(old) = rename_old_path(path)
397            {
398                moved = true;
399                return format!("{old}::{name}");
400            }
401            segment.to_string()
402        })
403        .collect();
404    if !moved {
405        return None;
406    }
407    // The public-API key is the SORTED added-key set joined; re-sort so the rebuilt
408    // key matches what the pre-rename change would have emitted.
409    parts.sort();
410    Some(parts.join("|"))
411}
412
413/// Classify the candidate signals into framed decisions (pre-rank, pre-cap).
414fn classify_candidates(inputs: &DecisionInputs<'_>) -> Vec<Decision> {
415    let mut decisions: Vec<Decision> = Vec::new();
416    append_boundary_decisions(&mut decisions, inputs);
417    append_public_api_decision(&mut decisions, inputs);
418    append_coordination_decisions(&mut decisions, inputs);
419    append_dependency_decisions(&mut decisions, inputs);
420    decisions
421}
422
423/// The stable delta key for one dependency entry: `<manifest>::<name>` for an
424/// added entry, `<manifest>::<name>@<from>-><to>` for a bump. The decision
425/// candidate key joins these with `|`, so the brief's `deltas` and the
426/// decision's `signal_key` name the same change.
427#[must_use]
428pub fn dependency_delta_key(
429    manifest: &str,
430    kind: DependencyChangeKind,
431    entry: &DependencyEntry,
432) -> String {
433    match (kind, &entry.from) {
434        (DependencyChangeKind::MajorBump, Some(from)) => {
435            format!("{manifest}::{}@{from}->{}", entry.name, entry.to)
436        }
437        _ => format!("{manifest}::{}", entry.name),
438    }
439}
440
441/// The candidate key for a dependency anchor: the manifest-scoped entry keys,
442/// name-sorted and `|`-joined, so one manifest yields one stable id per kind.
443/// Built from the same per-entry key the brief's `deltas` carry.
444fn dependency_candidate_key(anchor: &DependencyAnchor) -> String {
445    let keys: Vec<String> = anchor
446        .entries
447        .iter()
448        .map(|entry| dependency_delta_key(&anchor.manifest, anchor.kind, entry))
449        .collect();
450    keys.join("|")
451}
452
453/// A short section tag for anything outside `dependencies`, so a dev tool
454/// never reads as a runtime dependency in the question.
455fn section_tag(section: &str) -> &'static str {
456    match section {
457        "devDependencies" => " (dev)",
458        "optionalDependencies" => " (optional)",
459        "peerDependencies" => " (peer)",
460        _ => "",
461    }
462}
463
464fn dependency_names(anchor: &DependencyAnchor) -> String {
465    anchor
466        .entries
467        .iter()
468        .map(|entry| {
469            let tag = section_tag(&entry.section);
470            match (&anchor.kind, &entry.from) {
471                (DependencyChangeKind::MajorBump, Some(from)) => {
472                    format!("`{}`{tag} {from} -> {}", entry.name, entry.to)
473                }
474                _ => format!("`{}`{tag}", entry.name),
475            }
476        })
477        .collect::<Vec<_>>()
478        .join(", ")
479}
480
481fn dependency_question(anchor: &DependencyAnchor) -> String {
482    let count = anchor.entries.len();
483    let names = dependency_names(anchor);
484    let plural = if count == 1 { "y" } else { "ies" };
485    // Zero importers means the package is reached through the build, a config
486    // file, or types only, so the question points there instead of at modules.
487    let reach = if anchor.importers == 0 {
488        "not imported by any in-repo module".to_string()
489    } else {
490        format!(
491            "imported by {} in-repo {}",
492            anchor.importers,
493            modules_word(anchor.importers)
494        )
495    };
496    match anchor.kind {
497        DependencyChangeKind::Added => format!(
498            "`{}` adds {count} third-party dependenc{plural} ({names}), {reach}. What does each replace, and who owns the new surface?",
499            anchor.manifest,
500        ),
501        DependencyChangeKind::MajorBump if anchor.importers == 0 => format!(
502            "`{}` moves {count} dependenc{plural} across a major version ({names}), {reach}. Which changelog-listed changes reach the build, config, or types?",
503            anchor.manifest,
504        ),
505        DependencyChangeKind::MajorBump => format!(
506            "`{}` moves {count} dependenc{plural} across a major version ({names}), {reach}. Which changelog-listed behavior changes reach those importers?",
507            anchor.manifest,
508        ),
509    }
510}
511
512fn dependency_tradeoff(anchor: &DependencyAnchor) -> String {
513    let count = anchor.entries.len();
514    match anchor.kind {
515        DependencyChangeKind::Added => format!(
516            "Takes on {count} new maintenance and supply-chain surface{}; {} in-repo {} outside this diff already {} the added packages.",
517            if count == 1 { "" } else { "s" },
518            anchor.out_of_diff_importers,
519            modules_word(anchor.out_of_diff_importers),
520            agrees("import", anchor.out_of_diff_importers),
521        ),
522        DependencyChangeKind::MajorBump => format!(
523            "A major bump is a behavior change nobody in this diff wrote; {} in-repo {} outside this diff {} the bumped packages and {} not in the review.",
524            anchor.out_of_diff_importers,
525            modules_word(anchor.out_of_diff_importers),
526            agrees("import", anchor.out_of_diff_importers),
527            if anchor.out_of_diff_importers == 1 {
528                "is"
529            } else {
530                "are"
531            },
532        ),
533    }
534}
535
536fn append_dependency_decisions(decisions: &mut Vec<Decision>, inputs: &DecisionInputs<'_>) {
537    for anchor in inputs.dependency_anchors {
538        if anchor.entries.is_empty() {
539            continue;
540        }
541        decisions.push(build_decision(
542            DecisionSpec {
543                category: DecisionCategory::Dependency,
544                candidate_key: dependency_candidate_key(anchor),
545                question: dependency_question(anchor),
546                tradeoff: dependency_tradeoff(anchor),
547                anchor_file: anchor.manifest.clone(),
548                anchor_line: anchor.line,
549                blast: anchor.importers,
550                internal_consumer_count: anchor.out_of_diff_importers,
551                reversibility_weight: match anchor.kind {
552                    DependencyChangeKind::Added => None,
553                    DependencyChangeKind::MajorBump => Some(MAJOR_BUMP_REVERSIBILITY_WEIGHT),
554                },
555            },
556            inputs,
557        ));
558    }
559}
560
561fn append_boundary_decisions(decisions: &mut Vec<Decision>, inputs: &DecisionInputs<'_>) {
562    for key in &inputs.deltas.boundary_introduced {
563        let anchor = inputs
564            .boundary_anchors
565            .iter()
566            .find(|a| &a.zone_pair_key == key);
567        let (anchor_file, anchor_line, from_zone, to_zone) = anchor.map_or_else(
568            || (String::new(), 0, key.clone(), String::new()),
569            |a| {
570                (
571                    a.from_file.clone(),
572                    a.line,
573                    a.from_zone.clone(),
574                    a.to_zone.clone(),
575                )
576            },
577        );
578        let internal_consumer_count = (inputs.internal_consumers)(&anchor_file);
579        decisions.push(build_decision(
580            DecisionSpec {
581                category: DecisionCategory::CouplingBoundary,
582                candidate_key: key.clone(),
583                question: boundary_question(&from_zone, &to_zone),
584                tradeoff: boundary_tradeoff(&from_zone, &to_zone, internal_consumer_count),
585                anchor_file,
586                anchor_line,
587                blast: inputs.affected_not_shown,
588                internal_consumer_count,
589                reversibility_weight: None,
590            },
591            inputs,
592        ));
593    }
594}
595
596fn append_public_api_decision(decisions: &mut Vec<Decision>, inputs: &DecisionInputs<'_>) {
597    if !inputs.deltas.public_api_added.is_empty() {
598        // The candidate key is the full sorted added-key set joined: one stable
599        // id per change, never one-per-symbol (kills the 111-export noise).
600        let key = inputs.deltas.public_api_added.join("|");
601        let anchor_file = inputs
602            .deltas
603            .public_api_added
604            .first()
605            .and_then(|k| k.split("::").next())
606            .map(str::to_string)
607            .unwrap_or_default();
608        let internal_consumer_count = (inputs.internal_consumers)(&anchor_file);
609        decisions.push(build_decision(
610            DecisionSpec {
611                category: DecisionCategory::PublicApiContract,
612                candidate_key: key,
613                question: public_api_question(inputs.deltas.public_api_added.len()),
614                tradeoff: public_api_tradeoff(
615                    inputs.deltas.public_api_added.len(),
616                    internal_consumer_count,
617                ),
618                anchor_file,
619                anchor_line: inputs.public_api_anchor_line,
620                blast: inputs.affected_not_shown,
621                internal_consumer_count,
622                reversibility_weight: None,
623            },
624            inputs,
625        ));
626    }
627}
628
629fn append_coordination_decisions(decisions: &mut Vec<Decision>, inputs: &DecisionInputs<'_>) {
630    for gap in inputs.coordination {
631        let key = format!("contract:{}", gap.changed_file);
632        decisions.push(build_decision(
633            DecisionSpec {
634                category: DecisionCategory::PublicApiContract,
635                candidate_key: key,
636                question: coordination_question(
637                    &gap.changed_file,
638                    &gap.consumed_symbols,
639                    gap.consumer_count,
640                ),
641                tradeoff: coordination_tradeoff(gap.consumer_count),
642                anchor_file: gap.changed_file.clone(),
643                anchor_line: gap.line,
644                blast: gap.consumer_count,
645                // The coordination arm already carries the honest per-decision
646                // count; no precomputed-map lookup needed.
647                internal_consumer_count: gap.consumer_count,
648                reversibility_weight: None,
649            },
650            inputs,
651        ));
652    }
653}
654
655/// Extract the full decision surface from the assembled brief inputs: classify
656/// the SOLID-3 candidates, anchor each `signal_id`, rank by consequence, cap to
657/// the working-memory limit, collapse the rest, and drop suppressed decisions.
658///
659/// The emitted-signal-id allowlist is built over EVERY classified decision
660/// (before the cap and before suppression drops), so `accept_signal_id` still
661/// recognizes a collapsed-or-suppressed decision's anchor as fallow-emitted.
662#[must_use]
663pub fn extract_decision_surface(inputs: &DecisionInputs<'_>) -> DecisionSurface {
664    let cap = inputs.cap.clamp(MIN_DECISION_CAP, MAX_DECISION_CAP);
665
666    let mut classified = classify_candidates(inputs);
667
668    // The allowlist: every signal_id the deterministic layer emitted.
669    let emitted_signal_ids: Vec<String> = classified.iter().map(|d| d.signal_id.clone()).collect();
670
671    // Drop suppressed decisions (suppression parity): a `// fallow-ignore` on the
672    // anchor hides the decision. Done BEFORE the cap so a suppressed decision does
673    // not consume a slot. The signal_id stays on the allowlist (anchor is still a
674    // real fallow signal), so an agent re-proposing it is not "hallucinating".
675    classified.retain(|d| {
676        let source = (inputs.head_source)(&d.anchor_file);
677        !is_decision_suppressed(source.as_deref(), d.category, d.anchor_line)
678    });
679
680    // Rank by consequence desc; stable, deterministic tiebreak on signal_id.
681    // Rank by consequence, then by the category's reversibility weight, then by
682    // anchor path, so a tie is broken by a stated policy a reviewer can predict
683    // across runs rather than by hash order. The id is the final, total order.
684    classified.sort_by(|a, b| {
685        b.consequence
686            .cmp(&a.consequence)
687            .then_with(|| {
688                b.category
689                    .reversibility_weight()
690                    .cmp(&a.category.reversibility_weight())
691            })
692            .then_with(|| a.anchor_file.cmp(&b.anchor_file))
693            .then_with(|| a.signal_id.cmp(&b.signal_id))
694    });
695
696    let total = classified.len();
697    let truncated = if total > cap {
698        let collapsed = total - cap;
699        classified.truncate(cap);
700        Some(TruncationNote {
701            collapsed,
702            reason: format!(
703                "{collapsed} more structural decision{} collapsed below the cap of {cap}",
704                if collapsed == 1 { "" } else { "s" }
705            ),
706        })
707    } else {
708        None
709    };
710
711    DecisionSurface {
712        decisions: classified,
713        truncated,
714        emitted_signal_ids,
715    }
716}
717
718#[cfg(test)]
719mod tests {
720    use super::*;
721    use fallow_output::RoutingUnit;
722
723    fn deltas(boundary: &[&str], public_api: &[&str]) -> ReviewDeltas {
724        ReviewDeltas {
725            boundary_introduced: boundary.iter().map(|s| (*s).to_string()).collect(),
726            cycle_introduced: Vec::new(),
727            public_api_added: public_api.iter().map(|s| (*s).to_string()).collect(),
728            dependency_added: Vec::new(),
729            dependency_major_bumped: Vec::new(),
730        }
731    }
732
733    fn no_source(_: &str) -> Option<String> {
734        None
735    }
736
737    fn no_consumers(_: &str) -> u64 {
738        0
739    }
740
741    fn inputs<'a>(
742        deltas: &'a ReviewDeltas,
743        boundary_anchors: &'a [BoundaryAnchor],
744        coordination: &'a [CoordinationAnchor],
745        routing: &'a RoutingFacts,
746        head_source: &'a dyn Fn(&str) -> Option<String>,
747        cap: usize,
748    ) -> DecisionInputs<'a> {
749        DecisionInputs {
750            deltas,
751            boundary_anchors,
752            coordination,
753            dependency_anchors: &[],
754            public_api_anchor_line: 0,
755            affected_not_shown: 3,
756            routing,
757            head_source,
758            rename_old_path: &no_source,
759            internal_consumers: &no_consumers,
760            cap,
761        }
762    }
763
764    fn empty_routing() -> RoutingFacts {
765        RoutingFacts::default()
766    }
767
768    // (d) None of the four cut categories can ever appear: the enum has exactly
769    // three discriminants, so this is a compile-time + runtime guarantee.
770    #[test]
771    fn dependency_anchor_becomes_one_batched_dependency_decision() {
772        let deltas = deltas(&[], &[]);
773        let routing = empty_routing();
774        let anchors = vec![
775            DependencyAnchor {
776                manifest: "package.json".to_string(),
777                kind: DependencyChangeKind::MajorBump,
778                entries: vec![
779                    DependencyEntry {
780                        name: "react".to_string(),
781                        section: "dependencies".to_string(),
782                        from: Some("^18.2.0".to_string()),
783                        to: "^19.0.0".to_string(),
784                    },
785                    DependencyEntry {
786                        name: "zod".to_string(),
787                        section: "dependencies".to_string(),
788                        from: Some("^3.0.0".to_string()),
789                        to: "^4.0.0".to_string(),
790                    },
791                ],
792                importers: 12,
793                out_of_diff_importers: 9,
794                line: 14,
795            },
796            DependencyAnchor {
797                manifest: "package.json".to_string(),
798                kind: DependencyChangeKind::Added,
799                entries: vec![DependencyEntry {
800                    name: "dayjs".to_string(),
801                    section: "dependencies".to_string(),
802                    from: None,
803                    to: "^1.11.0".to_string(),
804                }],
805                importers: 0,
806                out_of_diff_importers: 0,
807                line: 9,
808            },
809        ];
810        let surface = extract_decision_surface(&DecisionInputs {
811            deltas: &deltas,
812            boundary_anchors: &[],
813            coordination: &[],
814            dependency_anchors: &anchors,
815            public_api_anchor_line: 0,
816            affected_not_shown: 0,
817            routing: &routing,
818            head_source: &no_source,
819            rename_old_path: &no_source,
820            internal_consumers: &no_consumers,
821            cap: 4,
822        });
823        assert_eq!(
824            surface.decisions.len(),
825            2,
826            "one decision per manifest per kind"
827        );
828        let bump = &surface.decisions[0];
829        assert_eq!(bump.category, DecisionCategory::Dependency);
830        assert_eq!(
831            bump.signal_key,
832            "package.json::react@^18.2.0->^19.0.0|package.json::zod@^3.0.0->^4.0.0"
833        );
834        assert_eq!(bump.anchor_file, "package.json");
835        assert_eq!(bump.anchor_line, 14);
836        assert_eq!(bump.blast, 12);
837        assert_eq!(bump.internal_consumer_count, 9);
838        assert_eq!(
839            bump.consequence,
840            12 * 3,
841            "a major bump ranks with a public-API change, not above it"
842        );
843        assert!(bump.question.contains("`react` ^18.2.0 -> ^19.0.0"));
844        assert!(bump.question.ends_with('?'));
845        assert!(
846            bump.tradeoff
847                .contains("9 in-repo modules outside this diff import")
848        );
849        let added = &surface.decisions[1];
850        assert_eq!(added.signal_key, "package.json::dayjs");
851        assert!(
852            added
853                .question
854                .contains("adds 1 third-party dependency (`dayjs`)")
855        );
856        assert!(
857            added
858                .question
859                .contains("not imported by any in-repo module"),
860            "zero importers points at build, config, or types, not at modules"
861        );
862        assert!(surface.accept_signal_id(&added.signal_id));
863    }
864
865    #[test]
866    fn only_three_categories_exist_no_cut_category_representable() {
867        let all = [
868            DecisionCategory::CouplingBoundary,
869            DecisionCategory::PublicApiContract,
870            DecisionCategory::Dependency,
871        ];
872        assert_eq!(all.len(), 3);
873        // Serialized tags never include a cut-category name.
874        for c in all {
875            let tag = c.tag();
876            for cut in ["abstraction", "deletion", "convention", "irreversib"] {
877                assert!(!tag.contains(cut), "cut category {cut} leaked into {tag}");
878            }
879        }
880    }
881
882    // (a) Every surfaced decision has a signal_id fallow emitted.
883    #[test]
884    fn every_decision_signal_id_resolves_to_an_emitted_candidate() {
885        let d = deltas(&["ui->-db"], &["src/api.ts::Widget"]);
886        let anchors = vec![BoundaryAnchor {
887            zone_pair_key: "ui->-db".to_string(),
888            from_file: "src/ui/page.ts".to_string(),
889            from_zone: "ui".to_string(),
890            to_zone: "db".to_string(),
891            line: 4,
892        }];
893        let routing = empty_routing();
894        let surface = extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &no_source, 4));
895        assert!(!surface.decisions.is_empty());
896        for decision in &surface.decisions {
897            assert!(
898                surface.accept_signal_id(&decision.signal_id),
899                "decision {} has an unanchored signal_id",
900                decision.question
901            );
902        }
903    }
904
905    // (b) An injected decision with no signal anchor is REJECTED.
906    #[test]
907    fn injected_unanchored_signal_id_is_rejected() {
908        let d = deltas(&["ui->-db"], &[]);
909        let anchors = vec![BoundaryAnchor {
910            zone_pair_key: "ui->-db".to_string(),
911            from_file: "src/ui/page.ts".to_string(),
912            from_zone: "ui".to_string(),
913            to_zone: "db".to_string(),
914            line: 1,
915        }];
916        let routing = empty_routing();
917        let surface = extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &no_source, 4));
918        // A fabricated id the deterministic layer never emitted.
919        assert!(!surface.accept_signal_id("sig:deadbeefdeadbeef"));
920        assert!(!surface.accept_signal_id("sig:0000000000000000"));
921        // The real one is accepted.
922        let real = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
923        assert!(surface.accept_signal_id(&real));
924    }
925
926    // (c) A >cap input is capped to 4 plus/minus 1 with a truncation reason.
927    #[test]
928    fn over_cap_input_is_capped_with_truncation_reason() {
929        // 6 boundary edges; default cap 4.
930        let d = deltas(&["a->-x", "b->-x", "c->-x", "d->-x", "e->-x", "f->-x"], &[]);
931        let routing = empty_routing();
932        let surface = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 4));
933        assert_eq!(surface.decisions.len(), 4, "capped to default 4");
934        let note = surface.truncated.expect("truncation note present");
935        assert_eq!(note.collapsed, 2);
936        assert!(note.reason.contains("collapsed"));
937        assert!(note.reason.contains('2'));
938    }
939
940    #[test]
941    fn cap_is_clamped_to_the_4_plus_minus_1_band() {
942        let d = deltas(
943            &[
944                "a->-x", "b->-x", "c->-x", "d->-x", "e->-x", "f->-x", "g->-x",
945            ],
946            &[],
947        );
948        let routing = empty_routing();
949        // cap=10 clamps to MAX (5).
950        let high = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 10));
951        assert_eq!(high.decisions.len(), MAX_DECISION_CAP);
952        // cap=1 clamps to MIN (3).
953        let low = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 1));
954        assert_eq!(low.decisions.len(), MIN_DECISION_CAP);
955    }
956
957    // (e) A `// fallow-ignore` suppresses a flagged decision.
958    #[test]
959    fn fallow_ignore_suppresses_a_flagged_decision() {
960        let d = deltas(&["ui->-db"], &[]);
961        let anchors = vec![BoundaryAnchor {
962            zone_pair_key: "ui->-db".to_string(),
963            from_file: "src/ui/page.ts".to_string(),
964            from_zone: "ui".to_string(),
965            to_zone: "db".to_string(),
966            line: 3,
967        }];
968        let routing = empty_routing();
969
970        // No suppression: one decision surfaces.
971        let unsuppressed =
972            extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &no_source, 4));
973        assert_eq!(unsuppressed.decisions.len(), 1);
974
975        // File-level suppression hides it.
976        let file_src = |f: &str| {
977            (f == "src/ui/page.ts").then(|| {
978                "// fallow-ignore-file decision-surface\nimport db from 'db';\n".to_string()
979            })
980        };
981        let suppressed =
982            extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &file_src, 4));
983        assert!(
984            suppressed.decisions.is_empty(),
985            "file-level ignore hides it"
986        );
987        // But the signal id stays on the allowlist (the anchor is still real).
988        let id = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
989        assert!(suppressed.accept_signal_id(&id));
990
991        // Line-level suppression immediately above the anchor line also hides it.
992        let line_src = |f: &str| {
993            (f == "src/ui/page.ts").then(|| {
994                "line1\n// fallow-ignore-next-line decision-surface\nimport db from 'db';\n"
995                    .to_string()
996            })
997        };
998        let line_suppressed =
999            extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &line_src, 4));
1000        assert!(
1001            line_suppressed.decisions.is_empty(),
1002            "line-level ignore hides it"
1003        );
1004    }
1005
1006    #[test]
1007    fn bare_blanket_ignore_suppresses_without_a_kind() {
1008        let d = deltas(&["ui->-db"], &[]);
1009        let anchors = vec![BoundaryAnchor {
1010            zone_pair_key: "ui->-db".to_string(),
1011            from_file: "src/ui/page.ts".to_string(),
1012            from_zone: "ui".to_string(),
1013            to_zone: "db".to_string(),
1014            line: 2,
1015        }];
1016        let routing = empty_routing();
1017        let bare = |f: &str| {
1018            (f == "src/ui/page.ts")
1019                .then(|| "// fallow-ignore-next-line\nimport db from 'db';\n".to_string())
1020        };
1021        let surface = extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &bare, 4));
1022        assert!(surface.decisions.is_empty(), "bare blanket ignore hides it");
1023    }
1024
1025    #[test]
1026    fn unrelated_kind_ignore_does_not_suppress() {
1027        let d = deltas(&["ui->-db"], &[]);
1028        let anchors = vec![BoundaryAnchor {
1029            zone_pair_key: "ui->-db".to_string(),
1030            from_file: "src/ui/page.ts".to_string(),
1031            from_zone: "ui".to_string(),
1032            to_zone: "db".to_string(),
1033            line: 2,
1034        }];
1035        let routing = empty_routing();
1036        let other = |f: &str| {
1037            (f == "src/ui/page.ts").then(|| {
1038                "// fallow-ignore-next-line unused-export\nimport db from 'db';\n".to_string()
1039            })
1040        };
1041        let surface = extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &other, 4));
1042        assert_eq!(
1043            surface.decisions.len(),
1044            1,
1045            "an ignore naming a different kind must not suppress a decision"
1046        );
1047    }
1048
1049    #[test]
1050    fn routed_expert_is_paired_with_a_decision() {
1051        let d = deltas(&["ui->-db"], &[]);
1052        let anchors = vec![BoundaryAnchor {
1053            zone_pair_key: "ui->-db".to_string(),
1054            from_file: "src/ui/page.ts".to_string(),
1055            from_zone: "ui".to_string(),
1056            to_zone: "db".to_string(),
1057            line: 1,
1058        }];
1059        let routing = RoutingFacts {
1060            units: vec![RoutingUnit {
1061                file: "src/ui/page.ts".to_string(),
1062                expert: vec!["@team/ui".to_string()],
1063                bus_factor_one: true,
1064            }],
1065        };
1066        let surface = extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &no_source, 4));
1067        assert_eq!(surface.decisions.len(), 1);
1068        assert_eq!(surface.decisions[0].expert, vec!["@team/ui".to_string()]);
1069        assert!(surface.decisions[0].bus_factor_one);
1070    }
1071
1072    #[test]
1073    fn public_api_is_batch_consolidated_to_one_decision_r1() {
1074        // 111 added export keys collapse to ONE public-API decision (R1).
1075        let keys: Vec<String> = (0..111).map(|i| format!("src/ui/index.ts::C{i}")).collect();
1076        let key_refs: Vec<&str> = keys.iter().map(String::as_str).collect();
1077        let d = deltas(&[], &key_refs);
1078        let routing = empty_routing();
1079        let surface = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 4));
1080        let public_api_count = surface
1081            .decisions
1082            .iter()
1083            .filter(|dec| dec.category == DecisionCategory::PublicApiContract)
1084            .count();
1085        assert_eq!(
1086            public_api_count, 1,
1087            "R1: one public-API decision per change"
1088        );
1089        assert!(surface.decisions[0].question.contains("111"));
1090    }
1091
1092    #[test]
1093    fn public_api_decision_carries_honest_consumer_count_and_tradeoff() {
1094        // A public-API delta whose anchor has 7 in-repo out-of-diff consumers must
1095        // surface that honest number on the decision AND name it as a fact in the
1096        // trade-off clause, distinct from the project-wide ranking proxy (`blast`).
1097        let d = deltas(&[], &["src/ui/index.ts::Widget"]);
1098        let routing = empty_routing();
1099        let seven = |_: &str| 7u64;
1100        let surface = extract_decision_surface(&DecisionInputs {
1101            deltas: &d,
1102            boundary_anchors: &[],
1103            coordination: &[],
1104            dependency_anchors: &[],
1105            public_api_anchor_line: 0,
1106            // The project-wide proxy must NOT become the display number.
1107            affected_not_shown: 99,
1108            routing: &routing,
1109            head_source: &no_source,
1110            rename_old_path: &no_source,
1111            internal_consumers: &seven,
1112            cap: 4,
1113        });
1114        let dec = surface
1115            .decisions
1116            .iter()
1117            .find(|dec| dec.category == DecisionCategory::PublicApiContract)
1118            .expect("a public-API decision");
1119        assert_eq!(dec.internal_consumer_count, 7, "honest per-anchor count");
1120        assert_ne!(
1121            dec.internal_consumer_count, dec.blast,
1122            "display number must stay distinct from the ranking proxy"
1123        );
1124        assert!(
1125            dec.tradeoff.contains("7 in-repo"),
1126            "trade-off clause states the count as a fact: {}",
1127            dec.tradeoff
1128        );
1129        assert!(
1130            dec.question.ends_with('?'),
1131            "the decision stays a question (taste ownership)"
1132        );
1133    }
1134
1135    #[test]
1136    fn coordination_gap_becomes_a_public_api_contract_decision() {
1137        let d = deltas(&[], &[]);
1138        let coordination = vec![CoordinationAnchor {
1139            changed_file: "src/core.ts".to_string(),
1140            consumed_symbols: vec!["compute".to_string()],
1141            consumer_count: 4,
1142            line: 7,
1143        }];
1144        let routing = empty_routing();
1145        let surface =
1146            extract_decision_surface(&inputs(&d, &[], &coordination, &routing, &no_source, 4));
1147        assert_eq!(surface.decisions.len(), 1);
1148        assert_eq!(
1149            surface.decisions[0].category,
1150            DecisionCategory::PublicApiContract
1151        );
1152        assert_eq!(surface.decisions[0].blast, 4);
1153        // The contract symbol's declaration line flows onto the decision so a PR
1154        // review can anchor an inline comment to the exact export.
1155        assert_eq!(surface.decisions[0].anchor_line, 7);
1156        assert!(surface.decisions[0].previous_signal_id.is_none());
1157    }
1158
1159    #[test]
1160    fn renamed_anchor_carries_a_previous_signal_id_for_review_memory() {
1161        // A coordination decision on a file renamed src/old.ts -> src/new.ts. The
1162        // signal_id keys on the NEW path; previous_signal_id keys on the OLD path,
1163        // so a cloud memory layer carries a prior dismissal across the `git mv`.
1164        let d = deltas(&[], &[]);
1165        let coordination = vec![CoordinationAnchor {
1166            changed_file: "src/new.ts".to_string(),
1167            consumed_symbols: vec!["compute".to_string()],
1168            consumer_count: 2,
1169            line: 0,
1170        }];
1171        let routing = empty_routing();
1172        let rename = |rel: &str| -> Option<String> {
1173            (rel == "src/new.ts").then(|| "src/old.ts".to_string())
1174        };
1175        let surface = extract_decision_surface(&DecisionInputs {
1176            deltas: &d,
1177            boundary_anchors: &[],
1178            coordination: &coordination,
1179            dependency_anchors: &[],
1180            public_api_anchor_line: 0,
1181            affected_not_shown: 2,
1182            routing: &routing,
1183            head_source: &no_source,
1184            rename_old_path: &rename,
1185            internal_consumers: &no_consumers,
1186            cap: 4,
1187        });
1188        assert_eq!(surface.decisions.len(), 1);
1189        let decision = &surface.decisions[0];
1190        assert_eq!(
1191            decision.signal_id,
1192            derive_signal_id(DecisionCategory::PublicApiContract, "contract:src/new.ts")
1193        );
1194        assert_eq!(
1195            decision.previous_signal_id,
1196            Some(derive_signal_id(
1197                DecisionCategory::PublicApiContract,
1198                "contract:src/old.ts"
1199            ))
1200        );
1201    }
1202
1203    #[test]
1204    fn signal_id_is_deterministic_and_namespaced_by_category() {
1205        let a = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
1206        let b = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
1207        assert_eq!(a, b, "deterministic");
1208        let c = derive_signal_id(DecisionCategory::PublicApiContract, "ui->-db");
1209        assert_ne!(a, c, "category namespaces the hash");
1210        assert!(a.starts_with("sig:"));
1211    }
1212
1213    #[test]
1214    fn consequence_ranks_less_reversible_categories_higher() {
1215        // Same blast: dependency > public-api > coupling on reversibility weight.
1216        let dep = DecisionCategory::Dependency.reversibility_weight();
1217        let api = DecisionCategory::PublicApiContract.reversibility_weight();
1218        let coupling = DecisionCategory::CouplingBoundary.reversibility_weight();
1219        assert!(dep > api && api > coupling);
1220    }
1221}