// engine/telemetry/retention.ts — 30-day telemetry file rotation (SPEC-741)
import { readdir, unlink, stat, appendFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
/**
 * File pattern matching telemetry call log files.
 * Only rotates calls-*.jsonl files, never digest files.
 */
const CALLS_FILE_PATTERN = /^calls-(\d{4}-\d{2}-\d{2})\.jsonl$/;
/**
 * Rotate (delete) telemetry call log files older than maxAgeDays.
 * Scans only planu/.telemetry/calls-*.jsonl — never touches digests/.
 * Appends a record to rotation.log on each run (idempotent).
 *
 * @param rootDir    - Project root directory (contains planu/ subdirectory)
 * @param maxAgeDays - Files older than this number of days are deleted (default: 30)
 */
export async function rotateTelemetry(rootDir, maxAgeDays = 30) {
    const telemetryDir = join(rootDir, 'planu', '.telemetry');
    const rotationLog = join(telemetryDir, 'rotation.log');
    const result = {
        scanned: 0,
        deleted: [],
        errors: [],
    };
    // Ensure directory exists
    try {
        await mkdir(telemetryDir, { recursive: true });
    }
    catch {
        // Ignore — directory already exists
    }
    // Scan directory for call log files
    let entries;
    try {
        entries = await readdir(telemetryDir);
    }
    catch {
        // Directory doesn't exist yet — nothing to rotate
        return result;
    }
    const cutoffMs = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
    for (const name of entries) {
        if (!CALLS_FILE_PATTERN.test(name)) {
            continue;
        }
        result.scanned++;
        const filePath = join(telemetryDir, name);
        try {
            const info = await stat(filePath);
            if (info.mtimeMs < cutoffMs) {
                await unlink(filePath);
                result.deleted.push(name);
            }
        }
        catch (err) {
            result.errors.push({
                path: filePath,
                reason: err instanceof Error ? err.message : String(err),
            });
        }
    }
    // Append rotation log entry (idempotent — one entry per run)
    try {
        const logEntry = JSON.stringify({
            ts: new Date().toISOString(),
            scanned: result.scanned,
            deleted: result.deleted,
            errors: result.errors.length,
        }) + '\n';
        await appendFile(rotationLog, logEntry, 'utf-8');
    }
    catch {
        // Non-fatal — rotation itself succeeded
    }
    return result;
}
//# sourceMappingURL=retention.js.map