frigg 0.10.0

Frigg gives AI agents local, source-backed code search and navigation without sending whole repositories through every prompt.
Documentation
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Precise SCIP record upsert, replace, and overlay bookkeeping for symbol graph storage.
//!
//! Maintains per-file occurrence indexes and reference counts so file-scoped replaces and overlay
//! merges stay consistent while precise navigation queries remain bounded.

use std::collections::BTreeSet;
use std::time::Instant;

use super::*;

/// File-scoped replace: drops prior occurrences for the path, then upserts the new set.
pub(super) fn replace_precise_occurrences_for_file(
    graph: &mut SymbolGraph,
    repository_id: &str,
    path: &str,
    occurrences: &[PreciseOccurrenceRecord],
) {
    let keys = graph
        .precise_occurrence_keys_by_file
        .remove(&precise_file_key(repository_id, path))
        .unwrap_or_default()
        .into_iter()
        .collect::<Vec<_>>();
    for key in keys {
        remove_precise_occurrence(graph, &key);
    }
    for occurrence in occurrences {
        upsert_precise_occurrence(graph, occurrence);
    }
}

/// Overlay merge: upserts occurrences without removing existing ones for the file.
pub(super) fn overlay_precise_occurrences_for_file(
    graph: &mut SymbolGraph,
    _repository_id: &str,
    _path: &str,
    occurrences: &[PreciseOccurrenceRecord],
) {
    for occurrence in occurrences {
        upsert_precise_occurrence(graph, occurrence);
    }
}

/// File-scoped symbol replace with ref-count bookkeeping so multi-file symbols stay resident.
pub(super) fn replace_precise_symbols_for_file(
    graph: &mut SymbolGraph,
    repository_id: &str,
    path: &str,
    symbols: &[PreciseSymbolRecord],
) {
    let file_key = precise_file_key(repository_id, path);
    let previous_symbols = graph
        .precise_symbols_by_file
        .remove(&file_key)
        .unwrap_or_default();

    for previous_symbol in previous_symbols {
        decrement_precise_symbol_ref_count(graph, repository_id, &previous_symbol);
    }

    let mut next_symbols = BTreeSet::new();
    for symbol in symbols {
        let symbol_key = (symbol.repository_id.clone(), symbol.symbol.clone());
        upsert_precise_symbol_record(graph, &symbol_key, symbol);
        if next_symbols.insert(symbol.symbol.clone()) {
            increment_precise_symbol_ref_count(graph, &symbol_key);
        }
    }

    graph.precise_symbols_by_file.insert(file_key, next_symbols);
}

/// Overlay symbols for a file, incrementing ref-counts only for first reference from that file.
pub(super) fn overlay_precise_symbols_for_file(
    graph: &mut SymbolGraph,
    repository_id: &str,
    path: &str,
    symbols: &[PreciseSymbolRecord],
) {
    let file_key = precise_file_key(repository_id, path);
    let mut newly_referenced_symbols = Vec::new();
    for symbol in symbols {
        let symbol_key = (symbol.repository_id.clone(), symbol.symbol.clone());
        let is_new_for_file = {
            let file_symbols = graph
                .precise_symbols_by_file
                .entry(file_key.clone())
                .or_default();
            file_symbols.insert(symbol.symbol.clone())
        };
        upsert_precise_symbol_record(graph, &symbol_key, symbol);
        if is_new_for_file {
            newly_referenced_symbols.push(symbol_key);
        }
    }

    for symbol_key in newly_referenced_symbols {
        increment_precise_symbol_ref_count(graph, &symbol_key);
    }
}

/// File-scoped relationship replace; decrements prior edges then installs the new set.
pub(super) fn replace_precise_relationships_for_file(
    graph: &mut SymbolGraph,
    repository_id: &str,
    path: &str,
    relationships: &[PreciseRelationshipRecord],
) {
    let file_key = precise_file_key(repository_id, path);
    let previous_relationship_keys = graph
        .precise_relationships_by_file
        .remove(&file_key)
        .unwrap_or_default();

    for relationship_key in previous_relationship_keys {
        decrement_precise_relationship_ref_count(graph, &relationship_key);
    }

    let mut next_relationship_keys = BTreeSet::new();
    for relationship in relationships {
        let relationship_key = PreciseRelationshipKey::from(relationship);
        upsert_precise_relationship(graph, relationship);
        increment_precise_relationship_ref_count(graph, &relationship_key);
        next_relationship_keys.insert(relationship_key);
    }

    graph
        .precise_relationships_by_file
        .insert(file_key, next_relationship_keys);
}

