#!/usr/bin/env python3
# screen.py - the batch screener for the Phage Therapy Literome
# https://literome.phage-therapy.org/   -   see screen.md for what it does and how far to trust it
#
# Sorts a PubMed batch against the Literome's criteria for inclusion into: already held,
# duplicate, preprint now published, tag, keep untagged, delete, and needs a human. It is
# checked rather than trusted: run against a year of records the curator had already accepted,
# it wrongly rejects about 5 per cent, and the borderline cases are read by hand either way.
#
# Published so that the collection can be criticized. Reuse it freely; it is written for one
# bibliography and its vocabulary is that bibliography's, so expect to change the patterns.
#
"""Screen a PubMed/Reference Manager RIS export against the Literome.

  python3 -I screen.py <export.ris> <toolchain dir> <literome json dir> <out dir> [<held.ris> ...]

Sorts every record into: already held, duplicate within the batch, preprint and
journal version, probably include (by criterion), probably exclude (by reason),
needs judgment. Criteria: LITEROME_INCLUSION_CRITERIA.md.
"""
import sys, re, json, glob, os, csv, unicodedata
from collections import Counter, defaultdict
ris_path, tc, jdir, out = sys.argv[1:5]
held_extra = sys.argv[5:]
sys.path.insert(0, tc)
from ris_lib import load_ris, ris_doi
os.makedirs(out, exist_ok=True)

def g(r, k):
    v = r.get(k) or ''
    return ' '.join(v) if isinstance(v, list) else v
def norm(t):
    t = unicodedata.normalize('NFKD', t or '').encode('ascii', 'ignore').decode().lower()
    t = re.sub(r'[\x10\x11]', '', t); t = re.sub(r'<[^>]+>', '', t)
    t = re.sub(r'[^a-z0-9]+', ' ', t).strip()
    # Stripping punctuation turns a line-broken "macro-phage" into "macro phage", which gives
    # "phage" a word boundary it never had. 47287 is a colorectal-cancer immunology paper that
    # matched criteria that way (2026-11-24). Rejoin it before anything looks for a phage.
    return re.sub(r'\bmacro (phage)', r'macro\1', t)
def pmid(r):
    m = re.search(r'PM:(\d+)', g(r, 'UR')); return m.group(1) if m else ''
def year(r):
    m = re.match(r'(\d{4})', g(r, 'Y1') or g(r, 'PY')); return int(m.group(1)) if m else None
def surname(r):
    a = r.get('A1') or r.get('AU') or ''
    if isinstance(a, list): a = a[0] if a else ''
    w = norm(a.split(',')[0]).split(); return w[-1] if w else ''

# "Phage therapy" and "bacteriophage therapy" are the search terms that built this batch, so
# every record contains them and they can never be evidence of anything (Abedon, 2026-11-24:
# "mention of phage therapy should never be taken as a sufficient inclusion criterion").
# Sentences like these set a scene rather than report work, and matching them is what gave
# routine characterization papers criteria 4 and 8.
BACKGROUND = re.compile(
    r'antimicrobial resistan\w+|antibiotic resistance (?:is|has|poses|represents|continues|remains)'
    r'|(?:have|has) been reported|presenting (?:an?|the) alternative|as an? [\w ]{0,20}alternative'
    r'|growing (?:threat|concern|problem|public)|global (?:health|threat|concern|burden)'
    r'|public health (?:threat|concern|crisis|problem)|serious threat|major threat|urgent(?:ly)? need'
    r'|garnered (?:attention|interest)|has attracted|attracting (?:attention|interest)|renewed interest'
    r'|regained (?:attention|interest)|re[- ]?emerged as|emerged as (?:a|an) (?:promising|attractive|viable)'
    r'|promising alternative|alternative to antibiotics|post[- ]antibiotic|era of antibiotic'
    r'|last[- ]resort|few (?:new )?antibiotics|antibiotic pipeline|world health organization'
    r'|one of the most (?:widely|commonly|frequently)|most (?:widely|commonly) used|widely used'
    r'|has (?:long )?been used|have been used|is commonly used|are commonly used|traditionally'
    r'|interest in develop|efforts? to develop|(?:are|is) under way|expected to be|studies thus'
    r'|there has been|there have been|much attention')

SECTION = re.compile(r'^\s*(BACKGROUND|INTRODUCTION|OBJECTIVES?|AIMS?|PURPOSE|RATIONALE'
                     r'|METHODS?|MATERIALS|RESULTS?|FINDINGS|CONCLUSIONS?|DISCUSSION'
                     r'|IMPORTANCE|SIGNIFICANCE)\b\s*[:.]', re.I)
BG_SECTIONS = {'background', 'introduction', 'rationale'}

def sectioned(ab):
    """Each sentence with the structured-abstract section it sits under, if any."""
    cur = None
    for sent in re.split(r'(?<=[.?!])\s+', ab or ''):
        m = SECTION.match(sent)
        if m: cur = m.group(1).lower().rstrip('s')
        yield cur, sent

def _is_background(sec, sent):
    return (sec in BG_SECTIONS or (sec or '') + 's' in BG_SECTIONS
            or BACKGROUND.search(norm(sent)))

def strip_background(ab):
    out = [s for sec, s in sectioned(ab) if not _is_background(sec, s)]
    return norm(' '.join(out))

def rec(r):
    t = g(r, 'T1') or g(r, 'TI')
    ab = re.sub(r'[\x10\x11]', '', g(r, 'N2'))
    n1 = g(r, 'N1')
    jr = g(r, 'JA') or g(r, 'JF')
    return dict(id=r.get('ID'), title=t, nt=norm(t), ab=ab, txt=norm(t + ' ' + ab),
                doi=(ris_doi(r) or '').lower(), pmid=pmid(r), year=year(r), au=surname(r),
                body=strip_background(t + '. ' + ab),
                j=jr, vl=g(r, 'VL'), sp=g(r, 'SP'),
                review=bool(re.search(r'PT - (Review|Systematic Review)', n1)),
                is_pre=bool(re.search(r'rxiv|preprint|research square|ssrn', jr, re.I)) or bool(re.search(r'PT - Preprint', n1)),
                hasab=bool(ab))

B = [rec(r) for r in load_ris(ris_path)]

# ── what is already held ─────────────────────────────────────────────────────
H = []
for f in glob.glob(jdir + '/literome_[0-9]*.json'):
    for e in json.load(open(f)):
        H.append(dict(id=e['ref_id'], nt=norm(e['title']), doi=(e['doi'] or '').lower(),
                      au=(norm(e['authors'].split(',')[0]).split() or [''])[-1],
                      vl=e['volume'], sp=re.sub(r'\D.*', '', e['pages'] or ''), year=e['year'], pmid='',
                      pre=e['status'] == 'preprint'))
for p in held_extra:
    for r in load_ris(p):
        x = rec(r)
        H.append(dict(id=x['id'], nt=x['nt'], doi=x['doi'], au=x['au'], vl=x['vl'],
                      sp=re.sub(r'\D.*', '', x['sp'] or ''), year=x['year'], pmid=x['pmid'], pre=x['is_pre']))
PRE = {x['id'] for x in H if x.get('pre')}
byDoi, byPmid, byTitle, byVP = {}, {}, {}, {}
for x in H:
    if x['doi']: byDoi.setdefault(x['doi'], x['id'])
    if x.get('pmid'): byPmid.setdefault(x['pmid'], x['id'])
    if x['nt']: byTitle.setdefault(x['nt'], x['id'])
    if x['vl'] and x['sp']: byVP.setdefault((x['au'], x['vl'], x['sp'].lstrip('0')), x['id'])
