compactHistory method

Future<int> compactHistory({
  1. Duration retention = const Duration(days: 90),
})

Compact old session history files (entries older than retention period).

Implementation

Future<int> compactHistory({
  Duration retention = const Duration(days: 90),
}) async {
  final cutoff = DateTime.now().subtract(retention);
  int deleted = 0;

  final dir = Directory(_baseDir);
  if (!await dir.exists()) return 0;

  await for (final entity in dir.list()) {
    if (entity is File && entity.path.endsWith('.jsonl')) {
      final stat = await entity.stat();
      if (stat.modified.isBefore(cutoff)) {
        await entity.delete();
        final sid = entity.uri.pathSegments.last.replaceAll('.jsonl', '');
        _sessionCache.remove(sid);
        _summaryCache.remove(sid);
        deleted++;
      }
    }
  }

  if (deleted > 0) await _saveSummaryIndex();
  return deleted;
}