spider_agent 2.54.3

A concurrent-safe multimodal agent for web automation and research.
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
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
//! Long-term experience memory for agent learning.
//!
//! Stores successful automation experiences in an append-only `.jsonl` log
//! and uses `memvid-rs` for semantic search over past strategies.
//! The memvid video+index is rebuilt lazily when recall is needed after
//! new experiences have been added.
//!
//! # Threading
//!
//! [`ExperienceMemory`] owns a `memvid_rs::MemvidRetriever`, whose interiors
//! (ffmpeg raw pointers, rusqlite's `RefCell`) are `!Send` and `!Sync`. Rather
//! than assert otherwise and guard it with a lock, the memory is **owned by a
//! dedicated thread** and reached through [`ExperienceMemoryHandle`], which
//! bridges requests over `flume` and replies over `tokio::sync::oneshot`.
//!
//! Consequences:
//!
//! - The value never crosses a thread boundary, so no `unsafe impl Send`/`Sync`
//!   is needed — the compiler checks what a comment used to promise.
//! - No `Mutex` or `RwLock` anywhere in this module. Requests serialize by
//!   construction, because one thread processes them in order.
//! - Callers no longer need `spawn_blocking` + `Handle::block_on` to contain
//!   `!Send` temporaries; every handle method is a plain `async fn`.

use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Outcome of an automation experience.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExperienceOutcome {
    /// Automation completed successfully.
    Success,
    /// Automation failed.
    Failure,
}

impl std::fmt::Display for ExperienceOutcome {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Success => write!(f, "success"),
            Self::Failure => write!(f, "failure"),
        }
    }
}

/// A single recorded automation experience.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExperienceRecord {
    /// Type of challenge encountered (e.g. "image-grid-selection").
    pub challenge_type: String,
    /// Domain/path pattern of the URL.
    pub url_pattern: String,
    /// Keywords extracted from the page title.
    pub title_keywords: Vec<String>,
    /// CSS classes/elements that identify the challenge.
    pub html_signals: Vec<String>,
    /// Human-readable summary of what strategy worked.
    pub strategy_summary: String,
    /// Serialized action steps as JSON.
    pub steps_json: String,
    /// Whether the automation succeeded or failed.
    pub outcome: ExperienceOutcome,
    /// Number of rounds the automation took.
    pub rounds_taken: u32,
    /// Unix timestamp of when the experience was recorded.
    pub timestamp: u64,
}

impl ExperienceRecord {
    /// Build an experience record from a completed automation session.
    ///
    /// Extracts URL pattern, title keywords, and constructs a strategy summary
    /// from the session data.
    pub fn from_session(
        url: &str,
        label: &str,
        memory: &super::AutomationMemory,
        steps_executed: usize,
        rounds: u32,
    ) -> Self {
        // Extract domain pattern from URL
        let url_pattern = url.split('/').take(3).collect::<Vec<_>>().join("/") + "/*";

        // Extract title keywords (non-trivial words)
        let title_keywords: Vec<String> = label
            .split_whitespace()
            .filter(|w| w.len() > 2)
            .map(|w| w.to_lowercase())
            .collect();

        // Build strategy summary from memory actions
        let actions: Vec<String> = memory
            .action_history
            .iter()
            .rev()
            .take(10)
            .rev()
            .cloned()
            .collect();
        let strategy_summary = if actions.is_empty() {
            format!("Completed '{}' in {} steps", label, steps_executed)
        } else {
            let action_summary = actions.join(" → ");
            if action_summary.len() > 300 {
                format!(
                    "{}...",
                    spider_agent_types::truncate_utf8_head(&action_summary, 297)
                )
            } else {
                action_summary
            }
        };

        let steps_json = serde_json::to_string(&actions).unwrap_or_default();

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        Self {
            challenge_type: label.to_string(),
            url_pattern,
            title_keywords,
            html_signals: Vec::new(),
            strategy_summary,
            steps_json,
            outcome: ExperienceOutcome::Success,
            rounds_taken: rounds,
            timestamp,
        }
    }

    /// Convert this record to a searchable text representation for memvid indexing.
    fn to_search_text(&self) -> String {
        format!(
            "challenge: {} url: {} keywords: {} strategy: {} outcome: {} rounds: {}",
            self.challenge_type,
            self.url_pattern,
            self.title_keywords.join(", "),
            self.strategy_summary,
            self.outcome,
            self.rounds_taken,
        )
    }
}

/// A recalled experience with its relevance score.
#[derive(Debug, Clone)]
pub struct RecalledExperience {
    /// The original experience record.
    pub record: ExperienceRecord,
    /// Relevance score from semantic search (0.0 - 1.0).
    pub relevance: f32,
}

