Coverage for app / services / knowledge / recommendations / base.py: 98%

110 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""What a knowledge recommendation is, and the registry of its kinds. 

2 

3A recommendation is one thing worth changing about a workspace's knowledge, 

4with the evidence that says so and the step that would change it. Each kind 

5is one class, registered with :func:`register_kind` and served as a 

6catalogue, so adding one is a class, not a branch on a page. 

7 

8A kind reads recorded facts only — the retrieval record, the citations 

9record, grants, settings and documents — and never a model. Its figures may 

10count the whole workspace; its examples are the viewer's own questions only, 

11as the usage panel's answers are. An action names an existing flow and what 

12to fill it with (:class:`Prefill`); nothing is ever changed by showing one. 

13""" 

14 

15from __future__ import annotations 

16 

17import hashlib 

18from abc import ABC, abstractmethod 

19from dataclasses import dataclass, field 

20from datetime import datetime 

21from enum import StrEnum 

22from typing import TYPE_CHECKING, Any 

23from uuid import UUID 

24 

25if TYPE_CHECKING: 

26 from app.services.knowledge.recommendations.context import ( 

27 RecommendationContext, 

28 ) 

29 

30 

31class Section(StrEnum): 

32 """Where a kind's recommendations come from, in the order a page lists 

33 them.""" 

34 

35 #: What agents were asked and their knowledge could not answer. 

36 answers = "answers" 

37 #: How the knowledge is used. 

38 use = "use" 

39 #: How it is kept. 

40 upkeep = "upkeep" 

41 

42 

43SECTION_LABELS: dict[str, str] = { 

44 Section.answers: "What agents could not answer", 

45 Section.use: "How it is used", 

46 Section.upkeep: "How it is kept", 

47} 

48if set(SECTION_LABELS) != set(Section): 

49 raise RuntimeError("Every recommendation section needs a label") 

50 

51 

52class SubjectKind(StrEnum): 

53 """What a recommendation is about.""" 

54 

55 agent = "agent" 

56 repository = "repository" 

57 knowledge = "knowledge" 

58 #: A web site, by its host. 

59 site = "site" 

60 #: Two sources at once. 

61 pair = "pair" 

62 

63 

64class Flow(StrEnum): 

65 """The existing flows an action opens, and what each fills.""" 

66 

67 #: Generate knowledge (the generate dialog), on a kind, from the 

68 #: viewer's own questions when there are any. 

69 generate_knowledge = "generate_knowledge" 

70 #: A new website source for a site. 

71 add_website = "add_website" 

72 #: Attach a repository to an agent. 

73 attach_repository = "attach_repository" 

74 #: A source's page, on a tab. 

75 open_source = "open_source" 

76 #: A source's settings, with the changes to make filled in. 

77 edit_source = "edit_source" 

78 #: A repository's page, on a tab. 

79 open_repository = "open_repository" 

80 #: A repository's details, with its kind filled in. 

81 edit_repository = "edit_repository" 

82 

83 

84@dataclass(frozen=True) 

85class Subject: 

86 kind: SubjectKind 

87 #: An id, a host, or two ids joined by ``|``. 

88 id: str 

89 name: str 

90 

91 

92@dataclass(frozen=True) 

93class Figure: 

94 """One count the recommendation rests on.""" 

95 

96 label: str 

97 value: int 

98 

99 

100@dataclass(frozen=True) 

101class Example: 

102 """One of the viewer's own questions behind it, and what it lacked.""" 

103 

104 text: str 

105 detail: str | None = None 

106 at: datetime | None = None 

107 

108 

109@dataclass(frozen=True) 

110class Prefill: 

111 """What an action fills its flow with. Every field is optional; a flow 

112 reads the ones it takes.""" 

113 

114 category: str | None = None 

115 #: The viewer's own turns a generation describes its knowledge from. 

116 from_turns: tuple[UUID, ...] = () 

117 agent_id: UUID | None = None 

118 agent_name: str | None = None 

119 repository_id: UUID | None = None 

120 repository_name: str | None = None 

121 knowledge_id: UUID | None = None 

122 knowledge_name: str | None = None 

123 #: The page tab an ``open_*`` flow opens on. 

124 tab: str | None = None 

125 url: str | None = None 

