eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Read-only impact lookup for code and command surfaces.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Instant;

use crate::core::memory_scope::MemoryScopeContext;
use crate::core::search::{
    SearchDedupMode, SearchOptions, SearchReport, SearchSourceMode,
    run_search_with_read_connection, search_degraded_data_json,
};
use crate::db::{DbConnection, DbError, StoredMemory};
use crate::models::{
    CreateMemoryAnchorInput, MemoryAnchorKind, MemoryAnchorSource, MemoryScope, MemoryScopeStats,
    StoredMemoryAnchor, memory_tags_include_global_scope,
};
use crate::search::SpeedMode;

pub const IMPACT_SCHEMA_V1: &str = "ee.impact.v1";

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ImpactFallbackStatus {
    SkippedLimitFilled,
    Searched,
    Unavailable,
}

impl ImpactFallbackStatus {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SkippedLimitFilled => "skipped_limit_filled",
            Self::Searched => "searched",
            Self::Unavailable => "unavailable",
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImpactSurfaceQuery {
    pub kind: MemoryAnchorKind,
    pub value: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImpactOptions {
    pub workspace_path: PathBuf,
    pub database_path: Option<PathBuf>,
    pub index_dir: Option<PathBuf>,
    pub surface: ImpactSurfaceQuery,
    pub limit: u32,
    pub speed: SpeedMode,
    pub source_mode: SearchSourceMode,
    pub strict_source_mode: bool,
    pub memory_scope: MemoryScope,
    pub strict_scope: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImpactResolvedSurface {
    pub schema: &'static str,
    pub kind: MemoryAnchorKind,
    pub anchor_value_hash: String,
    pub redacted_anchor_value: String,
}

#[derive(Clone, Debug)]
pub struct ImpactReport {
    pub schema: &'static str,
    pub surface: ImpactResolvedSurface,
    pub requested_limit: u32,
    pub results: Vec<ImpactResult>,
    pub exact_anchor_count: usize,
    pub fallback_count: usize,
    pub fallback_status: ImpactFallbackStatus,
    pub fallback_report: Option<SearchReport>,
    pub scope_stats: MemoryScopeStats,
    pub elapsed_ms: f64,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImpactResult {
    pub rank: usize,
    pub memory_id: String,
    pub match_type: ImpactMatchType,
    pub score: f32,
    pub memory: ImpactMemorySummary,
    pub anchor: Option<ImpactAnchorSummary>,
    pub fallback_hit: Option<serde_json::Value>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ImpactMatchType {
    ExactAnchor,
    SearchFallback,
}

impl ImpactMatchType {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ExactAnchor => "exact_anchor",
            Self::SearchFallback => "search_fallback",
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImpactMemorySummary {
    pub level: String,
    pub kind: String,
    pub trust_class: String,
    pub trust_subclass: Option<String>,
    pub confidence: f32,
    pub utility: f32,
    pub importance: f32,
    pub content_preview: String,
    pub provenance_uri: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImpactAnchorSummary {
    pub kind: MemoryAnchorKind,
    pub anchor_value_hash: String,
    pub redacted_anchor_value: String,
    pub confidence: f32,
    pub source: String,
    pub freshness_state: String,
    pub generation: i64,
    pub captured_span_hash: String,
}

#[derive(Debug)]
pub enum ImpactError {
    InvalidSurface { kind: MemoryAnchorKind },
    Storage(DbError),
}

impl fmt::Display for ImpactError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSurface { kind } => write!(
                formatter,
                "Surface value could not be normalized as a {} anchor.",
                kind.as_str()
            ),
            Self::Storage(error) => write!(formatter, "{error}"),
        }
    }
}

impl std::error::Error for ImpactError {}

impl From<DbError> for ImpactError {
    fn from(error: DbError) -> Self {
        Self::Storage(error)
    }
}

impl ImpactReport {
    #[must_use]
    pub fn data_json(&self) -> serde_json::Value {
        let fallback = self.fallback_report.as_ref();
        serde_json::json!({
            "schema": self.schema,
            "command": "impact",
            "surface": self.surface.data_json(),
            "request": {
                "limit": self.requested_limit,
            },
            "phases": {
                "exactAnchor": {
                    "status": "ok",
                    "resultCount": self.exact_anchor_count,
                },
                "searchFallback": {
                    "status": self.fallback_status.as_str(),
                    "resultCount": self.fallback_count,
                },
                "graphNeighbors": {
                    "status": "not_available",
                    "resultCount": 0,
                    "reason": "anchor_graph_projection_not_wired_for_impact_yet",
                },
            },
            "scopeStats": self.scope_stats.data_json(),
            "results": self.results.iter().map(ImpactResult::data_json).collect::<Vec<_>>(),
            "resultCount": self.results.len(),
            "elapsedMs": self.elapsed_ms,
            "fallbackSearch": fallback.map(|report| {
                serde_json::json!({
                    "status": report.status.as_str(),
                    "query": report.query,
                    "resultCount": report.results.len(),
                    "degraded": search_degraded_data_json("impact.search_fallback", &report.degraded),
                })
            }),
            "degraded": fallback
                .map(|report| search_degraded_data_json("impact.search_fallback", &report.degraded))
                .unwrap_or_default(),
        })
    }
}

impl ImpactResolvedSurface {
    #[must_use]
    pub fn data_json(&self) -> serde_json::Value {
        serde_json::json!({
            "schema": self.schema,
            "kind": self.kind.as_str(),
            "anchorValueHash": self.anchor_value_hash,
            "redactedValue": self.redacted_anchor_value,
        })
    }
}

impl ImpactResult {
    #[must_use]
    pub fn data_json(&self) -> serde_json::Value {
        let mut value = serde_json::json!({
            "rank": self.rank,
            "memoryId": self.memory_id,
            "matchType": self.match_type.as_str(),
            "score": self.score,
            "memory": self.memory.data_json(),
        });
        if let Some(object) = value.as_object_mut() {
            if let Some(anchor) = &self.anchor {
                object.insert("anchor".to_owned(), anchor.data_json());
            }
            if let Some(hit) = &self.fallback_hit {
                object.insert("fallbackHit".to_owned(), hit.clone());
            }
        }
        value
    }
}

impl ImpactMemorySummary {
    #[must_use]
    pub fn from_memory(memory: &StoredMemory) -> Self {
        Self {
            level: memory.level.clone(),
            kind: memory.kind.clone(),
            trust_class: memory.trust_class.clone(),
            trust_subclass: memory.trust_subclass.clone(),
            confidence: memory.confidence,
            utility: memory.utility,
            importance: memory.importance,
            content_preview: impact_content_preview(&memory.content),
            provenance_uri: memory.provenance_uri.clone(),
            created_at: memory.created_at.clone(),
            updated_at: memory.updated_at.clone(),
        }
    }

    #[must_use]
    pub fn data_json(&self) -> serde_json::Value {
        serde_json::json!({
            "level": self.level,
            "kind": self.kind,
            "trustClass": self.trust_class,
            "trustSubclass": self.trust_subclass,
            "confidence": self.confidence,
            "utility": self.utility,
            "importance": self.importance,
            "contentPreview": self.content_preview,
            "provenanceUri": self.provenance_uri,
            "createdAt": self.created_at,
            "updatedAt": self.updated_at,
        })
    }
}

impl ImpactAnchorSummary {
    #[must_use]
    pub fn from_anchor(anchor: &StoredMemoryAnchor) -> Self {
        Self {
            kind: anchor.anchor_kind,
            anchor_value_hash: anchor.anchor_value_hash.clone(),
            redacted_anchor_value: anchor.redacted_anchor_value.clone(),
            confidence: anchor.confidence,
            source: anchor.source.as_str().to_owned(),
            freshness_state: anchor.freshness_state.as_str().to_owned(),
            generation: anchor.generation,
            captured_span_hash: anchor.captured_span_hash.clone(),
        }
    }

    #[must_use]
    pub fn data_json(&self) -> serde_json::Value {
        serde_json::json!({
            "kind": self.kind.as_str(),
            "anchorValueHash": self.anchor_value_hash,
            "redactedValue": self.redacted_anchor_value,
            "confidence": self.confidence,
            "source": self.source,
            "freshnessState": self.freshness_state,
            "generation": self.generation,
            "capturedSpanHash": self.captured_span_hash,
        })
    }
}

pub fn run_impact(options: &ImpactOptions) -> Result<ImpactReport, ImpactError> {
    let started = Instant::now();
    let workspace_root = default_workspace_root(&options.workspace_path);
    // Query surfaces consult the filesystem so a real workspace file anchors
    // even when it is outside the lexical repo-path allowlist (GH#14). This
    // keeps `ee impact --path` in agreement with `ee recall --path`, which
    // already accepts any workspace-relative path selector.
    let query_anchor = CreateMemoryAnchorInput::from_query_surface(
        "mem_impactquery000000000000000000",
        options.surface.kind,
        &options.surface.value,
        1.0,
        MemoryAnchorSource::Explicit,
        "impact.query",
        0,
        Some(workspace_root.as_path()),
    )
    .ok_or(ImpactError::InvalidSurface {
        kind: options.surface.kind,
    })?;
    let surface = ImpactResolvedSurface {
        schema: IMPACT_SCHEMA_V1,
        kind: query_anchor.anchor_kind,
        anchor_value_hash: query_anchor.anchor_value_hash.clone(),
        redacted_anchor_value: query_anchor.redacted_anchor_value.clone(),
    };

    let database_path = options
        .database_path
        .clone()
        .unwrap_or_else(|| default_workspace_database_path(&options.workspace_path));
    let connection = DbConnection::open_file(&database_path)?;
    let workspace_id = resolve_workspace_id(&connection, &workspace_root)?;
    let scope_context = MemoryScopeContext::for_workspace(
        &workspace_root,
        options.memory_scope,
        options.strict_scope,
    );
    let mut scope_stats = scope_context.stats();
    let exact_anchors = connection
        .query_memory_anchors(query_anchor.anchor_kind, &query_anchor.anchor_value_hash)?;
    let mut exact_results = exact_impact_results(
        &connection,
        &workspace_id,
        &scope_context,
        &mut scope_stats,
        &exact_anchors,
        options.limit,
    )?;
    let exact_anchor_count = exact_results.len();

    let mut fallback_report = None;
    let mut fallback_count = 0_usize;
    let mut fallback_status = ImpactFallbackStatus::SkippedLimitFilled;
    let mut seen_memory_ids: BTreeSet<String> = exact_results
        .iter()
        .map(|result| result.memory_id.clone())
        .collect();
    let limit = usize::try_from(options.limit).unwrap_or(usize::MAX);
    if exact_results.len() < limit {
        let fallback_limit = options.limit.saturating_sub(exact_results.len() as u32);
        let search_options = SearchOptions {
            workspace_path: workspace_root.clone(),
            database_path: options.database_path.clone(),
            index_dir: options.index_dir.clone(),
            query: options.surface.value.clone(),
            limit: fallback_limit.max(1),
            speed: options.speed,
            explain: false,
            as_of: None,
            include_tombstoned: false,
            include_expired: false,
            include_future: false,
            include_stale: false,
            relevance_floor: None,
            dedup_mode: SearchDedupMode::DocId,
            source_mode: options.source_mode,
            strict_source_mode: options.strict_source_mode,
            memory_scope: options.memory_scope,
            strict_scope: options.strict_scope,
        };
        match run_search_with_read_connection(&search_options, &connection) {
            Ok(report) => {
                fallback_status = ImpactFallbackStatus::Searched;
                append_fallback_results(
                    &connection,
                    &report,
                    &mut seen_memory_ids,
                    limit,
                    &mut exact_results,
                    &mut fallback_count,
                )?;
                scope_stats.merge(&report.scope_stats);
                fallback_report = Some(report);
            }
            Err(_) => {
                fallback_status = ImpactFallbackStatus::Unavailable;
            }
        }
    }

    for (index, result) in exact_results.iter_mut().enumerate() {
        result.rank = index + 1;
    }

    Ok(ImpactReport {
        schema: IMPACT_SCHEMA_V1,
        surface,
        requested_limit: options.limit,
        results: exact_results,
        exact_anchor_count,
        fallback_count,
        fallback_status,
        fallback_report,
        scope_stats,
        elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
    })
}

fn exact_impact_results(
    connection: &DbConnection,
    workspace_id: &str,
    scope_context: &MemoryScopeContext,
    scope_stats: &mut MemoryScopeStats,
    anchors: &[StoredMemoryAnchor],
    limit: u32,
) -> Result<Vec<ImpactResult>, ImpactError> {
    let mut grouped = BTreeMap::<String, Vec<StoredMemoryAnchor>>::new();
    for anchor in anchors {
        grouped
            .entry(anchor.memory_id.clone())
            .or_default()
            .push(anchor.clone());
    }

    let mut results = Vec::new();
    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
    if limit == 0 {
        return Ok(results);
    }
    for (memory_id, mut memory_anchors) in grouped {
        let Some(memory) = connection.get_memory(&memory_id)? else {
            scope_stats.record_candidate_id(false, Some(&memory_id));
            continue;
        };
        if memory.tombstoned_at.is_some() {
            scope_stats.record_candidate_id(false, Some(&memory_id));
            continue;
        }
        let tags = connection.get_memory_tags(&memory_id)?;
        let workspace_candidate =
            memory.workspace_id == workspace_id || memory_tags_include_global_scope(&tags);
        let in_scope =
            workspace_candidate && scope_context.memory_in_scope_with_tags(&memory, &tags);
        scope_stats.record_candidate_id(in_scope, Some(&memory_id));
        if !in_scope {
            continue;
        }
        memory_anchors.sort_by(|left, right| {
            left.anchor_kind
                .cmp(&right.anchor_kind)
                .then_with(|| left.anchor_value_hash.cmp(&right.anchor_value_hash))
                .then_with(|| left.memory_id.cmp(&right.memory_id))
        });
        let anchor = memory_anchors.first().cloned();
        results.push(ImpactResult {
            rank: 0,
            memory_id,
            match_type: ImpactMatchType::ExactAnchor,
            score: anchor
                .as_ref()
                .map_or(1.0, |stored| stored.confidence.clamp(0.0, 1.0)),
            memory: ImpactMemorySummary::from_memory(&memory),
            anchor: anchor.as_ref().map(ImpactAnchorSummary::from_anchor),
            fallback_hit: None,
        });
        if results.len() >= limit {
            break;
        }
    }
    Ok(results)
}

fn append_fallback_results(
    connection: &DbConnection,
    report: &SearchReport,
    seen_memory_ids: &mut BTreeSet<String>,
    limit: usize,
    results: &mut Vec<ImpactResult>,
    fallback_count: &mut usize,
) -> Result<(), ImpactError> {
    let search_data = report.data_json();
    let rendered_hits = search_data
        .get("results")
        .and_then(serde_json::Value::as_array)
        .cloned()
        .unwrap_or_default();
    let rendered_by_memory_id = rendered_hits
        .into_iter()
        .filter_map(|hit| {
            let memory_id = hit
                .get("memoryId")
                .or_else(|| hit.get("docId"))
                .and_then(serde_json::Value::as_str)?
                .to_owned();
            Some((memory_id, hit))
        })
        .collect::<BTreeMap<_, _>>();

    for hit in &report.results {
        if results.len() >= limit {
            break;
        }
        let memory_id = hit.doc_id.as_str();
        if !memory_id.starts_with("mem_") || !seen_memory_ids.insert(memory_id.to_owned()) {
            continue;
        }
        let Some(memory) = connection.get_memory(memory_id)? else {
            continue;
        };
        results.push(ImpactResult {
            rank: 0,
            memory_id: memory_id.to_owned(),
            match_type: ImpactMatchType::SearchFallback,
            score: hit.relevance_score(),
            memory: ImpactMemorySummary::from_memory(&memory),
            anchor: None,
            fallback_hit: rendered_by_memory_id.get(memory_id).cloned(),
        });
        *fallback_count = fallback_count.saturating_add(1);
    }
    Ok(())
}

fn default_workspace_root(workspace_path: &Path) -> PathBuf {
    crate::config::workspace::canonical_workspace_root_or_lexical(workspace_path)
}

fn default_workspace_database_path(workspace_path: &Path) -> PathBuf {
    default_workspace_root(workspace_path)
        .join(".ee")
        .join("ee.db")
}

fn resolve_workspace_id(
    connection: &DbConnection,
    workspace_path: &Path,
) -> Result<String, DbError> {
    let requested = crate::core::curate::stable_workspace_id(workspace_path);
    if let Ok(Some(workspace)) = crate::core::workspace::select_existing_workspace_row(
        connection,
        &requested,
        &[workspace_path],
    ) {
        return Ok(workspace.id);
    }
    Ok(connection
        .get_workspace_by_path(&workspace_path.to_string_lossy())?
        .map(|workspace| workspace.id)
        .unwrap_or(requested))
}

fn impact_content_preview(content: &str) -> String {
    const MAX_CHARS: usize = 240;
    let collapsed = content.split_whitespace().collect::<Vec<_>>().join(" ");
    if collapsed.chars().count() <= MAX_CHARS {
        return collapsed;
    }
    let mut preview = collapsed.chars().take(MAX_CHARS).collect::<String>();
    preview.push('…');
    preview
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::{CreateMemoryInput, CreateWorkspaceInput};
    use crate::models::{MemoryAnchorKind, MemoryScope};

    type TestResult = Result<(), String>;

    fn seed_anchor_database(
        connection: &DbConnection,
        workspace: &Path,
    ) -> Result<(String, String), DbError> {
        connection.migrate()?;
        let workspace_id = crate::core::curate::stable_workspace_id(workspace);
        connection.insert_workspace(
            &workspace_id,
            &CreateWorkspaceInput {
                path: workspace.to_string_lossy().to_string(),
                name: Some("impact-test".to_owned()),
            },
        )?;
        let memory_id = "mem_30000000000000000000000001".to_owned();
        connection.insert_memory(
            &memory_id,
            &CreateMemoryInput {
                workspace_id: workspace_id.clone(),
                level: "procedural".to_owned(),
                kind: "rule".to_owned(),
                content: "Before editing `src/core/impact.rs`, run the anchor impact query."
                    .to_owned(),
                workflow_id: None,
                confidence: 0.9,
                utility: 0.8,
                importance: 0.7,
                provenance_uri: Some("test://impact".to_owned()),
                trust_class: "human_explicit".to_owned(),
                trust_subclass: Some("test".to_owned()),
                tags: Vec::new(),
                valid_from: None,
                valid_to: None,
            },
        )?;
        Ok((workspace_id, memory_id))
    }

    #[test]
    fn impact_exact_anchor_results_are_first_and_redacted() -> TestResult {
        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir
            .path()
            .canonicalize()
            .map_err(|error| error.to_string())?;
        let db_path = workspace.join("impact.ee.db");
        let connection = DbConnection::open_file(&db_path).map_err(|error| error.to_string())?;
        let (_workspace_id, memory_id) =
            seed_anchor_database(&connection, &workspace).map_err(|error| error.to_string())?;

        let report = run_impact(&ImpactOptions {
            workspace_path: workspace,
            database_path: Some(db_path),
            index_dir: None,
            surface: ImpactSurfaceQuery {
                kind: MemoryAnchorKind::Path,
                value: "src/core/impact.rs".to_owned(),
            },
            limit: 1,
            speed: SpeedMode::Instant,
            source_mode: SearchSourceMode::LexicalOnly,
            strict_source_mode: false,
            memory_scope: MemoryScope::Swarm,
            strict_scope: false,
        })
        .map_err(|error| error.to_string())?;

        assert_eq!(report.results.len(), 1);
        assert_eq!(report.results[0].memory_id, memory_id);
        assert_eq!(report.results[0].match_type, ImpactMatchType::ExactAnchor);
        assert_eq!(
            report.fallback_status,
            ImpactFallbackStatus::SkippedLimitFilled
        );
        let data = report.data_json();
        assert_eq!(data["schema"], IMPACT_SCHEMA_V1);
        assert_eq!(data["surface"]["kind"], "path");
        assert!(
            data["surface"]["anchorValueHash"]
                .as_str()
                .unwrap_or_default()
                .starts_with("blake3:")
        );
        assert_eq!(data["results"][0]["matchType"], "exact_anchor");
        let anchor_block = data["results"][0]["anchor"].to_string();
        assert!(!anchor_block.contains("src/core/impact.rs"));
        Ok(())
    }

    #[test]
    fn impact_zero_limit_returns_no_exact_anchor_results() -> TestResult {
        let tempdir = tempfile::tempdir().map_err(|error| error.to_string())?;
        let workspace = tempdir
            .path()
            .canonicalize()
            .map_err(|error| error.to_string())?;
        let db_path = workspace.join("impact.ee.db");
        let connection = DbConnection::open_file(&db_path).map_err(|error| error.to_string())?;
        seed_anchor_database(&connection, &workspace).map_err(|error| error.to_string())?;

        let report = run_impact(&ImpactOptions {
            workspace_path: workspace,
            database_path: Some(db_path),
            index_dir: None,
            surface: ImpactSurfaceQuery {
                kind: MemoryAnchorKind::Path,
                value: "src/core/impact.rs".to_owned(),
            },
            limit: 0,
            speed: SpeedMode::Instant,
            source_mode: SearchSourceMode::LexicalOnly,
            strict_source_mode: false,
            memory_scope: MemoryScope::Swarm,
            strict_scope: false,
        })
        .map_err(|error| error.to_string())?;

        assert!(report.results.is_empty());
        assert_eq!(report.exact_anchor_count, 0);
        assert_eq!(
            report.fallback_status,
            ImpactFallbackStatus::SkippedLimitFilled
        );
        assert_eq!(report.data_json()["resultCount"], 0);
        Ok(())
    }

    #[test]
    fn impact_rejects_invalid_surface_values() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let report = run_impact(&ImpactOptions {
            workspace_path: tempdir.path().to_path_buf(),
            database_path: Some(tempdir.path().join("missing.ee.db")),
            index_dir: None,
            surface: ImpactSurfaceQuery {
                kind: MemoryAnchorKind::EnvVar,
                value: "not_an_ee_variable".to_owned(),
            },
            limit: 5,
            speed: SpeedMode::Instant,
            source_mode: SearchSourceMode::LexicalOnly,
            strict_source_mode: false,
            memory_scope: MemoryScope::Swarm,
            strict_scope: false,
        });
        assert!(matches!(
            report,
            Err(ImpactError::InvalidSurface {
                kind: MemoryAnchorKind::EnvVar
            })
        ));
    }
}