All files / src/utils/intelligence build.ts

100% Statements 62/62
96.77% Branches 30/31
100% Functions 16/16
100% Lines 56/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245                                    8x               58x                                                 69x 69x   69x       69x 69x 69x   69x 3x 3x 3x     69x 69x 69x   69x                                         9x 9x 9x   9x 11x 11x 11x     9x                                                       18x 1x     17x 17x   17x 24x 24x 38x   24x 34x   24x     17x 24x 6x   18x                                                 11x   11x 10x   16x 16x 8x     8x     8x     8x           8x           8x                                         5x 5x 1x     4x                 4x 4x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Utils/Intelligence/Build
 * @description Index construction, querying, cross-reference generation,
 * and series management.
 */
 
import type {
  ArticleCrossReference,
  ArticleIndexEntry,
  ArticleSeries,
  IntelligenceIndex,
} from './types.js';
import { addIdToMap, createNullMap, removeIdFromMap, slugify } from './internals.js';
 
/** Maximum cross-reference results when no limit is specified */
const DEFAULT_MAX_RELATED = 10;
 
/**
 * Create a fresh, empty {@link IntelligenceIndex}.
 *
 * @returns An empty index with no articles, actors, domains, trends, or series
 */
export function createEmptyIndex(): IntelligenceIndex {
  return {
    articles: [],
    actors: createNullMap(),
    policyDomains: createNullMap(),
    procedures: createNullMap(),
    trends: [],
    series: [],
    lastUpdated: new Date().toISOString(),
  };
}
 
/**
 * Add an {@link ArticleIndexEntry} to the index and keep all lookup maps in sync.
 *
 * The function is immutable-safe: it returns a new index object rather than
 * mutating the supplied one. Duplicate entries (same `id`) are replaced.
 *
 * @param index - Existing intelligence index
 * @param entry - Article index entry to add
 * @returns Updated index with the new entry reflected in all maps
 */
export function addArticleToIndex(
  index: IntelligenceIndex,
  entry: ArticleIndexEntry
): IntelligenceIndex {
  const existingIdx = index.articles.findIndex((a) => a.id === entry.id);
  const oldEntry = existingIdx >= 0 ? index.articles[existingIdx] : undefined;
  const articles =
    existingIdx >= 0
      ? [...index.articles.slice(0, existingIdx), entry, ...index.articles.slice(existingIdx + 1)]
      : [...index.articles, entry];
 
  const actors = Object.assign(createNullMap(), index.actors);
  const policyDomains = Object.assign(createNullMap(), index.policyDomains);
  const procedures = Object.assign(createNullMap(), index.procedures);
 
  if (oldEntry) {
    removeIdFromMap(actors, oldEntry.keyActors, entry.id);
    removeIdFromMap(policyDomains, oldEntry.keyTopics, entry.id);
    removeIdFromMap(procedures, oldEntry.procedures, entry.id);
  }
 
  addIdToMap(actors, entry.keyActors, entry.id);
  addIdToMap(policyDomains, entry.keyTopics, entry.id);
  addIdToMap(procedures, entry.procedures, entry.id);
 
  return {
    ...index,
    articles,
    actors,
    policyDomains,
    procedures,
    lastUpdated: new Date().toISOString(),
  };
}
 
/**
 * Build a complete index from an array of entries in O(n) time.
 *
 * Unlike calling {@link addArticleToIndex} in a loop (which clones maps on every
 * call, yielding O(n²) behaviour), this function mutates local maps in a single
 * pass and returns a final immutable index.
 *
 * @param entries - All article entries to include
 * @returns A fully populated {@link IntelligenceIndex}
 */
export function buildIndexFromEntries(entries: ArticleIndexEntry[]): IntelligenceIndex {
  const actors = createNullMap();
  const policyDomains = createNullMap();
  const procedures = createNullMap();
 
  for (const entry of entries) {
    addIdToMap(actors, entry.keyActors, entry.id);
    addIdToMap(policyDomains, entry.keyTopics, entry.id);
    addIdToMap(procedures, entry.procedures, entry.id);
  }
 
  return {
    articles: [...entries],
    actors,
    policyDomains,
    procedures,
    trends: [],
    series: [],
    lastUpdated: new Date().toISOString(),
  };
}
 