/// Configuration for the experience memory system.
#[derive(Debug, Clone)]
pub struct ExperienceMemoryConfig {
    /// Maximum number of experiences to retrieve per query.
    pub max_recall: usize,
    /// Maximum total characters of context to inject into prompts.
    pub max_context_chars: usize,
    /// Minimum relevance score threshold for recall results.
    pub min_relevance_score: f32,
    /// Text chunk size for memvid indexing.
    pub chunk_size: usize,
    /// Chunk overlap for memvid indexing.
    pub overlap: usize,
}

impl Default for ExperienceMemoryConfig {
    fn default() -> Self {
        Self {
            max_recall: 3,
            max_context_chars: 2000,
            min_relevance_score: 0.15,
            chunk_size: 512,
            overlap: 32,
        }
    }
}

/// Statistics about the experience memory.
#[derive(Debug, Clone, Default)]
pub struct MemoryStats {
    /// Total number of stored experiences.
    pub experience_count: usize,
    /// Size of the .jsonl log file in bytes.
    pub log_size_bytes: u64,
    /// Size of the memvid video file in bytes.
    pub video_size_bytes: u64,
    /// Size of the memvid index file in bytes.
    pub index_size_bytes: u64,
    /// Whether the index needs rebuilding.
    pub dirty: bool,
}

/// Manages long-term experience storage and semantic retrieval.
///
/// Experiences are stored in an append-only `.jsonl` file (source of truth).
/// A memvid video+index is rebuilt lazily when recall is needed after new
/// experiences have been added. This avoids the cost of rebuilding on every
/// store operation.
///
/// Not `Clone` because it owns the memvid retriever handle.
pub struct ExperienceMemory {
    /// Path to the .jsonl append-only experience log.
    log_path: PathBuf,
    /// Path to the memvid .mp4 video file.
    video_path: PathBuf,
    /// Path to the memvid .db index file.
    index_path: PathBuf,
    /// Lazy-loaded memvid retriever.
    retriever: Option<memvid_rs::MemvidRetriever>,
    /// True when .jsonl has new entries since last index build.
    dirty: bool,
    /// Cache of query hash → recalled experiences.
    recall_cache: DashMap<u64, Vec<RecalledExperience>>,
    /// Configuration for this memory instance.
    pub config: ExperienceMemoryConfig,
}

// Deliberately NOT `unsafe impl Send`/`Sync`. The `!Send` interiors (rusqlite's
// `RefCell` and ffmpeg raw pointers inside `MemvidRetriever`) stay pinned to the
// thread that owns them; cross-thread access goes through
// [`ExperienceMemoryHandle`], so the compiler enforces the invariant that a
// `SAFETY` comment used to assert by hand.

impl std::fmt::Debug for ExperienceMemory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExperienceMemory")
            .field("log_path", &self.log_path)
            .field("video_path", &self.video_path)
            .field("index_path", &self.index_path)
            .field("has_retriever", &self.retriever.is_some())
            .field("dirty", &self.dirty)
            .field("cache_entries", &self.recall_cache.len())
            .field("config", &self.config)
            .finish()
    }
}

impl ExperienceMemory {
    /// Create or load an experience memory from a directory.
    ///
    /// If the directory doesn't exist, it will be created.
    /// If existing `.jsonl` / `.mp4` / `.db` files are found, they are loaded.
    pub async fn new(
        dir: impl Into<PathBuf>,
        config: ExperienceMemoryConfig,
    ) -> std::io::Result<Self> {
        let dir = dir.into();
        tokio::fs::create_dir_all(&dir).await?;

        let log_path = dir.join("experiences.jsonl");
        let video_path = dir.join("experiences.mp4");
        let index_path = dir.join("experiences.db");

        // Determine if we have unindexed experiences
        let log_exists = log_path.exists();
        let index_exists = video_path.exists() && index_path.exists();
        let dirty = log_exists && !index_exists;

        Ok(Self {
            log_path,
            video_path,
            index_path,
            retriever: None,
            dirty,
            recall_cache: DashMap::new(),
            config,
        })
    }

    /// Append an experience record to the .jsonl log.
    ///
    /// Marks the index as dirty so it will be rebuilt on next recall.
    pub async fn store_experience(&mut self, record: &ExperienceRecord) -> std::io::Result<()> {
        let mut line = serde_json::to_string(record)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        line.push('\n');

        use tokio::io::AsyncWriteExt;
        let mut file = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.log_path)
            .await?;
        file.write_all(line.as_bytes()).await?;
        file.flush().await?;

        self.dirty = true;
        self.recall_cache.clear();
        self.retriever = None;

        log::debug!(
            "Stored experience: challenge={} outcome={} rounds={}",
            record.challenge_type,
            record.outcome,
            record.rounds_taken,
        );

