p = 'backend/app/services/clinical_library.py'
s = open(p).read()
old = s[s.index('def references_from('):]
new = '''def references_from(passages: list[dict], limit: int = 16,
                    subject: str = "") -> list[dict]:
    """One entry per book and page, headed by what that page was read for.

    Forty chunks of Nelson are not forty references — but they are not one
    either. Two pages of a book are two places to look, and the reader who
    wants to check a claim wants the page it is on. What collapses is the
    duplicate: the same page cited twice is one line.

    `subject` is the article's own topic, and stands in wherever a chunk opens
    mid-paragraph with nothing to name itself by.
    """
    seen: dict[tuple, dict] = {}
    for passage in passages:
        source = passage.get("source") or {}
        title = source.get("title")
        if not title:
            continue
        page = source.get("page")
        key = (title, page)
        if key in seen:
            continue
        seen[key] = {
            "title": title,
            "author": source.get("author") or None,
            "page": page if isinstance(page, int) else None,
            "topic": citations.topic_of(passage.get("text") or "", subject),
        }
    # The corpus stores a filename; a reader needs a citation. `citations`
    # turns one into the other and drops what is not a source at all.
    return citations.tidy(list(seen.values()), limit=limit)
'''
s = s.replace(old, new)
open(p, 'w').write(s)
print('written')