/**
 * Find articles that share topics or actors with the supplied lists.
 *
 * Results are scored by overlap count and returned in descending relevance order.
 *
 * @param index - Intelligence index to search
 * @param topics - Key topics to match against `keyTopics`
 * @param actors - Key actors to match against `keyActors`
 * @param maxResults - Maximum number of results to return (default: 10)
 * @returns Scored, sorted array of matching article entries
 */
export function findRelatedArticles(
  index: IntelligenceIndex,
  topics: string[],
  actors: string[],
  maxResults: number = DEFAULT_MAX_RELATED
): ArticleIndexEntry[] {
  if (topics.length === 0 && actors.length === 0) {
    return [];
  }
 
  const topicSet = new Set(topics);
  const actorSet = new Set(actors);
 
  const scored = index.articles.map((article) => {
    let score = 0;
    for (const t of article.keyTopics) {
      if (topicSet.has(t)) score++;
    }
    for (const a of article.keyActors) {
      if (actorSet.has(a)) score++;
    }
    return { article, score };
  });
 
  return scored
    .filter(({ score }) => score > 0)
    .sort((a, b) => b.score - a.score)
    .slice(0, maxResults)
    .map(({ article }) => article);
}
 
/**
 * Auto-generate {@link ArticleCrossReference} objects for an article based on
 * topic and actor overlap with existing index entries.
 *
 * **Strength** is determined by total overlap (topics + actors):
 * - ≥3 shared items → `strong`
 * - 2 shared items → `moderate`
 * - 1 shared item  → `weak`
 *
 * **Relationship** is determined by date comparison:
 * - Target article is older (`date < entry.date`) → `follows_up`
 * - Target article is newer (`date > entry.date`) → `preceded_by`
 * - Target article has the same date → `related`
 *
 * @param index - Intelligence index containing previously indexed articles
 * @param entry - The article for which cross-references should be generated
 * @returns Array of auto-generated cross-references (excludes self-references)
 */
export function generateCrossReferences(
  index: IntelligenceIndex,
  entry: ArticleIndexEntry
): ArticleCrossReference[] {
  const related = findRelatedArticles(index, entry.keyTopics, entry.keyActors);
 
  return related
    .filter((a) => a.id !== entry.id)
    .map((a) => {
      const topicOverlap = a.keyTopics.filter((t) => entry.keyTopics.includes(t)).length;
      const actorOverlap = a.keyActors.filter((ac) => entry.keyActors.includes(ac)).length;
      const totalOverlap = topicOverlap + actorOverlap;
 
      const strength: ArticleCrossReference['strength'] =
        totalOverlap >= 3 ? 'strong' : totalOverlap === 2 ? 'moderate' : 'weak';
 
      const relationship: ArticleCrossReference['relationship'] =
        a.date < entry.date ? 'follows_up' : a.date > entry.date ? 'preceded_by' : 'related';
 
      const context =
        topicOverlap > 0 && actorOverlap > 0
          ? `Shares ${topicOverlap} topic(s) and ${actorOverlap} actor(s)`
          : topicOverlap > 0
            ? `Shares ${topicOverlap} topic(s)`
            : `Shares ${actorOverlap} actor(s)`;
 
      const ref: ArticleCrossReference = {
        targetArticleId: a.id,
        relationship,
        context,
        strength,
      };
      return ref;
    });
}
 
/**
 * Find an existing {@link ArticleSeries} for the given procedure reference, or
 * create a new one and add it to the index.
 *
 * **Note:** This function mutates `index.series` for convenience. Callers that
 * require immutability should replace the series array after calling this.
 *
 * @param index - Intelligence index to search / mutate
 * @param procedureRef - EP procedure reference (e.g. "2024/0001(COD)")
 * @param name - Display name for the series if it needs to be created
 * @returns The found or newly created series
 */
export function findOrCreateSeries(
  index: IntelligenceIndex,
  procedureRef: string,
  name: string
): ArticleSeries {
  const existing = index.series.find((s) => s.procedureRef === procedureRef);
  if (existing) {
    return existing;
  }
 
  const newSeries: ArticleSeries = {
    id: `series-${slugify(procedureRef)}`,
    name,
    procedureRef,
    articles: [],
    status: 'ongoing',
    summary: `Tracking legislative procedure ${procedureRef}`,
  };
 
  index.series.push(newSeries);
  return newSeries;
}