words = lambda t: set(w for w in t.split() if len(w) > 2)
TIT = [(t, i) for t, i in byTitle.items()]
def held(x):
    if x['doi'] and x['doi'] in byDoi: return byDoi[x['doi']], 'same DOI'
    if x['pmid'] and x['pmid'] in byPmid: return byPmid[x['pmid']], 'same PMID'
    if x['nt'] in byTitle: return byTitle[x['nt']], 'same title'
    k = (x['au'], x['vl'], re.sub(r'\D.*', '', x['sp'] or '').lstrip('0'))
    if k[1] and k[2] and k in byVP: return byVP[k], 'same author, volume, page'
    wa = words(x['nt']); best = None
    if wa:
        for t, i in TIT:
            wb = words(t)
            if not wb: continue
            d = 2 * len(wa & wb) / (len(wa) + len(wb))
            if d >= 0.9 and (best is None or d > best[0]): best = (d, i)
    if best: return best[1], f'near-identical title ({best[0]:.2f})'
    return None, ''

# ── duplicates inside the batch ──────────────────────────────────────────────
par = {}
def find(a):
    while par.get(a, a) != a: a = par[a]
    return a
def union(a, b): par[find(a)] = find(b)
for key in ('doi', 'pmid', 'nt'):
    d = defaultdict(list)
    for x in B:
        if x[key]: d[x[key]].append(x['id'])
    for v in d.values():
        for i in v[1:]: union(v[0], i)
cl = defaultdict(list)
for x in B:
    if find(x['id']) != x['id'] or any(find(y['id']) == x['id'] for y in B if y is not x):
        cl[find(x['id'])].append(x['id'])
batch_dups = {ids[i]: ids[0] for ids in (sorted(v, key=int) for v in cl.values() if len(v) > 1) for i in range(1, len(ids))}

# ── the criteria ─────────────────────────────────────────────────────────────
# Each pattern has to name what the work DID. Words that merely set a scene - "antibiotic
# resistance is a growing threat", "patients", "stability", "surface" - used to be enough,
# and they are what put routine characterization papers in the include list (2026-11-24).
C = [
 ('in vivo or clinical', 1, r'\bmice\b|\bmouse\b|murine|\brats?\b|rabbit|galleria|zebrafish|larva|in vivo|\bpigs?\b|piglet'
                            r'|chicken|broiler|poultry|cattle|calves|\bsheep\b|crucian|\bcarp\b|tilapia|shrimp|c elegans|caenorhabditis'
                            r'|animal model|infection model|animal (?:study|studies|experiment)'
                            r'|clinical trial|case report|case series|compassionate|volunteer'
                            r'|patients? (?:were|was|received|underwent|treated|refractory|presented)|in patients|treated patients|patient outcome'
                            r'|case stud|clinical case|the patient\b|compassionate'
                            r'|organoid|organ[- ]on[- ]a?[- ]?chip|\bex vivo\b'),
 ('food, agriculture, or environment', 1, r'\bfood\b|\bmeat\b|\bbeef\b|\bpork\b|\bmilk\b|dairy|cheese|lettuce|spinach|sprout'
                            r'|carcass|\begg\b|seafood|aquacultur|\bcrop\b|tomato|potato|\brice\b|almond|soil|wastewater|sewage|irrigation'
                            r'|phytopatho|plant (?:patho|disease|protect|growth[- ]promot)|sanitation|biocontrol|post[- ]?harvest|shelf life'),
 ('biofilm', 3, r'anti[- ]?biofilm|biofilm (?:eradicat|remov|reduct|inhibit|disrupt|degrad|clear|dispers|prevent|biomass|formation was)'
                r'|(?:eradicat|eliminat|remov|reduc|inhibit|disrupt|degrad|clear|dispers|prevent|destroy|abolish)'
                r'\w*[^.]{0,30}biofilm'
                r'|biofilm[- ](?:related|associated|forming infection)|established biofilm|mature biofilm'
                r'|(?:sensitivit|susceptibilit|efficac|lysis|killing|lyse|lysing)\w*[^.]{0,60}biofilm'
                r'|(?:lytic|antibacterial|anti[- ]?biofilm|phage|lysin|phages)[^.]{0,20}(?:activit|effect)\w*[^.]{0,50}biofilm'
                r'|biofilm\w*[^.]{0,40}(?:sensitiv|susceptib|lysed|lysis|cleared|reduc|eradicat)'
                r'|against[^.]{0,24}biofilm'),
 ('with antibiotics', 4, r'phage[- ]antibiotic|antibiotics?.{0,40}synerg|synerg.{0,40}antibiotic|synergistic (?:effect|activity|interaction)\w*[^.]{0,44}(?:antibiotic|antimicrobial|phage|drug|colistin|polymyxin)|(?:antibiotic|antimicrobial|\b(?:bacterio|pro)?phage)\w*[^.]{0,44}synergistic'
                            r'|combination (?:with|treatment|therapy)\b|in combination\b|combination of (?:the )?(?:phage|antibiotic|two|both)'
                            r'|combined with (?:the )?(?:antibiotic|phage)|co[- ]administ'
                            r'|\bre[- ]?sensiti|collateral sensitiv|checkerboard|sub[- ]?mic\b|antibiotic adjuvant|adjuvant (?:to|with) (?:the )?antibiotic'
                            r'|polymyxin|colistin|meropenem|ciprofloxacin|vancomycin|gentamicin|ceftazidime|rifampicin'),
 ('cocktail', 5, r'cocktail|phage mixture|multi[- ]?phage'),
 ('what resistance costs', 6, r'trade[- ]?off|fitness cost|phage steering|attenuat|reduced virulence|loss of (?:virulence|capsule)'
                            r'|resistan\w* mutant|resistance evolution|evolv\w* resistance|\bre[- ]?sensiti'),
 ('susceptibility across the infecting population', 6,
                            r'phagogram|mixed populations? of phage|phage[- ](?:sensitiv|resistan)\w*[^.]{0,20}'
                            r'(?:and|or) phage[- ](?:sensitiv|resistan)'
                            r'|intra[- ]individual (?:diversity|variation)|within[- ](?:patient|host) (?:diversity|variation)'
                            r'|(?:diversity|variation|heterogeneity) (?:of|in) (?:bacteriophage |phage )?suscept'
                            r'|mixed versus single isolate|single or (?:a )?mix'),
 ('depolymerase', 7, r'capsule[- ]degrading|polysaccharide[- ]degrading'
                r'|depolymerase[^.]{0,40}(?:activity against|degrad|cleav|digest|treat|reduc|appli|purif|express|clon|structur)'
                r'|(?:degrad|cleav|digest|purif|recombinant|express\w+|structur\w+)\w*[^.]{0,30}depolymerase'),
 ('microbiome', 8, r'microbiome|microbiota|virome|fecal|faecal|gut community|decoloni'),
 ('formulation or delivery', 9, r'formulat|hydrogel|nanoparticle|liposome|microneedle|spray[- ]?dr|freeze[- ]?dr|lyophil'
                            r'|encapsulat\w*[^.]{0,40}(?:alginate|chitosan|liposome|hydrogel|particle|capsule|bead|matrix|polymer|emulsion)'
                            r'|(?:alginate|chitosan|liposome|hydrogel|microparticle|nanoparticle|bead|polymer)[^.]{0,40}encapsulat'
                            r'|endotoxin remov|\bgmp\b|manufactur|aerosol|nebuli|topical|ointment|shelf[- ]stable'
                            r'|nanofib|electrospun|electrospinn|wound dressing|\bdressing|scaffold|\bpatch\b|\bfilm\b|bandage'
                            r'|phage[- ](?:based|borne|mediated) delivery|delivery (?:system|vehicle|platform|vesicle) for'
                            r'|deliver(?:y|ing|ed)? of (?:the )?(?:bacterio)?(?:phage|antibiotic|antimicrobial|penicillin|drug|lysin)'
                            r'|deliver (?:antibiotic|antimicrobial|penicillin|drug|phage)\w* (?:into|directly|to the)'),
 # The thing itself: bacterial numbers going down because a phage was applied. Burden and
 # load are the words used for it in animals, hosts and communities, as against the broth
 # killing curves of exclusion 1.
 ('bacterial numbers reduced', 7, r'(?:reduc\w+|decreas\w+|lower\w*|clear\w+|eliminat\w+) (?:the )?bacterial (?:burden|load|count|number|population|coloni)'
                            r'|bacterial (?:burden|load|count)s? (?:were|was) (?:signific\w+ )?(?:reduc|decreas|lower)'
                            r'|reduc\w+ (?:in )?(?:cfu|colony[- ]forming)'
                            r'|log reduction in (?:bacterial|cfu|viable|colony|cell|the bacterial)'),
]
FOODENV = re.compile(dict((n, p) for n, _, p in C)['food, agriculture, or environment'])
VIVO = re.compile(dict((n, p) for n, _, p in C)['in vivo or clinical'])
FORMUL = re.compile(dict((n, p) for n, _, p in C)['formulation or delivery'])
COCKTAIL = re.compile(dict((n, p) for n, _, p in C)['cocktail'])
# A drug name on its own is usually a susceptibility table about the bacterium, not a phage
# paired with a drug (46739, 15 Lactococcus isolates tested against eight agents).
ABX_DRUG = re.compile(r'polymyxin|colistin|meropenem|ciprofloxacin|vancomycin|gentamicin|ceftazidime|rifampicin')
ABX_PAIR = re.compile(r'phage[- ]antibiotic|antibiotics?.{0,40}synerg|synerg.{0,40}antibiotic|synergistic (?:effect|activity|interaction)\w*[^.]{0,44}(?:antibiotic|antimicrobial|phage|drug|colistin|polymyxin)|(?:antibiotic|antimicrobial|\b(?:bacterio|pro)?phage)\w*[^.]{0,44}synergistic'
                      r'|combination (?:with|treatment|therapy)\b|in combination\b|combination of (?:the )?(?:phage|antibiotic|two|both)'
                      r'|combined with (?:the )?(?:antibiotic|phage)|co[- ]administ'
                      r'|\bre[- ]?sensiti|collateral sensitiv|checkerboard|sub[- ]?mic\b|antibiotic adjuvant|adjuvant (?:to|with) (?:the )?antibiotic')
