Skip to content

AI powered OSINT engine to discover and map 840+ social media identities across the web

feat: external tool baselines evaluated over the frozen corpus

arxhr007a3564ca8eda7
diff --git a/src/aliens_eye/cli.py b/src/aliens_eye/cli.py
index 0980dd8..b60924c 100644
--- a/src/aliens_eye/cli.py
+++ b/src/aliens_eye/cli.py
@@ -177,6 +177,25 @@ def build_selfcheck_parser() -> ArgumentParser:
"--report", choices=["table", "json"], default="table",
help="Output format: rich table (default) or machine-readable JSON",
)
+ parser.add_argument(
+ "--split", choices=["train", "holdout", "all"], default="train",
+ help="Ground-truth split to score: train (default), holdout (sites the "
+ "model never trained on), or all",
+ )
+ parser.add_argument(
+ "--ground-truth", type=str,
+ help="Path to a custom ground-truth JSON (overrides --split)",
+ )
+ parser.add_argument(
+ "--corpus", type=str,
+ help="Score against a frozen response corpus instead of the live web "
+ "(reproducible; see 'aliens_eye corpus record')",
+ )
+ parser.add_argument(
+ "--allow-corpus-misses", action="store_true",
+ help="With --corpus, score URLs absent from the corpus as fetch errors "
+ "instead of failing loudly",
+ )
return parser
@@ -192,6 +211,15 @@ def build_train_parser() -> ArgumentParser:
collect.add_argument("--negatives", type=int, default=2, help="Negative samples per site")
collect.add_argument("--seed", type=int, default=None, help="Random seed")
collect.add_argument("--sites", type=str, help="Path to a custom sites JSON")
+ collect.add_argument(
+ "--split", choices=["train", "holdout", "all"], default="train",
+ help="Ground-truth split to collect from. Defaults to train; anything "
+ "else reintroduces train/eval leakage and requires --allow-leakage",
+ )
+ collect.add_argument(
+ "--allow-leakage", action="store_true",
+ help="Permit collecting training data from a non-train split (research use only)",
+ )
collect.add_argument("-v", "--verbose", action="store_true")
fit = sub.add_parser("fit", help="Train the model from a labeled dataset CSV")
@@ -201,6 +229,96 @@ def build_train_parser() -> ArgumentParser:
return parser
+def build_corpus_parser() -> ArgumentParser:
+ parser = ArgumentParser(
+ prog="aliens_eye corpus",
+ description="Record and inspect a frozen response corpus for reproducible evaluation",
+ )
+ sub = parser.add_subparsers(dest="corpus_command", required=True)
+
+ record = sub.add_parser("record", help="Capture live responses for the ground-truth accounts")
+ record.add_argument("--out", type=str, required=True, help="Corpus directory to write")
+ record.add_argument(
+ "--split", choices=["train", "holdout", "all"], default="all",
+ help="Ground-truth split to capture (default: all)",
+ )
+ record.add_argument("--ground-truth", type=str, help="Custom ground-truth JSON (overrides --split)")
+ record.add_argument("--negatives", type=int, default=4, help="Negative usernames per site")
+ record.add_argument(
+ "--plausible-ratio", type=float, default=0.5,
+ help="Fraction of negatives with realistic handle morphology rather than random strings",
+ )
+ record.add_argument("--seed", type=int, default=1234, help="Seed for negative generation")
+ record.add_argument("--concurrency", type=int, default=20)
+ record.add_argument("--timeout", type=float, default=15.0)
+ record.add_argument("--sites", type=str, help="Path to a custom sites JSON")
+ record.add_argument("-v", "--verbose", action="store_true")
+
+ stats = sub.add_parser("stats", help="Summarise a recorded corpus")
+ stats.add_argument("path", type=str, help="Corpus directory")
+ stats.add_argument("--json", action="store_true", dest="json_out", help="Machine-readable output")
+ stats.add_argument("-v", "--verbose", action="store_true")
+ return parser
+
+
+def build_eval_parser() -> ArgumentParser:
+ parser = ArgumentParser(
+ prog="aliens_eye eval",
+ description="Reproducible detector evaluation over a frozen corpus",
+ )
+ sub = parser.add_subparsers(dest="eval_command", required=True)
+
+ ablate = sub.add_parser(
+ "ablate", help="Score detector configurations over a corpus (baselines, judges, feature groups)"
+ )
+ ablate.add_argument("--corpus", type=str, required=True, help="Corpus directory")
+ ablate.add_argument(
+ "--split", choices=["train", "holdout", "all"], default="holdout",
+ help="Ground-truth split to score (default: holdout)",
+ )
+ ablate.add_argument("--ground-truth", type=str, help="Custom ground-truth JSON")
+ ablate.add_argument("--model", type=str, help="Path to a custom ML model JSON")
+ ablate.add_argument(
+ "--only", type=str,
+ help="Comma-separated ablation names to run (default: all)",
+ )
+ ablate.add_argument(
+ "--fingerprints", action="store_true",
+ help="Enable the fingerprint store, populated in a fixed order",
+ )
+ ablate.add_argument("--out", type=str, help="Write the full result bundle as JSON here")
+ ablate.add_argument("--json", action="store_true", dest="json_out", help="Print JSON to stdout")
+ ablate.add_argument("-v", "--verbose", action="store_true")
+
+ external = sub.add_parser(
+ "external",
+ help="Compare against external tool rule sets (Sherlock / Maigret / WhatsMyName) over the corpus",
+ )
+ external.add_argument("--corpus", type=str, required=True, help="Corpus directory")
+ external.add_argument(
+ "--split", choices=["train", "holdout", "all"], default="all",
+ help="Ground-truth split to score (default: all)",
+ )
+ external.add_argument("--ground-truth", type=str, help="Custom ground-truth JSON")
+ external.add_argument("--model", type=str, help="Path to a custom ML model JSON")
+ external.add_argument(
+ "--sherlock", type=str,
+ help="Path to Sherlock's data.json (MIT; fetch it yourself, it is not vendored)",
+ )
+ external.add_argument(
+ "--maigret", type=str,
+ help="Path to Maigret's data.json (MIT); read with the Sherlock rule semantics",
+ )
+ external.add_argument(
+ "--whatsmyname", type=str,
+ help="Path to wmn-data.json (CC BY-SA 4.0, (C) Micah Hoffman et al.)",
+ )
+ external.add_argument("--out", type=str, help="Write the result bundle as JSON here")
+ external.add_argument("--json", action="store_true", dest="json_out", help="Print JSON to stdout")
+ external.add_argument("-v", "--verbose", action="store_true")
+ return parser
+
+
def build_diff_parser() -> ArgumentParser:
parser = ArgumentParser(
prog="aliens_eye diff",
@@ -759,8 +877,10 @@ def _print_domains(console, domains: dict) -> None:
async def run_selfcheck_command(args) -> None:
+ from aliens_eye.core.http import fetch_url
from aliens_eye.selfcheck import run_selfcheck
+ console = get_console()
if args.report == "json":
set_plain(True, stderr=True)
elif args.plain:
@@ -771,9 +891,46 @@ async def run_selfcheck_command(args) -> None:
detector = Detector()
if not args.no_ml:
detector.load_model(logger, Path(args.model) if args.model else None)
+ fetch = fetch_url
+ jobs = None
+ if args.corpus:
+ from aliens_eye.corpus.replay import ReplayFetcher
+ from aliens_eye.ml.collect import load_selfcheck_data
+
+ replay = ReplayFetcher(Path(args.corpus), strict=not args.allow_corpus_misses)
+ fetch = replay
+ # The corpus supplies the evaluation set, filtered to the requested
+ # split. Regenerating negatives here would miss the corpus entirely and
+ # leave the negative class empty.
+ sites = None
+ if args.split != "all":
+ sites = set(
+ load_selfcheck_data(
+ args.split, Path(args.ground_truth) if args.ground_truth else None
+ )
+ )
+ jobs = replay.eval_jobs(sites)
+ if not jobs:
+ console.print(
+ f"[red]Corpus at {args.corpus} holds no labelled records for split "
+ f"{args.split!r}.[/red]"
+ )
+ return
+ positives = sum(1 for j in jobs if j[3] == 1)
+ if args.report != "json":
+ console.print(
+ f"[dim]Replaying {len(jobs)} corpus rows "
+ f"({positives} positive / {len(jobs) - positives} negative) "
+ f"from {args.corpus} — no network.[/dim]"
+ )
+
await run_selfcheck(
sites_data, detector, config, logger,
negatives=args.negatives, report_format=args.report,
+ split=args.split,
+ ground_truth_path=Path(args.ground_truth) if args.ground_truth else None,
+ fetch=fetch,
+ jobs=jobs,
)
@@ -783,6 +940,12 @@ async def run_train_command(args) -> None:
if args.train_command == "collect":
from aliens_eye.ml.collect import collect_dataset
+ if args.split != "train" and not args.allow_leakage:
+ console.print(
+ f"[red]Refusing to collect training data from the '{args.split}' split:[/red] "
+ "it overlaps the evaluation holdout. Pass --allow-leakage to override."
+ )
+ return
sites_data = load_sites_data(Path(args.sites) if args.sites else None)
count = await collect_dataset(
sites_data,
@@ -790,6 +953,7 @@ async def run_train_command(args) -> None:
logger,
negatives_per_site=args.negatives,
seed=args.seed,
+ split=args.split,
)
console.print(f"[green]Collected {count} labeled samples -> {args.out}[/green]")
elif args.train_command == "fit":
@@ -804,6 +968,243 @@ async def run_train_command(args) -> None:
)
+async def run_corpus_command(args) -> None:
+ logger = setup_logger(args.verbose)
+ console = get_console()
+
+ if args.corpus_command == "record":
+ from aliens_eye.corpus.record import record_corpus
+ from aliens_eye.ml.collect import load_selfcheck_data
+
+ sites_data = load_sites_data(Path(args.sites) if args.sites else None)
+ ground_truth = load_selfcheck_data(
+ args.split, Path(args.ground_truth) if args.ground_truth else None
+ )
+ console.print(
+ f"[blue]Recording[/blue] {sum(len(v) for v in ground_truth.values())} positives + "
+ f"{args.negatives}/site negatives across {len(ground_truth)} sites -> {args.out}"
+ )
+ manifest = await record_corpus(
+ sites_data,
+ ground_truth,
+ Path(args.out),
+ logger,
+ negatives_per_site=args.negatives,
+ concurrency=args.concurrency,
+ seed=args.seed,
+ split=args.split,
+ plausible_ratio=args.plausible_ratio,
+ config=ScannerConfig(retries=2, timeout=args.timeout),
+ )
+ console.print(
+ f"[green]Captured {manifest['records']} records[/green] "
+ f"({manifest['errors']} fetch errors) across {len(manifest['sites'])} sites"
+ )
+ if manifest["skipped_sites"]:
+ console.print(
+ f"[yellow]Skipped (missing from sites.json):[/yellow] "
+ f"{', '.join(manifest['skipped_sites'])}"
+ )
+ return
+
+ from rich.table import Table
+
+ from aliens_eye.corpus.replay import ReplayFetcher
+
+ replay = ReplayFetcher(Path(args.path), strict=False)
+ stats = replay.stats()
+ if args.json_out:
+ print(json.dumps(stats, indent=2))
+ return
+ table = Table(title=f"Corpus: {args.path}", header_style="bold blue")
+ table.add_column("Field", style="yellow")
+ table.add_column("Value", justify="right")
+ for key, value in stats.items():
+ table.add_row(key, str(value))
+ console.print(table)
+
+
+async def run_eval_command(args) -> None:
+ from rich.table import Table
+
+ from aliens_eye.eval.ablate import run_ablations
+
+ if args.eval_command == "external":
+ await run_eval_external_command(args)
+ return
+
+ if args.json_out:
+ set_plain(True, stderr=True)
+ logger = setup_logger(args.verbose)
+ console = get_console()
+
+ detector = Detector()
+ detector.load_model(logger, Path(args.model) if args.model else None)
+ if detector.model is None:
+ console.print("[yellow]No ML model loaded; ml_only and blended rows will match heuristic_only.[/yellow]")
+
+ sites = None
+ if args.split != "all":
+ from aliens_eye.ml.collect import load_selfcheck_data
+
+ sites = set(
+ load_selfcheck_data(
+ args.split, Path(args.ground_truth) if args.ground_truth else None
+ )
+ )
+
+ bundle = await run_ablations(
+ Path(args.corpus),
+ detector,
+ logger,
+ sites=sites,
+ names=[n.strip() for n in args.only.split(",")] if args.only else None,
+ use_fingerprints=args.fingerprints,
+ )
+
+ if args.out:
+ out = Path(args.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(json.dumps(bundle, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+
+ if args.json_out:
+ print(json.dumps(bundle, indent=2, sort_keys=True))
+ return
+
+ console.print(
+ f"[blue]Corpus[/blue] {bundle['corpus']} "
+ f"[blue]split[/blue] {args.split} "
+ f"[blue]rows[/blue] {bundle['usable_rows']} usable "
+ f"({bundle['positives']} pos / {bundle['negatives']} neg, "
+ f"{bundle['excluded_rows']} excluded)"
+ )
+ table = Table(title="Ablation results", header_style="bold blue")
+ table.add_column("Configuration", style="yellow")
+ for col in ("P", "R", "F1", "F1 95% CI", "FPR", "Maybe", "vs shipped"):
+ table.add_column(col, justify="right")
+ for row in bundle["results"]:
+ m = row["overall"]
+ f1 = m["f1"]
+ style = "green" if f1 >= 0.8 else "yellow" if f1 >= 0.6 else "red"
+ boot = row.get("bootstrap", {})
+ ci = f"{boot.get('ci_low', 0):.2f}-{boot.get('ci_high', 0):.2f}" if boot else "-"
+ delta = row.get("vs_reference")
+ if delta is None:
+ vs = "[dim]reference[/dim]"
+ elif delta["separable"]:
+ vs = f"[bold]{delta['delta']:+.3f}[/bold]"
+ else:
+ vs = f"[dim]{delta['delta']:+.3f} ns[/dim]"
+ table.add_row(
+ row["name"],
+ f"{m['precision']:.3f}", f"{m['recall']:.3f}",
+ f"[{style}]{f1:.3f}[/{style}]", ci,
+ f"{m['false_positive_rate']:.3f}", f"{m['maybe_rate']:.3f}", vs,
+ )
+ console.print(table)
+ console.print(
+ "[dim]ns = 95% paired-bootstrap CI on the F1 difference spans zero: "
+ "this corpus cannot distinguish that configuration from the shipped blend.[/dim]"
+ )
+ if args.out:
+ console.print(f"[dim]Full bundle written to {args.out}[/dim]")
+
+
+async def run_eval_external_command(args) -> None:
+ from rich.table import Table
+
+ from aliens_eye.eval.external import compare_external
+
+ if args.json_out:
+ set_plain(True, stderr=True)
+ logger = setup_logger(args.verbose)
+ console = get_console()
+
+ rule_paths = {
+ name: Path(value)
+ for name, value in (
+ ("sherlock", args.sherlock),
+ ("maigret", args.maigret),
+ ("whatsmyname", args.whatsmyname),
+ )
+ if value
+ }
+ if not rule_paths:
+ console.print(
+ "[red]No rule sets given.[/red] Pass at least one of --sherlock / --maigret / "
+ "--whatsmyname. The rule data is not vendored; fetch it from the upstream "
+ "project and mind its licence."
+ )
+ return
+ missing = [str(p) for p in rule_paths.values() if not p.exists()]
+ if missing:
+ console.print(f"[red]Rule file(s) not found:[/red] {', '.join(missing)}")
+ return
+
+ detector = Detector()
+ detector.load_model(logger, Path(args.model) if args.model else None)
+
+ sites = None
+ if args.split != "all":
+ from aliens_eye.ml.collect import load_selfcheck_data
+
+ sites = set(
+ load_selfcheck_data(
+ args.split, Path(args.ground_truth) if args.ground_truth else None
+ )
+ )
+
+ bundle = await compare_external(
+ Path(args.corpus), detector, logger, rule_paths, sites=sites
+ )
+
+ if args.out:
+ out = Path(args.out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(json.dumps(bundle, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+ if args.json_out:
+ print(json.dumps(bundle, indent=2, sort_keys=True))
+ return
+
+ console.print(
+ f"[blue]Corpus[/blue] {bundle['corpus']} "
+ f"[blue]usable rows[/blue] {bundle['usable_rows']}"
+ )
+ for entry in bundle["external"]:
+ m = entry["overall"]
+ console.print(
+ f"\n[bold]{entry['name']}[/bold] "
+ f"rules {entry['source']['usable_rules']} "
+ f"covered {entry['samples']} rows ({entry['site_coverage']:.0%}) "
+ f"no rule {entry['rows_without_rule']} undecided {entry['rows_rule_undecided']}"
+ )
+ table = Table(header_style="bold blue")
+ table.add_column("Detector", style="yellow")
+ for col in ("P", "R", "F1", "FPR", "vs this tool", "95% CI"):
+ table.add_column(col, justify="right")
+ table.add_row(
+ entry["name"],
+ f"{m['precision']:.3f}", f"{m['recall']:.3f}", f"{m['f1']:.3f}",
+ f"{m['false_positive_rate']:.3f}", "[dim]reference[/dim]", "",
+ )
+ for our_name, cmp in entry["vs_ours"].items():
+ verdict = "[bold]separable[/bold]" if cmp["separable"] else "[dim]ns[/dim]"
+ table.add_row(
+ f"ours: {our_name}", "", "",
+ f"{cmp['our_f1_on_covered_rows']:.3f}", "",
+ f"{cmp['delta']:+.3f} {verdict}",
+ f"[{cmp['ci_low']:+.3f}, {cmp['ci_high']:+.3f}]",
+ )
+ console.print(table)
+ console.print(
+ "\n[dim]External verdicts come from reimplemented rule semantics applied to the "
+ "same stored responses, not from running the upstream tools. Rows a tool has no "
+ "rule for are excluded from its score rather than counted against it.[/dim]"
+ )
+ if args.out:
+ console.print(f"[dim]Full bundle written to {args.out}[/dim]")
+
+
def run_diff_command(args) -> None:
from aliens_eye.core.report import ReportError, diff_reports, load_report
@@ -879,6 +1280,12 @@ def main() -> None:
elif argv and argv[0] == "train":
args = build_train_parser().parse_args(argv[1:])
asyncio.run(run_train_command(args))
+ elif argv and argv[0] == "corpus":
+ args = build_corpus_parser().parse_args(argv[1:])
+ asyncio.run(run_corpus_command(args))
+ elif argv and argv[0] == "eval":
+ args = build_eval_parser().parse_args(argv[1:])
+ asyncio.run(run_eval_command(args))
elif argv and argv[0] == "diff":
args = build_diff_parser().parse_args(argv[1:])
run_diff_command(args)
diff --git a/src/aliens_eye/eval/external.py b/src/aliens_eye/eval/external.py
new file mode 100644
index 0000000..30e135b
--- /dev/null
+++ b/src/aliens_eye/eval/external.py
@@ -0,0 +1,347 @@
+"""External-tool baselines, evaluated over the frozen corpus.
+
+Sherlock, Maigret and WhatsMyName do not differ from this tool by algorithm so
+much as by *curated per-site rules*. A fair comparison therefore has to run their
+rules, not a paraphrase of their approach -- and it has to run them over the same
+stored responses, so the comparison isolates detection logic from HTTP client
+behaviour, retry policy, and which sites happened to be reachable that day.
+
+**These are reimplementations of the documented rule semantics, not the upstream
+code.** Each engine below states its interpretation explicitly so a reviewer can
+check it. Where upstream behaviour is ambiguous the interpretation is the
+charitable one -- the reading most likely to make the external tool look good.
+
+Rule data is **not vendored**. It is fetched by the user and passed by path:
+
+* Sherlock -- ``sherlock_project/resources/data.json`` (MIT)
+* WhatsMyName -- ``wmn-data.json`` (CC BY-SA 4.0, (C) Micah Hoffman et al.)
+* Maigret -- ``maigret/resources/data.json`` (MIT), read with the Sherlock engine
+ since it uses the same ``checkType``/``errorType`` vocabulary.
+
+Keeping the data out of the tree avoids relicensing questions and keeps the
+comparison honest about its provenance: the version fetched is recorded in the
+result bundle.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlparse
+
+#: Verdicts an external rule can return. ``None`` means the tool has no rule for
+#: that site and the row must be excluded from its score rather than counted
+#: against it.
+FOUND = "Found"
+NOT_FOUND = "Not Found"
+UNKNOWN = None
+
+
+def _netloc(url: str) -> str:
+ """Host key for matching rules to corpus rows, ignoring a leading ``www.``."""
+ host = urlparse(url).netloc.lower()
+ return host[4:] if host.startswith("www.") else host
+
+
+def _as_list(value: Any) -> list[str]:
+ if value is None:
+ return []
+ if isinstance(value, str):
+ return [value] if value else []
+ return [str(v) for v in value if v]
+
+
+@dataclass
+class ExternalRule:
+ site_name: str
+ netloc: str
+ raw: dict[str, Any]
+
+
+class RuleEngine:
+ """Base: maps corpus rows to a verdict using an external tool's rules."""
+
+ name = "external"
+
+ def __init__(self, rules: dict[str, ExternalRule], source: dict[str, Any]) -> None:
+ self.rules = rules
+ self.source = source
+
+ @property
+ def covered_netlocs(self) -> set[str]:
+ return set(self.rules)
+
+ def rule_for(self, url: str) -> ExternalRule | None:
+ return self.rules.get(_netloc(url))
+
+ def decide(self, url: str, final_url: str, status: int, body: str) -> str | None:
+ raise NotImplementedError
+
+
+class SherlockEngine(RuleEngine):
+ """Sherlock / Maigret ``errorType`` semantics.
+
+ * ``status_code`` -- the account exists iff the response is 2xx. (Sherlock
+ also honours an explicit ``errorCode``; when present, that code means
+ absent.)
+ * ``message`` -- the account exists iff none of the error messages appear in
+ the body. Multiple messages are OR-ed, matching upstream.
+ * ``response_url`` -- the account exists iff the request was not redirected
+ away from the profile URL. Sites using this rule bounce unknown users to a
+ home or error page.
+
+ Maigret's ``checkType`` uses the same vocabulary and is accepted here.
+ """
+
+ name = "sherlock"
+
+ @classmethod
+ def load(cls, path: Path) -> SherlockEngine:
+ text = Path(path).read_text(encoding="utf-8")
+ data = json.loads(text)
+ rules: dict[str, ExternalRule] = {}
+ for site_name, entry in data.items():
+ if not isinstance(entry, dict) or "url" not in entry:
+ continue
+ host = _netloc(str(entry["url"]))
+ if host and host not in rules:
+ rules[host] = ExternalRule(site_name, host, entry)
+ return cls(
+ rules,
+ {
+ "engine": "sherlock",
+ "path": str(path),
+ "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
+ "entries": len(data),
+ "usable_rules": len(rules),
+ },
+ )
+
+ def decide(self, url: str, final_url: str, status: int, body: str) -> str | None:
+ rule = self.rule_for(url)
+ if rule is None:
+ return UNKNOWN
+ entry = rule.raw
+ check = entry.get("errorType") or entry.get("checkType") or "status_code"
+
+ if check == "message":
+ messages = _as_list(entry.get("errorMsg") or entry.get("absenceStrs"))
+ if not messages:
+ return UNKNOWN
+ return NOT_FOUND if any(m in body for m in messages) else FOUND
+
+ if check == "response_url":
+ # Redirected away from the requested profile URL -> absent.
+ return NOT_FOUND if _strip(final_url) != _strip(url) else FOUND
+
+ # status_code
+ error_code = entry.get("errorCode")
+ if error_code is not None:
+ codes = {int(c) for c in _as_list(error_code)} if not isinstance(
+ error_code, int
+ ) else {int(error_code)}
+ if status in codes:
+ return NOT_FOUND
+ return FOUND if 200 <= status < 300 else NOT_FOUND
+
+
+class WhatsMyNameEngine(RuleEngine):
+ """WhatsMyName ``e_code``/``e_string`` vs ``m_code``/``m_string`` semantics.
+
+ An account exists iff the status matches ``e_code`` **and** ``e_string``
+ appears in the body. It is absent iff the status matches ``m_code`` and, when
+ an ``m_string`` is given, that string appears. Anything else is UNKNOWN --
+ the format is explicitly two-sided and does not force a decision, so scoring
+ an unmatched row either way would misrepresent the tool.
+ """
+
+ name = "whatsmyname"
+
+ @classmethod
+ def load(cls, path: Path) -> WhatsMyNameEngine:
+ text = Path(path).read_text(encoding="utf-8")
+ data = json.loads(text)
+ entries = data.get("sites", data if isinstance(data, list) else [])
+ rules: dict[str, ExternalRule] = {}
+ for entry in entries:
+ if not isinstance(entry, dict) or "uri_check" not in entry:
+ continue
+ host = _netloc(str(entry["uri_check"]))
+ if host and host not in rules:
+ rules[host] = ExternalRule(str(entry.get("name", host)), host, entry)
+ return cls(
+ rules,
+ {
+ "engine": "whatsmyname",
+ "path": str(path),
+ "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
+ "entries": len(entries),
+ "usable_rules": len(rules),
+ "license": data.get("license") if isinstance(data, dict) else None,
+ },
+ )
+
+ def decide(self, url: str, final_url: str, status: int, body: str) -> str | None:
+ rule = self.rule_for(url)
+ if rule is None:
+ return UNKNOWN
+ entry = rule.raw
+ e_code, e_string = entry.get("e_code"), entry.get("e_string") or ""
+ m_code, m_string = entry.get("m_code"), entry.get("m_string") or ""
+
+ if e_code is not None and status == int(e_code) and (not e_string or e_string in body):
+ return FOUND
+ if m_code is not None and status == int(m_code) and (not m_string or m_string in body):
+ return NOT_FOUND
+ return UNKNOWN
+
+
+ENGINES = {
+ "sherlock": SherlockEngine,
+ "maigret": SherlockEngine,
+ "whatsmyname": WhatsMyNameEngine,
+}
+
+
+def _strip(url: str) -> str:
+ return url.rstrip("/").lower()
+
+
+def score_engine(engine: RuleEngine, observations) -> dict[str, Any]:
+ """Score one external engine over pre-collected corpus observations.
+
+ Rows the engine has no rule for, or returns UNKNOWN on, are **excluded** and
+ reported as coverage rather than counted as errors. Charging a tool for sites
+ it never claimed to support would understate it.
+ """
+ from aliens_eye.selfcheck import _metrics
+
+ tp = fp = fn = tn = 0
+ covered = unknown = no_rule = 0
+ predictions: list[tuple[int, int]] = []
+ covered_urls: list[str] = []
+ per_site: dict[str, dict[str, int]] = {}
+
+ for obs in observations:
+ if obs.error:
+ continue
+ if engine.rule_for(obs.url) is None:
+ no_rule += 1
+ continue
+ verdict = engine.decide(obs.url, obs.final_url or obs.url, obs.status_code, obs.body or "")
+ if verdict is UNKNOWN:
+ unknown += 1
+ continue
+ covered += 1
+ covered_urls.append(obs.url)
+ predicted = 1 if verdict == FOUND else 0
+ predictions.append((obs.label, predicted))
+
+ cell = per_site.setdefault(obs.site, {"tp": 0, "fp": 0, "fn": 0, "tn": 0})
+ if obs.label == 1 and predicted == 1:
+ key = "tp"
+ elif obs.label == 1:
+ key = "fn"
+ elif predicted == 1:
+ key = "fp"
+ else:
+ key = "tn"
+ cell[key] += 1
+ tp += key == "tp"
+ fp += key == "fp"
+ fn += key == "fn"
+ tn += key == "tn"
+
+ overall = _metrics(tp, fp, fn, tn)
+ overall["maybe_rate"] = 0.0
+ return {
+ "name": engine.name,
+ "source": engine.source,
+ "samples": covered,
+ "rows_without_rule": no_rule,
+ "rows_rule_undecided": unknown,
+ "overall": overall,
+ "per_site": {
+ s: _metrics(c["tp"], c["fp"], c["fn"], c["tn"]) for s, c in per_site.items()
+ },
+ "predictions": predictions,
+ "covered_urls": covered_urls,
+ }
+
+
+async def compare_external(
+ corpus: Path,
+ detector,
+ logger,
+ rule_paths: dict[str, Path],
+ sites: set[str] | None = None,
+ bootstrap_iterations: int = 4000,
+) -> dict[str, Any]:
+ """Score external engines and our own configurations on the same rows.
+
+ Each external tool covers a different subset of the corpus, so a single
+ shared row set would shrink to whatever the least-covering tool supports.
+ Instead every external engine is compared against our configurations
+ **restricted to that engine's covered rows** -- a like-for-like comparison
+ per tool, with the covered row count reported alongside so the reader knows
+ how much corpus each number rests on.
+ """
+ from aliens_eye.eval.ablate import (
+ build_ablations,
+ collect_observations,
+ paired_delta_f1,
+ score_ablation,
+ )
+
+ observations = await collect_observations(corpus, sites, logger)
+ ablations = {a.name: a for a in build_ablations(getattr(detector.model, "ml_weight", None))}
+ ours = {
+ name: score_ablation(ablations[name], observations, detector)
+ for name in ("status_only", "heuristic_only", "ml_only", "blended_shipped")
+ }
+ # score_ablation walks observations in order and skips error rows, so the
+ # prediction lists align positionally with the usable rows.
+ usable = [o for o in observations if not o.error]
+ index_of = {o.url: i for i, o in enumerate(usable)}
+
+ comparisons = []
+ for engine_name, path in sorted(rule_paths.items()):
+ engine_cls = ENGINES[engine_name]
+ engine = engine_cls.load(Path(path))
+ engine.name = engine_name
+ scored = score_engine(engine, observations)
+ idx = [index_of[u] for u in scored["covered_urls"] if u in index_of]
+
+ against = {}
+ for our_name, our_result in ours.items():
+ subset = [our_result["predictions"][i] for i in idx]
+ delta = paired_delta_f1(
+ scored["predictions"], subset, iterations=bootstrap_iterations
+ )
+ from aliens_eye.eval.ablate import _f1_from_pairs
+
+ against[our_name] = {
+ "our_f1_on_covered_rows": round(_f1_from_pairs(subset), 4),
+ **delta,
+ }
+ scored.pop("predictions", None)
+ scored.pop("covered_urls", None)
+ scored["vs_ours"] = against
+ scored["site_coverage"] = round(
+ scored["samples"] / max(1, len(usable)), 4
+ )
+ comparisons.append(scored)
+
+ for result in ours.values():
+ result.pop("predictions", None)
+
+ return {
+ "corpus": str(corpus),
+ "usable_rows": len(usable),
+ "ours": ours,
+ "external": comparisons,
+ "bootstrap_iterations": bootstrap_iterations,
+ }
diff --git a/tests/test_external.py b/tests/test_external.py
new file mode 100644
index 0000000..feeec4a
--- /dev/null
+++ b/tests/test_external.py
@@ -0,0 +1,251 @@
+"""External rule engines: faithfulness of the reimplemented semantics, and the
+coverage accounting that keeps the comparison fair."""
+
+import json
+
+import pytest
+
+from aliens_eye.eval.ablate import Observation
+from aliens_eye.eval.external import (
+ FOUND,
+ NOT_FOUND,
+ UNKNOWN,
+ SherlockEngine,
+ WhatsMyNameEngine,
+ _netloc,
+ score_engine,
+)
+
+SHERLOCK_RULES = {
+ "StatusSite": {"errorType": "status_code", "url": "https://status.example/{}"},
+ "CodedSite": {"errorType": "status_code", "errorCode": 202, "url": "https://coded.example/{}"},
+ "MessageSite": {
+ "errorType": "message",
+ "errorMsg": "nobody goes by that name",
+ "url": "https://msg.example/{}",
+ },
+ "MultiMessageSite": {
+ "errorType": "message",
+ "errorMsg": ["no such user", "not found here"],
+ "url": "https://multi.example/{}",
+ },
+ "RedirectSite": {"errorType": "response_url", "url": "https://redir.example/{}"},
+ "WwwSite": {"errorType": "status_code", "url": "https://www.wwwsite.example/{}"},
+ "NoUrl": {"errorType": "status_code"},
+}
+
+WMN_RULES = {
+ "license": ["test"],
+ "sites": [
+ {
+ "name": "StrictSite",
+ "uri_check": "https://strict.example/{account}",
+ "e_code": 200,
+ "e_string": "profile-header",
+ "m_code": 404,
+ "m_string": "not found",
+ },
+ {
+ "name": "CodeOnlySite",
+ "uri_check": "https://codeonly.example/{account}",
+ "e_code": 200,
+ "e_string": "",
+ "m_code": 404,
+ "m_string": "",
+ },
+ ],
+}
+
+
+def sherlock(tmp_path):
+ path = tmp_path / "sherlock.json"
+ path.write_text(json.dumps(SHERLOCK_RULES), encoding="utf-8")
+ return SherlockEngine.load(path)
+
+
+def wmn(tmp_path):
+ path = tmp_path / "wmn.json"
+ path.write_text(json.dumps(WMN_RULES), encoding="utf-8")
+ return WhatsMyNameEngine.load(path)
+
+
+# --- host matching --------------------------------------------------------
+
+
+def test_netloc_ignores_www():
+ assert _netloc("https://www.github.com/x") == _netloc("https://github.com/x")
+
+
+def test_netloc_is_case_insensitive():
+ assert _netloc("https://GitHub.COM/x") == "github.com"
+
+
+def test_www_prefixed_rule_matches_bare_host(sherlock):
+ assert sherlock.rule_for("https://wwwsite.example/bob") is not None
+
+
+def test_entries_without_a_url_are_skipped(sherlock):
+ assert all(rule.site_name != "NoUrl" for rule in sherlock.rules.values())
+
+
+def test_unknown_host_has_no_rule(sherlock):
+ assert sherlock.rule_for("https://nowhere.example/bob") is None
+ assert sherlock.decide("https://nowhere.example/bob", "", 200, "") is UNKNOWN
+
+
+# --- Sherlock semantics ---------------------------------------------------
+
+
+def test_status_code_rule_treats_2xx_as_found(sherlock):
+ url = "https://status.example/bob"
+ assert sherlock.decide(url, url, 200, "") == FOUND
+ assert sherlock.decide(url, url, 204, "") == FOUND
+ assert sherlock.decide(url, url, 404, "") == NOT_FOUND
+ assert sherlock.decide(url, url, 500, "") == NOT_FOUND
+
+
+def test_explicit_error_code_means_absent(sherlock):
+ """A 202 is 2xx, but this site's rule declares 202 to mean 'no such user'."""
+ url = "https://coded.example/bob"
+ assert sherlock.decide(url, url, 202, "") == NOT_FOUND
+ assert sherlock.decide(url, url, 200, "") == FOUND
+
+
+def test_message_rule_is_absence_of_the_error_string(sherlock):
+ url = "https://msg.example/bob"
+ assert sherlock.decide(url, url, 200, "welcome to bob's page") == FOUND
+ assert sherlock.decide(url, url, 200, "sorry, nobody goes by that name") == NOT_FOUND
+
+
+def test_message_rule_ors_multiple_messages(sherlock):
+ url = "https://multi.example/bob"
+ assert sherlock.decide(url, url, 200, "no such user") == NOT_FOUND
+ assert sherlock.decide(url, url, 200, "not found here") == NOT_FOUND
+ assert sherlock.decide(url, url, 200, "all good") == FOUND
+
+
+def test_message_rule_ignores_status(sherlock):
+ """Upstream checks the body, not the code, for message-type sites."""
+ url = "https://msg.example/bob"
+ assert sherlock.decide(url, url, 404, "welcome to bob's page") == FOUND
+
+
+def test_response_url_rule_detects_redirect_away(sherlock):
+ url = "https://redir.example/bob"
+ assert sherlock.decide(url, url, 200, "") == FOUND
+ assert sherlock.decide(url, "https://redir.example/login", 200, "") == NOT_FOUND
+
+
+def test_response_url_rule_tolerates_trailing_slash(sherlock):
+ url = "https://redir.example/bob"
+ assert sherlock.decide(url, url + "/", 200, "") == FOUND
+
+
+def test_source_records_provenance(sherlock):
+ assert sherlock.source["engine"] == "sherlock"
+ assert len(sherlock.source["sha256"]) == 64
+ assert sherlock.source["usable_rules"] == len(sherlock.rules)
+
+
+# --- WhatsMyName semantics ------------------------------------------------
+
+
+def test_wmn_requires_both_code_and_string(wmn):
+ url = "https://strict.example/bob"
+ assert wmn.decide(url, url, 200, "<div class=profile-header>") == FOUND
+ # Right code, missing marker -> the format does not let us conclude.
+ assert wmn.decide(url, url, 200, "<div class=something-else>") is UNKNOWN
+
+
+def test_wmn_missing_rule_marks_absent(wmn):
+ url = "https://strict.example/bob"
+ assert wmn.decide(url, url, 404, "user not found") == NOT_FOUND
+
+
+def test_wmn_returns_unknown_when_neither_side_matches(wmn):
+ """The format is two-sided; forcing a verdict would misrepresent the tool."""
+ url = "https://strict.example/bob"
+ assert wmn.decide(url, url, 503, "gateway error") is UNKNOWN
+
+
+def test_wmn_code_only_rules_skip_string_matching(wmn):
+ url = "https://codeonly.example/bob"
+ assert wmn.decide(url, url, 200, "anything at all") == FOUND
+ assert wmn.decide(url, url, 404, "") == NOT_FOUND
+
+
+def test_wmn_records_upstream_license(wmn):
+ assert wmn.source["license"] == ["test"]
+
+
+# --- scoring and coverage accounting --------------------------------------
+
+
+def _obs(site, url, label, status, body=""):
+ return Observation(site, "u", url, label, status, {}, {}, None, body, url)
+
+
+def test_rows_without_a_rule_are_excluded_not_penalised(sherlock):
+ observations = [
+ _obs("status", "https://status.example/a", 1, 200),
+ _obs("elsewhere", "https://nowhere.example/a", 1, 404),
+ ]
+ result = score_engine(sherlock, observations)
+ assert result["samples"] == 1
+ assert result["rows_without_rule"] == 1
+ # The uncovered row must not appear as a false negative.
+ assert result["overall"]["fn"] == 0
+
+
+def test_undecided_rows_are_excluded_not_penalised(wmn):
+ observations = [
+ _obs("strict", "https://strict.example/a", 1, 200, "profile-header"),
+ _obs("strict", "https://strict.example/b", 1, 503, "gateway error"),
+ ]
+ result = score_engine(wmn, observations)
+ assert result["samples"] == 1
+ assert result["rows_rule_undecided"] == 1
+ assert result["overall"]["tp"] == 1
+
+
+def test_capture_error_rows_are_skipped(sherlock):
+ observations = [
+ _obs("status", "https://status.example/a", 1, 200),
+ Observation("status", "u", "https://status.example/b", 0, 0, {}, {}, "timeout"),
+ ]
+ assert score_engine(sherlock, observations)["samples"] == 1
+
+
+def test_scoring_builds_a_correct_confusion_matrix(sherlock):
+ observations = [
+ _obs("status", "https://status.example/a", 1, 200), # tp
+ _obs("status", "https://status.example/b", 0, 200), # fp
+ _obs("status", "https://status.example/c", 1, 404), # fn
+ _obs("status", "https://status.example/d", 0, 404), # tn
+ ]
+ m = score_engine(sherlock, observations)["overall"]
+ assert (m["tp"], m["fp"], m["fn"], m["tn"]) == (1, 1, 1, 1)
+ assert m["precision"] == 0.5
+ assert m["recall"] == 0.5
+
+
+def test_external_engines_never_abstain(sherlock):
+ """External tools are two-state; their Maybe rate must read as zero."""
+ observations = [_obs("status", "https://status.example/a", 1, 200)]
+ assert score_engine(sherlock, observations)["overall"]["maybe_rate"] == 0.0
+
+
+def test_predictions_align_with_covered_urls(sherlock):
+ observations = [
+ _obs("status", "https://status.example/a", 1, 200),
+ _obs("elsewhere", "https://nowhere.example/a", 1, 200),
+ _obs("status", "https://status.example/b", 0, 404),
+ ]
+ result = score_engine(sherlock, observations)
+ assert len(result["predictions"]) == len(result["covered_urls"])
+ assert result["covered_urls"] == [
+ "https://status.example/a",
+ "https://status.example/b",
+ ]