Coverage for app / services / knowledge / trust.py: 92%

320 statements  

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

1"""Trust signals: what is on record about whether a knowledge source can be 

2relied on. 

3 

4Each signal is one class, registered with :func:`register_signal` and served 

5as a catalogue (``GET /app/knowledge/trust/signals``), so adding one is a 

6class, not a branch on a page. A signal reads recorded facts only, never a 

7model, and says which facts it read (``SignalResult.facts``). It has a 

8*state*, a meaning a ``StatusBadge`` scale draws, and no score: the facts are 

9of different kinds (a rule that blocks a site is a conflict; a missing 

10licence is a gap in the record), and a number would invent a weighting 

11between them. 

12 

13A signal that marks itself ``attention`` counts towards "Needs attention" 

14when it is ``unmet`` or in ``conflict`` (:func:`needs_attention`): what a 

15person should look at, as opposed to what is merely not on record (a file 

16upload has no licence record, and every upload would otherwise need 

17attention). 

18 

19Display only. The Tools rules a signal reads govern the web an agent 

20searches and fetches; they do not filter knowledge retrieval, and the copy 

21says so. 

22""" 

23 

24from __future__ import annotations 

25 

26from abc import ABC, abstractmethod 

27from collections import defaultdict 

28from collections.abc import Iterable, Sequence 

29from dataclasses import dataclass, field 

30from datetime import datetime, timedelta 

31from enum import StrEnum 

32from typing import Any 

33from uuid import UUID 

34 

35from sqlalchemy import func 

36from sqlalchemy.orm import Session 

37 

38from app.db.postgres.enums import HistoryEnum, RuleEnum 

39from app.db.postgres.models import ( 

40 GenerationRun, 

41 KnowledgeDocument, 

42 ResourceVersion, 

43 Rule, 

44 User, 

45) 

46from app.services import workspace as workspace_service 

47from app.services.knowledge import stats, web_config 

48from app.util import web_domains 

49from app.util.time import naive_utcnow 

50 

51TRUSTED = "trusted_sources" 

52BLOCKED = "blocked_sources" 

53 

54 

55class SignalState(StrEnum): 

56 met = "met" 

57 partial = "partial" 

58 unmet = "unmet" 

59 conflict = "conflict" 

60 in_progress = "in_progress" 

61 unknown = "unknown" 

62 not_applicable = "not_applicable" 

63 

64 

65#: The states that put an ``attention`` signal on "Needs attention". 

66ATTENTION_STATES = frozenset({SignalState.unmet, SignalState.conflict}) 

67 

68 

69@dataclass(frozen=True) 

70class Fact: 

71 """One recorded fact a signal read: a label and its value, and what it 

72 links to (a rule, a generation run, a person).""" 

73 

74 label: str 

75 value: str 

76 ref_kind: str | None = None 

77 ref_id: UUID | None = None 

78 url: str | None = None 

79 #: A moment the page formats in its reader's zone (``value`` then empty). 

80 at: datetime | None = None 

81 

82 

83@dataclass 

84class SignalResult: 

85 key: str 

86 state: SignalState 

87 summary: str 

88 facts: list[Fact] = field(default_factory=list) 

89 

90 

91# ── What the signals read ───────────────────────────────────────────────────── 

92 

93 

94@dataclass(frozen=True) 

95class ToolsRule: 

96 """One active Tools rule governing the workspace, and the sites it names.""" 

97 

98 id: UUID 

99 name: str 

100 action: str 

101 domains: tuple[str, ...] 

102 only: bool 

103 scope: str 

104 conditional: bool 

105 

106 

107@dataclass(frozen=True) 

108class FirstVersion: 

109 actor_user_id: UUID | None 

110 actor_name: str | None 

111 origin: str | None 

112 created_at: datetime | None 

113 

114 

115@dataclass(frozen=True) 

116class Imports: 

117 """A file source's documents imported from a link.""" 

118 

119 imported: int = 0 

120 with_publisher: int = 0 

121 discovered: int = 0 

122 

123 

124@dataclass 

125class TrustContext: 

126 """Everything the signals read, for a batch of sources, loaded at once.""" 

127 

128 figures: dict[UUID, stats.SourceFigures] 

129 hosts: dict[UUID, frozenset[str]] 

130 rules: list[ToolsRule] 

131 first_versions: dict[UUID, FirstVersion] 

132 generations: dict[UUID, str] 

133 imports: dict[UUID, Imports] 

134 now: datetime 

135 

136 @classmethod 

