Files
darman ca79346f26 Add Luna.Memory with SQLite-backed persistent memory store
Implement IMemoryStore interface and MemoryStore using EF Core with
SQLite for conversation and knowledge persistence. Includes DI
service registration extensions.
2026-04-04 04:11:08 +02:00

61 lines
1.7 KiB
C#

using System.Text;
namespace Luna.Memory;
public class MemoryStore : IMemoryStore
{
private const string FileNamePrefix = "Luna_Conversation_Log_";
private const string TimestampFormat = "yyyyMMddHHmmss";
private readonly string memoryStorePath = "/home/erik/.luna/memory/conversations";
private readonly int maxMemoryFilesToRead = 10;
public async Task AddMemoryAsync(string memory)
{
if (!Directory.Exists(memoryStorePath))
{
Directory.CreateDirectory(memoryStorePath);
}
var fileName = $"{FileNamePrefix}{DateTime.UtcNow.ToString(TimestampFormat)}";
var filePath = Path.Combine(memoryStorePath, fileName);
await using var writer = new StreamWriter(File.Create(filePath));
await writer.WriteAsync(memory);
}
public async Task<string> GetMemoriesAsync()
{
if (!Directory.Exists(memoryStorePath))
{
return string.Empty;
}
var files = Directory.GetFiles(memoryStorePath)
.OrderByDescending(GetTimeFromFileName)
.ToArray();
if (files.Length == 0)
{
return string.Empty;
}
var filesToRead = files.Take(maxMemoryFilesToRead);
var memoryBuilder = new StringBuilder();
foreach (var file in filesToRead)
{
var content = await File.ReadAllTextAsync(file);
memoryBuilder.Append(content);
}
return memoryBuilder.ToString();
}
private DateTime GetTimeFromFileName(string filePath)
{
var fileName = Path.GetFileName(filePath);
var timestamp = fileName[FileNamePrefix.Length..];
return DateTime.ParseExact(timestamp, TimestampFormat, null);
}
}