// engine/autopilot/crash-shield-rate-limiter.ts — SPEC-628: Rate-limit crash scans to max once per 6h per project
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { hashProjectPath, projectDataDir } from '../../storage/base-store.js';
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
function stateFilePath(projectPath) {
    const projectId = hashProjectPath(projectPath);
    return join(projectDataDir(projectId), 'crash-shield-state.json');
}
/**
 * Returns { skip: true, reason } if a crash scan was recorded within maxAgeMs.
 * Returns { skip: false } on first run or when the window has expired.
 */
export async function shouldSkipCrashScan(projectPath, maxAgeMs = SIX_HOURS_MS) {
    try {
        const raw = await readFile(stateFilePath(projectPath), 'utf-8');
        const state = JSON.parse(raw);
        const elapsed = Date.now() - new Date(state.lastRunAt).getTime();
        if (elapsed < maxAgeMs) {
            const hoursAgo = Math.round(elapsed / (60 * 60 * 1000));
            return { skip: true, reason: `ran ${String(hoursAgo)}h ago` };
        }
    }
    catch {
        // No state file yet — first run
    }
    return { skip: false };
}
/** Persist the timestamp of the latest completed crash scan. */
export async function recordCrashScanRun(projectPath) {
    const filePath = stateFilePath(projectPath);
    await mkdir(dirname(filePath), { recursive: true });
    await writeFile(filePath, JSON.stringify({ lastRunAt: new Date().toISOString() }, null, 2), 'utf-8');
}
//# sourceMappingURL=crash-shield-rate-limiter.js.map