126 name: str | None = None 

127 refresh: str | None = None 

128 max_age_days: int | None = None 

129 

130 

131@dataclass(frozen=True) 

132class Action: 

133 flow: Flow 

134 label: str 

135 prefill: Prefill = field(default_factory=Prefill) 

136 

137 

138@dataclass(frozen=True) 

139class Touches: 

140 """What a recommendation is about, for the pages that show it: a 

141 repository's page shows those touching it or one of its sources, an 

142 agent's those touching the agent.""" 

143 

144 agents: frozenset[UUID] = frozenset() 

145 repositories: frozenset[UUID] = frozenset() 

146 sources: frozenset[UUID] = frozenset() 

147 

148 

149@dataclass(frozen=True) 

150class Recommendation: 

151 kind: str 

152 subject: Subject 

153 title: str 

154 #: Why, in a sentence or two, from the figures. 

155 why: str 

156 figures: tuple[Figure, ...] 

157 examples: tuple[Example, ...] 

158 actions: tuple[Action, ...] 

159 #: What the evidence reads, for a dismissal to hold while it holds. 

160 fingerprint: str 

161 touches: Touches = field(default_factory=Touches) 

162 #: How large the evidence is, to order recommendations of one kind. 

163 weight: float = 0.0 

164 

165 

166class RecommendationKind(ABC): 

167 key: str 

168 label: str 

169 #: What it looks for, for the catalogue. 

170 description: str 

171 section: Section 

172 

173 @abstractmethod 

174 def find(self, ctx: RecommendationContext) -> list[Recommendation]: ... 

175 

176 def recommendation(self, **fields: Any) -> Recommendation: 

177 return Recommendation(kind=self.key, **fields) 

178 

179 

180_REGISTRY: dict[str, RecommendationKind] = {} 

181 

182 

183def register_kind(cls: type[RecommendationKind]) -> type[RecommendationKind]: 

184 instance = cls() 

185 if instance.key in _REGISTRY: 

186 raise ValueError(f"Recommendation kind {instance.key!r} registered twice") 

187 _REGISTRY[instance.key] = instance 

188 return cls 

189 

190 

191def kinds() -> list[RecommendationKind]: 

192 """Every kind, in the order a page lists what they find: by section, 

193 then as registered.""" 

194 order = list(Section) 

195 return sorted(_REGISTRY.values(), key=lambda k: order.index(k.section)) 

196 

197 

198def get_kind(key: str) -> RecommendationKind | None: 

199 return _REGISTRY.get(key) 

200 

201 

202def catalogue() -> list[dict[str, str]]: 

203 return [ 

204 { 

205 "key": k.key, 

206 "label": k.label, 

207 "description": k.description, 

208 "section": k.section.value, 

209 "section_label": SECTION_LABELS[k.section], 

210 } 

211 for k in kinds() 

212 ] 

213 

214 

215#: The counts a fingerprint moves at: a dismissal holds while a count stays 

216#: in its band, so one more question does not bring it back and ten more do. 

217BANDS = (1, 3, 10, 30, 100, 300, 1_000, 3_000, 10_000) 

218 

219 

220def band(count: int) -> int: 

221 """The band ``count`` falls in (0 below the first).""" 

222 return sum(1 for edge in BANDS if count >= edge) 

223 

224 

225def fingerprint(*parts: object) -> str: 

226 """A short, stable digest of what the evidence reads.""" 

227 text = "|".join("" if p is None else str(p) for p in parts) 

228 return hashlib.sha256(text.encode()).hexdigest()[:32] 

229 

230 

231def plural(n: int, one: str, many: str | None = None) -> str: 

232 return f"{n:,} {one if n == 1 else (many or one + 's')}" 

233 

234 

235__all__ = [ 

236 "BANDS", 

237 "Action", 

238 "Example", 

239 "Figure", 

240 "Flow", 

241 "Prefill", 

242 "Recommendation", 

243 "RecommendationKind", 

244 "SECTION_LABELS", 

245 "Section", 

246 "Subject", 

247 "SubjectKind", 

248 "Touches", 

249 "band", 

250 "catalogue", 

251 "fingerprint", 

252 "get_kind", 

253 "kinds", 

254 "plural", 

255 "register_kind", 

256]