PHAGE_WORD = re.compile(r'\b(?:bacterio|pro)?phage')
ESCAPES_OFF_TARGET = {'biofilm', 'depolymerase', 'microbiome', 'with antibiotics', 'cocktail',
                      'bacterial numbers reduced'}
# "fecal" is where a lot of phages are found. Criterion 8 is about deliberately changing a
# community, so the word has to appear somewhere other than an isolation sentence (47244,
# "isolated from chicken fecal and sewage samples"; 47270, the same). The provenance test is
# NOT extended to the other criteria: checked on the 2025 batch, it flagged 8 records and
# 4 of them were real results carrying a hedge - antibiofilm activity of "candidate phages",
# depolymerase production, resistance without loss of ecological performance, microbiome
# sparing. Those criteria's words turn up in findings, not in closing hopes (2026-11-24).
MICROBIOME = re.compile(dict((n, p) for n, _, p in C)['microbiome'])
FECAL_ONLY = re.compile(r'fecal|faecal')
HABITAT = re.compile(r'ubiquitous|commonly found|are found|is found|inhabit|reside|naturally occur'
                     r'|present in|constituent|member of|widespread in|abundant in|colonis\w+ the')
# A paper whose title is bacterial genomics, and whose only phage is a defence system the
# bacterium carries, is about the bacterium (46739: "Comparative Genomics of Lactococcus spp.
# ... Reveals Virulence Determinants, Antibiotic Resistance, and Phage Defence Mechanisms").
BACT_SUBJECT = re.compile(r'(?:comparative genomics|pangenom|pan[- ]genom|genomic (?:analys|characteri|epidemiolog|surveill)'
                          r'|whole[- ]genome (?:sequenc|analys)|molecular epidemiolog)'
                          r'(?=[\s\S]*(?:phage defen|antiphage|anti phage|phage resistan|defence mechanism|defense mechanism))')
REVIEW_SUBJ = re.compile(r'phage therapy|bacteriophage therapy|phage treatment|phage application|phage[- ]?based'
                         r'|phage biocontrol|phage[- ]?mediated|phage[- ]?antibiotic'
                         r'|\b(?:bacterio|pro)?phages? as [\w ]{0,24}(?:therapeut|antibacterial|antimicrobial|biocontrol|treatment|agent)'
                         r'|therapeutic (?:agent|potential|use|applicat|option|strateg)'
                         r'|phage therapeutic|antibacterial (?:agent|strateg|therap)'
                         r'|\b(?:bacterio|pro)?phages? (?:for|against|to|in) [\w ]{0,44}?'
                         r'(?:pathogen|bacteri|infection|control|coloni[sz]|decontamin|resistan)')
CHARACTERIZATION = re.compile(r'isolation\b|isolated\b|isolating\b|characteri[sz]|genom|sequenc|annotat|morpholog|novel (?:lytic )?\b(?:bacterio|pro)?phage|new (?:lytic )?\b(?:bacterio|pro)?phage|identification of')
BEYOND_CHAR = re.compile('|'.join(p for _, _, p in C))
# Phage display is a laboratory method for finding peptides and antibodies, not a way of
# reducing bacteria, whatever it is aimed at. Always out.
# PhIP-Seq is phage display by another name, and in a paper that is not about bacteria at
# all it is the only reason the record reached the search: an adenovirus glioma trial and
# an IgG4 allergen study were both tagged in the 2026 batch on that one phrase.
DISPLAY = re.compile(r'phage display|display[- ]selected|displayed? (?:peptide|scfv|antibod|random)|biopanning|phage[- ]displayed'
                     r'|phip[- ]?seq|phage immunoprecipitation')
# Phages put to some other use - cancer, vaccines, imaging, antifungals. Out only when
# nothing says a bacterium is the target: a phage that clears a bacterium in a tumor, or a
# depolymerase paper whose title happens to end "implications for vaccine design", is in.
OFF_TARGET = re.compile(r'cancer|tumou?r|carcinoma|oncolog|theranostic|chemotherap|vaccin|imaging|antifungal|drug discovery'
                        r'|immunotherap|immuni[sz]ation|\bcd\d{1,3}\b|lymph node|antigen[- ]presenting|dendritic cell'
                        r'|gene therapy|biosensor|bioimaging'
                        r'|antivir|coronavir|sars[- ]?cov|influenza|\bhiv\b|hepatitis|norovir|rotavir'
                        r'|respiratory (?:virus|syncytial)|antiparasit|antiprotozoal'
                        r'|protein (?:regulation|delivery)|bacteria[- ]based delivery|drug delivery')
