// engine/session-safeguard/session-context-freshness.ts — SPEC-585: Detect stale session-context.md
import { stat } from 'node:fs/promises';
import { join } from 'node:path';
const MS_PER_DAY = 86_400_000;
const STALE_THRESHOLD_DAYS = 1;
/** Find the mtime of the newest spec.md under planu/specs/. */
async function newestSpecMtime(projectPath) {
    try {
        const { glob } = await import('glob');
        const specFiles = await glob('planu/specs/**/spec.md', {
            cwd: projectPath,
            absolute: true,
        });
        if (specFiles.length === 0) {
            return null;
        }
        let newest = null;
        for (const file of specFiles) {
            try {
                const s = await stat(file);
                if (newest === null || s.mtime > newest) {
                    newest = s.mtime;
                }
            }
            catch {
                /* skip unreadable */
            }
        }
        return newest;
    }
    catch {
        return null;
    }
}
/**
 * Check whether session-context.md is stale relative to the newest spec.md.
 * Stale = session-context.md mtime is > 1 day older than newest spec.md.
 */
export async function checkSessionContextFreshness(projectPath) {
    const sessionContextPath = join(projectPath, 'planu', 'session-context.md');
    let sessionMtime = null;
    try {
        const s = await stat(sessionContextPath);
        sessionMtime = s.mtime;
    }
    catch {
        /* file missing */
    }
    const specMtime = await newestSpecMtime(projectPath);
    if (sessionMtime === null) {
        // session-context.md missing → always stale
        return { stale: true, ageDays: Infinity };
    }
    if (specMtime === null) {
        // No specs found → consider fresh
        return { stale: false, ageDays: 0 };
    }
    const ageDays = (specMtime.getTime() - sessionMtime.getTime()) / MS_PER_DAY;
    return { stale: ageDays > STALE_THRESHOLD_DAYS, ageDays: Math.round(ageDays * 10) / 10 };
}
//# sourceMappingURL=session-context-freshness.js.map