        Ok(())
    }

    /// Recall relevant past experiences for a given query.
    ///
    /// If the index is dirty (new experiences added since last build),
    /// it will be rebuilt first. Results are cached by query hash.
    pub async fn recall(
        &mut self,
        query: &str,
        k: usize,
    ) -> Result<Vec<RecalledExperience>, Box<dyn std::error::Error + Send + Sync>> {
        let query_hash = super::fnv1a64(query.as_bytes());

        // Check cache first
        if let Some(cached) = self.recall_cache.get(&query_hash) {
            return Ok(cached.clone());
        }

        // Rebuild index if dirty
        if self.dirty {
            self.rebuild_index().await?;
        }

        // Load retriever if needed
        if self.retriever.is_none() {
            if !self.video_path.exists() || !self.index_path.exists() {
                return Ok(Vec::new());
            }
            self.retriever = Some(
                memvid_rs::MemvidRetriever::new(
                    self.video_path.to_string_lossy().as_ref(),
                    self.index_path.to_string_lossy().as_ref(),
                )
                .await?,
            );
        }

        let retriever = self.retriever.as_mut().expect("retriever loaded");
        let search_results = retriever.search(query, k).await?;

        // Load all records for matching
        let all_records = self.load_all_records().await?;

        let mut experiences = Vec::with_capacity(search_results.len());
        for (score, text) in &search_results {
            // Match search result text back to an experience record
            let relevance = *score;
            if relevance < self.config.min_relevance_score {
                continue;
            }

            // Find the best matching record for this search result
            if let Some(record) = Self::match_record_to_search_result(&all_records, text) {
                experiences.push(RecalledExperience { record, relevance });
            }
        }

        // Cache results (cap at 256 entries to bound memory)
        if self.recall_cache.len() >= 256 {
            self.recall_cache.clear();
        }
        self.recall_cache.insert(query_hash, experiences.clone());

        Ok(experiences)
    }

    /// Format recalled experiences as context suitable for prompt injection.
    ///
    /// Output is capped at `max_context_chars` to keep prompts manageable.
    pub fn recall_to_context(
        experiences: &[RecalledExperience],
        max_context_chars: usize,
    ) -> String {
        if experiences.is_empty() {
            return String::new();
        }

        let mut ctx = String::from("## Learned Strategies (from past experience)\n");
        let mut remaining = max_context_chars.saturating_sub(ctx.len());

        for exp in experiences {
            let mut entry = format!(
                "### {} (relevance: {:.2})\n",
                exp.record.challenge_type, exp.relevance,
            );
            entry.push_str(&format!("URL pattern: {}\n", exp.record.url_pattern));

            // Truncate strategy summary if needed
            let summary = if exp.record.strategy_summary.len() > 300 {
                format!("{}...", &exp.record.strategy_summary[..297])
            } else {
                exp.record.strategy_summary.clone()
            };
            entry.push_str(&format!("Strategy: {}\n", summary));

            if exp.record.rounds_taken > 0 {
                entry.push_str(&format!(
                    "Outcome: {} in {} rounds\n",
                    exp.record.outcome, exp.record.rounds_taken
                ));
            }
            entry.push_str("---\n");

            if entry.len() > remaining {
                break;
            }
            remaining -= entry.len();
            ctx.push_str(&entry);
        }

        ctx
    }

    /// Remove experiences matching a semantic query from the log.
    ///
    /// Searches for the top-k matches and removes them from the `.jsonl` file.
    /// Marks the index as dirty.
    pub async fn release_by_query(
        &mut self,
        query: &str,
        k: usize,
    ) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> {
        let matches = self.recall(query, k).await?;
        if matches.is_empty() {
            return Ok(0);
        }

        // Collect timestamps of records to remove
        let remove_timestamps: std::collections::HashSet<u64> =
            matches.iter().map(|m| m.record.timestamp).collect();

        let all_records = self.load_all_records().await?;
        let remaining: Vec<&ExperienceRecord> = all_records
            .iter()
            .filter(|r| !remove_timestamps.contains(&r.timestamp))
            .collect();

        let removed_count = all_records.len() - remaining.len();

        // Rewrite the log with remaining records
        self.rewrite_log(&remaining).await?;

        self.dirty = true;
        self.recall_cache.clear();
        self.retriever = None;

        Ok(removed_count)
    }

    /// Delete all experience data and reset state.
    pub async fn release_all(&mut self) -> std::io::Result<()> {
        for path in [&self.log_path, &self.video_path, &self.index_path] {
            if path.exists() {
                let _ = tokio::fs::remove_file(path).await;
            }
        }
        self.dirty = false;
        self.recall_cache.clear();
        self.retriever = None;
        Ok(())
    }

    /// Get statistics about the current memory state.
    ///
    /// Uses io_uring when available for non-blocking file reads.
    pub async fn stats(&self) -> MemoryStats {
        // Read log content asynchronously — also gives us the size.
        let log_data = tokio::fs::read(&self.log_path).await.unwrap_or_default();
        let log_size = log_data.len() as u64;
        let count = String::from_utf8_lossy(&log_data)
            .lines()
            .filter(|l| !l.trim().is_empty())
            .count();

        // File sizes for video/index — use std::fs::metadata (fast, sync stat).
        let video_size = std::fs::metadata(&self.video_path)
            .map(|m| m.len())
            .unwrap_or(0);
        let index_size = std::fs::metadata(&self.index_path)
            .map(|m| m.len())
            .unwrap_or(0);

        MemoryStats {
            experience_count: count,
            log_size_bytes: log_size,
            video_size_bytes: video_size,
            index_size_bytes: index_size,
            dirty: self.dirty,
        }
    }

    /// Force rebuild the memvid index from the .jsonl log.
    pub async fn flush(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.rebuild_index().await?;
        Ok(())
    }

    /// Clear the recall cache. Called at the start of each new automation run.
    pub fn clear_cache(&self) {
        self.recall_cache.clear();
    }

    /// Read-only view of this memory's configuration.
    pub fn config(&self) -> &ExperienceMemoryConfig {
        &self.config
    }

    // ---- Internal helpers ----

    /// Rebuild the memvid video+index from the .jsonl log.
    async fn rebuild_index(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let records = self.load_all_records().await?;
        if records.is_empty() {
            self.dirty = false;
            return Ok(());
        }

        // Build combined text from all records
        let combined_text: String = records
            .iter()
            .map(|r| r.to_search_text())
            .collect::<Vec<_>>()
            .join("\n\n");

        let video_path_str = self.video_path.to_string_lossy().into_owned();
        let index_path_str = self.index_path.to_string_lossy().into_owned();
        let chunk_size = self.config.chunk_size;
        let overlap = self.config.overlap;

        // Encode and build index
        let mut encoder = memvid_rs::MemvidEncoder::new(None).await?;
        encoder
            .add_text(&combined_text, chunk_size, overlap)
            .await?;
        encoder
            .build_video(&video_path_str, &index_path_str)
            .await?;

        self.dirty = false;
        self.retriever = None; // will be reloaded on next recall
        self.recall_cache.clear();

        log::debug!(
            "Rebuilt experience index: {} records, video={}, index={}",
            records.len(),
            self.video_path.display(),
            self.index_path.display(),
        );

        Ok(())
    }

    /// Load all experience records from the .jsonl log.
    async fn load_all_records(&self) -> std::io::Result<Vec<ExperienceRecord>> {
        if !self.log_path.exists() {
            return Ok(Vec::new());
        }

        let content = tokio::fs::read_to_string(&self.log_path).await?;
        let records: Vec<ExperienceRecord> = content
            .lines()
            .filter(|line| !line.trim().is_empty())
            .filter_map(|line| serde_json::from_str(line).ok())
            .collect();

        Ok(records)
    }

    /// Rewrite the .jsonl log with only the given records.
    async fn rewrite_log(&self, records: &[&ExperienceRecord]) -> std::io::Result<()> {
        let mut content = String::new();
        for record in records {
            let line = serde_json::to_string(record)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            content.push_str(&line);
            content.push('\n');
        }

        tokio::fs::write(&self.log_path, content.as_bytes()).await
    }

    /// Match a search result text back to the most similar experience record.
    fn match_record_to_search_result(
        records: &[ExperienceRecord],
        search_text: &str,
    ) -> Option<ExperienceRecord> {
        let search_lower = search_text.to_lowercase();
        // Build the search word set once — not per record inside the closure.
        let search_words: std::collections::HashSet<&str> =
            search_lower.split_whitespace().collect();
        records
            .iter()
            .max_by_key(|r| {
                let record_text = r.to_search_text().to_lowercase();
                // Simple overlap score: count shared words
                let record_words: std::collections::HashSet<&str> =
                    record_text.split_whitespace().collect();
                record_words.intersection(&search_words).count()
            })
            .cloned()
    }
}

