contextForMatches method

KnowledgeSearchResponse contextForMatches(
  1. Iterable<SearchResult> ranked, {
  2. KnowledgeSearchPolicy? policy,
  3. int limit = 5,
  4. int? contextLimit,
})

Applies the same eligibility and context policy to externally ranked hits. Unknown or excluded chunk IDs are ignored. Scores do not establish authority.

Implementation

KnowledgeSearchResponse contextForMatches(
  Iterable<SearchResult> ranked, {
  KnowledgeSearchPolicy? policy,
  int limit = 5,
  int? contextLimit,
}) {
  final snapshot = _snapshot;
  if (snapshot == null || _synchronizing) {
    throw StateError('Synchronize the index before assembling context.');
  }
  final budget = contextLimit ?? limit;
  if (limit <= 0 || budget <= 0) {
    return KnowledgeSearchResponse(matches: [], context: [], notices: []);
  }
  final effective = policy ?? KnowledgeSearchPolicy();
  final paths = snapshot.conceptPaths;
  for (final path in [
    ...effective.governingSources.keys,
    ...effective.governingSources.values,
  ]) {
    if (!paths.contains(path)) {
      throw ArgumentError('Unknown governing concept: $path');
    }
  }
  final eligible = {
    for (final chunk in snapshot.chunks)
      if (effective.allows(snapshot, chunk.sourcePath)) chunk.id: chunk,
  };
  final best = <String, SearchResult>{};
  for (final hit in ranked.where(
    (hit) => eligible.containsKey(hit.chunk.id),
  )) {
    final chunk = eligible[hit.chunk.id]!;
    best.putIfAbsent(
      chunk.sourcePath,
      () => SearchResult(
        chunk: chunk,
        embedding: hit.embedding,
        similarity: hit.similarity,
      ),
    );
  }
  final matches = best.values.take(limit).toList();
  final byPath = <String, Chunk>{};
  for (final chunk in eligible.values) {
    byPath.putIfAbsent(chunk.sourcePath, () => chunk);
  }
  final context = <KnowledgeContextHit>[];
  final seen = <String>{};
  final notices = <String>[];
  void add(String path, String reason, {String? via, OkfGraphEdge? edge}) {
    if (context.length >= budget || seen.contains(path)) return;
    final governor = effective.governingSources[path];
    if (governor != null) {
      if (!byPath.containsKey(governor)) {
        notices.add('Governing source excluded or has no passage: $governor');
      } else {
        add(governor, 'governing', via: path);
      }
    }
    if (context.length >= budget || !seen.add(path)) return;
    final chunk = byPath[path];
    if (chunk == null) return;
    context.add(
      KnowledgeContextHit(
        best[path] ??
            SearchResult(chunk: chunk, embedding: null, similarity: 0),
        reason,
        viaPath: via,
        edge: edge,
      ),
    );
  }

  for (final match in matches) {
    add(match.chunk.sourcePath, 'match');
    if (!effective.expandRelationships) continue;
    for (final edge in snapshot.graph.edges.where(
      (edge) => edge.source.documentPath == match.chunk.sourcePath,
    )) {
      final target = edge.targetConcept?.documentPath;
      if (target != null && byPath.containsKey(target)) {
        add(target, 'relationship', via: match.chunk.sourcePath, edge: edge);
      } else if (edge.resolution == OkfGraphResolution.unresolved ||
          edge.resolution == OkfGraphResolution.invalid) {
        notices.add('Unresolved relationship: ${edge.rawTarget}');
      }
    }
  }
  return KnowledgeSearchResponse(
    matches: matches,
    context: context,
    notices: notices.toSet().toList(),
  );
}