137 def load( 

138 cls, 

139 db: Session, 

140 ws: Any, 

141 sources: Sequence[Any], 

142 figures: dict[UUID, stats.SourceFigures], 

143 *, 

144 now: datetime | None = None, 

145 ) -> TrustContext: 

146 ids = [s.id for s in sources] 

147 return cls( 

148 figures=figures, 

149 hosts=source_hosts(db, sources), 

150 rules=tools_rules(db, ws), 

151 first_versions=first_versions(db, ids), 

152 generations=generation_flows(db, sources), 

153 imports=imports_of(db, [s.id for s in sources if s.source_type == "file"]), 

154 now=now or naive_utcnow(), 

155 ) 

156 

157 

158#: A URL's host, userinfo and port included (normalised in Python). 

159_HOST = r"^[a-zA-Z][a-zA-Z0-9+.-]*://([^/?#]+)" 

160 

161 

162def source_hosts(db: Session, sources: Sequence[Any]) -> dict[UUID, frozenset[str]]: 

163 """The sites each source's content comes from, as Tools rules name them 

164 (``web_domains.normalise_domain``): a website's starting URLs and pages, 

165 a file source's documents imported from a link.""" 

166 hosts: dict[UUID, set[str]] = defaultdict(set) 

167 for source in sources: 

168 if source.source_type == "web" and isinstance(source.source_config, dict): 

169 for url in source.source_config.get("urls") or []: 

170 if domain := web_domains.normalise_domain(url): 

171 hosts[source.id].add(domain) 

172 ids = [s.id for s in sources if s.source_type in ("web", "file")] 

173 if ids: 

174 address = func.coalesce( 

175 KnowledgeDocument.document_metadata.op("->>")("source_url"), 

176 KnowledgeDocument.source_id, 

177 ) 

178 for knowledge_id, raw in ( 

179 db.query(KnowledgeDocument.knowledge_id, func.substring(address, _HOST)) 

180 .filter(KnowledgeDocument.knowledge_id.in_(ids)) 

181 .distinct() 

182 .all() 

183 ): 

184 if raw and (domain := web_domains.normalise_domain(raw)): 

185 hosts[knowledge_id].add(domain) 

186 return {k: frozenset(v) for k, v in hosts.items()} 

187 

188 

189def tools_rules(db: Session, ws: Any) -> list[ToolsRule]: 

190 """The active Tools rules governing ``ws`` — its own, and what a project 

191 inherits or is required to apply (``workspace.governing_rules``) — one 

192 per action naming sites.""" 

193 from app.services.rules import scopes 

194 

195 out: list[ToolsRule] = [] 

196 rows = ( 

197 db.query(Rule) 

198 .filter( 

199 workspace_service.governing_rules(ws), 

200 Rule.is_active.is_(True), 

201 Rule.layer == RuleEnum.Layer.tools, 

202 ) 

203 .order_by(Rule.priority.desc(), Rule.name) 

204 .all() 

205 ) 

206 for rule in rows: 

207 scope = scopes.get_scope(rule.scope_type) 

208 for action in rule.actions or []: 

209 if not isinstance(action, dict) or action.get("type") not in ( 

210 TRUSTED, 

211 BLOCKED, 

212 ): 

213 continue 

214 domains = web_domains.normalise_domains(action.get("domains")) 

215 if not domains: 

216 continue 

217 out.append( 

218 ToolsRule( 

219 id=rule.id, 

220 name=rule.name, 

221 action=action["type"], 

222 domains=domains, 

223 only=action.get("only") is True, 

224 scope=scope.label if scope is not None else str(rule.scope_type), 

225 conditional=bool(rule.conditions), 

226 ) 

227 ) 

228 return out 

229 

230 

231def first_versions(db: Session, ids: Sequence[UUID]) -> dict[UUID, FirstVersion]: 

232 """Each source's first edit-history version: who added it, or a 

233 CHAIN-R release.""" 

234 if not ids: 

235 return {} 

236 rows = ( 

237 db.query( 

238 ResourceVersion.resource_id, 

239 ResourceVersion.actor_user_id, 

240 ResourceVersion.origin, 

241 ResourceVersion.created_at, 

242 ) 

243 .filter( 

244 ResourceVersion.resource_type == HistoryEnum.ResourceType.knowledge, 

245 ResourceVersion.resource_id.in_(list(ids)), 

246 ) 

247 .distinct(ResourceVersion.resource_id) 

248 .order_by(ResourceVersion.resource_id, ResourceVersion.version_number.asc()) 

249 .all() 

250 ) 

