// storage/autopilot-log-store.ts — SPEC-772: Autopilot cascade log persistence
import { readFile, mkdir } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { atomicWriteFile } from '../engine/safety/atomic-write-file.js';
const MAX_ENTRIES = 500;
function logPath(projectId) {
    return join('data', 'projects', projectId, 'autopilot-log.jsonl');
}
/** Read all entries from autopilot-log.jsonl. Returns empty array if file missing. */
async function readEntries(path) {
    try {
        const raw = await readFile(path, 'utf-8');
        return raw
            .split('\n')
            .filter(Boolean)
            .map((line) => JSON.parse(line));
    }
    catch {
        return [];
    }
}
/**
 * Append an entry to autopilot-log.jsonl.
 * Rotates oldest entries when the file exceeds MAX_ENTRIES (500).
 * Best-effort — never throws.
 */
export async function appendAutopilotLogEntry(projectId, entry) {
    try {
        const path = logPath(projectId);
        await mkdir(dirname(path), { recursive: true });
        const existing = await readEntries(path);
        const updated = [...existing, entry].slice(-MAX_ENTRIES);
        await atomicWriteFile(path, updated.map((e) => JSON.stringify(e)).join('\n') + '\n');
    }
    catch {
        // best-effort — never block caller
    }
}
/**
 * Read autopilot log entries from the last `hours` hours for a given project.
 * Returns empty array if file missing or unreadable.
 */
export async function readRecentAutopilotAlerts(projectId, hours = 24) {
    const path = logPath(projectId);
    const entries = await readEntries(path);
    const cutoff = Date.now() - hours * 60 * 60 * 1000;
    return entries.filter((e) => new Date(e.timestamp).getTime() >= cutoff);
}
//# sourceMappingURL=autopilot-log-store.js.map