pruneLogs function
Bounded log retention pruning.
Binds: INV-G4, FR-136f. Bounded to the last 20 plans OR 30 days, whichever prunes first. This means we keep the subset of the newest 20 plans that are also no older than 30 days. Everything else is pruned.
If pruning encounters an error, it MUST NOT throw — it returns a PruneResult with a warning instead.
Implementation
PruneResult pruneLogs(List<PlanPruneInput> plans, {DateTime? now}) {
try {
final referenceTime = now ?? DateTime.now();
// Sort descending by timestamp (newest first)
final sorted = List<PlanPruneInput>.from(plans)
..sort((a, b) => b.timestamp.compareTo(a.timestamp));
final cutoff = referenceTime.subtract(const Duration(days: 30));
final pathsToPrune = <String>[];
for (var i = 0; i < sorted.length; i++) {
final plan = sorted[i];
// Keep only up to index 19 (the newest 20) and only if it's within the last 30 days.
if (i >= 20 || plan.timestamp.isBefore(cutoff)) {
pathsToPrune.add(plan.path);
}
}
return PruneResult(pathsToPrune: pathsToPrune);
} catch (e) {
return PruneResult(
pathsToPrune: const [],
warning: 'Failed to prune logs: $e',
);
}
}