Coverage for app / services / system_resources / knowledge.py: 100%

48 statements  

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

1""" 

2Built-in knowledge — every repository CHAIN-R provides, in one registry. 

3 

4A built-in repository is a ``BuiltInRepository`` (declared with the other 

5spec types in :mod:`.definition`): its spec, the sources it holds, the 

6setting that turns it off, and whether users may grant it. 

7Everything that treats built-in knowledge differently reads this registry 

8rather than naming a repository: provisioning (:mod:`.provision`), the sync 

9that indexes written sources (:mod:`.written`), the crawler's gate 

10(``web_crawl.due_sources``), the source figures, the trust panel, the agent 

11setup catalogue and the recommendations. 

12 

13Two kinds of source: 

14 

15- **Written** (``WrittenSourceSpec``) — markdown CHAIN-R writes, shipped in 

16 the image beside the code and indexed through the same path an upload 

17 takes. The CHAIN-R User Guide is one, and so is every Reasoning built-in 

18 (:mod:`.reasoning`). Nothing is fetched from anybody. 

19- **From a publisher** — a website source read from the publisher's own 

20 site under a licence that allows it (:mod:`.licences`), crawled only while 

21 an agent uses it: a feed (``news.NewsSourceSpec``: News, and the updates 

22 in :mod:`.publishers`) or reference pages (``publishers.PageSourceSpec``). 

23 

24Data only, like the rest of the package. The ids are fixed: see 

25:mod:`.definition`. 

26""" 

27 

28from __future__ import annotations 

29 

30import re 

31from collections.abc import Iterable 

32from typing import Any, Union 

33from uuid import UUID 

34 

35from app.util.knowledge_categories import KnowledgeCategory 

36 

37from .definition import ( 

38 GUIDE_DIR, 

39 GUIDE_KNOWLEDGE, 

40 GUIDE_MIME_TYPE, 

41 GUIDE_REPOSITORY, 

42 BuiltInRepository, 

43 WrittenSourceSpec, 

44) 

45from .news import NEWS_REPOSITORY, NEWS_SOURCES, NewsSourceSpec 

46from .publishers import LAW, SECURITY, UPDATES, PageSourceSpec 

47from .reasoning import REASONING 

48 

49#: A written source's file type: the guide's (markdown, chunked in-process 

50#: with its headings kept). 

51WRITTEN_MIME_TYPE = GUIDE_MIME_TYPE 

52 

53 

54SourceSpec = Union[WrittenSourceSpec, NewsSourceSpec, PageSourceSpec] 

55 

56 

57GUIDE_SOURCE = WrittenSourceSpec( 

58 knowledge=GUIDE_KNOWLEDGE, 

59 folder=GUIDE_DIR, 

60 credits="Written by CHAIN-R; re-indexed whenever a release changes it.", 

61) 

62 

63GUIDE = BuiltInRepository( 

64 repository=GUIDE_REPOSITORY, 

65 sources=(GUIDE_SOURCE,), 

66 label="guide repository", 

67 source_label="guide knowledge base", 

68 grantable=False, 

69) 

70 

71NEWS = BuiltInRepository( 

72 repository=NEWS_REPOSITORY, 

73 sources=NEWS_SOURCES, 

74 label="News repository", 

75 source_label="news source", 

76 switch="BUILT_IN_NEWS_ENABLED", 

77 topics=("news", "latest", "today", "week", "announced", "recent"), 

78) 

79 

80#: Every built-in repository, in the order pages list them: Domain, then 

81#: Temporal, then Reasoning. 

82BUILT_IN_REPOSITORIES: tuple[BuiltInRepository, ...] = ( 

83 GUIDE, 

84 LAW, 

85 SECURITY, 

86 NEWS, 

87 UPDATES, 

88 *REASONING, 

89) 

90 

91_BY_SOURCE: dict[UUID, tuple[BuiltInRepository, SourceSpec]] = { 

92 source.id: (entry, source) 

93 for entry in BUILT_IN_REPOSITORIES 

94 for source in entry.sources 

95} 

96 

97 

98def enabled(settings: Any = None) -> tuple[BuiltInRepository, ...]: 

99 """The built-in repositories this deployment provides.""" 

100 return tuple(entry for entry in BUILT_IN_REPOSITORIES if entry.enabled(settings)) 

101 

102 