BACTERIAL = re.compile(r'bacteri(?!ophage)(?!a[- ]based)|antibacterial|pathogen|multidrug|\bmrsa\b|eskape|\bmdr\b|infection|\bcoli\b|aureus|pneumoniae'
                       r'|aeruginosa|salmonella|listeria|enterococc|streptococc|staphylococc|klebsiella|acinetobacter|bacteroides'
                       r'|clostrid|vibrio|campylobacter|helicobacter|mycobacter|shigella|proteus|serratia|enterobacter|biofilm')
# Needs the closing boundary: without it "lysin" matched "lysing", which threw out phage
# papers whose titles said "with potential in lysing Vibrio" (2026-11-24).
LYSIN_ONLY = re.compile(r'\b(?:endo)?lysins?\b|peptidoglycan hydrolase|enzybiotic')
# Abedon's rule for phage proteins (2026-11-24): "if people are developing phage proteins
# basically as antibiotics, that's basically an antibiotic study rather than a phage therapy
# study. Now if they are testing these proteins in conjunction with whole phages, i.e.,
# toward phage-antibiotic synergy ... then that's phage therapy."
# Depolymerases are exempt, and deliberately so: "they are not explicitly a bactericidal
# agent but instead something that facilitates other antibacterial activities, whether they
# are immune systems or phages. But importantly, they can facilitate phages, including in
# their purified form."
PROTEIN_SUBJECT = re.compile(r'\b(?:endo)?lysins?\b|peptidoglycan hydrolase|enzybiotic|\bholins?\b'
                             r'|phage[- ]encoded protein|receptor[- ]binding protein|\brbps?\b'
                             r'|tail[- ]?spike protein|phage protein')
# Abedon, 2026-11-24, on 46918 ("A phiSa3int (NM3) Prophage Domestication in S. aureus
# Leads to Increased Virulence Through Human Immune Evasion"): "that's why that reference
# doesn't make the cut." A prophage raising its host's virulence is the BACTERIUM's biology
# with a phage as the mechanism - the same side of the line as host-factor genetics (46823).
# Title only, and deliberately not prophage diversity (47089) or prophage-encoded phage
# resistance (46749), both of which he keeps.
PROPHAGE_VIRULENCE = re.compile(
    r'prophage[^.]{0,44}(?:virulence|pathogenicity|immune evasion|immune[- ]evasion|domesticat|toxigenic)'
    r'|(?:virulence|pathogenicity|immune evasion)[^.]{0,44}prophage'
    r'|lysogenic conversion|lysogeny[^.]{0,30}virulence'
    r'|prophage (?:count|presence|carriage|prevalence|load|burden|content)'
    r'|prophage[^.]{0,44}(?:antibiotic|antimicrobial) resistance gene')
# Abedon, 2026-11-24: "The only prophage things that should remain is where induction is
# being used as an antibacterial strategy." So a paper whose subject is the prophage goes,
# unless induction is the intervention (46775, antibiotic-mediated prophage activation with
# therapeutic implications, which he keeps). A prophage-encoded protein conferring phage
# resistance is a defence paper, not prophage biology, and is left to that path (46749).
PROPHAGE_SUBJECT = re.compile(r'prophage|lysogen|temperate phage|integrated phage')
INDUCTION_STRATEGY = re.compile(
    r'(?:deliberate|controlled|targeted|harness\w+|exploit\w+|engineer\w+|trigger\w+)[^.]{0,30}'
    r'(?:prophage |lysogen\w* )?induction'
    r'|(?:prophage|lysogen\w*) induction (?:as|for) (?:a |an )?(?:therap|antibacterial|treatment|strateg|approach)'
    r'|(?:antibiotic|drug|chemical|\buv\b|mitomycin)[- ]?(?:mediated|induced|triggered) '
    r'(?:prophage|lysogen\w*) (?:activation|induction)'
    r'|induc\w+[^.]{0,30}(?:prophage|lysogen\w*)[^.]{0,40}(?:to kill|antibacterial|eradicat|clear the)')

def induction_strategy(x):
    """Induction put to work against bacteria, from the title or a work sentence."""
    if INDUCTION_STRATEGY.search(x['nt']): return True
    return any(INDUCTION_STRATEGY.search(n) for n in work_sentences(x))
TOOL_PAPER = re.compile(
    r'(?:technique|platform|pipeline|toolkit|workflow|framework|algorithm|software|web ?server'
    r'|\bmodel|approach|method|\btool)\w*[^.]{0,24}(?:for |to )?(?:detect|identif|predict|classif|screen)'
    r'|(?:detect|identif|predict|classif)\w*[^.]{0,24}'
    r'(?:technique|platform|pipeline|toolkit|framework|algorithm|software)'
    r'|(?:in silico|machine learning|deep learning|\bllm\b|neural network|language model|\bvae\b'
    r'|transformer)[^.]{0,40}(?:detect|identif|predict|classif)'
    r'|host (?:range )?prediction|phage[- ]host prediction')
WET_WORK = re.compile(r'efficacy|treatment of|therapy (?:of|for|in)|\bin vivo\b|clinical trial')
DEPOLY = re.compile(r'depolymerase|capsule[- ]degrading|polysaccharide[- ]degrading'
                    r'|(?:digest|cleav|degrad|hydroly)\w*[^.]{0,30}'
                    r'(?:capsul|exopolysacchar|\beps\b|polysacchar|saccharide|\bcps\b|o[- ]antigen)')
# A resistance or defence protein is the bacterium's, not an antibacterial being developed.
DEFENCE_PROT = re.compile(r'phage resistan|resistance (?:gene|protein|system|mechanism|factor)'
                          r'|confers? [\w ]{0,20}resistance|defen[cs]e (?:system|mechanism|protein)'
                          r'|anti[- ]?phage|immunit|abortive infection')
AS_ANTIBACTERIAL = re.compile(r'antibacterial|antimicrobial|bacteriolytic|bactericid|bacteriostatic'
                              r'|precision weapon|biotherapeutic|\btherap|\btreat|candidate (?:for|against)'
                              r'|effective against|activity against|efficacy against|\bagainst (?:multidrug|mdr|uropathogenic|drug)'
                              r'|phagocytosis|immune clearance|opsoni')
# Tested in conjunction with a whole phage - his test for when the protein work IS phage therapy.
_PROT = r'(?:(?:endo)?lysin|enzybiotic|peptidoglycan hydrolase|depolymerase|protein|enzyme)'
# The rule is for papers ABOUT a protein. A title that names a phage as an entity in its own
# right - "A new bacteriophage infecting S. epidermidis", "Generating ... bacteriophages
# through tailspike exchange" - is a phage paper whose protein is secondary. This strips the
# compounds where "phage" is only an adjective ("phage lysins", "phage-encoded protein") and
# then asks whether a phage is still named.
# Naming the phage a protein came FROM is provenance, not a phage doing anything: "lysis
# cassette from phage PZL-Ah152", "Holin and Endolysin From Escherichia Phage UE-M6",
# "endolysin LysSA05 function of Epsilon15 bacteriophage" - all three are lysin papers.
PHAGE_SOURCE = re.compile(r'(?:from|of|encoded by|derived from)\s+[\w ]{0,24}?\b(?:bacterio|pro)?phage\s*[\w]*')
HOST_FACTORS = re.compile(r'(?:bacterial|host) (?:gene|factor)s?[^.]{0,44}(?:phage|infection)'
                         r'|host factors?\b'
                         r'|(?:genome[- ]wide|functional genomic|crispri|transposon)[^.]{0,30}'
                         r'(?:screen|identification)[^.]{0,34}(?:phage|infection)')