/// A boxed error that is safe to carry back across the bridge.
type BridgeError = Box<dyn std::error::Error + Send + Sync>;

/// Number of memory worker threads currently alive.
///
/// Incremented as a worker starts and decremented as it exits, so a leaked
/// worker is observable rather than a matter of trust. See
/// [`live_worker_count`].
static LIVE_WORKERS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// How many experience-memory worker threads are currently running.
///
/// One per live [`ExperienceMemoryHandle`] family: every clone of a handle
/// shares a worker, and the worker retires once the last clone drops. A count
/// that does not fall back to its baseline after handles are dropped means a
/// worker leaked.
pub fn live_worker_count() -> usize {
    LIVE_WORKERS.load(std::sync::atomic::Ordering::Acquire)
}

/// Decrements [`LIVE_WORKERS`] however the worker body leaves scope, including
/// on panic — a leaked *count* would be as misleading as a leaked thread.
struct WorkerCensus;

impl Drop for WorkerCensus {
    fn drop(&mut self) {
        LIVE_WORKERS.fetch_sub(1, std::sync::atomic::Ordering::Release);
    }
}

/// Work items accepted by the memory thread.
///
/// Each carries the `oneshot` the worker answers on. A dropped reply channel is
/// not an error: it means the caller went away, and the worker just moves on.
enum MemoryRequest {
    /// Append an experience to the log.
    Store(
        Box<ExperienceRecord>,
        tokio::sync::oneshot::Sender<std::io::Result<()>>,
    ),
    /// Semantic recall of up to `k` past experiences.
    Recall(
        String,
        usize,
        tokio::sync::oneshot::Sender<Result<Vec<RecalledExperience>, BridgeError>>,
    ),
    /// Drop experiences matching a query, returning how many were removed.
    ReleaseByQuery(
        String,
        usize,
        tokio::sync::oneshot::Sender<Result<usize, BridgeError>>,
    ),
    /// Delete every experience artifact.
    ReleaseAll(tokio::sync::oneshot::Sender<std::io::Result<()>>),
    /// Current memory statistics.
    Stats(tokio::sync::oneshot::Sender<MemoryStats>),
    /// Force an index rebuild.
    Flush(tokio::sync::oneshot::Sender<Result<(), BridgeError>>),
    /// Drop the recall cache. Fire-and-forget.
    ClearCache,
}