251 actors = {r.actor_user_id for r in rows if r.actor_user_id is not None} 

252 names = ( 

253 dict(db.query(User.id, User.name).filter(User.id.in_(list(actors))).all()) 

254 if actors 

255 else {} 

256 ) 

257 return { 

258 r.resource_id: FirstVersion( 

259 actor_user_id=r.actor_user_id, 

260 actor_name=names.get(r.actor_user_id), 

261 origin=r.origin, 

262 created_at=r.created_at, 

263 ) 

264 for r in rows 

265 } 

266 

267 

268def generation_flows(db: Session, sources: Sequence[Any]) -> dict[UUID, str]: 

269 """``generation_id → flow`` for the sources a generative flow made.""" 

270 run_ids = {s.generation_id for s in sources if getattr(s, "generation_id", None)} 

271 if not run_ids: 

272 return {} 

273 return { 

274 run_id: str(getattr(flow, "value", flow)) 

275 for run_id, flow in db.query(GenerationRun.id, GenerationRun.flow) 

276 .filter(GenerationRun.id.in_(list(run_ids))) 

277 .all() 

278 } 

279 

280 

281def imports_of(db: Session, ids: Sequence[UUID]) -> dict[UUID, Imports]: 

282 """Each file source's documents imported from a link: how many, how many 

283 name their publisher, and how many discovery found.""" 

284 if not ids: 

285 return {} 

286 meta = KnowledgeDocument.document_metadata 

287 return { 

288 row[0]: Imports(int(row[1] or 0), int(row[2] or 0), int(row[3] or 0)) 

289 for row in db.query( 

290 KnowledgeDocument.knowledge_id, 

291 func.count().filter(meta.op("->>")("source_url").isnot(None)), 

292 func.count().filter(meta.op("->>")("publisher").isnot(None)), 

293 func.count().filter(meta.op("->>")("import_origin") == "generation"), 

294 ) 

295 .filter(KnowledgeDocument.knowledge_id.in_(list(ids))) 

296 .group_by(KnowledgeDocument.knowledge_id) 

297 .all() 

298 } 

299 

300 

301# ── The signals ─────────────────────────────────────────────────────────────── 

302 

303 

304class Signal(ABC): 

305 key: str 

306 label: str 

307 description: str 

308 #: Whether its ``unmet`` / ``conflict`` counts towards "Needs attention". 

309 attention: bool = False 

310 

311 @abstractmethod 

312 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: ... 

313 

314 def result(self, state: SignalState, summary: str, *facts: Fact) -> SignalResult: 

315 return SignalResult(self.key, state, summary, list(facts)) 

316 

317 

318_REGISTRY: dict[str, Signal] = {} 

319 

320 

321def register_signal(cls: type[Signal]) -> type[Signal]: 

322 instance = cls() 

323 if instance.key in _REGISTRY: 

324 raise ValueError(f"Trust signal {instance.key!r} registered twice") 

325 _REGISTRY[instance.key] = instance 

326 return cls 

327 

328 

329def signals() -> list[Signal]: 

330 """Every signal, in the order a page lists them.""" 

331 return list(_REGISTRY.values()) 

332 

333 

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

335 return [ 

336 { 

337 "key": s.key, 

338 "label": s.label, 

339 "description": s.description, 

340 "attention": s.attention, 

341 } 

342 for s in signals() 

343 ] 

344 

345 

346def _plural(n: int, one: str, many: str | None = None) -> str: 

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

348 

349 

350def _built_in_spec(source: Any) -> Any: 

351 """The built-in source spec ``source`` was provisioned from, or None.""" 

352 if getattr(source, "is_system", False) is not True: 

353 return None 

354 from app.services.system_resources.knowledge import source_spec 

355 

356 return source_spec(getattr(source, "id", None)) 

357 

358 

359def _terms_checked(source: Any) -> str | None: 

360 """When a built-in website source's terms were last checked.""" 

361 return getattr(_built_in_spec(source), "terms_checked", None) 

362 

363 

364def _written_credits(source: Any) -> str | None: 

365 """A written built-in source's credits: CHAIN-R wrote it, so its licence 

366 is CHAIN-R's own, and whose ideas it follows is its credit.""" 

367 from app.services.system_resources.knowledge import WrittenSourceSpec 

368 

369 spec = _built_in_spec(source) 

370 return spec.credits if isinstance(spec, WrittenSourceSpec) else None 

371 

372 

373@register_signal 

374class LicenceSignal(Signal): 

375 key = "licence" 