STRUCTURAL = re.compile(r'crystal structure|structural (?:insight|basis|determinant|feature)|cryo[- ]?em'
                        r'|atomic (?:model|structure)|structures? of (?:a|an|the|two|three)\b'
                        r'|(?:capsid|virion|tail|baseplate|portal) structure')
# A phage-like particle still delivers as a phage does; a recombinant bacterium does not.
# Abedon 2026-11-24: "It should be the phage that is the emphasis, not something else
# delivering an only quasi-phage-like thing." 46607 is no longer in the collection.
LIVE_VECTOR = re.compile(r'phage[- ]like particle')
PHAGE_COMPOUND = re.compile(r'\b(?:bacterio|pro)?phage[- ](?:derived |encoded )?'
                            r'(?:(?:endo)?lysins?|holins?|proteins?|enzymes?|receptor[- ]binding protein'
                            r'|tail[- ]?spike protein|peptidoglycan hydrolase|enzybiotics?)')
# A phage paired with any phage protein is phage therapy, not only with a lysin: 45340 is
# "Phage- and enzybiotic-coated urinary catheters".
WITH_PHAGE = re.compile(r'\b(?:bacterio|pro)?phages? (?:and|plus|with|&) (?:the |its )?' + _PROT
                        + r'|' + _PROT + r's? (?:and|plus|with) (?:the )?\b(?:bacterio|pro)?phage'
                        r'|and its (?:endo)?lysin|in (?:combination|conjunction) with (?:the )?\b(?:bacterio|pro)?phage'
                        r'|phage[- ](?:lysin|enzyme|protein)[- ]?(?:combination|synerg|cocktail)'
                        r'|(?:endo)?lysin[^.]{0,30}synerg[^.]{0,30}\b(?:bacterio|pro)?phage'
                        r'|\b(?:bacterio|pro)?phage[^.]{0,20}synerg[^.]{0,20}(?:endo)?lysin'
                        r'|co[- ]?administ\w+[^.]{0,30}\b(?:bacterio|pro)?phage')
# A title that names a phage as a subject in its own right, rather than only as where the
# enzyme came from, is a phage paper as much as an enzyme paper: those go to judgment.
PHAGE_TOO = re.compile(r'(?<!from )(?<!of )(?<!encoded by )\b(?:bacterio|pro)?phages?\b(?![- ](?:derived|encoded))'
                       r'(?!\s+(?:endo)?lysin)(?!\s+lytic)')
# What rescues an enzyme paper is a phage doing the work, not the words "phage therapy",
# which almost every such abstract uses in its opening line (Abedon, 2026-11-24, on 46674:
# a holin-endolysin fusion whose abstract begins "phage therapy has garnered attention").
WHOLE_PHAGE = re.compile(r'\bphages? (?:were|was|are|is) (?:applied|administered|used|added|given)'
                         r'|treat\w+ with (?:the )?\b(?:bacterio|pro)?phages?|\b(?:bacterio|pro)?phage[- ]treated'
                         r'|\bphage cocktail|whole phage|intact phage|phage particles? (?:were|was|deliver)'
                         r'|phage[- ]?(?:borne|delivered|encapsulated)')

# A record can fail every Literome criterion and still be worth keeping. Abedon kept 46596,
# a routine-looking AIEC phage characterization, for one line of its abstract: "both plaque
# morphology and phage adsorption efficiency are influenced by the composition of the culture
# medium and the carbon source, likely due to alterations in LPS structure on the bacterial
# surface" - "That's ecology, if not explicitly stated as such" (2026-11-24). So the screener
# sorts into three destinations, not two, and nothing with phage-biology interest is ever put
# up for deletion.
ECOLOGY = re.compile(
    # Deliberately NOT host range, burst size, latent period, one-step growth or plaque
    # morphology: those are the standard battery exclusion 1 names, and matching them put 27
    # routine characterization papers up for keeping. What counts is a determinant of
    # infection or a question about phage biology, not a parameter table.
    # defence and counter-defence
    r'defen[cs]e system|counter[- ]defen|anti[- ]?phage|crispr|restriction[- ]modification'
    r'|toxin[- ]antitoxin|cbass|retron|\bbrex\b|abortive infection|superinfection exclusion'
    # coevolution, communities, populations
    r'|co[- ]?evolution|arms race|fluctuating selection|phageome|virome|metagenom'
    r'|(?:phage|viral|virus|host|lysogen)\w*[^.]{0,36}co[- ]?exist'
    r'|co[- ]?exist\w*[^.]{0,36}(?:phage|host|lysogen)'
    r'|prophage diversity|diversity of (?:phage|prophage)|phage ecolog|niche'
    # what decides whether infection happens at all
    r'|\blps\b structur|lipopolysaccharide structur|o[- ]antigen|surface polysacchar|host determinant'
    r'|carbon source|culture medium|medium composition|growth condition|abiotic|adsorption efficiency'
    # A body fluid ACTING ON infection, nothing looser: a bare mention of serum or lipid
    # swept in a pancreatitis paper and four others (2026-11-24).
    r'|(?:serum|plasma|blood component|mucin|saliva|urine|bile|sputum)[^.]{0,50}(?:affect|hinder|inhibit|reduc|influenc|impair|modulat|block)[^.]{0,30}(?:phage|infect|adsorp)'
    r'|(?:phage|infect\w+)[^.]{0,40}(?:hinder|inhibit|impair|neutralis|neutraliz)\w*[^.]{0,30}(?:serum|plasma|blood|mucin|saliva|urine|bile)'
    r'')
# Structural and packaging mechanism is what a paper is ABOUT, not a finding that turns up in
# passing. Noted in an abstract it rescued nothing worth rescuing - 46809 was a routine ESBL
# E. coli phage characterization saved by the words "headful packaging" (Abedon wanted it
# deleted, 2026-11-24) - so these count only from the title.
ECOLOGY_TITLE = re.compile(
    r'genome packaging|phage trna|structural basis|cryo[- ]?em|terminase'
    r'|portal (?:protein|vertex)|phage[- ]host interaction'
    r'|tail fib\w* (?:protein|determin|specific)|baseplate')

