diff --git a/src/focus/tags.py b/src/focus/tags.py new file mode 100644 index 0000000..6c5bca8 --- /dev/null +++ b/src/focus/tags.py @@ -0,0 +1,49 @@ +"""Human highlights drive ``hl:`` tags. Nothing else on the item moves. + +``llm tag`` replaces only ``llm:*`` (see ``llm.tagger.apply_tags``), so +this namespace stays disjoint. A Zotero-only key has no bib row and is +not an error. +""" + +from __future__ import annotations + +from typing import Any, Iterable + +from focus.protocols import load + + +def tag_for(protocol: str, label: str) -> str: + """The bib tag for one protocol label (``hl::`` unless + the YAML sets ``tag``).""" + proto = load(protocol) + found = proto.label(label) + if found is None: + raise ValueError(f"label {label!r} is not in {protocol}") + return found.tag + + +def sync_item_tags( + bib_store: Any, item_key: str, annotations: Iterable[Any] +) -> dict[str, Any]: + """Make the item's ``hl:*`` tags exactly the tags of its live human + annotations. Other tags are left as they are. + + Returns ``{"skipped": "no bib row"}`` when the key is not in bib, + else ``{"tags": [...]}`` with the ``hl:`` tags now on the item. + """ + try: + current = list(bib_store.get(item_key).tags) + except KeyError: + return {"skipped": "no bib row"} + wanted: set[str] = set() + for ann in annotations: + if ann.deleted_at is not None or ann.provenance != "human": + continue + wanted.add(tag_for(ann.protocol, ann.label)) + have = {tag for tag in current if tag.startswith("hl:")} + for tag in sorted(have - wanted): + bib_store.remove_tag(item_key, tag) + missing = wanted - have + if missing: + bib_store.add_tags(item_key, sorted(missing)) + return {"tags": sorted(wanted)} diff --git a/tests/focus/test_tags.py b/tests/focus/test_tags.py new file mode 100644 index 0000000..f79b8b4 --- /dev/null +++ b/tests/focus/test_tags.py @@ -0,0 +1,118 @@ +"""hl: tags follow live human annotations and leave every other tag alone.""" + +from __future__ import annotations + +import pytest + +from bib.item import Rule +from bib.store import Store +from focus.store import Annotation +from focus.tags import sync_item_tags, tag_for + +KEY = "TAGKEY01" + + +def _ann(**overrides) -> Annotation: + fields = { + "id": "ann-1", + "item_key": KEY, + "attachment": "", + "protocol": "comment-stance", + "protocol_version": 1, + "label": "support", + "quote": "we support it", + "prefix": "", + "suffix": "", + "start_char": None, + "end_char": None, + "page": None, + "rects": None, + "note": "", + "actor": "kert", + "provenance": "human", + "model": None, + "created_at": "2026-11-14T00:00:00+00:00", + "deleted_at": None, + } + fields.update(overrides) + return Annotation(**fields) + + +@pytest.fixture +def bib(): + store = Store(":memory:") + try: + yield store + finally: + store.close() + + +def test_tag_for_uses_the_protocol_tag(): + assert tag_for("comment-stance", "support") == "hl:comment-stance:support" + assert ( + tag_for("cms-disposition", "finalized-as-proposed") + == "hl:cms-disposition:finalized-as-proposed" + ) + with pytest.raises(ValueError, match="no such protocol"): + tag_for("missing", "support") + with pytest.raises(ValueError, match="not in comment-stance"): + tag_for("comment-stance", "nope") + + +def test_sync_add_relabel_delete_and_leave_other_tags(bib: Store): + bib.create( + Rule(key=KEY, title="A comment"), + tags=["llm:payment", "sup:cited", "source:fr", "hl:comment-stance:other"], + ) + added = sync_item_tags(bib, KEY, [_ann()]) + assert added == {"tags": ["hl:comment-stance:support"]} + tags = set(bib.get(KEY).tags) + assert tags >= { + "llm:payment", + "sup:cited", + "source:fr", + "hl:comment-stance:support", + } + assert "hl:comment-stance:other" not in tags + + relabeled = sync_item_tags( + bib, KEY, [_ann(label="do-not-support"), _ann(id="ann-2", label="support")] + ) + assert relabeled["tags"] == [ + "hl:comment-stance:do-not-support", + "hl:comment-stance:support", + ] + assert "hl:comment-stance:support" in bib.get(KEY).tags + + sync_item_tags( + bib, KEY, [_ann(label="do-not-support", deleted_at="2026-11-14T01:00:00+00:00")] + ) + left = set(bib.get(KEY).tags) + assert not any(tag.startswith("hl:") for tag in left) + assert left >= {"llm:payment", "sup:cited", "source:fr"} + + +def test_model_annotations_do_not_tag(bib: Store): + bib.create(Rule(key=KEY, title="A comment"), tags=["llm:payment"]) + result = sync_item_tags( + bib, + KEY, + [_ann(provenance="model", model="local"), _ann(id="h", label="support")], + ) + assert result == {"tags": ["hl:comment-stance:support"]} + assert "llm:payment" in bib.get(KEY).tags + # a second sync with the same human label writes nothing new + again = sync_item_tags(bib, KEY, [_ann()]) + assert again == {"tags": ["hl:comment-stance:support"]} + assert bib.get(KEY).tags.count("hl:comment-stance:support") == 1 + + +def test_missing_bib_row_is_skipped(bib: Store): + assert sync_item_tags(bib, "ZZNOTEXIST", [_ann()]) == {"skipped": "no bib row"} + + +def test_bad_label_writes_nothing(bib: Store): + bib.create(Rule(key=KEY, title="A comment"), tags=["source:fr"]) + with pytest.raises(ValueError, match="not in comment-stance"): + sync_item_tags(bib, KEY, [_ann(label="nope")]) + assert bib.get(KEY).tags == ["source:fr"]