1pub 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
48pub const DEFAULT_DECISION_CAP: usize = 4;
51pub const MIN_DECISION_CAP: usize = 3;
53pub const MAX_DECISION_CAP: usize = 5;
55
56#[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#[derive(Debug, Clone)]
73pub struct BoundaryAnchor {
74 pub zone_pair_key: String,
77 pub from_file: String,
79 pub from_zone: String,
81 pub to_zone: String,
83 pub line: u32,
85}
86
87#[derive(Debug, Clone)]
90pub struct CoordinationAnchor {
91 pub changed_file: String,
93 pub consumed_symbols: Vec<String>,
95 pub consumer_count: u64,
97 pub line: u32,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum DependencyChangeKind {
106 Added,
108 MajorBump,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct DependencyEntry {
115 pub name: String,
117 pub section: String,
120 pub from: Option<String>,
122 pub to: String,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct DependencyAnchor {
132 pub manifest: String,
134 pub kind: DependencyChangeKind,
136 pub entries: Vec<DependencyEntry>,
138 pub importers: u64,
140 pub out_of_diff_importers: u64,
142 pub line: u32,
144}
145
146pub struct DecisionInputs<'a> {
148 pub deltas: &'a ReviewDeltas,
150 pub boundary_anchors: &'a [BoundaryAnchor],
152 pub coordination: &'a [CoordinationAnchor],
154 pub dependency_anchors: &'a [DependencyAnchor],
156 pub public_api_anchor_line: u32,
159 pub affected_not_shown: u64,
162 pub routing: &'a RoutingFacts,
164 pub head_source: &'a dyn Fn(&str) -> Option<String>,
167 pub rename_old_path: &'a dyn Fn(&str) -> Option<String>,
171 pub internal_consumers: &'a dyn Fn(&str) -> u64,
176 pub cap: usize,
178}
179
180fn 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
191fn 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 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 if lines
227 .iter()
228 .any(|l| l.contains("fallow-ignore-file") && token_matches(l))
229 {
230 return true;
231 }
232 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
243fn 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
250fn 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
258fn 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
272fn modules_word(n: u64) -> &'static str {
274 if n == 1 { "module" } else { "modules" }
275}
276
277fn 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
287fn 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
297fn 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
309fn 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
318struct DecisionSpec {
321 category: DecisionCategory,
322 candidate_key: String,
323 question: String,
324 anchor_file: String,
325 anchor_line: u32,
326 blast: u64,
327 internal_consumer_count: u64,
329 tradeoff: String,
331 reversibility_weight: Option<u64>,
336}
337
338const MAJOR_BUMP_REVERSIBILITY_WEIGHT: u64 = 3;
341
342fn 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 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
381fn 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 parts.sort();
410 Some(parts.join("|"))
411}
412
413fn 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#[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
441fn 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
453fn 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 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 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 internal_consumer_count: gap.consumer_count,
648 reversibility_weight: None,
649 },
650 inputs,
651 ));
652 }
653}
654
655#[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 let emitted_signal_ids: Vec<String> = classified.iter().map(|d| d.signal_id.clone()).collect();
670
671 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 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 #[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 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 #[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 #[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 assert!(!surface.accept_signal_id("sig:deadbeefdeadbeef"));
920 assert!(!surface.accept_signal_id("sig:0000000000000000"));
921 let real = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
923 assert!(surface.accept_signal_id(&real));
924 }
925
926 #[test]
928 fn over_cap_input_is_capped_with_truncation_reason() {
929 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 let high = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 10));
951 assert_eq!(high.decisions.len(), MAX_DECISION_CAP);
952 let low = extract_decision_surface(&inputs(&d, &[], &[], &routing, &no_source, 1));
954 assert_eq!(low.decisions.len(), MIN_DECISION_CAP);
955 }
956
957 #[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 let unsuppressed =
972 extract_decision_surface(&inputs(&d, &anchors, &[], &routing, &no_source, 4));
973 assert_eq!(unsuppressed.decisions.len(), 1);
974
975 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 let id = derive_signal_id(DecisionCategory::CouplingBoundary, "ui->-db");
989 assert!(suppressed.accept_signal_id(&id));
990
991 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 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 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 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 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 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 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}