# Where a phage CAME FROM is not where it was used. Nearly every isolation paper says
# "isolated from sewage", "from wastewater", "from mulberry field soil", and that put 27
# characterization papers into the tag pile on criterion 1b alone (2026-11-24). The same
# criterion also fired on aspirational conclusions ("supporting its potential as a biocontrol
# candidate"), on background about the setting, and once on a phage's name (47259, whose
# nearest relative is called vB_KpM-Milk). So for this criterion the word has to sit in the
# title, or in a sentence that says a phage was actually put to work there.
# A characterization paper whose title names a specific disease is doing applied work even
# when its abstract never says in vivo: Abedon kept 46596 (adherent-invasive E. coli, i.e.
# Crohn's) and 46616 (bovine mastitis). Those go to judgment, never to deletion.
DISEASE = re.compile(r'mastitis|urinary tract|\buti\b|crohn|colitis|periodontitis|endocarditis|osteomyel'
                     r'|pneumonia\b|sepsis|septic|\bwound|\bburn|otitis|sinusitis|cystic fibrosis'
                     r'|bacter[ae]emia|diarrh|dysenter(?!iae)|cholera|typhoid|tuberculosis|\bacne\b|keratitis'
                     r'|prostatitis|peritonitis|abscess(?!us)|\bulcer(?!ans)|enteritis|gastroenteritis'
                     r'|adherent[- ]invasive')
PROVENANCE = re.compile(r'isolat|recover|obtain|collect|sampl|sourc|enrich|screen\w+ from|derived from|origin'
                        r'|acquired (?:by|from|through|after)|lateral transfer|horizontal transfer')
# "from <somewhere>" is provenance even with no verb attached, which is how titles say it.
VEHICLE = re.compile(r'by [\w ]{0,12}(?:escherichia|salmonella|listeria|lactobacill|bifidobacter'
                     r'|nissle|lactococc|bacteri)[a-z]*(?: coli| nissle| lactis)?'
                     r'|by [\w ]{0,12}e coli'
                     r'|(?:bacteria|bacterial|probiotic)[- ](?:based|mediated) '
                     r'(?:deliver\w*|platform|chassis|vector|system)')
FROM_SOURCE = re.compile(r'from [\w ]{0,24}?(?:sewage|wastewater|waste water|soil|slurry|manure|fa?eces|fa?ecal'
                         r'|effluent|sludge|water|pond|river|lagoon|compost|rumen|silage)')
# NOT a bare \bappli: that matched "applicability" in "supporting its applicability in food
# safety and biotechnology", which is a hope rather than an experiment (46709, 2026-11-24).
APPLIED = re.compile(r'\bapplied\b|\bapplication (?:of|to|in)\b|\bapplying\b'
                     r'|added to|spray|spike|inoculat|challeng|wash|decontaminat|biopreserv|sanitis|sanitiz'
                     r'|treat\w* (?:the )?(?:food|meat|milk|produce|lettuce|chicken|carcass|surface|plant|soil|water|seedling)'
                     r'|reduc\w+[^.]{0,40}\b(?:on|in|from)\b[^.]{0,30}(?:food|meat|milk|cheese|produce|lettuce|spinach|sprout|carcass|egg|chicken|fish|shrimp|plant|leaf|leaves|root|soil|water)'
                     r'|shelf life|storage trial|stored at|post[- ]?harvest|field trial|greenhouse|pond|\bin planta\b')

# What the authors hope someone will do with their phage is not something they did. Nearly
# every isolation abstract closes on "supporting its potential use as a biocontrol agent".
ASPIRATION = re.compile(r'\bpotential|promis\w+|suggest\w*|support\w+ (?:its|the)|\bcandidate'
                        r'|could (?:be|serve|provide|offer)|may (?:be|serve|provide|offer)|might (?:be|serve|provide)|prospect'
                        r'|possible component|one of the components'
                        r'|offer\w*[^.]{0,24}(?:implication|approach|insight|option|promise|advantage|opportunit)'
                        r'|warrant|future (?:use|applicat|studies|stud|work|design|development)|instrumental in|guiding the|will be used|highlight\w* (?:its|the)|pav\w+ the way'
                        r'|pending|further (?:investigat|stud|work|research|evaluat)|remains? to be|yet to be|awaits'
                        r'|requires? (?:further|additional)|should be (?:explored|investigated|tested)'
                        r'|(?:is|it s|its) essential to|essential to (?:know|understand)|in order to'
                        r'|with the (?:aim|goal|objective)|to develop \w+ (?:phage )?(?:therap|applicat|improved)'
                        r'|essential for|(?:are|is) (?:crucial|important|vital|necessary|key)\b'
                        r'|crucial steps?|important steps?|\bneed for\b')
# A model is a model. Abedon 2026-11-24: "Ex vivo models, tissue culture models, all sorts
# of models are fine, just so long as it's not just broth and plaquing." The guard that
# refused to let a cell line count as in vivo is therefore gone. Requiring instead that a
# phage be applied and bacteria measured was tried and withdrawn: it sent eleven of his own
# records to judgment, clinical case reports among them, because their abstracts do not use
# that vocabulary. The screener now loses three catches it used to make by the wrong reason
# (46686, 46841, 46867); those are hand decisions.
PHAGE_APPLIED = re.compile(
    r'\b(?:bacterio)?phages?\b[^.]{0,70}\b(?:treat|therap|administ|appli|dos|instill|inoculat'
    r'|challeng|given|receiv|expos|added|deliver)\w*'
    r'|\b(?:treat|therap|administ|appli|dos|inoculat|deliver)\w*[^.]{0,50}\b(?:bacterio)?phages?\b'
    r'|phage (?:therapy|treatment|cocktail|suspension|preparation|lysate) (?:was|were|is|significantly)')
BACT_ENDPOINT = re.compile(
    r'bacterial (?:load|burden|count|number|titer|titre|density|population)|\bcfus?\b|log(?:10)? reduction'
    r'|reduc\w+[^.]{0,45}(?:bacteri|colon|load|burden|count|cfu|viable)'
    r'|clear\w+[^.]{0,35}(?:bacteri|infection|colon)|eradicat|bacteremia|bacteraemia'
    r'|surviv\w+[^.]{0,35}(?:rate|mice|rats|animals|larvae|fish|chicks?|broiler)'
    r'|protect\w+[^.]{0,35}(?:mice|rats|animals|larvae|fish|chicks?|broiler|against)'
    r'|(?:bacterial|pathogen)\w* (?:killing|elimination|inhibition)|rescued?\b|cured?\b'
    r'|inhibit\w+[^.]{0,35}(?:growth|bacteri|biofilm)|kill\w+[^.]{0,35}(?:bacteri|cells|pathogen)')

def work_sentences(x):
    """Sentences that report what was done: no background, no provenance, no aspiration."""
    out = []
    for sec, sent in sectioned((x['title'] or '') + '. ' + (x['ab'] or '')):
        n = norm(sent)
        if not n or _is_background(sec, sent) or PROVENANCE.search(n) or ASPIRATION.search(n):
            continue
        out.append(n)
    return out

def title_claims(x):
    """False when the title only claims potential, so its criteria must be earned below."""
    return not ASPIRATION.search(x['nt'])

def env_ok(x):
    """True when criterion 1b is about application rather than provenance."""
    bare = FROM_SOURCE.sub(' ', x['nt'])
    if title_claims(x) and FOODENV.search(bare) and not BACT_SUBJECT.search(x['nt']): return True
    return any(FOODENV.search(FROM_SOURCE.sub(' ', n)) and APPLIED.search(n) for n in work_sentences(x))

def micro_ok(x):
    """True unless criterion 8 rests only on faecal matter as an isolation source."""
    if title_claims(x) and MICROBIOME.search(x['nt']): return True
    sents = [n for n in work_sentences(x) if MICROBIOME.search(n)]
    # No work sentence carries the word, so nothing supports the criterion.
    if not sents: return False
    return any(not HABITAT.search(n) and (not FECAL_ONLY.search(n) or not PROVENANCE.search(n))
               for n in sents)

