Coverage for app / services / system_resources / definition.py: 99%
169 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2What CHAINR Bot *is* — the rows the platform provisions for every user — and
3the spec types every built-in resource is declared with (the built-in
4skillsets themselves live in :mod:`.skillsets`).
6Everything here is data. :mod:`.provision` writes it to the database and
7:mod:`.written` indexes the user guide into the knowledge base; neither decides
8what the bot says or knows. Changing the bot is therefore a change to this
9file (or to ``guide/``) and a release — never an API call, which refuses
10system rows outright (see ``verify_resource_access``).
12The ids are fixed literals rather than generated so every deployment agrees
13on them: a link to the bot, a rule pinned to it and a dashboard tile pointed
14at it all survive a fresh database, and the provisioner can find its rows
15again without a lookup by name that a user's own "CHAINR Bot" could shadow.
16"""
18from __future__ import annotations
20from dataclasses import dataclass, field
21from pathlib import Path
22from typing import Any
23from uuid import UUID
25from app.db.postgres.enums import DashboardEnum, EvaluationEnum, RuleEnum
26from app.util import knowledge_categories
27from app.util.knowledge_categories import KnowledgeCategory
29from . import web_sources
31#: Where the user guide lives. Shipped inside the image with the code, so the
32#: guide an image indexes is always the guide for the release it runs.
33GUIDE_DIR = Path(__file__).parent / "guide"
35#: The guide's file type. Markdown is chunked in-process by
36#: ``docling_client`` — no Docling round-trip — and keeps its headings.
37GUIDE_MIME_TYPE = "text/markdown"
38GUIDE_SUFFIX = ".md"
41@dataclass(frozen=True)
42class SystemAgentSpec:
43 id: UUID
44 name: str
45 description: str
46 icon: str
47 accent: str
48 system_prompt: str
49 #: Stored on ``Agent.config`` — an empty dict rather than None, so the
50 #: drift check compares the same value every release.
51 config: dict[str, Any] = field(default_factory=dict)
53 def fields(self) -> dict[str, Any]:
54 return {
55 "name": self.name,
56 "description": self.description,
57 "icon": self.icon,
58 "accent": self.accent,
59 "system_prompt": self.system_prompt,
60 "config": dict(self.config),
61 # Asks before answering a request it could read several ways —
62 # the behaviour every new agent gets, shown first on the bot.
63 "clarify_scope": True,
64 # No pinned model: the bot answers with the deployment's default
65 # model, so it works on any install without naming a provider.
66 "ai_model_id": None,
67 }
70@dataclass(frozen=True)
71class SystemRepositorySpec:
72 id: UUID
73 name: str
74 description: str
75 icon: str
76 accent: str
77 #: What kind of knowledge it holds, which fixes the kind of every source
78 #: in it (``knowledge/repositories.require_one_category``).
79 category: KnowledgeCategory = knowledge_categories.DEFAULT
81 def fields(self) -> dict[str, Any]:
82 return {
83 "name": self.name,
84 "description": self.description,
85 "icon": self.icon,
86 "accent": self.accent,
87 "category": self.category.value,
88 }
91@dataclass(frozen=True)
92class SystemKnowledgeSpec:
93 id: UUID
94 name: str
95 description: str
96 source_type: str = "file"
98 def fields(self) -> dict[str, Any]:
99 return {
100 "name": self.name,
101 "description": self.description,
102 "source_type": self.source_type,
103 "source_config": {},
104 }
107@dataclass(frozen=True)
108class WrittenSourceSpec:
109 """A built-in file source whose documents are markdown in the image, one
110 document per file, named by its filename."""
112 knowledge: SystemKnowledgeSpec
113 #: The folder its documents live in, shipped with the code.
114 folder: Path
115 #: Who wrote it and whose work it follows, as its trust panel shows it.
116 credits: str
118 @property
119 def id(self) -> UUID:
120 return self.knowledge.id
122 @property
123 def name(self) -> str:
124 return self.knowledge.name
126 @property
127 def source_type(self) -> str:
128 return "file"
130 def fields(self) -> dict[str, Any]:
131 return self.knowledge.fields()
133 def files(self) -> list[Path]:
134 """Its documents, in a stable order."""
135 if not self.folder.is_dir():
136 return []
137 return sorted(
138 path
139 for path in self.folder.iterdir()
140 if path.is_file() and path.suffix == GUIDE_SUFFIX
141 )
144@dataclass(frozen=True)
145class BuiltInRepository:
146 """One built-in repository and the sources it holds, exactly."""
148 repository: SystemRepositorySpec
149 #: Its sources: ``WrittenSourceSpec`` or ``news.NewsSourceSpec``.
150 sources: tuple[Any, ...]
151 #: How provisioning names it and each of its sources in its summary.
152 label: str
153 source_label: str
154 #: The setting that turns it off (provisioning, crawling, offering), or
155 #: None for one that is always there.
156 switch: str | None = None
157 #: Whether users may grant it to their own agents. The user guide may
158 #: not be offered: it is CHAINR Bot's, provisioned with the bot.
159 grantable: bool = True
160 #: Words a question about its subject tends to use, for the
161 #: recommendations that suggest it.
162 topics: tuple[str, ...] = ()
164 @property
165 def id(self) -> UUID:
166 return self.repository.id
168 @property
169 def name(self) -> str:
170 return self.repository.name
172 @property
173 def category(self) -> KnowledgeCategory:
174 return self.repository.category
176 def enabled(self, settings: Any = None) -> bool:
177 """Whether the deployment provides it. A setting a settings object
178 does not carry reads as on, as an unset one does."""
179 if self.switch is None:
180 return True
181 if settings is None:
182 from app.common.settings import get_settings
184 settings = get_settings()
185 return getattr(settings, self.switch, True) is not False
188@dataclass(frozen=True)
189class SystemSkillSpec:
190 id: UUID
191 name: str
192 description: str
193 tags: tuple[str, ...]
194 #: Validated by the same ``_GraphDefinitionSchema`` a user's skill is
195 #: (``tests/test_system_resources.py``), and restricted to svc-ai's
196 #: built-in workers — a ``cw_`` worker belongs to somebody.
197 graph_definition: dict[str, Any]
199 def fields(self) -> dict[str, Any]:
200 return {
201 "name": self.name,
202 "description": self.description,
203 "tags": list(self.tags),
204 "graph_definition": self.graph_definition,
205 }
208@dataclass(frozen=True)
209class SystemSkillsetSpec:
210 id: UUID
211 name: str
212 description: str
213 #: Its skills, in the order the Skillsets page lists them.
214 skills: tuple[SystemSkillSpec, ...]
216 def fields(self) -> dict[str, Any]:
217 return {"name": self.name, "description": self.description}
220@dataclass(frozen=True)
221class SystemCaseSpec:
222 """One case of a gold dataset, in the shape a user's case takes.
224 Held to the same validation (``Schema.TestSuite`` / ``Schema.TestCase``
225 and ``context.parse_situation``) by ``tests/test_gold_datasets.py``.
226 """
228 id: UUID
229 name: str
230 prompt: str
231 #: ``[{text, gate}]`` items, added to the dataset's own.
232 criteria: tuple[dict[str, Any], ...] = ()
233 expected_output: str | None = None
234 #: ``answer`` / ``clarify`` / ``decline``, or None for "not stated".
235 expected_behaviour: str | None = None
236 #: ``facts``, ``must_use_tools``, ``must_not_use_tools``.
237 expectation: dict[str, Any] | None = None
238 #: ``data``, ``history``, ``tool_fixtures``.
239 situation: dict[str, Any] | None = None
240 tags: tuple[str, ...] = ()
242 def fields(self) -> dict[str, Any]:
243 return {
244 "name": self.name,
245 "input": {"prompt": self.prompt},
246 "expected_output": self.expected_output,
247 "criteria": [dict(item) for item in self.criteria] or None,
248 "examples": None,
249 "expected_behaviour": self.expected_behaviour,
250 "expectation": self.expectation,
251 "situation": self.situation,
252 "tags": list(self.tags) or None,
253 }
256@dataclass(frozen=True)
257class SystemDatasetSpec:
258 """A gold dataset: a standard benchmark every user can run and copy."""
260 id: UUID
261 name: str
262 description: str
263 #: What every good answer in the dataset must do.
264 criteria: tuple[dict[str, Any], ...]
265 #: The mean score that counts as passing — set per dataset, because the
266 #: bar depends on what the cases stand for.
267 pass_mark: float
268 cases: tuple[SystemCaseSpec, ...]
270 def fields(self) -> dict[str, Any]:
271 return {
272 "name": self.name,
273 "description": self.description,
274 "status": EvaluationEnum.Status.active,
275 "criteria": [dict(item) for item in self.criteria],
276 "pass_mark": self.pass_mark,
277 }
280@dataclass(frozen=True)
281class SystemRuleSpec:
282 """A built-in governance rule: a definition users create rules from.
284 Held to the checks a generated rule is (``validate_proposed_rule``'s
285 condition and action validators) by ``tests/test_built_in_rules.py``.
286 """
288 id: UUID
289 name: str
290 description: str
291 layer: RuleEnum.Layer
292 conditions: tuple[dict[str, Any], ...] = ()
293 actions: tuple[dict[str, Any], ...] = ()
294 priority: int = 0
296 def fields(self) -> dict[str, Any]:
297 return {
298 "name": self.name,
299 "description": self.description,
300 "layer": self.layer,
301 # A rule created from a built-in starts global; the user narrows
302 # it in the builder before creating it.
303 "scope_type": RuleEnum.Scope.global_,
304 "scope_id": None,
305 "conditions": [dict(block) for block in self.conditions],
306 "actions": [dict(block) for block in self.actions],
307 # A built-in governs nobody — the engine loads only the rules a
308 # user owns — and inactive says so to anything that reads it
309 # without that filter.
310 "is_active": False,
311 "priority": self.priority,
312 }
315@dataclass(frozen=True)
316class SystemWidgetSpec:
317 """One tile on a built-in board, declared as its renderer validates it.
319 ``tests/test_built_in_dashboards.py`` runs every config through its
320 renderer's ``validate_config`` and requires it back unchanged, so a
321 definition never depends on normalisation to mean what it says.
322 """
324 id: UUID
325 widget_type: DashboardEnum.WidgetType
326 title: str
327 config: dict[str, Any]
328 x: int
329 y: int
330 w: int
331 h: int
332 #: Dynamic tiles only: how often the shared cache is regenerated.
333 refresh_interval_seconds: int | None = None
335 def fields(self, position: int) -> dict[str, Any]:
336 return {
337 "widget_type": self.widget_type,
338 "title": self.title,
339 "config": dict(self.config),
340 "x": self.x,
341 "y": self.y,
342 "w": self.w,
343 "h": self.h,
344 "position": position,
345 "refresh_interval_seconds": self.refresh_interval_seconds,
346 }
349@dataclass(frozen=True)
350class SystemDashboardSpec:
351 """A built-in board: one row every user opens, drawing their own data."""
353 id: UUID
354 name: str
355 description: str
356 icon: str
357 accent: str
358 #: Order on the Dashboards page's Built-in section.
359 position: int
360 widgets: tuple[SystemWidgetSpec, ...]
362 def fields(self) -> dict[str, Any]:
363 return {
364 "name": self.name,
365 "description": self.description,
366 "icon": self.icon,
367 "accent": self.accent,
368 # Home is one user's choice of board; a shared row cannot be it.
369 "is_home": False,
370 "position": self.position,
371 }
374BOT_SYSTEM_PROMPT = """\
375You are CHAINR Bot, the built-in assistant of CHAIN-R — a privacy- and \
376sovereignty-focused AI control plane where people run governed AI agents \
377over their own knowledge and watch what those agents do.
379Every user can talk to you from their first minute on the platform, before \
380they have built anything. You have two jobs:
3821. **Help people use CHAIN-R.** Explain how the platform works — from agents \
383and the knowledge they answer from to governance, evaluation and dashboards, \
384as the user guide describes it — and walk people through doing things in it: \
385where to click, what each option means, and what to try next.
3862. **Be a capable general assistant.** Answer questions, draft and edit \
387text, reason through problems, and explain ideas clearly.
389How to answer questions about the platform:
390- Ground them in the CHAIN-R user guide you have been given, and cite it. \
391If the guide does not cover something, say so plainly rather than guessing; \
392never invent a feature, menu, setting or limit.
393- Name places in the app the way the interface does (for example \
394"Inference → Agents" or "Governance → Rules").
395- When someone asks how to handle recurring work on their own material in \
396CHAIN-R — work that needs their documents, skills or rules of their own — \
397suggest building an agent of their own and explain how, as well as \
398answering what they asked.
400What you are and are not:
401- You are a platform-managed agent. Nobody can edit your instructions, \
402knowledge or configuration, and you cannot change anything in the user's \
403account: you cannot create, edit or delete their agents, knowledge, rules or \
404dashboards. Tell them how to do it instead.
405- You can see the conversation you are in, what you remember of your \
406earlier conversations with this user, documents they attach in this chat, \
407the CHAIN-R user guide and what your tools return, web search included. You \
408cannot see the user's other agents, their other documents or data, or their \
409conversations with other agents, so do not claim to.
410- Nobody can grant you a repository or skillset, built-in ones included, so \
411never tell anyone to grant one to you.
412- Each user's conversations and memories with you are private to them.
414How to answer everything else:
415- **Use the user guide only for questions about CHAIN-R.** For anything \
416else, answer the question itself. Do not cite the guide, quote it or point \
417anyone to it, even when a passage of it shares a word with the question, and \
418never suggest building an agent or granting a repository in place of an \
419answer.
420- **Material you are given comes first.** When the user supplies a \
421document, data or a policy, answer from it. If it does not say, say so \
422plainly and suggest where the answer could be found; do not fill the gap \
423from general knowledge, and never estimate a figure, date or rate it does \
424not give. Quote it exactly when asked to.
425- **Never invent.** No made-up figures, names, dates, quotations, studies, \
426citations or links. If you are not sure something exists, say so rather \
427than present it as real. Correct a false premise instead of building on \
428it. For anything current, use the tool that provides it — web search when \
429no other tool does — and answer from what it returns; if it fails, say so. \
430Material you are given still comes first: do not use a tool for what it \
431answers, or to fill a gap it leaves. What you remember of earlier \
432conversations is not material you are given: never repeat an earlier \
433answer in place of using a tool now.
434- **Tools.** Use a tool when the answer depends on information only it can \
435give, and not otherwise. Report what it returned exactly, errors included. \
436If a search finds nothing or fails, say what the tool reported; never blame \
437rules, filters or restrictions it did not name. Your searches put a few \
438publishers first; treat them as a starting point and corroborate across \
439independent sources. \
440Never take an action — sending, deleting, buying or changing anything — \
441that the user did not explicitly ask for; when they ask you to prepare \
442something, prepare it and stop. If a tool needs a detail only the person \
443can give, ask for it with ask_user rather than guess.
444- **Contested questions.** On political and moral questions where \
445reasonable people disagree, set out the main positions fairly, in terms \
446their own supporters would recognise; do not give your own verdict or tell \
447anyone how to vote, and do not adopt a loaded premise from either side. \
448State settled facts and scientific consensus plainly, without false \
449balance. Treat comparable requests about different parties or sides alike.
450- **Personal data.** Share only the personal data a request needs and the \
451person asking is plainly entitled to. Never guess or infer sensitive \
452characteristics — health, ethnicity, religion, sexuality, political views — \
453about identifiable people, and never help locate, track or re-identify a \
454private individual. Keep identifiers out of summaries unless they are the \
455point. Describe data-protection rights accurately, limits included.
456- **Help, safely.** Decline what would cause real harm, and say briefly \
457why; answer what only sounds sensitive.
458- **Documents.** When asked for a document, report or PDF, research it \
459first: search for what it needs, read the most useful pages rather than \
460relying on search snippets, and cite them. Cover the request in full: \
461several things asked for means several, each with what makes it useful, \
462and an image where one helps.
463- **Asking.** Decide what you reasonably can yourself — for an open request \
464("interesting illusions"), choose — and say what you chose. When a request \
465is too ambiguous to answer well, ask with ask_user: one form, only what \
466would change your answer, and only what the person wants or alone knows. \
467Never ask them to find, choose or fix what they asked you for — a file, an \
468image, a link, a source: do it yourself, or say what you could not do. \
469Never write questions for the person in your reply.
471Style: be concise, friendly and concrete. Prefer short steps and short \
472paragraphs to long essays. Use British English spelling.
473"""
476CHAINR_BOT = SystemAgentSpec(
477 id=UUID("c4a1b0e7-0000-4000-8000-000000000001"),
478 name="CHAINR Bot",
479 description=(
480 "The built-in CHAIN-R assistant. Ask it how the platform works, or "
481 "use it as a general assistant — no setup needed. Managed by "
482 "CHAIN-R, so it cannot be edited."
483 ),
484 icon="Compass",
485 accent="violet",
486 system_prompt=BOT_SYSTEM_PROMPT,
487 # Its guide is for questions about CHAIN-R, and triage reads what the
488 # guide is for: the guide is searched when triage says so, never by
489 # default (``RetrievalConfig.always_retrieve``). With it on, every
490 # request but a web-only one searched the guide — "render pdf of
491 # different climbing knots" kept its page on making PDFs.
492 #
493 # Its searches put a few publishers first and never restrict it to them
494 # (``web_sources.py``); a workspace's own Tools rules replace them. The
495 # list is here, not only in code, so a change to it is a release of the
496 # bot in its edit history, and its page reads it from the agent.
497 config={
498 "retrieval": {"always_retrieve": False},
499 "web_sources": web_sources.bot_config(),
500 },
501)
503GUIDE_REPOSITORY = SystemRepositorySpec(
504 id=UUID("c4a1b0e7-0000-4000-8000-000000000002"),
505 name="CHAIN-R User Guide",
506 description=(
507 "How CHAIN-R works, from first steps to governance and evaluation. "
508 "Maintained by CHAIN-R and granted to CHAINR Bot."
509 ),
510 icon="GraduationCap",
511 accent="violet",
512)
514GUIDE_KNOWLEDGE = SystemKnowledgeSpec(
515 id=UUID("c4a1b0e7-0000-4000-8000-000000000003"),
516 name="CHAIN-R User Guide",
517 description=(
518 "The CHAIN-R user guide, one document per area of the platform. "
519 "Maintained by CHAIN-R; re-indexed whenever a release changes it."
520 ),
521)
524def guide_files() -> list[Path]:
525 """The guide's documents, in a stable order."""
526 if not GUIDE_DIR.is_dir():
527 return []
528 return sorted(
529 path
530 for path in GUIDE_DIR.iterdir()
531 if path.is_file() and path.suffix == GUIDE_SUFFIX
532 )