"use strict";
// Default Worker Executors — built-in executors for the worker queue.
//
// These executors handle common background tasks without requiring a
// running LLM. They do rule-based processing and can be swapped for
// model-backed versions when an LLM is available.
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_EXECUTORS = void 0;
exports.registerDefaultExecutors = registerDefaultExecutors;
const modeClassifier_1 = require("./modeClassifier");
const commandExtractor_1 = require("./commandExtractor");
const promiseLedger_1 = require("./promiseLedger");
// ─── Classify Task Executor ─────────────────────────────────────────
const classifyTaskExecutor = async (job) => {
    const input = job.input;
    if (!input.message || typeof input.message !== 'string') {
        throw new Error('classify_task requires input.message string.');
    }
    const classification = (0, modeClassifier_1.classifyMode)(input.message);
    return {
        mode: classification.mode,
        confidence: classification.confidence,
        reason: classification.reason,
        matchedPatterns: classification.matchedPatterns,
    };
};
// ─── Extract Tasks Executor ─────────────────────────────────────────
const extractTasksExecutor = async (job) => {
    const input = job.input;
    if (!input.message || typeof input.message !== 'string') {
        throw new Error('extract_tasks requires input.message string.');
    }
    const result = (0, commandExtractor_1.extractCommands)(input.message);
    return {
        commands: result.commands,
        valid: result.valid,
        errors: result.errors,
    };
};
// ─── Validate JSON Executor ─────────────────────────────────────────
const validateJsonExecutor = async (job) => {
    const input = job.input;
    if (!input.json || typeof input.json !== 'string') {
        throw new Error('validate_json requires input.json string.');
    }
    try {
        const parsed = JSON.parse(input.json);
        return { valid: true, parsed };
    }
    catch (err) {
        return { valid: false, error: err instanceof Error ? err.message : String(err) };
    }
};
// ─── Summarise Notes Executor (rule-based, no LLM) ─────────────────
const summariseNotesExecutor = async (job) => {
    const input = job.input;
    if (!Array.isArray(input.notes)) {
        throw new Error('summarise_notes requires input.notes array.');
    }
    const count = input.notes.length;
    const contents = input.notes
        .filter((n) => n.content)
        .map((n) => n.content)
        .slice(0, 20); // Cap to prevent oversized summaries
    return {
        note_count: count,
        summary: contents.length > 0
            ? `${count} note(s). Topics: ${contents.map((c) => c.slice(0, 50)).join('; ')}`
            : `${count} note(s), no content available.`,
    };
};
// ─── Detect Failures Executor ───────────────────────────────────────
const detectFailuresExecutor = async (job) => {
    const input = job.input;
    if (!Array.isArray(input.jobs)) {
        throw new Error('detect_failures requires input.jobs array.');
    }
    const failures = input.jobs.filter((j) => j.status === 'failed');
    const byType = new Map();
    for (const f of failures) {
        const key = f.job_type ?? 'unknown';
        byType.set(key, (byType.get(key) ?? 0) + 1);
    }
    const repeated = Array.from(byType.entries())
        .filter(([, count]) => count >= 2)
        .map(([type, count]) => ({ type, count }));
    return {
        total_failures: failures.length,
        repeated_failures: repeated,
        has_repeated: repeated.length > 0,
    };
};
// ─── Expire Promises Executor ───────────────────────────────────────
const expirePromisesExecutor = async (job) => {
    const input = job.input;
    if (!input.projectDir)
        throw new Error('expire_promises requires input.projectDir.');
    const maxAgeDays = input.maxAgeDays ?? 30;
    const cutoff = new Date(Date.now() - maxAgeDays * 86_400_000);
    const pending = await (0, promiseLedger_1.listPromises)(input.projectDir, { status: 'pending' });
    let expired = 0;
    for (const p of pending) {
        // Expire if no due date and older than maxAgeDays, or if overdue by maxAgeDays.
        const created = new Date(p.created_at);
        const overdue = p.next_due_at ? new Date(p.next_due_at) < cutoff : created < cutoff;
        if (overdue) {
            await (0, promiseLedger_1.updatePromise)(input.projectDir, p.promise_id, { status: 'expired' });
            expired++;
        }
    }
    return { expired, checked: pending.length, maxAgeDays };
};
// ─── Executor registry ──────────────────────────────────────────────
exports.DEFAULT_EXECUTORS = {
    classify_task: classifyTaskExecutor,
    extract_tasks: extractTasksExecutor,
    validate_json: validateJsonExecutor,
    summarise_notes: summariseNotesExecutor,
    detect_failures: detectFailuresExecutor,
    expire_promises: expirePromisesExecutor,
};
/** Register all default executors on a worker queue. */
function registerDefaultExecutors(queue) {
    for (const [jobType, executor] of Object.entries(exports.DEFAULT_EXECUTORS)) {
        queue.registerExecutor(jobType, executor);
    }
}
//# sourceMappingURL=workerExecutors.js.map