def abx_ok(x):
    """True when criterion 4 is a phage paired with a drug, not a susceptibility table."""
    if title_claims(x) and ABX_PAIR.search(x['nt']): return True
    for n in work_sentences(x):
        if ABX_PAIR.search(n): return True
        if ABX_DRUG.search(n) and PHAGE_WORD.search(n): return True
    return False

def _in_work(x, pat):
    """The criterion has to sit in the title or in a sentence that reports work."""
    if title_claims(x) and pat.search(x['nt']): return True
    return any(pat.search(n) for n in work_sentences(x))

ISOLATED_FROM = re.compile(r'(?:isolat\w*|recover\w*|obtain\w*|collect\w*|sourc\w*|sampl\w*) from [\w ]{0,40}')

def vivo_ok(x):
    """True when criterion 1 rests on an animal or a patient rather than a cell line."""
    if title_claims(x) and VIVO.search(ISOLATED_FROM.sub(' ', FROM_SOURCE.sub(' ', x['nt']))): return True
    for n in work_sentences(x):
        if not VIVO.search(n): continue
        return True
    return False

NO_PHAGE = re.compile(r'\b(?:bacterio|pro)?phage|lysogen|\bvirome|phageome|\bphi[a-z0-9]|\bvb_')

# Receptors are not a criterion of their own. Abedon 2026-11-24: "Receptors matter only for
# the sake of designing cocktails, I think." That makes receptor work part of criterion 5,
# and no rule of its own is needed: 46860, whose abstract states that "developing effective
# phage cocktails requires combining phages with different target receptors", is already
# tagged on the cocktail criterion. A dedicated receptor rule was written and withdrawn - it
# could not tell 46860's stated premise from the closing hope in 46630 ("will be instrumental
# in guiding the future design of phage cocktails"), which Abedon deleted for being
# aspirational, and so resurrected exactly the record he had rejected. 47213, 46935, 47129
# and 47301 stay deleted as prediction, structure, receptor biology and host-factor genetics.

# Phage-tail-like particles count: "Microbial Primer: The R-pyocins of Pseudomonas
# aeruginosa" is one of his, and a pyocin is a phage-like particle.
# Every compound form counts - mycobacteriophage, vibriophage, cyanophage, mycophage,
# coliphage - which the first version missed because it anchored on a word boundary.
# Macrophage is the one to keep out. "Bacterial viruses" and "phagotherapy" are how a good
# deal of the older literature names its subject.
PHAGE_IN_TITLE = re.compile(r'\b(?!macro)\w*phage|phageome|\bvirome|(?:endo)?lysin|\bvb_|\bphi[a-z0-9]'
                            r'|lytic agent|viral predator|pyocin|tailocin|lysogen|bacterial virus')

DEFENCE_REVIEW = re.compile(r'(?:bacterial |host )?defen[cs]e (?:mechanism|system|strateg|arsenal)'
                            r'|anti[- ]?phage (?:defen[cs]e|system|immunit)|phage defen[cs]e'
                            r'|(?:bacterial|microbial) immun(?:e system|ity)'
                            r'|arms race|resist(?:ance|ing) (?:to |against )?(?:bacterio)?phage')

DISPLAY_TEXT = re.compile(r'phage display|displayed? (?:peptide|scfv|antibod|random|library)|biopanning'
                          r'|phage[- ]displayed|phip[- ]?seq|phage immunoprecipitation'
                          r'|phage(?:mid)? librar|scfv librar|naive librar')