103def grantable(settings: Any = None) -> tuple[BuiltInRepository, ...]: 

104 """The built-in repositories users may grant their own agents.""" 

105 return tuple(entry for entry in enabled(settings) if entry.grantable) 

106 

107 

108def of_repository(repository_id: UUID | None) -> BuiltInRepository | None: 

109 return next( 

110 (entry for entry in BUILT_IN_REPOSITORIES if entry.id == repository_id), 

111 None, 

112 ) 

113 

114 

115def of_source(knowledge_id: UUID | None) -> BuiltInRepository | None: 

116 """The built-in repository a built-in source belongs to, or None for any 

117 other source (and one a release dropped).""" 

118 found = _BY_SOURCE.get(knowledge_id) if knowledge_id is not None else None 

119 return found[0] if found else None 

120 

121 

122def source_spec(knowledge_id: UUID | None) -> SourceSpec | None: 

123 found = _BY_SOURCE.get(knowledge_id) if knowledge_id is not None else None 

124 return found[1] if found else None 

125 

126 

127def crawl_enabled(knowledge_id: UUID | None, settings: Any = None) -> bool: 

128 """Whether a built-in website source may be crawled at all: its 

129 repository is provided here. Whether an agent uses it is the crawler's 

130 other half (``web_crawl.system_sources_in_use``).""" 

131 entry = of_source(knowledge_id) 

132 return entry is not None and entry.enabled(settings) 

133 

134 

135def ids() -> tuple[UUID, ...]: 

136 """Every built-in repository's and built-in source's fixed id.""" 

137 return tuple( 

138 id_ 

139 for entry in BUILT_IN_REPOSITORIES 

140 for id_ in (entry.id, *(source.id for source in entry.sources)) 

141 ) 

142 

143 

144_WORD = re.compile(r"[a-z0-9][a-z0-9-]*") 

145 

146 

147def words(text: str | None) -> frozenset[str]: 

148 """The words of ``text``, lower-cased, as topics are written.""" 

149 return frozenset(_WORD.findall((text or "").lower())) 

150 

151 

152def suggested( 

153 category: KnowledgeCategory, 

154 text: str | None = None, 

155 *, 

156 exclude: Iterable[UUID] = (), 

157 settings: Any = None, 

158) -> list[BuiltInRepository]: 

159 """The grantable built-ins of ``category`` this deployment provides, 

160 best match first: those whose ``topics`` share the most words with 

161 ``text`` (an agent's description, the questions it was asked), the 

162 rest in registry order. Never one in ``exclude`` (already granted).""" 

163 said = words(text) 

164 excluded = set(exclude) 

165 candidates = [ 

166 entry 

167 for entry in grantable(settings) 

168 if entry.category is category and entry.id not in excluded 

169 ] 

170 return sorted( 

171 candidates, 

172 key=lambda entry: -len(said & frozenset(entry.topics)), 

173 ) 

174 

175 

176def matching( 

177 category: KnowledgeCategory, 

178 text: str | None, 

179 *, 

180 exclude: Iterable[UUID] = (), 

181 settings: Any = None, 

182) -> list[BuiltInRepository]: 

183 """``suggested``, keeping only those sharing at least one topic word.""" 

184 said = words(text) 

185 return [ 

186 entry 

187 for entry in suggested(category, text, exclude=exclude, settings=settings) 

188 if said & frozenset(entry.topics) 

189 ] 

190 

191 

192def written_sources(settings: Any = None) -> tuple[WrittenSourceSpec, ...]: 

193 """Every written source this deployment provides, the guide first.""" 

194 return tuple( 

195 source 

196 for entry in enabled(settings) 

197 for source in entry.sources 

198 if isinstance(source, WrittenSourceSpec) 

199 ) 

200 

201 

202__all__ = [ 

203 "BUILT_IN_REPOSITORIES", 

204 "BuiltInRepository", 

205 "GUIDE", 

206 "GUIDE_SOURCE", 

207 "NEWS", 

208 "SourceSpec", 

209 "WRITTEN_MIME_TYPE", 

210 "WrittenSourceSpec", 

211 "crawl_enabled", 

212 "enabled", 

213 "grantable", 

214 "ids", 

215 "matching", 

216 "of_repository", 

217 "of_source", 

218 "source_spec", 

219 "suggested", 

220 "words", 

221 "written_sources", 

222]