/// Overlay relationships for a file without dropping edges still claimed by other files.
pub(super) fn overlay_precise_relationships_for_file(
    graph: &mut SymbolGraph,
    repository_id: &str,
    path: &str,
    relationships: &[PreciseRelationshipRecord],
) {
    let file_key = precise_file_key(repository_id, path);
    let mut newly_referenced_relationships = Vec::new();
    for relationship in relationships {
        let relationship_key = PreciseRelationshipKey::from(relationship);
        let is_new_for_file = {
            let file_relationships = graph
                .precise_relationships_by_file
                .entry(file_key.clone())
                .or_default();
            file_relationships.insert(relationship_key.clone())
        };
        upsert_precise_relationship(graph, relationship);
        if is_new_for_file {
            newly_referenced_relationships.push(relationship_key);
        }
    }

    for relationship_key in newly_referenced_relationships {
        increment_precise_relationship_ref_count(graph, &relationship_key);
    }
}

/// Inserts or overwrites a precise symbol and indexes it under its repository.
pub(super) fn upsert_precise_symbol_record(
    graph: &mut SymbolGraph,
    symbol_key: &(String, String),
    symbol: &PreciseSymbolRecord,
) {
    graph
        .precise_symbols
        .insert(symbol_key.clone(), symbol.clone());
    graph
        .precise_symbol_keys_by_repository
        .entry(symbol_key.0.clone())
        .or_default()
        .insert(symbol_key.1.clone());
}

/// Inserts or replaces one occurrence and refreshes file/symbol secondary indexes.
pub(super) fn upsert_precise_occurrence(
    graph: &mut SymbolGraph,
    occurrence: &PreciseOccurrenceRecord,
) {
    let key = PreciseOccurrenceKey::from(occurrence);
    if let Some(previous) = graph.precise_occurrences.get(&key).cloned() {
        remove_precise_occurrence_indexes(graph, &key, &previous);
    }
    graph
        .precise_occurrences
        .insert(key.clone(), occurrence.clone());
    insert_precise_occurrence_indexes(graph, &key, occurrence);
}

/// Removes one occurrence and cleans empty secondary index entries.
pub(super) fn remove_precise_occurrence(graph: &mut SymbolGraph, key: &PreciseOccurrenceKey) {
    if let Some(previous) = graph.precise_occurrences.remove(key) {
        remove_precise_occurrence_indexes(graph, key, &previous);
    }
}

/// Links an occurrence key into per-file and per-symbol indexes.
pub(super) fn insert_precise_occurrence_indexes(
    graph: &mut SymbolGraph,
    key: &PreciseOccurrenceKey,
    occurrence: &PreciseOccurrenceRecord,
) {
    graph
        .precise_occurrence_keys_by_file
        .entry(precise_file_key(
            &occurrence.repository_id,
            &occurrence.path,
        ))
        .or_default()
        .insert(key.clone());
    graph
        .precise_occurrence_keys_by_symbol
        .entry(precise_symbol_key(
            &occurrence.repository_id,
            &occurrence.symbol,
        ))
        .or_default()
        .insert(key.clone());
}

/// Unlinks an occurrence from secondary indexes, dropping empty index sets.
pub(super) fn remove_precise_occurrence_indexes(
    graph: &mut SymbolGraph,
    key: &PreciseOccurrenceKey,
    occurrence: &PreciseOccurrenceRecord,
) {
    let file_key = precise_file_key(&occurrence.repository_id, &occurrence.path);
    let remove_file_entry =
        if let Some(keys) = graph.precise_occurrence_keys_by_file.get_mut(&file_key) {
            keys.remove(key);
            keys.is_empty()
        } else {
            false
        };
    if remove_file_entry {
        graph.precise_occurrence_keys_by_file.remove(&file_key);
    }

    let symbol_key = precise_symbol_key(&occurrence.repository_id, &occurrence.symbol);
    let remove_symbol_entry =
        if let Some(keys) = graph.precise_occurrence_keys_by_symbol.get_mut(&symbol_key) {
            keys.remove(key);
            keys.is_empty()
        } else {
            false
        };
    if remove_symbol_entry {
        graph.precise_occurrence_keys_by_symbol.remove(&symbol_key);
    }
}