def judge(x):
    if not NO_PHAGE.search(x['txt']):
        return 'delete', 'no phage anywhere in it; it reached the search through another word', []
    hits = [name for name, _, pat in C if re.search(pat, x['body'])]
    if 'food, agriculture, or environment' in hits and not env_ok(x):
        hits = [h for h in hits if h != 'food, agriculture, or environment']
    if 'in vivo or clinical' in hits and not vivo_ok(x):
        hits = [h for h in hits if h != 'in vivo or clinical']
    if 'with antibiotics' in hits and not abx_ok(x):
        hits = [h for h in hits if h != 'with antibiotics']
    if 'microbiome' in hits and not micro_ok(x):
        hits = [h for h in hits if h != 'microbiome']
    # Formulation and cocktail are the other two whose words live in closing hopes
    # ("effective phage therapy formulations", "monophage and multi-phage therapy").
    for _n, _p in (('formulation or delivery', FORMUL), ('cocktail', COCKTAIL)):
        if _n in hits and not _in_work(x, _p):
            hits = [h for h in hits if h != _n]
    # What a title says the work is about carries more than what an abstract mentions.
    thits = [name for name, _, pat in C if re.search(pat, x['nt'])
             and (name != 'food, agriculture, or environment' or env_ok(x))
             and (name != 'in vivo or clinical' or vivo_ok(x))
             and (name != 'with antibiotics' or abx_ok(x))
             and (name != 'microbiome' or micro_ok(x))
             and (name != 'formulation or delivery' or _in_work(x, FORMUL))
             and (name != 'cocktail' or _in_work(x, COCKTAIL))]
    if not x['nt']: return 'judge', 'no title to judge from', hits
    # The enzyme on its own is out, and a title naming an antibiotic or an application
    # does not rescue it - but a depolymerase is collected in its own right (criterion 7).
    protein_as_method = re.search(r'(?:through|via|using|by|based on)[\w \-]{0,24}'
                                  r'(?:receptor[- ]binding protein|\brbps?\b|protein analys)'
                                  r'|host range|prediction', x['nt'])
    phage_named = re.search(r'\b(?:bacterio|pro)?phages?\b',
                            PHAGE_SOURCE.sub(' ', PHAGE_COMPOUND.sub(' ', x['nt'])))
    if (PROTEIN_SUBJECT.search(x['nt']) and not DEPOLY.search(x['nt'])
            and not DEFENCE_PROT.search(x['nt']) and not protein_as_method
            and not phage_named):
        escape = (WITH_PHAGE.search(x['nt']) or WHOLE_PHAGE.search(x['nt'])
                  or LIVE_VECTOR.search(x['txt']))
        if not escape and not x['review']:
            escape = WITH_PHAGE.search(x['txt']) or WHOLE_PHAGE.search(x['txt'])
        if not escape:
            if AS_ANTIBACTERIAL.search(x['txt']):
                return 'delete', 'a phage protein developed as an antibacterial in its own right: an antibiotic study, not phage therapy (exclusion 2)', hits
            return 'judge', 'a phage protein is the subject, but not plainly as an antibacterial', hits
    if (not (set(hits) - {'microbiome'}) and PROPHAGE_SUBJECT.search(x['nt'])
            and not induction_strategy(x)
            and not DEFENCE_PROT.search(x['nt'])):
        return 'delete', 'prophage biology; only induction as an antibacterial strategy stays', hits
    if PROPHAGE_VIRULENCE.search(x['nt']):
        return 'delete', "a prophage raising its host's virulence: the bacterium's biology", hits
    if HOST_FACTORS.search(x['nt']) and not WET_WORK.search(x['txt']):
        return 'delete', "which bacterial genes a phage needs: the bacterium's genetics", hits
    if STRUCTURAL.search(x['nt']) and not WET_WORK.search(x['txt']):
        return 'delete', 'structural biology', hits
    if TOOL_PAPER.search(x['nt']) and not WET_WORK.search(x['nt']):
        return 'delete', 'a method or platform for detecting or predicting, not phage therapy', hits
    if DISPLAY.search(x['nt']):
        return 'delete', 'phage display, a way of finding peptides rather than of reducing bacteria', hits
    # An antibody paper reaches this search because phage display found the antibody. The
    # title never says phage, and the work is about a CAR-T construct, a nanobody, an EBV
    # epitope. 25 of the 2026 batch's 289 tags were of this kind. Requiring that the title
    # name no phage keeps the four real phage papers that mention display in passing.
    if DISPLAY_TEXT.search(x['txt']) and not PHAGE_IN_TITLE.search(x['nt']):
        return 'delete', 'an antibody or peptide found by phage display: the technique, not phage therapy (exclusion 8)', hits
    # Only a criterion that implies a bacterium is the target can cancel this: formulation
    # language cannot, or "Tumor-Homing Phage Nanofibers for Nanozyme-Enhanced Targeted
    # Breast Cancer Therapy" escapes on the word nanofiber (1335, 2026-11-24).
    if (OFF_TARGET.search(x['nt']) and not (set(thits) & ESCAPES_OFF_TARGET)
            and not BACTERIAL.search(VEHICLE.sub(' ', x['nt']))):
        return 'delete', 'phages put to a use other than reducing bacteria', hits
    if x['review']:
        # Criterion 10 is a review WHOSE SUBJECT is phage therapy, and exclusion 3 is the
        # review in which phages occupy a paragraph. A review of the gut microbiota and
        # colorectal cancer will always have one sentence about phages modulating a
        # community, so an abstract match cannot tell the two apart; the title can.
        # Without this, 124 of 447 tags in the 2026 batch were microbiome reviews with no
        # phage in them at all.
        #
        # This test comes FIRST, ahead of REVIEW_SUBJ, which carries two alternatives that
        # name no phage - "therapeutic strateg..." and "antibacterial agent..." - and so fired
        # on every review called "... Therapeutic Strategies". That bypassed the title rule
        # and accounts for 14 of the 40 records Abedon deleted from the 2025 tag pile on
        # 2026-11-25: Nature's Arsenal, Advancements in Antibacterial Therapy, the gut-lung
        # axis in tuberculosis, and so on.
        if not PHAGE_IN_TITLE.search(x['nt']):
            return 'delete', 'a review whose title is not about phages: one option among many (exclusion 3)', hits
        if REVIEW_SUBJ.search(x['nt']): return 'tag', 'review of phage therapy or biocontrol (criterion 10)', hits
        # A review of how bacteria defend themselves is the bacterium's biology: a keep, not a
        # tag. "Bacterial defense mechanisms against bacteriophages: an evolutionary arms race"
        # was tagged because its abstract mentions biofilm formation as a surface defence.
        if DEFENCE_REVIEW.search(x['nt']):
            return 'keep', 'a review of bacterial defence against phages rather than of therapy', hits
        if thits: return 'tag', 'review whose title names ' + '; '.join(thits) + ' (criterion 10)', hits
        if hits: return 'tag', 'review whose abstract shows ' + '; '.join(hits) + ' (criterion 10)', hits
        if ECOLOGY.search(x['txt']) or ECOLOGY_TITLE.search(x['nt']): return 'keep', 'review of phage biology rather than of therapy', hits
        return 'delete', 'review in which phages look like one option among many (exclusion 3)', hits
    # A title that says the work is a characterization settles it unless the abstract shows
    # the work went further. This has to come before the abstract hits below, or a passing
    # mention outvotes what the paper says it is.
    if CHARACTERIZATION.search(x['nt']) and not thits:
        if not hits:
            e = ECOLOGY.search(x['txt']) or ECOLOGY_TITLE.search(x['nt'])
            if e: return 'keep', f'characterization, but there is phage biology in it ({e.group(0)})', hits
            d = DISEASE.search(x['nt'])
            if d: return 'judge', f'characterization, but the title names a disease context ({d.group(0)})', hits
            return 'delete', 'characterization only (exclusion 1)', hits
        return 'tag', 'characterization, but the abstract shows ' + '; '.join(hits), hits
    if thits: return 'tag', '; '.join(thits), hits
    if hits: return 'tag', '; '.join(hits), hits
    if not x['hasab']:
        if REVIEW_SUBJ.search(x['nt']):
            return 'tag', 'no abstract, but the title\'s subject is phage therapy (criterion 10)', hits
        return 'judge', 'no abstract to judge from', hits
    e = ECOLOGY.search(x['txt']) or ECOLOGY_TITLE.search(x['nt'])
    if e: return 'keep', f'no Literome criterion, but phage biology worth keeping ({e.group(0)})', hits
    return 'judge', 'nothing in the abstract matches a criterion (criterion 2 is the likely question)', hits

rows = []
for x in sorted(B, key=lambda x: int(x['id'])):
    hid, how = held(x)
    if x['id'] in batch_dups:
        cat, why = 'duplicate in this batch', 'same as ' + batch_dups[x['id']]
    elif hid and hid in PRE and not x['is_pre']:
        # The Literome has the preprint; this is the journal version it was waiting for.
        cat, why = 'preprint now published', f'the Literome holds RM {hid} as a preprint ({how})'
    elif hid:
        cat, why = 'already held', f'{how} as RM {hid}'
    else:
        cat, why, _ = judge(x)
        # With no abstract there is only the title, and a title can carry the band-wagon
        # shape while the piece is entirely on subject. 47058, "Integration of
        # three-dimensional multicolor holography with microfluidic three-dimensional
        # biofilm-on-a-chip technology ... An innovation in phage therapy", was deleted on
        # its title; the Letter itself is about imaging phage penetration of biofilms and
        # choosing phage combinations and doses, which is criterion 10. Abedon ruled it a
        # keeper on 2026-11-25. An absent abstract is missing evidence, not evidence of
        # absence, so nothing is deleted on a title alone.
        if cat == 'delete' and not x['ab'].strip():
            cat, why = 'judge', 'no abstract in the export, so the title alone would have decided it: ' + why
    rows.append(dict(rm_id=x['id'], category=cat, reason=why, year=x['year'],
                     preprint='yes' if x['is_pre'] else '', review='yes' if x['review'] else '',
                     journal=x['j'], doi=x['doi'],
                     pubmed=f'https://pubmed.ncbi.nlm.nih.gov/{x["pmid"]}/' if x['pmid'] else '',
                     title=re.sub(r'[\x10\x11]', '', x['title'])))
with open(out + '/screened.csv', 'w', newline='', encoding='utf-8') as f:
    w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
print('records', len(rows))
for k, v in Counter(r['category'] for r in rows).most_common(): print(f'  {k:28} {v}')
fmt = lambda ids: ' OR '.join('{%s}' % i for i in sorted(ids, key=int))
for cat, name in [('already held', 'already_held'), ('preprint now published', 'preprint_now_published'),
                  ('duplicate in this batch', 'batch_duplicates'),
                  ('delete', 'to_delete'), ('keep', 'keep_untagged'),
                  ('judge', 'needs_judgment'), ('tag', 'to_tag')]:
    ids = [r['rm_id'] for r in rows if r['category'] == cat]
    if ids: open(f'{out}/{name}.txt', 'w').write(fmt(ids) + '\n')
json.dump(rows, open(out + '/rows.json', 'w'))