/// A cheap, `Send + Sync + Clone` handle to a thread-owned [`ExperienceMemory`].
///
/// The memory itself lives on a dedicated thread with its own current-thread
/// runtime, so its `!Send` memvid interiors never move. Cloning a handle clones
/// a channel sender; every clone talks to the same memory, and requests are
/// serviced one at a time in arrival order.
///
/// The worker shuts down when the last handle drops.
#[derive(Clone, Debug)]
pub struct ExperienceMemoryHandle {
    /// Request channel into the owning thread.
    tx: flume::Sender<MemoryRequest>,
    /// Configuration copy, so `max_recall` / `max_context_chars` reads on the
    /// hot path cost no round-trip.
    config: ExperienceMemoryConfig,
}

impl ExperienceMemoryHandle {
    /// Open (or create) an experience memory at `dir` on its own thread.
    ///
    /// The thread is named `experience-memory` and runs a current-thread
    /// runtime. Returns the error from [`ExperienceMemory::new`] if the store
    /// cannot be opened, in which case the thread exits immediately.
    pub async fn spawn(
        dir: impl Into<PathBuf>,
        config: ExperienceMemoryConfig,
    ) -> std::io::Result<Self> {
        let dir = dir.into();
        let worker_config = config.clone();
        // Depth of 1 keeps a burst of stores from queueing without bound; the
        // channel is async, so a full queue suspends the caller rather than
        // blocking a runtime thread.
        let (tx, rx) = flume::bounded::<MemoryRequest>(64);
        let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<std::io::Result<()>>();

        let spawned = std::thread::Builder::new()
            .name("experience-memory".into())
            .spawn(move || {
                LIVE_WORKERS.fetch_add(1, std::sync::atomic::Ordering::Release);
                // Fires on every exit path below, panics included.
                let _census = WorkerCensus;

                let runtime = match tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                {
                    Ok(runtime) => runtime,
                    Err(e) => {
                        let _ = ready_tx.send(Err(e));
                        return;
                    }
                };

                runtime.block_on(async move {
                    let mut memory = match ExperienceMemory::new(dir, worker_config).await {
                        Ok(memory) => {
                            if ready_tx.send(Ok(())).is_err() {
                                // Caller vanished before we finished opening.
                                return;
                            }
                            memory
                        }
                        Err(e) => {
                            let _ = ready_tx.send(Err(e));
                            return;
                        }
                    };

                    // Ends when every sender drops, i.e. the last handle died.
                    while let Ok(request) = rx.recv_async().await {
                        memory.serve(request).await;
                    }
                });
            })?;

        // Keep the JoinHandle out of the returned type: the worker is detached
        // and terminates on channel close, so there is nothing to join.
        drop(spawned);

        match ready_rx.await {
            Ok(Ok(())) => Ok(Self { tx, config }),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(std::io::Error::other(
                "experience memory thread died during startup",
            )),
        }
    }

    /// The configuration this memory was opened with.
    pub fn config(&self) -> &ExperienceMemoryConfig {
        &self.config
    }

    /// Send `request` and await its reply, mapping a dead worker to `Err`.
    async fn call<T>(
        &self,
        request: MemoryRequest,
        rx: tokio::sync::oneshot::Receiver<T>,
    ) -> Result<T, BridgeError> {
        self.tx
            .send_async(request)
            .await
            .map_err(|_| -> BridgeError { "experience memory thread is gone".into() })?;

        rx.await
            .map_err(|_| -> BridgeError { "experience memory dropped the reply".into() })
    }