/// Inserts or replaces one precise relationship and refreshes from/to indexes.
pub(super) fn upsert_precise_relationship(
    graph: &mut SymbolGraph,
    relationship: &PreciseRelationshipRecord,
) {
    let key = PreciseRelationshipKey::from(relationship);
    if let Some(previous) = graph.precise_relationships.get(&key).cloned() {
        remove_precise_relationship_indexes(graph, &key, &previous);
    }
    graph
        .precise_relationships
        .insert(key.clone(), relationship.clone());
    insert_precise_relationship_indexes(graph, &key, relationship);
}

/// Links a relationship key into from-symbol and to-symbol indexes.
pub(super) fn insert_precise_relationship_indexes(
    graph: &mut SymbolGraph,
    key: &PreciseRelationshipKey,
    relationship: &PreciseRelationshipRecord,
) {
    graph
        .precise_relationship_keys_by_from_symbol
        .entry(precise_symbol_key(
            &relationship.repository_id,
            &relationship.from_symbol,
        ))
        .or_default()
        .insert(key.clone());
    graph
        .precise_relationship_keys_by_to_symbol
        .entry(precise_symbol_key(
            &relationship.repository_id,
            &relationship.to_symbol,
        ))
        .or_default()
        .insert(key.clone());
}

/// Unlinks a relationship from secondary indexes, dropping empty index sets.
pub(super) fn remove_precise_relationship_indexes(
    graph: &mut SymbolGraph,
    key: &PreciseRelationshipKey,
    relationship: &PreciseRelationshipRecord,
) {
    let from_symbol_key =
        precise_symbol_key(&relationship.repository_id, &relationship.from_symbol);
    let remove_from_entry = if let Some(keys) = graph
        .precise_relationship_keys_by_from_symbol
        .get_mut(&from_symbol_key)
    {
        keys.remove(key);
        keys.is_empty()
    } else {
        false
    };
    if remove_from_entry {
        graph
            .precise_relationship_keys_by_from_symbol
            .remove(&from_symbol_key);
    }

    let to_symbol_key = precise_symbol_key(&relationship.repository_id, &relationship.to_symbol);
    let remove_to_entry = if let Some(keys) = graph
        .precise_relationship_keys_by_to_symbol
        .get_mut(&to_symbol_key)
    {
        keys.remove(key);
        keys.is_empty()
    } else {
        false
    };
    if remove_to_entry {
        graph
            .precise_relationship_keys_by_to_symbol
            .remove(&to_symbol_key);
    }
}

/// Records another file claiming a precise symbol so it is not dropped on partial replaces.
pub(super) fn increment_precise_symbol_ref_count(
    graph: &mut SymbolGraph,
    symbol_key: &(String, String),
) {
    let next = graph
        .precise_symbol_ref_counts
        .get(symbol_key)
        .copied()
        .unwrap_or(0)
        .saturating_add(1);
    graph
        .precise_symbol_ref_counts
        .insert(symbol_key.clone(), next);
}

/// Releases one file claim; removes the symbol when no files still reference it.
pub(super) fn decrement_precise_symbol_ref_count(
    graph: &mut SymbolGraph,
    repository_id: &str,
    symbol: &str,
) {
    let symbol_key = precise_symbol_key(repository_id, symbol);
    let current = graph
        .precise_symbol_ref_counts
        .get(&symbol_key)
        .copied()
        .unwrap_or(0);
    match current {
        0 | 1 => {
            graph.precise_symbol_ref_counts.remove(&symbol_key);
            graph.precise_symbols.remove(&symbol_key);
            let remove_repository_entry = if let Some(symbols) = graph
                .precise_symbol_keys_by_repository
                .get_mut(repository_id)
            {
                symbols.remove(symbol);
                symbols.is_empty()
            } else {
                false
            };
            if remove_repository_entry {
                graph
                    .precise_symbol_keys_by_repository
                    .remove(repository_id);
            }
        }
        count => {
            graph
                .precise_symbol_ref_counts
                .insert(symbol_key, count - 1);
        }
    }
}