376 label = "Licence and credit" 

377 description = ( 

378 "Whether the terms its content is used under, and the credit they ask " 

379 "for, are on record." 

380 ) 

381 

382 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: 

383 if source.source_type == "web": 

384 try: 

385 config = web_config.parse_web_config(source.source_config) 

386 except ValueError: 

387 return self.result( 

388 SignalState.unknown, "Its settings could not be read." 

389 ) 

390 facts = [] 

391 if config.attribution: 

392 facts.append(Fact("Credit", config.attribution)) 

393 if config.licence_url: 

394 facts.append( 

395 Fact("Licence", config.licence_url, url=config.licence_url) 

396 ) 

397 checked = _terms_checked(source) 

398 if checked: 

399 facts.append(Fact("Terms checked", checked)) 

400 if config.attribution and config.licence_url: 

401 return self.result( 

402 SignalState.met, "Licence and credit recorded.", *facts 

403 ) 

404 if config.attribution or config.licence_url: 

405 return self.result( 

406 SignalState.partial, 

407 "Credit recorded, no licence." 

408 if config.attribution 

409 else "Licence recorded, no credit.", 

410 *facts, 

411 ) 

412 return self.result( 

413 SignalState.unmet, "No licence or credit recorded.", *facts 

414 ) 

415 if source.source_type == "file": 

416 written = _written_credits(source) 

417 if written is not None: 

418 return self.result( 

419 SignalState.met, 

420 "Written by CHAIN-R.", 

421 Fact("Credit", written), 

422 ) 

423 imports = ctx.imports.get(source.id, Imports()) 

424 if imports.imported == 0: 

425 return self.result( 

426 SignalState.unknown, 

427 "Uploaded documents carry no licence record.", 

428 ) 

429 fact = Fact( 

430 "Publishers named", 

431 f"{imports.with_publisher:,} of {imports.imported:,} imported", 

432 ) 

433 if imports.with_publisher: 

434 return self.result( 

435 SignalState.partial, 

436 f"{_plural(imports.with_publisher, 'imported document')} " 

437 "name their publisher; no licence is recorded.", 

438 fact, 

439 ) 

440 return self.result( 

441 SignalState.unknown, "Imported documents name no publisher.", fact 

442 ) 

443 return self.result(SignalState.not_applicable, "Not published content.") 

444 

445 

446@register_signal 

447class ToolsRulesSignal(Signal): 

448 key = "tools_rules" 

449 label = "Tools rules here" 

450 description = ( 

451 "Whether the sites its content comes from are trusted or blocked by a " 

452 "Tools rule in force in this workspace. Tools rules govern the web an " 

453 "agent searches and reads; they do not filter knowledge retrieval." 

454 ) 

455 attention = True 

456 

457 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: 

458 hosts = ctx.hosts.get(source.id, frozenset()) 

459 if not hosts: 

460 return self.result(SignalState.not_applicable, "Its content names no site.") 

461 blocking = [ 

462 (rule, sorted(h for h in hosts if web_domains.covered(h, rule.domains))) 

463 for rule in ctx.rules 

464 if rule.action == BLOCKED 

465 ] 

466 blocking = [(rule, hit) for rule, hit in blocking if hit] 

467 trusted = [r for r in ctx.rules if r.action == TRUSTED] 

468 covered = { 

469 h for h in hosts if any(web_domains.covered(h, r.domains) for r in trusted) 

470 } 

471 facts = [ 

472 Fact( 

473 _rule_label(rule, "Blocks"), 

474 ", ".join(hit[:5]) + (f" +{len(hit) - 5}" if len(hit) > 5 else ""), 

475 ref_kind="rule", 

476 ref_id=rule.id, 

477 ) 

478 for rule, hit in blocking 

479 ] + [ 

480 Fact( 

481 _rule_label(rule, "Trusts"), 

482 ", ".join( 

483 sorted(h for h in hosts if web_domains.covered(h, rule.domains))[:5] 

484 ), 

485 ref_kind="rule", 

486 ref_id=rule.id, 

487 ) 

488 for rule in trusted 

489 if any(web_domains.covered(h, rule.domains) for h in hosts) 

490 ] 

491 if blocking: 

492 blocked = {h for _, hit in blocking for h in hit} 

493 return self.result( 

494 SignalState.conflict, 

495 f"A Tools rule here blocks {len(blocked):,} of its " 

496 f"{_plural(len(hosts), 'site')}.", 

497 *facts, 

498 ) 

499 if covered and covered == set(hosts): 