    /// Append an experience record to the log.
    pub async fn store_experience(&self, record: &ExperienceRecord) -> std::io::Result<()> {
        let (reply, rx) = tokio::sync::oneshot::channel();
        let request = MemoryRequest::Store(Box::new(record.clone()), reply);

        match self.call(request, rx).await {
            Ok(result) => result,
            Err(e) => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)),
        }
    }

    /// Recall up to `k` experiences relevant to `query`.
    pub async fn recall(
        &self,
        query: &str,
        k: usize,
    ) -> Result<Vec<RecalledExperience>, BridgeError> {
        let (reply, rx) = tokio::sync::oneshot::channel();
        let request = MemoryRequest::Recall(query.to_string(), k, reply);

        self.call(request, rx).await?
    }

    /// Remove experiences matching `query`, returning how many were removed.
    pub async fn release_by_query(&self, query: &str, k: usize) -> Result<usize, BridgeError> {
        let (reply, rx) = tokio::sync::oneshot::channel();
        let request = MemoryRequest::ReleaseByQuery(query.to_string(), k, reply);

        self.call(request, rx).await?
    }

    /// Delete all experience data.
    pub async fn release_all(&self) -> std::io::Result<()> {
        let (reply, rx) = tokio::sync::oneshot::channel();

        match self.call(MemoryRequest::ReleaseAll(reply), rx).await {
            Ok(result) => result,
            Err(e) => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, e)),
        }
    }

    /// Statistics about the current memory state.
    pub async fn stats(&self) -> Result<MemoryStats, BridgeError> {
        let (reply, rx) = tokio::sync::oneshot::channel();

        self.call(MemoryRequest::Stats(reply), rx).await
    }

    /// Force a rebuild of the memvid index.
    pub async fn flush(&self) -> Result<(), BridgeError> {
        let (reply, rx) = tokio::sync::oneshot::channel();

        self.call(MemoryRequest::Flush(reply), rx).await?
    }

    /// Drop the recall cache. Fire-and-forget: a dead worker is not an error
    /// worth surfacing for a cache hint.
    pub async fn clear_cache(&self) {
        let _ = self.tx.send_async(MemoryRequest::ClearCache).await;
    }
}

