/**
 * 任务上下文 — 任务清理辅助函数
 */
import fs from "node:fs/promises";
import path from "node:path";
import { safeJsonParse } from "../../core/helpers.js";
import { MAX_TASK_AGE_DAYS } from "./constants.js";
/**
 * 清理过期和超量任务: 使用 retention_policy 驱动清理决策。
 */
export async function cleanupStaleTasks(stateDir, dryRun) {
    const { evaluateCleanup, checkForbiddenContent } = await import("../../retention_policy.js");
    const files = await fs.readdir(stateDir);
    const taskFiles = files.filter((f) => f.startsWith("task-") && f.endsWith(".json"));
    const now = Date.now();
    const allForbiddenHits = [];
    const allTasks = [];
    for (const f of taskFiles) {
        try {
            const filePath = path.join(stateDir, f);
            const content = await fs.readFile(filePath, "utf-8");
            const ctx = safeJsonParse(content);
            if (!ctx)
                continue;
            const forbiddenHits = checkForbiddenContent("task_context", content);
            if (forbiddenHits.length > 0) {
                allForbiddenHits.push(`${ctx.task_id ?? f}: ${forbiddenHits.join(", ")}`);
            }
            const createdAt = ctx.created_at ? new Date(ctx.created_at).getTime() : now;
            const stat = await fs.stat(filePath);
            const earliestTime = Math.min(createdAt, stat.mtimeMs);
            const ageDays = Math.max(0, (now - earliestTime) / (24 * 60 * 60 * 1000));
            if (ctx.task_id && ctx.created_at && ctx.status) {
                allTasks.push({ task_id: ctx.task_id, created_at: ctx.created_at, status: ctx.status, file: filePath, age_days: ageDays });
            }
            else if (ageDays > MAX_TASK_AGE_DAYS) {
                allTasks.push({ task_id: f, created_at: "", status: "done", file: filePath, age_days: ageDays });
            }
        }
        catch {
            // 跳过不可读文件
        }
    }
    const records = allTasks.map(t => ({ id: t.task_id, age_days: t.age_days, is_referenced: !["done", "failed"].includes(t.status) }));
    const result = evaluateCleanup("task_context", records, dryRun);
    let removed = 0;
    if (!dryRun && result.cleanup_candidates.length > 0) {
        for (const taskId of result.cleanup_candidates) {
            const task = allTasks.find(t => t.task_id === taskId);
            if (task) {
                try {
                    await fs.unlink(task.file);
                    removed++;
                }
                catch {
                    // 文件已被删除
                }
            }
        }
    }
    return {
        removed: dryRun ? 0 : removed,
        protected: result.protected_records,
        forbidden_content_hits: allForbiddenHits,
        dry_run: result.dry_run,
    };
}
//# sourceMappingURL=cleanup.js.map