500 return self.result( 

501 SignalState.met, "Every site it uses is trusted here.", *facts 

502 ) 

503 if covered: 

504 return self.result( 

505 SignalState.partial, 

506 f"{len(covered):,} of its {_plural(len(hosts), 'site')} trusted here.", 

507 *facts, 

508 ) 

509 return self.result( 

510 SignalState.unknown, 

511 f"No Tools rule here names its {_plural(len(hosts), 'site')}.", 

512 ) 

513 

514 

515def _rule_label(rule: ToolsRule, verb: str) -> str: 

516 where = ( 

517 "" 

518 if rule.scope in ("Everything", "Organisation", "Project") 

519 else f" (one {rule.scope.lower()})" 

520 ) 

521 when = ", when its conditions hold" if rule.conditional else "" 

522 return f"{verb} — {rule.name}{where}{when}" 

523 

524 

525@register_signal 

526class FreshnessSignal(Signal): 

527 key = "freshness" 

528 label = "Up to date" 

529 description = ( 

530 "Whether a website source has been crawled as often as its refresh " 

531 "setting says." 

532 ) 

533 attention = True 

534 

535 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: 

536 if source.source_type != "web": 

537 return self.result( 

538 SignalState.not_applicable, "Kept as it was added, not crawled." 

539 ) 

540 figures = ctx.figures.get(source.id) 

541 crawl = figures.crawl if figures else None 

542 if crawl is None or crawl.cadence is None: 

543 return self.result(SignalState.unknown, "No crawl settings on record.") 

544 facts = [Fact("Refresh", crawl.cadence)] 

545 if crawl.last_success_at is not None: 

546 facts.append(Fact("Last crawled", "", at=crawl.last_success_at)) 

547 if crawl.status == "running": 

548 return self.result(SignalState.in_progress, "Crawling now.", *facts) 

549 interval = web_config.RefreshCadence(crawl.cadence).interval_seconds 

550 if not interval: 

551 return self.result( 

552 SignalState.not_applicable, 

553 "Refreshed by hand, not on a schedule.", 

554 *facts, 

555 ) 

556 if crawl.next_due_at is None and getattr(source, "is_system", False) is True: 

557 return self.result( 

558 SignalState.not_applicable, 

559 "Crawled only while an agent here uses it.", 

560 *facts, 

561 ) 

562 if crawl.last_success_at is None: 

563 return self.result(SignalState.unmet, "Never crawled successfully.", *facts) 

564 age = (ctx.now - crawl.last_success_at).total_seconds() 

565 if age > 2 * interval: 

566 return self.result( 

567 SignalState.unmet, f"Behind: last crawled {_ago(age)} ago.", *facts 

568 ) 

569 if age > 1.5 * interval or crawl.status in ("failed", "held"): 

570 reason = { 

571 "failed": "its last crawl failed", 

572 "held": "its last crawl waited for budget", 

573 }.get(crawl.status, f"last crawled {_ago(age)} ago") 

574 return self.result(SignalState.partial, f"Slipping: {reason}.", *facts) 

575 return self.result(SignalState.met, f"Crawled {_ago(age)} ago.", *facts) 

576 

577 

578def _ago(seconds: float) -> str: 

579 delta = timedelta(seconds=max(seconds, 0)) 

580 if delta < timedelta(hours=1): 

