#include "memory/memory_cache.h" #include "core/psram_object.h" #include #include #include #include #include #include #include namespace borla { namespace { constexpr const char* kTag = "MemoryCache2"; constexpr const char* kNamespace = "memory2"; constexpr const char* kSnapshotKey = "snapshot"; constexpr const char* kLegacyPartitionLabel = "claude_mem"; constexpr uint32_t kRecordMagic = 0x324D454DU; // "MEM2" constexpr uint16_t kRecordVersion = 1; constexpr uint32_t kLegacyMagic = 0x424F524CU; // "BORL" constexpr size_t kMaximumLegacyJsonBytes = 64 * 1024; struct StoredMemoryRecord { uint32_t magic = kRecordMagic; uint16_t version = kRecordVersion; uint16_t reserved = 0; MemorySnapshot snapshot{}; uint32_t checksum = 0; }; template void CopyLegacyTruncated( const char* value, std::array* output) { output->fill('\0'); if (value == nullptr) { return; } size_t length = std::min( std::strlen(value), Capacity - 1); while (length > 0 && (static_cast(value[length]) & 0xC0U) == 0x80U) { --length; } std::memcpy(output->data(), value, length); } } // namespace bool NvsMemoryCache::Load() { std::lock_guard lock(mutex_); snapshot_ = {}; if (LoadNvsLocked()) { return true; } if (!LoadLegacyPartitionLocked()) { ESP_LOGI(kTag, "no valid memory snapshot"); return true; } if (!SaveLocked(snapshot_)) { ESP_LOGW(kTag, "legacy snapshot loaded but NVS migration failed"); } return true; } void NvsMemoryCache::CopySnapshot(MemorySnapshot* output) const { if (output == nullptr) { return; } std::lock_guard lock(mutex_); *output = snapshot_; } bool NvsMemoryCache::Update(const MemorySnapshot& snapshot) { if (!IsValidMemorySnapshot(snapshot)) { return false; } std::lock_guard lock(mutex_); if (!SaveLocked(snapshot)) { return false; } snapshot_ = snapshot; ESP_LOGD(kTag, "snapshot saved child_bytes=%u brain_bytes=%u interactions=%ld", static_cast( std::strlen(snapshot_.child_name.data())), static_cast( std::strlen(snapshot_.brain_text.data())), static_cast(snapshot_.interaction_count)); return true; } bool NvsMemoryCache::LoadNvsLocked() { nvs_handle_t handle = 0; if (nvs_open(kNamespace, NVS_READONLY, &handle) != ESP_OK) { return false; } auto record = MakePsramObject(); if (!record) { ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); nvs_close(handle); return false; } size_t size = sizeof(*record); const esp_err_t result = nvs_get_blob(handle, kSnapshotKey, record.get(), &size); nvs_close(handle); if (result != ESP_OK || size != sizeof(*record) || record->magic != kRecordMagic || record->version != kRecordVersion || !IsValidMemorySnapshot(record->snapshot) || record->checksum != MemorySnapshotChecksum(record->snapshot)) { return false; } snapshot_ = record->snapshot; ESP_LOGI(kTag, "loaded memory snapshot from NVS"); return true; } bool NvsMemoryCache::LoadLegacyPartitionLocked() { const esp_partition_t* partition = esp_partition_find_first( ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, kLegacyPartitionLabel); if (partition == nullptr) { return false; } uint32_t header[2]{}; if (esp_partition_read( partition, 0, header, sizeof(header)) != ESP_OK || header[0] != kLegacyMagic || header[1] == 0 || header[1] > kMaximumLegacyJsonBytes || sizeof(header) + header[1] > partition->size) { return false; } auto* json = static_cast(heap_caps_calloc( header[1] + 1, sizeof(char), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); if (json == nullptr) { return false; } const esp_err_t read_result = esp_partition_read( partition, sizeof(header), json, header[1]); cJSON* root = read_result == ESP_OK ? cJSON_ParseWithLength(json, header[1]) : nullptr; heap_caps_free(json); if (!cJSON_IsObject(root)) { cJSON_Delete(root); return false; } auto migrated = MakePsramObject(); if (!migrated) { ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); cJSON_Delete(root); return false; } const cJSON* brain = cJSON_GetObjectItemCaseSensitive(root, "brain"); const cJSON* name = cJSON_GetObjectItemCaseSensitive(root, "name"); const cJSON* count = cJSON_GetObjectItemCaseSensitive(root, "count"); if (cJSON_IsString(brain)) { CopyLegacyTruncated( brain->valuestring, &migrated->brain_text); } if (cJSON_IsString(name)) { CopyLegacyTruncated( name->valuestring, &migrated->child_name); } if (cJSON_IsNumber(count) && count->valuedouble >= 0 && count->valuedouble <= INT32_MAX) { migrated->interaction_count = count->valueint; } cJSON_Delete(root); if (!IsValidMemorySnapshot(*migrated) || !migrated->HasData()) { return false; } snapshot_ = *migrated; ESP_LOGI(kTag, "migrated legacy claude_mem snapshot"); return true; } bool NvsMemoryCache::SaveLocked(const MemorySnapshot& snapshot) { auto record = MakePsramObject(); if (!record) { ESP_LOGE(kTag, "PSRAM work-buffer allocation failed"); return false; } record->snapshot = snapshot; record->checksum = MemorySnapshotChecksum(record->snapshot); nvs_handle_t handle = 0; esp_err_t result = nvs_open(kNamespace, NVS_READWRITE, &handle); if (result == ESP_OK) { result = nvs_set_blob( handle, kSnapshotKey, record.get(), sizeof(*record)); } if (result == ESP_OK) { result = nvs_commit(handle); } if (handle != 0) { nvs_close(handle); } if (result != ESP_OK) { ESP_LOGE(kTag, "NVS save failed: %s", esp_err_to_name(result)); return false; } return true; } } // namespace borla