/// Records another file claiming a precise relationship edge.
pub(super) fn increment_precise_relationship_ref_count(
    graph: &mut SymbolGraph,
    relationship_key: &PreciseRelationshipKey,
) {
    let next = graph
        .precise_relationship_ref_counts
        .get(relationship_key)
        .copied()
        .unwrap_or(0)
        .saturating_add(1);
    graph
        .precise_relationship_ref_counts
        .insert(relationship_key.clone(), next);
}

/// Releases one file claim on a relationship; removes the edge when the count hits zero.
pub(super) fn decrement_precise_relationship_ref_count(
    graph: &mut SymbolGraph,
    relationship_key: &PreciseRelationshipKey,
) {
    let current = graph
        .precise_relationship_ref_counts
        .get(relationship_key)
        .copied()
        .unwrap_or(0);
    match current {
        0 | 1 => {
            graph
                .precise_relationship_ref_counts
                .remove(relationship_key);
            if let Some(relationship) = graph.precise_relationships.remove(relationship_key) {
                remove_precise_relationship_indexes(graph, relationship_key, &relationship);
            }
        }
        count => {
            graph
                .precise_relationship_ref_counts
                .insert(relationship_key.clone(), count - 1);
        }
    }
}

/// Composite map key for repository-scoped SCIP symbol lookups.
pub(super) fn precise_symbol_key(repository_id: &str, symbol: &str) -> (String, String) {
    (repository_id.to_owned(), symbol.to_owned())
}

/// Composite map key for repository-scoped file indexes.
pub(super) fn precise_file_key(repository_id: &str, path: &str) -> (String, String) {
    (repository_id.to_owned(), path.to_owned())
}

/// Stable ordering for precise symbol query results.
pub(super) fn precise_symbol_order(
    left: &PreciseSymbolRecord,
    right: &PreciseSymbolRecord,
) -> std::cmp::Ordering {
    left.repository_id
        .cmp(&right.repository_id)
        .then(left.symbol.cmp(&right.symbol))
        .then(left.display_name.cmp(&right.display_name))
        .then(left.kind.cmp(&right.kind))
}

/// Stable ordering for precise occurrence query results (path, then range).
pub(super) fn precise_occurrence_order(
    left: &PreciseOccurrenceRecord,
    right: &PreciseOccurrenceRecord,
) -> std::cmp::Ordering {
    left.path
        .cmp(&right.path)
        .then(left.range.start_line.cmp(&right.range.start_line))
        .then(left.range.start_column.cmp(&right.range.start_column))
        .then(left.range.end_line.cmp(&right.range.end_line))
        .then(left.range.end_column.cmp(&right.range.end_column))
        .then(left.symbol.cmp(&right.symbol))
        .then(left.symbol_roles.cmp(&right.symbol_roles))
}

/// Stable ordering for precise relationship query results.
pub(super) fn precise_relationship_order(
    left: &PreciseRelationshipRecord,
    right: &PreciseRelationshipRecord,
) -> std::cmp::Ordering {
    left.from_symbol
        .cmp(&right.from_symbol)
        .then(left.to_symbol.cmp(&right.to_symbol))
        .then(left.kind.cmp(&right.kind))
}

