feat(summarizer): score articles in the map phase, brief only the important ones

The map prompt now grades every article 0-100 against an explicit rubric as
the first line of its block; the summarizer parses Score:, falls back to the
Importance: label when the line is missing, ranks blocks best-first and passes
only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase.

- new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks()
- reduce prompts drop the 'fill the brief with minor incidents and crime'
  filler instructions and the 'fill ticker with medium then low' clause
- new article_scores table (ensure_tables + alembic 012) persists every grade
  with selected/summary_id/model so thresholds can be tuned from data
- SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs
This commit is contained in:
hermes-backend 2026-11-13 21:47:30 -05:00
commit 853e87b7c5
8 changed files with 775 additions and 37 deletions

View file

@ -0,0 +1,174 @@
"""Map-phase grading: score parsing, batch attribution, selection, reduce input."""
from __future__ import annotations
import pytest
from intel import join_blocks, parse_map_scores, select_graded
def _articles(n: int, start: int = 100) -> list[dict]:
return [
{
"id": start + i,
"title": f"title {i}",
"content": "body",
"url": f"https://ex.com/{i}",
"domain": "ex.com",
}
for i in range(n)
]
def _block(n: int, score=None, importance=None, marker="Article") -> str:
lines = [f"{marker} {n}:"]
if score is not None:
lines.append(f"- Score: {score}")
if importance is not None:
lines.append(f"- Importance: {importance}")
lines.append("- Some fact bullet")
lines.append("- Category: politics")
return "\n".join(lines)
def test_parses_score_line():
raw = _block(1, score=84)
blocks, stats = parse_map_scores(raw, articles=_articles(1))
assert len(blocks) == 1
assert blocks[0]["score"] == 84
assert blocks[0]["importance"] is None
assert stats == {"blocks": 1, "graded": 1, "fallback": 0, "unattributed": 0}
def test_parses_category_and_article_id():
blocks, _ = parse_map_scores(_block(1, score=70), articles=_articles(1))
assert blocks[0]["category"] == "politics"
assert blocks[0]["article_id"] == 100
assert "Score: 70" in blocks[0]["text"]
@pytest.mark.parametrize(
"importance,expected",
[("critical", 95), ("high", 78), ("medium", 50), ("low", 22), ("none", 5)],
)
def test_missing_score_falls_back_to_importance_label(importance, expected):
blocks, stats = parse_map_scores(
_block(1, importance=importance), articles=_articles(1)
)
assert blocks[0]["score"] == expected
assert stats["fallback"] == 1
def test_missing_score_and_missing_importance_defaults_to_50():
blocks, stats = parse_map_scores("Article 1:\n- Some fact bullet", articles=_articles(1))
assert blocks[0]["score"] == 50
assert stats["fallback"] == 1
@pytest.mark.parametrize("line", ["- Score: high", "- Score: n/a", "- Score:"])
def test_garbage_score_line_falls_back(line):
blocks, stats = parse_map_scores(
f"{_block(1, importance='high').replace('- Importance: high', line + chr(10) + '- Importance: high')}",
articles=_articles(1),
)
assert blocks[0]["score"] == 78
assert stats["fallback"] == 1
def test_score_is_clamped():
blocks, stats = parse_map_scores(_block(1, score=150), articles=_articles(1))
assert blocks[0]["score"] == 100
assert stats["fallback"] == 0
blocks, _ = parse_map_scores(_block(1, score=0), articles=_articles(1))
assert blocks[0]["score"] == 0
def test_split_is_case_insensitive_and_markdown_tolerant():
raw = "**article 1:**\n- score: 77\n- Importance: high\n\n ARTICLE 2:\n- Score: 12"
blocks, stats = parse_map_scores(raw, articles=_articles(2))
assert [b["score"] for b in blocks] == [77, 12]
assert stats["graded"] == 2
def test_batch_index_attribution():
articles = _articles(8)
raw = _block(1, score=90) + "\n\n" + _block(2, score=10)
blocks, _ = parse_map_scores(raw, articles=articles, batch_index=1, batch_size=4)
assert [b["article_id"] for b in blocks] == [104, 105]
assert [b["position"] for b in blocks] == [4, 5]
def test_omitted_and_reordered_articles_attribute_by_number():
articles = _articles(4)
raw = "\n\n".join([_block(3, score=30), _block(1, score=88), _block(4, score=61)])
blocks, stats = parse_map_scores(raw, articles=articles, batch_size=4)
assert [b["article_id"] for b in blocks] == [102, 100, 103]
assert stats["graded"] == 3
assert stats["blocks"] == 3
def test_out_of_range_and_duplicate_blocks_are_counted_not_raised():
articles = _articles(2)
raw = "\n\n".join([_block(1, score=90), _block(1, score=20), _block(9, score=80)])
blocks, stats = parse_map_scores(raw, articles=articles, batch_size=2)
assert [b["article_id"] for b in blocks] == [100]
assert stats["unattributed"] == 2
assert stats["blocks"] == 3
@pytest.mark.parametrize("raw", ["", "no article blocks at all", None])
def test_never_raises_on_junk(raw):
blocks, stats = parse_map_scores(raw, articles=_articles(3))
assert blocks == []
assert stats["graded"] == 0
# ── selection ─────────────────────────────────────────────────────────────
def _scored(pairs):
return [
{"position": i, "score": score, "text": f"block {i}"} for i, score in enumerate(pairs)
]
def test_threshold_and_cap_selection_best_first():
blocks = _scored([55, 90, 61, 88, 40, 70])
selected, fallback = select_graded(blocks, min_score=60, top_n=3, fallback_top=3)
assert [b["score"] for b in selected] == [90, 88, 70]
assert [b["text"] for b in selected] == ["block 1", "block 3", "block 5"]
assert fallback is False
def test_ties_keep_original_order():
blocks = _scored([70, 90, 70, 90])
selected, _ = select_graded(blocks, min_score=60, top_n=4, fallback_top=3)
assert [b["text"] for b in selected] == ["block 1", "block 3", "block 0", "block 2"]
def test_nothing_clears_the_bar_uses_fallback_top():
blocks = _scored([40, 12, 55, 3])
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=3)
assert [b["score"] for b in selected] == [55, 40, 12]
assert fallback is True
def test_fallback_top_zero_yields_empty_selection():
blocks = _scored([40, 12, 55])
selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0)
assert selected == []
assert fallback is False
assert join_blocks(selected) == ""
def test_empty_blocks_select_nothing():
assert select_graded([], min_score=60, top_n=12, fallback_top=3) == ([], False)
def test_reduce_input_contains_only_selected_blocks():
raw = "\n\n".join([_block(n, score=s) for n, s in [(1, 12), (2, 95), (3, 5)]])
blocks, _ = parse_map_scores(raw, articles=_articles(3), batch_size=3)
selected, _ = select_graded(blocks, min_score=60, top_n=12, fallback_top=3)
data = join_blocks(selected)
assert "Article 2:" in data
assert "Article 1:" not in data
assert "Article 3:" not in data