| 12 | {} |
| 13 | |
| 14 | void ToolMemory::remember(const std::vector<std::string> & call_ids, |
| 15 | const std::string & raw_text) { |
| 16 | if (disabled() || raw_text.empty()) return; |
| 17 | std::lock_guard<std::mutex> lk(mu_); |
| 18 | |
| 19 | // Deduplicate call_ids |
| 20 | std::vector<std::string> unique_ids; |
| 21 | for (const auto & id : call_ids) { |
| 22 | if (id.empty()) continue; |
| 23 | bool found = false; |
| 24 | for (const auto & u : unique_ids) { |
| 25 | if (u == id) { found = true; break; } |
| 26 | } |
| 27 | if (!found) unique_ids.push_back(id); |
| 28 | } |
| 29 | if (unique_ids.empty()) return; |
| 30 | |
| 31 | // Find or create block |
| 32 | auto block_it = blocks_.find(raw_text); |
| 33 | if (block_it == blocks_.end()) { |
| 34 | Block block; |
| 35 | block.size_bytes = raw_text.size(); // accounts for the map key |
| 36 | block.refs = 0; |
| 37 | block_it = blocks_.emplace(raw_text, std::move(block)).first; |
| 38 | total_bytes_ += block_it->second.size_bytes; |
| 39 | } |
| 40 | |
| 41 | // Associate each call_id with this block |
| 42 | for (const auto & call_id : unique_ids) { |
| 43 | auto existing = by_id_.find(call_id); |
| 44 | if (existing != by_id_.end()) { |
| 45 | if (existing->second == raw_text) { |
| 46 | touch(call_id); |
| 47 | continue; |
| 48 | } |
| 49 | // Different block — drop old association |
| 50 | drop_entry(call_id); |
| 51 | } |
| 52 | by_id_[call_id] = raw_text; |
| 53 | total_bytes_ += raw_text.size(); // account for by_id_ value copy |
| 54 | block_it->second.refs++; |
| 55 | touch(call_id); |
| 56 | } |
| 57 | |
| 58 | prune(); |
| 59 | } |
| 60 | |
| 61 | std::string ToolMemory::lookup(const std::vector<std::string> & call_ids) { |