/**
 * Prune stale files on startup.
 *
 * Deletes session JSONL files older than 14 days.
 */
import { readdirSync, rmSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { getSessionsDir } from '../config.js';
const FOURTEEN_DAYS_MS = 14 * 24 * 60 * 60 * 1000;
/** Delete session JSONL files older than 14 days. */
export function pruneStaleFiles() {
    const cutoff = Date.now() - FOURTEEN_DAYS_MS;
    pruneSessionFiles(cutoff);
}
/** Walk the sessions root and prune JSONL files older than `cutoff`. */
function pruneSessionFiles(cutoff) {
    try {
        const sessionsRoot = getSessionsDir();
        for (const projectDir of readdirSync(sessionsRoot)) {
            pruneJsonlFilesRecursively(join(sessionsRoot, projectDir), cutoff);
        }
    }
    catch {
        /* ignore */
    }
}
/** Recursively delete `.jsonl` files in `dir` whose mtime is older than `cutoff`. */
function pruneJsonlFilesRecursively(dir, cutoff) {
    try {
        for (const entry of readdirSync(dir, { withFileTypes: true })) {
            const entryPath = join(dir, entry.name);
            if (entry.isDirectory()) {
                pruneJsonlFilesRecursively(entryPath, cutoff);
                continue;
            }
            if (!entry.isFile() || !entry.name.endsWith('.jsonl'))
                continue;
            try {
                if (statSync(entryPath).mtimeMs < cutoff) {
                    rmSync(entryPath, { force: true });
                }
            }
            catch {
                /* ignore */
            }
        }
    }
    catch {
        /* ignore */
    }
}
//# sourceMappingURL=prune-sessions.js.map