Coverage for app / knowledge / categories.py: 99%
161 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""How an agent uses each kind of knowledge: svc-ai's half of the
2categories both services carry (``app/util/knowledge_categories.py``).
4svc-core sends each knowledge base with the category of the repositories it
5was granted through (``KnowledgeBaseSpec.category``); this module decides
6what that changes, one class per category, so the pipeline and the graph
7never branch on a category's name:
9- **Domain** — today's retrieval, unchanged: an agent whose knowledge is all
10 domain reads exactly what it read before categories existed.
11- **Temporal** — dated content. A search asks for more candidates, keeps
12 those inside the turn's window (triage's ``time_window``, else the
13 source's own ``max_age_days``), weighs recency into the ranking, and
14 renders them newest first under their dates.
15- **Reasoning** — frameworks: judged for whether its method applies, and
16 packed into a block of its own that the answering node reads as the
17 approach to take, not as evidence.
19*Whether* a kind is searched for a request, and in what role, is the turn's
20mix (``app/knowledge/mix.py``). What triage said that decides it travels as
21a :class:`RetrievalTurn`, set by the gate in ``state.context``.
22"""
24from __future__ import annotations
26import re
27from abc import ABC
28from collections.abc import Iterable, Mapping
29from dataclasses import dataclass, field
30from datetime import date, datetime, timezone
31from typing import TYPE_CHECKING, Any, ClassVar, Literal
33from app.util import knowledge_categories, vocab
34from app.util.knowledge_categories import KnowledgeCategory
36if TYPE_CHECKING: # the spec module imports the graph, which imports this
37 from app.models.spec import RetrievedPassage
39# ── The turn ────────────────────────────────────────────────────────────────
41#: How recent a request about what is current wants dated knowledge to be:
42#: triage's ``time_window``, asked only of agents with temporal knowledge.
43TimeWindow = Literal["any", "day", "week", "month", "year"]
45TIME_WINDOWS: dict[str, str] = {
46 "any": "the request names no period: newest first, nothing left out",
47 "day": "today or yesterday",
48 "week": "the last seven days",
49 "month": "the last month",
50 "year": "the last year",
51}
52vocab.check(TIME_WINDOWS, TimeWindow)
54#: Each window in days. A day is two: a passage published yesterday evening
55#: is today's news in another time zone.
56WINDOW_DAYS: dict[str, int | None] = {
57 "any": None,
58 "day": 2,
59 "week": 7,
60 "month": 31,
61 "year": 366,
62}
63vocab.check({key: str(days) for key, days in WINDOW_DAYS.items()}, TimeWindow)
66def window_days(window: object) -> int | None:
67 """``window`` in days; None for ``any`` or a value that names none."""
68 return WINDOW_DAYS.get(str(window or ""), None)
71# ── A period the person names ───────────────────────────────────────────────
72#
73# Triage's window is read from the request's words; these are read in code,
74# both ways. "What has the NCSC warned about in the last two weeks?" came
75# back with no window, so the dated knowledge was never searched; "How
76# should we judge a vendor's 99% claim?" came back with two days.
78_COUNTS = {
79 "a": 1,
80 "an": 1,
81 "one": 1,
82 "two": 2,
83 "three": 3,
84 "four": 4,
85 "five": 5,
86 "six": 6,
87 "seven": 7,
88 "eight": 8,
89 "nine": 9,
90 "ten": 10,
91 "eleven": 11,
92 "twelve": 12,
93 "few": 3,
94 "couple of": 2,
95}
96_UNIT_DAYS = {"day": 1, "week": 7, "fortnight": 14, "month": 31, "year": 366}
97_MONTHS = (
98 "january february march april may june july august september october "
99 "november december"
100).split()
102_DAY = re.compile(
103 r"\b(?:today|tonight|yesterday|overnight|this\s+(?:morning|afternoon|evening)"
104 r"|(?:last|past)\s+24\s+hours)\b",
105 re.IGNORECASE,
106)
107_RELATIVE = re.compile(
108 r"\b(?:last|past|previous|recent)\s+(?:(\d{1,3}|"
109 + "|".join(sorted(_COUNTS, key=len, reverse=True))
110 + r")\s+)?(day|week|fortnight|month|year)s?\b",
111 re.IGNORECASE,
112)
113_THIS = re.compile(r"\b(?:this|current)\s+(week|month|year)\b", re.IGNORECASE)
114_SINCE = re.compile(r"\bsince\s+(" + "|".join(_MONTHS) + r")\b", re.IGNORECASE)
115#: Words that ask for what is recent without saying how recent: triage's
116#: window stands, and none is made up for them.
117_RECENCY = re.compile(
118 r"\b(?:recent|recently|lately|latest|newest|current|currently|nowadays|"
119 r"these\s+days|up[\s-]to[\s-]date|what(?:'s|\s+is)\s+new|anything\s+new)\b",
120 re.IGNORECASE,
121)
124def _window_for(days: int) -> TimeWindow:
125 """The narrowest window that reaches ``days`` back; ``any`` past a year."""
126 for window in ("day", "week", "month", "year"):
127 if days <= (WINDOW_DAYS[window] or 0):
128 return window # type: ignore[return-value]
129 return "any"
132def named_window(text: str, on: date | None = None) -> TimeWindow | None:
133 """The window the period ``text`` names reaches, or None when it names
134 none. Several periods: the one that reaches furthest back."""
135 reach: list[int] = []
136 if _DAY.search(text or ""):
137 reach.append(1)
138 for count, unit in _RELATIVE.findall(text or ""):
139 n = int(count) if count.isdigit() else _COUNTS.get(count.lower(), 1)
140 reach.append(max(1, n) * _UNIT_DAYS[unit.lower()])
141 for unit in _THIS.findall(text or ""):
142 reach.append(_UNIT_DAYS[unit.lower()])
143 on = on or today()
144 for month in _SINCE.findall(text or ""):
145 number = _MONTHS.index(month.lower()) + 1
146 year = on.year if number <= on.month else on.year - 1
147 reach.append((on - date(year, number, 1)).days + 1)
148 if not reach:
149 return None
150 return _window_for(max(reach))
153def turn_window(
154 triage_window: object, text: str, on: date | None = None
155) -> tuple[TimeWindow, str]:
156 """The window a turn's dated knowledge is kept to, and why it differs
157 from triage's (empty when it does not). The person's words decide:
159 - a period they name is the window, whatever triage said;
160 - words that ask for what is recent ("latest") keep triage's;
161 - with neither, triage's window goes: no period was asked for.
162 """
163 said = str(triage_window or "any")
164 said = said if said in WINDOW_DAYS else "any"
165 words = named_window(text, on)
166 if words is not None:
167 note = "" if words == said else f"the request names a period → {words}"
168 return words, note
169 if said == "any" or _RECENCY.search(text or ""):
170 return said, "" # type: ignore[return-value]
171 return "any", f"no period named: triage's {said} window dropped"
174#: Where a turn's ``RetrievalTurn`` travels in ``state.context``: set by the
175#: gate, read by the retrieval node and the turn's report.
176TURN_KEY = "knowledge_turn"
179@dataclass(frozen=True)
180class RetrievalTurn:
181 """What triage said about a request that decides which knowledge it
182 searches and how.
184 ``complexity`` is None when triage failed (nothing is ruled out then);
185 ``named`` holds the ids of knowledge bases the request names;
186 ``web_led``: a request about what is current that triage sent to the
187 web, which searches the agent's dated knowledge beside it and nothing
188 else of it (the gate's rule).
189 """
191 live: bool = False
192 complexity: str | None = None
193 window_days: int | None = None
194 named: frozenset[str] = frozenset()
195 web_led: bool = False
197 def wire(self) -> dict[str, Any]:
198 """As ``state.context`` carries it (checkpointed, so plain values)."""
199 return {
200 "live": self.live,
201 "complexity": self.complexity,
202 "window_days": self.window_days,
203 "named": sorted(self.named),
204 "web_led": self.web_led,
205 }
207 @classmethod
208 def read(cls, raw: object) -> RetrievalTurn:
209 """A wired turn, leniently: anything unreadable reads as the default
210 turn (all knowledge in scope, nothing windowed) — a checkpoint from
211 before categories, or a turn the gate did not see."""
212 if not isinstance(raw, Mapping):
213 return cls()
214 days = raw.get("window_days")
215 # A turn wired before the mix said this as ``only: ["temporal"]``.
216 only = raw.get("only")
217 legacy = isinstance(only, (list, tuple)) and set(map(str, only)) == {
218 KnowledgeCategory.temporal.value
219 }
220 return cls(
221 live=bool(raw.get("live")),
222 complexity=str(raw["complexity"]) if raw.get("complexity") else None,
223 window_days=int(days) if isinstance(days, int) and days > 0 else None,
224 named=frozenset(str(x) for x in raw.get("named") or ()),
225 web_led=bool(raw.get("web_led")) or legacy,
226 )
229# ── Dates ───────────────────────────────────────────────────────────────────
231#: How many days halve a dated passage's recency weight.
232RECENCY_HALF_LIFE_DAYS = 14
233#: The least share of its score a dated passage keeps for age (an undated one
234#: keeps exactly this): relevance still leads, recency orders the relevant.
235RECENCY_FLOOR = 0.6
238def passage_date(passage: RetrievedPassage) -> date | None:
239 """When a passage dates from: its publication, else when its page was
240 stored. ISO dates and timestamps; anything else is undated."""
241 for raw in (passage.published, passage.fetched_at):
242 text = str(raw or "").strip()[:10]
243 try:
244 return date.fromisoformat(text)
245 except ValueError:
246 continue
247 return None
250def today() -> date:
251 return datetime.now(timezone.utc).date()
254# ── Behaviours ──────────────────────────────────────────────────────────────
257class Behaviour(ABC):
258 """What one category changes. The defaults are domain's: nothing."""
260 category: ClassVar[KnowledgeCategory]
261 #: Packed into a block of its own rather than with the evidence.
262 separate: ClassVar[bool] = False
263 #: That block's share of the context budget (a separate kind only).
264 budget_share: ClassVar[float] = 0.0
265 #: How many times the candidates a search of it asks for.
266 candidate_factor: ClassVar[int] = 1
267 #: What the relevance judge is told about it beside its description.
268 judge_note: ClassVar[str] = ""
269 #: What triage and the agent's tool guidance are told about it.
270 inventory_note: ClassVar[str] = ""
271 #: The line a knowledge tool's results from it open with.
272 tool_note: ClassVar[str] = ""
273 #: What discovery's searches look for when setting one up
274 #: (``discovery.LOOKING_FOR`` keys, checked there).
275 looking_for: ClassVar[tuple[str, ...]] = ("sites", "documents")
276 #: What the design of a generated repository of this kind is told.
277 design_note: ClassVar[str] = (
278 "Reference material: the official pages and documents that state it."
279 )
280 #: What the query planner writes for a lane of this kind, when a turn's
281 #: lanes each get their own queries (``retrieval.lane_plan_schema``).
282 query_note: ClassVar[str] = (
283 "Searches of the reference material for what the request asks: "
284 "rephrasings of the question, its sub-questions and a short "
285 "keyword-style variant. Do not repeat the original question."
286 )
288 def adjust(
289 self,
290 passages: list[RetrievedPassage],
291 kb: Mapping[str, Any],
292 turn: RetrievalTurn,
293 on: date,
294 ) -> tuple[list[RetrievedPassage], int]:
295 """Its passages after the relevance judge, and how many it left out."""
296 return passages, 0
299class Domain(Behaviour):
300 category = KnowledgeCategory.domain
303#: The line a knowledge tool's results from temporal knowledge open with.
304DATED_RESULTS_LINE = (
305 "Dated knowledge: each result shows when it was published. Prefer the "
306 "newest, and say how current the answer is."
307)
310class Temporal(Behaviour):
311 category = KnowledgeCategory.temporal
312 candidate_factor = 2
313 judge_note = (
314 "dated: rate what a passage says for the request; how recent it is "
315 "is weighed apart"
316 )
317 inventory_note = (
318 "Temporal — time-sensitive and dated: searched for requests about what "
319 "is current, and read newest first."
320 )
321 tool_note = DATED_RESULTS_LINE
322 looking_for = ("feeds", "sites")
323 query_note = (
324 "Searches of dated material, phrased for what changed: updates, "
325 "announcements and new or revised guidance on the request's subject. "
326 "Leave dates and periods out: how recent is applied apart. Do not "
327 "repeat the original question."
328 )
329 design_note = (
330 "Dated material that changes: prefer feeds and news or updates pages, "
331 "which are read often and newest first, over documents that do not "
332 "change."
333 )
335 def adjust(self, passages, kb, turn, on):
336 window = turn.window_days or _max_age_days(kb)
337 kept: list[RetrievedPassage] = []
338 left_out = 0
339 for passage in passages:
340 when = passage_date(passage)
341 age = (on - when).days if when else None
342 if window and age is not None and age > window and not passage.targeted:
343 left_out += 1
344 continue
345 weight = (
346 0.0 if age is None else 0.5 ** (max(age, 0) / RECENCY_HALF_LIFE_DAYS)
347 )
348 kept.append(
349 passage.model_copy(
350 update={
351 "score": passage.score
352 * (RECENCY_FLOOR + (1 - RECENCY_FLOOR) * weight)
353 }
354 )
355 )
356 return kept, left_out
359class Reasoning(Behaviour):
360 category = KnowledgeCategory.reasoning
361 separate = True
362 budget_share = 0.3
363 judge_note = (
364 "a framework of methods: rate whether its method applies to the task, "
365 "not whether it shares the request's words"
366 )
367 inventory_note = (
368 "Reasoning — analytical and decision frameworks: applied as the method "
369 "for a request that calls for analysis or a decision, never cited as "
370 "facts."
371 )
372 tool_note = (
373 "A framework: apply its method to the task. It is not evidence for facts."
374 )
375 looking_for = ("documents", "sites")
376 query_note = (
377 "Searches for a method or framework that applies to the task — 'a "
378 "method for …', 'criteria for weighing …', 'a framework for …' — "
379 "never for the facts of the request."
380 )
381 design_note = (
382 "Methods for analysis and decisions: prefer documents and pages that "
383 "set out a framework, criteria or a checklist, over news or "
384 "commentary."
385 )
388#: One behaviour per category.
389REGISTRY: dict[KnowledgeCategory, Behaviour] = {
390 behaviour.category: behaviour for behaviour in (Domain(), Temporal(), Reasoning())
391}
392if set(REGISTRY) != set(KnowledgeCategory):
393 raise RuntimeError("Every knowledge category needs a behaviour")
396def category_of(kb: Mapping[str, Any]) -> KnowledgeCategory:
397 """A knowledge base spec's category; one sent without one is domain."""
398 return knowledge_categories.of(kb.get("category"))
401def behaviour(kb: Mapping[str, Any]) -> Behaviour:
402 return REGISTRY[category_of(kb)]
405def holds(
406 knowledge_bases: Iterable[Mapping[str, Any]], category: KnowledgeCategory
407) -> bool:
408 return any(category_of(kb) is category for kb in knowledge_bases)
411def all_domain(knowledge_bases: Iterable[Mapping[str, Any]]) -> bool:
412 """Whether every knowledge base is domain: what each one reads is then
413 exactly what it read before categories existed."""
414 return all(category_of(kb) is KnowledgeCategory.domain for kb in knowledge_bases)
417def _max_age_days(kb: Mapping[str, Any]) -> int | None:
418 """A website source's own window (``source_config.max_age_days``)."""
419 value = (kb.get("source_config") or {}).get("max_age_days")
420 return value if isinstance(value, int) and value > 0 else None
423@dataclass
424class Split:
425 """Passages by how they are packed: with the evidence, or apart."""
427 evidence: list[RetrievedPassage] = field(default_factory=list)
428 apart: dict[KnowledgeCategory, list[RetrievedPassage]] = field(default_factory=dict)
431def split(
432 passages: Iterable[RetrievedPassage], by_kb: Mapping[str, KnowledgeCategory]
433) -> Split:
434 out = Split()
435 for passage in passages:
436 category = by_kb.get(passage.kb_id, knowledge_categories.DEFAULT)
437 if REGISTRY[category].separate:
438 out.apart.setdefault(category, []).append(passage)
439 else:
440 out.evidence.append(passage)
441 return out
444__all__ = [
445 "Behaviour",
446 "DATED_RESULTS_LINE",
447 "REGISTRY",
448 "RetrievalTurn",
449 "TIME_WINDOWS",
450 "TimeWindow",
451 "all_domain",
452 "behaviour",
453 "category_of",
454 "holds",
455 "passage_date",
456 "split",
457 "today",
458 "window_days",
459]