impl ExperienceMemory {
    /// Execute one bridged request, answering on its reply channel.
    ///
    /// A send failure means the caller is gone; the work is already done, so it
    /// is dropped without ceremony.
    async fn serve(&mut self, request: MemoryRequest) {
        match request {
            MemoryRequest::Store(record, reply) => {
                let _ = reply.send(self.store_experience(&record).await);
            }
            MemoryRequest::Recall(query, k, reply) => {
                let _ = reply.send(self.recall(&query, k).await);
            }
            MemoryRequest::ReleaseByQuery(query, k, reply) => {
                let _ = reply.send(self.release_by_query(&query, k).await);
            }
            MemoryRequest::ReleaseAll(reply) => {
                let _ = reply.send(self.release_all().await);
            }
            MemoryRequest::Stats(reply) => {
                let _ = reply.send(self.stats().await);
            }
            MemoryRequest::Flush(reply) => {
                let _ = reply.send(self.flush().await);
            }
            MemoryRequest::ClearCache => self.clear_cache(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_experience_outcome_display() {
        assert_eq!(ExperienceOutcome::Success.to_string(), "success");
        assert_eq!(ExperienceOutcome::Failure.to_string(), "failure");
    }

    #[test]
    fn test_experience_record_serialization() {
        let record = ExperienceRecord {
            challenge_type: "image-grid-selection".to_string(),
            url_pattern: "https://example.com/*".to_string(),
            title_keywords: vec!["select".to_string(), "images".to_string()],
            html_signals: vec!["grid-item".to_string()],
            strategy_summary: "Click matching grid tiles".to_string(),
            steps_json: "[]".to_string(),
            outcome: ExperienceOutcome::Success,
            rounds_taken: 3,
            timestamp: 1700000000,
        };

        let json = serde_json::to_string(&record).unwrap();
        let deserialized: ExperienceRecord = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.challenge_type, "image-grid-selection");
        assert_eq!(deserialized.outcome, ExperienceOutcome::Success);
        assert_eq!(deserialized.rounds_taken, 3);
        assert_eq!(deserialized.title_keywords.len(), 2);
    }

    #[test]
    fn test_config_defaults() {
        let config = ExperienceMemoryConfig::default();
        assert_eq!(config.max_recall, 3);
        assert_eq!(config.max_context_chars, 2000);
        assert_eq!(config.min_relevance_score, 0.15);
        assert_eq!(config.chunk_size, 512);
        assert_eq!(config.overlap, 32);
    }

    #[test]
    fn test_recall_to_context_empty() {
        let ctx = ExperienceMemory::recall_to_context(&[], 2000);
        assert!(ctx.is_empty());
    }

    #[test]
    fn test_recall_to_context_formatting() {
        let experiences = vec![RecalledExperience {
            record: ExperienceRecord {
                challenge_type: "grid-selection".to_string(),
                url_pattern: "https://example.com/*".to_string(),
                title_keywords: vec!["select".to_string()],
                html_signals: vec![],
                strategy_summary: "Click grid tiles matching description".to_string(),
                steps_json: "[]".to_string(),
                outcome: ExperienceOutcome::Success,
                rounds_taken: 2,
                timestamp: 1700000000,
            },
            relevance: 0.82,
        }];

        let ctx = ExperienceMemory::recall_to_context(&experiences, 2000);
        assert!(ctx.contains("Learned Strategies"));
        assert!(ctx.contains("grid-selection"));
        assert!(ctx.contains("0.82"));
        assert!(ctx.contains("Click grid tiles matching description"));
        assert!(ctx.contains("example.com"));
    }

    #[test]
    fn test_recall_to_context_respects_max_chars() {
        let experiences: Vec<RecalledExperience> = (0..100)
            .map(|i| RecalledExperience {
                record: ExperienceRecord {
                    challenge_type: format!("challenge-type-{}", i),
                    url_pattern: format!("https://example{}.com/*", i),
                    title_keywords: vec![],
                    html_signals: vec![],
                    strategy_summary: "A".repeat(200),
                    steps_json: "[]".to_string(),
                    outcome: ExperienceOutcome::Success,
                    rounds_taken: 1,
                    timestamp: 1700000000 + i as u64,
                },
                relevance: 0.9,
            })
            .collect();

        let ctx = ExperienceMemory::recall_to_context(&experiences, 500);
        assert!(ctx.len() <= 600); // some slack for the last entry that fits
    }

    #[test]
    fn test_memory_stats_default() {
        let stats = MemoryStats::default();
        assert_eq!(stats.experience_count, 0);
        assert_eq!(stats.log_size_bytes, 0);
        assert!(!stats.dirty);
    }

    #[test]
    fn test_experience_record_to_search_text() {
        let record = ExperienceRecord {
            challenge_type: "image-grid".to_string(),
            url_pattern: "https://example.com/*".to_string(),
            title_keywords: vec!["select".to_string(), "all".to_string()],
            html_signals: vec![],
            strategy_summary: "Click matching tiles".to_string(),
            steps_json: "[]".to_string(),
            outcome: ExperienceOutcome::Success,
            rounds_taken: 3,
            timestamp: 0,
        };

        let text = record.to_search_text();
        assert!(text.contains("image-grid"));
        assert!(text.contains("example.com"));
        assert!(text.contains("select, all"));
        assert!(text.contains("Click matching tiles"));
        assert!(text.contains("success"));
    }

    #[tokio::test]
    async fn test_store_and_load() {
        let dir = std::env::temp_dir().join(format!("spider_exp_test_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);

        let mut mem = ExperienceMemory::new(&dir, ExperienceMemoryConfig::default())
            .await
            .unwrap();

        let record = ExperienceRecord {
            challenge_type: "test".to_string(),
            url_pattern: "https://test.com/*".to_string(),
            title_keywords: vec!["test".to_string()],
            html_signals: vec![],
            strategy_summary: "Test strategy".to_string(),
            steps_json: "[]".to_string(),
            outcome: ExperienceOutcome::Success,
            rounds_taken: 1,
            timestamp: 1700000000,
        };

        mem.store_experience(&record).await.unwrap();

        let stats = mem.stats().await;
        assert_eq!(stats.experience_count, 1);
        assert!(stats.dirty);
        assert!(stats.log_size_bytes > 0);

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[tokio::test]
    async fn test_release_all() {
        let dir = std::env::temp_dir().join(format!("spider_exp_release_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);

        let mut mem = ExperienceMemory::new(&dir, ExperienceMemoryConfig::default())
            .await
            .unwrap();

        let record = ExperienceRecord {
            challenge_type: "test".to_string(),
            url_pattern: "https://test.com/*".to_string(),
            title_keywords: vec![],
            html_signals: vec![],
            strategy_summary: "Test".to_string(),
            steps_json: "[]".to_string(),
            outcome: ExperienceOutcome::Success,
            rounds_taken: 1,
            timestamp: 1700000000,
        };

        mem.store_experience(&record).await.unwrap();
        assert!(mem.log_path.exists());

        mem.release_all().await.unwrap();
        assert!(!mem.log_path.exists());

        let stats = mem.stats().await;
        assert_eq!(stats.experience_count, 0);
        assert!(!stats.dirty);

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Compile-time proof that the handle is safe to share, without any
    /// `unsafe impl` propping it up.
    #[test]
    fn handle_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ExperienceMemoryHandle>();
    }

    fn sample_record(timestamp: u64) -> ExperienceRecord {
        ExperienceRecord {
            challenge_type: "bridge".to_string(),
            url_pattern: "https://test.com/*".to_string(),
            title_keywords: vec![],
            html_signals: vec![],
            strategy_summary: "Bridged store".to_string(),
            steps_json: "[]".to_string(),
            outcome: ExperienceOutcome::Success,
            rounds_taken: 1,
            timestamp,
        }
    }

    #[tokio::test]
    async fn handle_stores_and_reports_stats() {
        let dir = std::env::temp_dir().join(format!("spider_exp_bridge_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);

        let handle = ExperienceMemoryHandle::spawn(&dir, ExperienceMemoryConfig::default())
            .await
            .expect("memory thread starts");

        handle
            .store_experience(&sample_record(1700000000))
            .await
            .expect("store succeeds through the bridge");

        let stats = handle.stats().await.expect("stats reply");
        assert_eq!(stats.experience_count, 1);
        assert!(stats.dirty);

        handle.release_all().await.expect("release succeeds");
        let stats = handle.stats().await.expect("stats reply");
        assert_eq!(stats.experience_count, 0);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The whole point of the redesign: a handle crosses threads on a
    /// multi-thread runtime while the `!Send` memory stays put on its own.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn handle_is_usable_across_worker_threads() {
        let dir = std::env::temp_dir().join(format!("spider_exp_mt_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);

        let handle = ExperienceMemoryHandle::spawn(&dir, ExperienceMemoryConfig::default())
            .await
            .expect("memory thread starts");

        let tasks: Vec<_> = (0..8)
            .map(|i| {
                let handle = handle.clone();
                tokio::spawn(async move {
                    handle
                        .store_experience(&sample_record(1700000000 + i))
                        .await
                        .expect("store from a worker thread");
                })
            })
            .collect();

        for task in tasks {
            task.await.expect("task completes");
        }

        // Requests serialize on the owning thread, so all 8 landed.
        let stats = handle.stats().await.expect("stats reply");
        assert_eq!(stats.experience_count, 8);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Spawn and drop many memories; workers must retire rather than pile up.
    ///
    /// This is the leak check the old `Arc<RwLock<..>>` design had no way to
    /// express: there was no thread to account for, only a lock nobody could
    /// verify was sound.
    ///
    /// The assertion is on *accumulation*, not on an exact count.
    /// [`live_worker_count`] is process-global and the sibling bridge tests
    /// spawn their own workers concurrently, so pinning the count to a
    /// baseline sampled at entry is racy. A leak here is unmistakable
    /// regardless: 16 undropped workers would leave the gauge at 16-plus,
    /// where correct behavior keeps it near zero for the whole run.
    #[tokio::test]
    async fn workers_retire_when_handles_drop() {
        const CYCLES: usize = 16;
        /// Headroom for workers belonging to concurrently running tests.
        const CONCURRENT_SLACK: usize = 4;

        let mut peak = 0;

        for i in 0..CYCLES {
            let dir =
                std::env::temp_dir().join(format!("spider_exp_leak_{}_{i}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);

            let handle = ExperienceMemoryHandle::spawn(&dir, ExperienceMemoryConfig::default())
                .await
                .expect("memory thread starts");
            let clone = handle.clone();

            handle
                .store_experience(&sample_record(1700000000 + i as u64))
                .await
                .expect("store succeeds");

            peak = peak.max(live_worker_count());

            // Both handles go out of scope here, retiring this cycle's worker.
            drop(handle);
            drop(clone);

            let _ = std::fs::remove_dir_all(&dir);
        }

        // Workers exit asynchronously once their channel closes, so let the
        // last few settle before reading the gauge.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while live_worker_count() > CONCURRENT_SLACK && std::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }

        assert!(
            peak <= 1 + CONCURRENT_SLACK,
            "workers accumulated across {CYCLES} spawn/drop cycles (peak {peak}); \
             a retiring worker should never leave more than one of ours alive",
        );
        assert!(
            live_worker_count() <= CONCURRENT_SLACK,
            "memory worker threads leaked after their handles dropped ({} still live)",
            live_worker_count(),
        );
    }

    /// A clone outliving the original keeps the shared memory addressable —
    /// the worker retires on the *last* handle drop, not the first.
    #[tokio::test]
    async fn clone_outlives_the_original_handle() {
        let dir = std::env::temp_dir().join(format!("spider_exp_drop_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);

        let handle = ExperienceMemoryHandle::spawn(&dir, ExperienceMemoryConfig::default())
            .await
            .expect("memory thread starts");
        let clone = handle.clone();

        handle
            .store_experience(&sample_record(1700000000))
            .await
            .expect("store through the original");
        drop(handle);

        // Same memory, still serving.
        clone
            .store_experience(&sample_record(1700000001))
            .await
            .expect("clone still works after the original drops");

        let stats = clone.stats().await.expect("stats reply");
        assert_eq!(stats.experience_count, 2);

        let _ = std::fs::remove_dir_all(&dir);
    }
}