/// Lower rank is a better navigation match; `None` when neither query nor fallback applies.
pub(super) fn precise_navigation_symbol_rank(
    precise_symbol: &PreciseSymbolRecord,
    symbol_query: &str,
    fallback_symbol_name: &str,
) -> Option<u8> {
    let symbol_tail = precise_navigation_identifier(&precise_symbol.symbol);
    let symbol_tail = symbol_tail
        .as_deref()
        .unwrap_or(precise_symbol.symbol.as_str());
    if precise_symbol.symbol == symbol_query {
        return Some(0);
    }
    if precise_symbol.display_name == symbol_query {
        return Some(1);
    }
    if symbol_tail == symbol_query {
        return Some(2);
    }
    if precise_symbol
        .display_name
        .eq_ignore_ascii_case(symbol_query)
    {
        return Some(3);
    }
    if symbol_tail.eq_ignore_ascii_case(symbol_query) {
        return Some(4);
    }
    if precise_symbol.display_name == fallback_symbol_name {
        return Some(5);
    }
    if symbol_tail == fallback_symbol_name {
        return Some(6);
    }
    if precise_symbol
        .display_name
        .eq_ignore_ascii_case(fallback_symbol_name)
    {
        return Some(7);
    }
    if symbol_tail.eq_ignore_ascii_case(fallback_symbol_name) {
        return Some(8);
    }

    None
}

/// Builds a structured SCIP invalid-input error without source coordinates.
pub(super) fn invalid_input(
    artifact_label: &str,
    code: ScipInvalidInputCode,
    message: impl Into<String>,
) -> ScipIngestError {
    ScipIngestError::InvalidInput {
        diagnostic: ScipInvalidInputDiagnostic {
            artifact_label: artifact_label.to_owned(),
            code,
            message: message.into(),
            line: None,
            column: None,
        },
    }
}

/// Builds a structured SCIP resource-budget exceeded error with limit/actual values.
pub(super) fn resource_budget_exceeded(
    artifact_label: &str,
    code: ScipResourceBudgetCode,
    message: impl Into<String>,
    limit: u64,
    actual: u64,
) -> ScipIngestError {
    ScipIngestError::ResourceBudgetExceeded {
        diagnostic: ScipResourceBudgetDiagnostic {
            artifact_label: artifact_label.to_owned(),
            code,
            message: message.into(),
            limit,
            actual,
        },
    }
}

/// Fails the current ingest phase when wall-clock elapsed time exceeds the configured budget.
pub(super) fn enforce_elapsed_budget(
    artifact_label: &str,
    started_at: Instant,
    budgets: ScipResourceBudgets,
    phase: &str,
) -> ScipIngestResult<()> {
    if budgets.max_elapsed_ms == u64::MAX {
        return Ok(());
    }

    let elapsed_ms = u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
    if elapsed_ms > budgets.max_elapsed_ms {
        return Err(resource_budget_exceeded(
            artifact_label,
            ScipResourceBudgetCode::ElapsedMs,
            format!("scip ingest elapsed time exceeded while {phase}"),
            budgets.max_elapsed_ms,
            elapsed_ms,
        ));
    }

    Ok(())
}

/// Stable ordering for heuristic relation edge lists.
pub(super) fn symbol_relation_order(
    left: &SymbolRelation,
    right: &SymbolRelation,
) -> std::cmp::Ordering {
    left.from_symbol
        .cmp(&right.from_symbol)
        .then(left.to_symbol.cmp(&right.to_symbol))
        .then(left.relation.cmp(&right.relation))
}

/// Stable ordering for heuristic adjacency results (relation, then symbol id/path/line).
pub(super) fn adjacent_symbol_order(
    left: &AdjacentSymbol,
    right: &AdjacentSymbol,
) -> std::cmp::Ordering {
    left.relation
        .cmp(&right.relation)
        .then(left.symbol.symbol_id.cmp(&right.symbol.symbol_id))
        .then(left.symbol.path.cmp(&right.symbol.path))
        .then(left.symbol.line.cmp(&right.symbol.line))
}

/// Orders heuristic hints by descending confidence, then source location.
pub(super) fn heuristic_relation_hint_order(
    left: &HeuristicRelationHint,
    right: &HeuristicRelationHint,
) -> std::cmp::Ordering {
    right
        .confidence
        .rank()
        .cmp(&left.confidence.rank())
        .then(left.source_symbol.path.cmp(&right.source_symbol.path))
        .then(left.source_symbol.line.cmp(&right.source_symbol.line))
        .then(
            left.source_symbol
                .symbol_id
                .cmp(&right.source_symbol.symbol_id),
        )
        .then(
            left.target_symbol
                .symbol_id
                .cmp(&right.target_symbol.symbol_id),
        )
        .then(left.relation.cmp(&right.relation))
}