581 return _plural(max(int(delta.total_seconds() // 60), 1), "minute") 

582 if delta < timedelta(days=2): 

583 return _plural(int(delta.total_seconds() // 3600), "hour") 

584 return _plural(delta.days, "day") 

585 

586 

587@register_signal 

588class IndexHealthSignal(Signal): 

589 key = "index_health" 

590 label = "Searchable" 

591 description = "Whether everything it holds has been indexed for agents to search." 

592 attention = True 

593 

594 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: 

595 figures = ctx.figures.get(source.id) 

596 if source.source_type == "graph": 

597 if figures and figures.items > 0: 

598 return self.result( 

599 SignalState.met, 

600 f"{_plural(figures.items, 'entity', 'entities')} to explore.", 

601 ) 

602 return self.result(SignalState.unknown, "The graph is empty.") 

603 if source.source_type not in ("file", "web"): 

604 return self.result( 

605 SignalState.not_applicable, "Read where it lives, not indexed." 

606 ) 

607 docs = figures.documents if figures else stats.DocumentCounts() 

608 if docs.total == 0: 

609 return self.result(SignalState.unknown, "Nothing stored yet.") 

610 facts = [ 

611 Fact(state.replace("_", " ").capitalize(), f"{docs.count(state):,}") 

612 for state in (*stats.INDEX_STATES, stats.HELD) 

613 if docs.count(state) 

614 ] 

615 if docs.count("failed"): 

616 return self.result( 

617 SignalState.unmet, 

618 f"{_plural(docs.count('failed'), 'document')} could not be indexed.", 

619 *facts, 

620 ) 

621 waiting = sum(docs.count(s) for s in ("pending", "indexing", "importing")) 

622 if docs.count(stats.HELD): 

623 return self.result( 

624 SignalState.in_progress, 

625 f"{_plural(docs.count(stats.HELD), 'document')} waiting for budget.", 

626 *facts, 

627 ) 

628 if waiting: 

629 return self.result( 

630 SignalState.in_progress, 

631 f"{_plural(waiting, 'document')} being indexed.", 

632 *facts, 

633 ) 

634 if docs.count("not_indexed"): 

635 return self.result( 

636 SignalState.partial, 

637 f"{_plural(docs.count('not_indexed'), 'document')} held no text to index.", 

638 *facts, 

639 ) 

640 return self.result( 

641 SignalState.met, f"All {_plural(docs.total, 'document')} indexed.", *facts 

642 ) 

643 

644 

645@register_signal 

646class ProvenanceSignal(Signal): 

647 key = "provenance" 

648 label = "Where it came from" 

649 description = "Who added it, or which generation run made it." 

650 

651 def evaluate(self, ctx: TrustContext, source: Any) -> SignalResult: 

652 if getattr(source, "is_system", False) is True: 

653 return self.result(SignalState.met, "Maintained by CHAIN-R.") 

654 facts: list[Fact] = [] 

655 first = ctx.first_versions.get(source.id) 

656 flow = ctx.generations.get(getattr(source, "generation_id", None)) 

657 if flow is not None: 

658 facts.append( 

659 Fact( 

660 "Generated by", 

661 flow.replace("_", " "), 

662 ref_kind="generation", 

663 ref_id=source.generation_id, 

664 ) 

665 ) 

666 if first is not None and first.actor_user_id is not None: 

667 facts.append( 

668 Fact( 

669 "Added by", 

670 first.actor_name or "a member", 

671 ref_kind="user", 

672 ref_id=first.actor_user_id, 

673 ) 

674 ) 

675 elif first is not None and first.origin == "release": 

676 facts.append(Fact("Added by", "CHAIN-R release")) 

677 discovered = ctx.imports.get(source.id, Imports()).discovered 

678 if discovered: 

679 facts.append(Fact("Found by discovery", _plural(discovered, "document"))) 

680 if not facts: 

681 return self.result(SignalState.unknown, "No record of who added it.") 

682 summary = ( 

683 f"Generated, then kept by {first.actor_name or 'a member'}." 

684 if flow is not None and first is not None and first.actor_user_id 

685 else "Generated by CHAIN-R." 

686 if flow is not None 

687 else f"Added by {facts[0].value}." 

688 ) 

689 return self.result(SignalState.met, summary, *facts) 

690 

691 

692# ── Reading them ────────────────────────────────────────────────────────────── 

693 

694 

695def evaluate(ctx: TrustContext, source: Any) -> list[SignalResult]: 

696 """Every signal for ``source``, in registry order.""" 

697 return [signal.evaluate(ctx, source) for signal in signals()] 

698 

699 

700def evaluate_all( 

701 ctx: TrustContext, sources: Iterable[Any] 

702) -> dict[UUID, list[SignalResult]]: 

703 return {source.id: evaluate(ctx, source) for source in sources} 

704 

705 

706def needs_attention(results: Iterable[SignalResult]) -> list[str]: 

707 """The keys of the ``attention`` signals ``unmet`` or in ``conflict`` — 

708 one definition of "Needs attention", for cards, lists and pages.""" 

709 attention = {s.key for s in signals() if s.attention} 

710 return [ 

711 r.key for r in results if r.key in attention and r.state in ATTENTION_STATES 

712 ] 

713 

714 

715def tally(results: Iterable[list[SignalResult]]) -> dict[str, dict[str, int]]: 

716 """Per signal, how many sources are in each state: a repository's 

717 summary.""" 

718 out: dict[str, dict[str, int]] = {s.key: {} for s in signals()} 

719 for source_results in results: 

720 for result in source_results: 

721 states = out.setdefault(result.key, {}) 

722 states[result.state.value] = states.get(result.state.value, 0) + 1 

723 return out