// engine/agent-squad/dispatcher.ts — SPEC-551: Dispatch specialist agents on autopilot events
import { readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { resolveAgents } from '../agent-router.js';
import { appendSquadRun, getSquadConfig } from '../../storage/agent-squad-store.js';
const CONFIG_DIR = join(dirname(fileURLToPath(import.meta.url)), '../../config');
async function loadRegistry() {
    try {
        const raw = await readFile(join(CONFIG_DIR, 'agent-registry.json'), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return [];
    }
}
function applyOverrides(registry, overrides) {
    if (overrides.length === 0) {
        return registry;
    }
    return registry.map((entry) => {
        const override = overrides.find((o) => o.agentId === entry.id);
        return override ? { ...entry, enabled: override.enabled } : entry;
    });
}
export async function dispatchSquadForPhase(ctx, phase) {
    const [registry, config] = await Promise.all([loadRegistry(), getSquadConfig(ctx.projectId)]);
    const effective = applyOverrides(registry, config.overrides);
    const plans = resolveAgents({ tags: ctx.specTags, type: ctx.specType, scope: ctx.specScope }, effective, phase);
    // Record each dispatched agent as a run (fire-and-forget persistence)
    const now = new Date().toISOString();
    for (const plan of plans) {
        const record = {
            agentId: plan.agentId,
            phase: plan.phase,
            model: plan.model,
            verdict: 'skipped',
            summary: `Dispatched for phase ${phase}`,
            triggeredAt: now,
        };
        void appendSquadRun(ctx.projectId, ctx.specId, record).catch((err) => {
            console.error(`[agent-squad] failed to persist run for ${plan.agentId}:`, err);
        });
    }
    return plans;
}
//# sourceMappingURL=dispatcher.js.map