mod adaptive;
mod context;
pub(crate) mod furniture;
mod queue;
mod weights;
pub(crate) use adaptive::{Adaptive, MIN_RELEVANCE};
pub(crate) use context::link_contexts;
use context::prose_words;
pub(crate) use queue::{BestFirst, Offer, cluster_key};
use pagesift_extract::Query;
use pagesift_net::Url;
use weights::TermWeights;
const W_ANCHOR: f32 = 2.0;
const W_LOCATOR: f32 = 1.5;
const W_CONTEXT: f32 = 1.0;
const W_PARENT: f32 = 0.5;
const PHRASE_BONUS: f32 = 0.5;
const DEPTH_DECAY: f32 = 0.9;
const LANGUAGE_PORTAL_SCORE: f32 = 0.6;
const SECTION_PRIOR: f32 = furniture::FURNITURE_FACTOR * (W_ANCHOR * 0.5 + PHRASE_BONUS);
const SUBSITE_PRIOR: f32 = SECTION_PRIOR * 0.5;
const FOREIGN_LANGUAGE_FACTOR: f32 = furniture::FURNITURE_FACTOR;
pub(crate) const LIST_FREE: usize = 8;
pub(crate) struct Focus {
pub query: Query,
weights: TermWeights,
host: Option<String>,
english_home: bool,
}
impl Focus {
pub(crate) fn new(query: &str) -> Self {
let query = Query::new(query);
let weights = TermWeights::new(query.len());
Self {
query,
weights,
host: None,
english_home: false,
}
}
pub(crate) fn found_english_home(&mut self) {
self.english_home = true;
}
pub(crate) fn with_host(mut self, host: &str) -> Self {
self.host = Some(host.trim_start_matches("www.").to_ascii_lowercase());
self
}
fn same_host(&self, url: &Url) -> bool {
match (&self.host, url.host_str()) {
(Some(h), Some(u)) => u.trim_start_matches("www.").eq_ignore_ascii_case(h),
_ => true,
}
}
fn english_entry(&self, url: &Url, anchor: Option<&str>) -> bool {
if self.same_host(url) {
return language_portal(url, anchor);
}
let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
let same_site = self
.host
.as_deref()
.is_none_or(|h| pagesift_content::site_key(h) == pagesift_content::site_key(&host));
let english_label = matches!(
host.split('.').next().unwrap_or_default(),
"en" | "eng" | "english"
);
let root = url.path().split('/').filter(|s| !s.is_empty()).count() == 0;
same_site && english_label && root
}
pub(crate) fn observe_page(&mut self, markdown: &str) {
self.weights.observe(self.query.hit_mask(markdown));
}
fn coverage(&self, text: &str) -> f32 {
self.weights.coverage(self.query.hit_mask(text))
}
pub(crate) fn page_relevance(
&self,
url: &Url,
title: Option<&str>,
markdown: &str,
links: usize,
) -> f32 {
let mut r = 0.5 * self.coverage(title.unwrap_or_default()) + 0.5 * self.coverage(markdown);
if furniture::is_hub(links, prose_words(markdown)) {
r *= furniture::HUB_FACTOR;
}
if furniture::is_furniture_url(url, &self.wanted()) {
r *= furniture::FURNITURE_FACTOR;
}
r
}
fn wanted(&self) -> impl Fn(&str) -> bool {
let query = &self.query;
move |w: &str| query.hit_mask(w) != 0
}
pub(crate) fn link_score(
&self,
url: &Url,
anchor: Option<&str>,
context: Option<&str>,
parent: f32,
depth: usize,
) -> f32 {
let anchor_mask = self.query.hit_mask(anchor.unwrap_or_default());
let mut raw = W_ANCHOR * self.weights.coverage(anchor_mask)
+ W_LOCATOR * self.coverage(&locator(url))
+ W_CONTEXT * self.coverage(context.unwrap_or_default())
+ W_PARENT * parent;
if anchor_mask.count_ones() >= 2 {
raw += PHRASE_BONUS;
}
let wanted = self.wanted();
let furniture = furniture::is_furniture_url(url, &wanted)
|| anchor.is_some_and(|a| furniture::is_furniture_anchor(a, &wanted));
if furniture::is_dated_url(url) {
raw *= furniture::DATED_FACTOR;
} else if furniture {
raw *= furniture::FURNITURE_FACTOR;
} else if self.english() && foreign_language_segment(url) {
raw *= FOREIGN_LANGUAGE_FACTOR;
} else if self.english() && !self.english_home && self.english_entry(url, anchor) {
raw = raw.max(LANGUAGE_PORTAL_SCORE);
} else {
match section(url, anchor) {
Some(Section::SameHost) if self.same_host(url) => raw = raw.max(SECTION_PRIOR),
Some(_) => raw = raw.max(SUBSITE_PRIOR),
None => {}
}
}
raw * DEPTH_DECAY.powi(depth.min(64) as i32)
}
pub(crate) fn is_language_portal(&self, url: &Url) -> bool {
self.english() && !self.english_home && self.english_entry(url, None)
}
pub(crate) fn alternate_score(&self, lang: &str, depth: usize) -> Option<f32> {
let english = lang == "en" || lang.starts_with("en-");
(self.english() && english && depth == 0 && !self.english_home)
.then_some(LANGUAGE_PORTAL_SCORE)
}
fn english(&self) -> bool {
self.query.terms().iter().all(|t| t.is_ascii())
}
}
#[derive(PartialEq, Eq, Debug)]
enum Section {
SameHost,
Subsite,
}
fn section(url: &Url, anchor: Option<&str>) -> Option<Section> {
let mut segs: Vec<&str> = url.path().split('/').filter(|s| !s.is_empty()).collect();
if segs.first().is_some_and(|s| is_language_code(s)) {
segs.remove(0);
}
let segments = segs.len();
let short = anchor.is_some_and(|a| (1..=4).contains(&a.split_whitespace().count()));
if !short || url.query().is_some() {
return None;
}
match segments {
0 => Some(Section::Subsite),
1 => Some(Section::SameHost),
_ => None,
}
}
fn foreign_language_segment(url: &Url) -> bool {
const CODES: &[&str] = &[
"de", "fr", "es", "it", "nl", "pt", "ru", "ja", "jp", "zh", "zh-cn", "zh-tw", "zh-hans",
"zh-hant", "ko", "kr", "ar", "sv", "fi", "da", "no", "nb", "pl", "tr", "cs", "el", "he",
"hi", "th", "vi", "id", "hu", "ro", "uk", "ca", "eu", "gl", "cy", "ga", "mi",
];
url.path()
.split('/')
.filter(|s| !s.is_empty())
.any(|seg| CODES.contains(&language_code(seg).as_str()))
}
fn language_portal(url: &Url, anchor: Option<&str>) -> bool {
let anchor = anchor.unwrap_or_default().trim().to_ascii_lowercase();
if matches!(
anchor.as_str(),
"english"
| "en"
| "eng"
| "in english"
| "english site"
| "english version"
| "english page"
| "english top"
| "english home"
) {
return true;
}
url.path()
.split('/')
.rfind(|seg| !seg.is_empty())
.is_some_and(|seg| {
matches!(
language_code(seg).as_str(),
"en" | "english" | "en-us" | "en-gb"
)
})
}
fn is_language_code(seg: &str) -> bool {
let code = language_code(seg);
let two = |p: &str| p.len() == 2 && p.bytes().all(|b| b.is_ascii_alphabetic());
two(&code)
|| code
.split_once('-')
.is_some_and(|(a, b)| two(a) && (2..=4).contains(&b.len()))
}
fn language_code(seg: &str) -> String {
seg.split_once('.')
.map_or(seg, |(s, _)| s)
.to_ascii_lowercase()
}
fn locator(url: &Url) -> String {
let mut s = String::with_capacity(url.as_str().len());
if let Some(host) = url.host_str() {
for label in host.split('.') {
if label != "www" {
s.push_str(label);
s.push(' ');
}
}
}
s.push_str(url.path());
if let Some(q) = url.query() {
s.push(' ');
s.push_str(q);
}
s
}
#[cfg(test)]
mod tests {
use super::*;
fn u(s: &str) -> Url {
Url::parse(s).unwrap()
}
#[test]
fn relevant_links_score_higher_and_depth_decays() {
let f = Focus::new("refund policy");
let good = f.link_score(
&u("https://e.com/help/refund-policy"),
Some("Refund policy"),
None,
0.0,
1,
);
let ctx = f.link_score(
&u("https://e.com/help/x"),
Some("here"),
Some("Read our refund policy here"),
0.0,
1,
);
let bad = f.link_score(&u("https://e.com/team/x"), Some("Our team"), None, 0.0, 1);
assert!(good > ctx && ctx > bad, "{good} {ctx} {bad}");
assert_eq!(bad, 0.0);
let section = f.link_score(&u("https://e.com/docs/"), Some("Docs"), None, 0.0, 1);
let dated = f.link_score(
&u("https://e.com/blog/2026/04/refund-story/"),
Some("A refund story"),
None,
0.0,
1,
);
assert!(section > dated && dated > 0.0, "{section} {dated}");
assert!(section < ctx, "{section} {ctx}");
let subsite = f.link_score(&u("https://inf.e.com/"), Some("Informatics"), None, 0.0, 1);
let german = f.link_score(&u("https://e.com/de/"), Some("Deutsch"), None, 0.0, 1);
assert!(
subsite < section && subsite > german,
"{section} {subsite} {german}"
);
assert!(f.alternate_score("en-gb", 0).is_some());
assert!(f.alternate_score("de", 0).is_none());
assert!(
f.alternate_score("en", 1).is_none(),
"only the seed's alternate"
);
let en_section = f.link_score(
&u("https://e.com/en/studies/"),
Some("Studies"),
None,
0.0,
1,
);
assert!(
(en_section - section).abs() < 1e-6,
"{en_section} {section}"
);
assert!(f.is_language_portal(&u("https://e.com/en/")));
assert!(f.is_language_portal(&u("https://e.com/en.html")));
assert!(!f.is_language_portal(&u("https://e.com/en/docs/")));
let g = Focus::new("api authentication").with_host("www.e.com");
let own = g.link_score(&u("https://e.com/en/"), Some("English"), None, 0.0, 1);
let dept = g.link_score(&u("https://cs.e.com/en/"), Some("English"), None, 0.0, 1);
assert!(own > dept && dept < section, "{own} {dept} {section}");
assert!(!g.is_language_portal(&u("https://cs.e.com/en/")));
assert!(g.is_language_portal(&u("https://en.e.com/")));
assert!(!g.is_language_portal(&u("https://en.other.com/")));
assert!(!g.is_language_portal(&u("https://en.e.com/news/")));
let mut g = g;
g.found_english_home();
let later = g.link_score(
&u("https://e.com/staff/en.html"),
Some("English"),
None,
0.0,
1,
);
assert!(later < own, "{later} {own}");
assert!(!g.is_language_portal(&u("https://e.com/en/")));
let api = Focus::new("api authentication");
let reference = api.link_score(
&u("https://e.com/docs/api/"),
Some("API reference"),
None,
0.0,
2,
);
let blog = api.link_score(
&u("https://e.com/blog/api-news/"),
Some("API news"),
None,
0.0,
2,
);
assert!(reference > 2.0 * blog, "{reference} {blog}");
let deep = f.link_score(
&u("https://e.com/help/refund-policy"),
Some("Refund policy"),
None,
0.0,
3,
);
assert!(deep < good);
let parent = f.link_score(&u("https://e.com/team/x"), Some("Our team"), None, 1.0, 1);
assert!(parent > bad);
let home = u("https://e.com/");
assert!(
f.page_relevance(&home, Some("Refund policy"), "refund", 3)
> f.page_relevance(&home, None, "refund", 3)
);
}
#[test]
fn furniture_and_hubs_are_demoted() {
let f = Focus::new("international students admission");
let content = f.link_score(
&u("https://e.edu/admissions/international/"),
Some("International students"),
None,
0.2,
2,
);
let news = f.link_score(
&u("https://e.edu/news/2026/05/story-1/"),
Some("International students celebrate the festival"),
None,
0.2,
1,
);
assert!(content > news, "{content} {news}");
let about = f.link_score(&u("https://e.edu/about/"), Some("About"), None, 0.9, 1);
let study = f.link_score(&u("https://e.edu/study/"), Some("Study"), None, 0.9, 1);
assert!(about < study);
let home = u("https://e.edu/");
let text = "international students admission";
let article = f.page_relevance(&home, None, text, 3);
let hub = f.page_relevance(&home, None, text, 40);
let list = "- [International students admission](https://e.edu/a)\n- [International students admission](https://e.edu/b)\n- [International students admission](https://e.edu/c)\n- [International students admission](https://e.edu/d)\n- [International students admission](https://e.edu/e)\n- [International students admission](https://e.edu/f)\n- [International students admission](https://e.edu/g)\n- [International students admission](https://e.edu/h)\n";
assert!(f.page_relevance(&home, None, list, 8) < article);
let dated = f.page_relevance(&u("https://e.edu/news/2026/"), None, text, 3);
assert!(hub < article && dated < article, "{article} {hub} {dated}");
}
#[test]
fn host_labels_count_and_common_terms_fade() {
let mut f = Focus::new("international students visa");
let intl = f.link_score(&u("https://international.e.edu/"), None, None, 0.0, 1);
let plain = f.link_score(&u("https://www.e.edu/"), None, None, 0.0, 1);
assert!(intl > plain && plain == 0.0, "{intl} {plain}");
for i in 0..6 {
f.observe_page(if i == 0 {
"students visa"
} else {
"students and more students"
});
}
let students = f.link_score(&u("https://e.edu/x"), Some("students"), None, 0.0, 1);
let visa = f.link_score(&u("https://e.edu/y"), Some("visa"), None, 0.0, 1);
assert!(visa > students, "{visa} {students}");
}
}