// engine/autopilot/event-bus.ts — SPEC-413: Simple in-memory event bus for autopilot triggers
// SPEC-772: log each emitted event to autopilot-log.jsonl (best-effort, fire-and-forget)
import { appendAutopilotLogEntry } from '../../storage/autopilot-log-store.js';
const handlers = new Map();
export function onAutopilotEvent(name, handler) {
    const existing = handlers.get(name) ?? [];
    existing.push(handler);
    handlers.set(name, existing);
}
export function emitAutopilotEvent(event) {
    // Fire-and-forget: never throw, never await
    const eventHandlers = handlers.get(event.name) ?? [];
    for (const handler of eventHandlers) {
        const handlerStart = Date.now();
        // Execute each handler in its own micro-task to avoid blocking
        Promise.resolve()
            .then(async () => {
            const ret = handler(event);
            if (ret instanceof Promise) {
                await ret;
            }
            // SPEC-772: log pass after successful handler execution
            if (event.projectId) {
                const entry = {
                    specId: event.specId ?? '',
                    hookName: event.name,
                    result: 'pass',
                    timestamp: new Date().toISOString(),
                    durationMs: Date.now() - handlerStart,
                };
                void appendAutopilotLogEntry(event.projectId, entry);
            }
        })
            .catch((err) => {
            /* v8 ignore start */
            const message = err instanceof Error ? err.message : String(err);
            console.error(`[autopilot] handler error for ${event.name}: ${message}`);
            // SPEC-772: log fail when handler throws
            if (event.projectId) {
                const entry = {
                    specId: event.specId ?? '',
                    hookName: event.name,
                    result: 'fail',
                    error: message,
                    timestamp: new Date().toISOString(),
                    durationMs: Date.now() - handlerStart,
                };
                void appendAutopilotLogEntry(event.projectId, entry);
            }
            /* v8 ignore stop */
        });
    }
}
/** Clears all handlers — used in tests */
export function clearAutopilotHandlers() {
    handlers.clear();
}
//# sourceMappingURL=event-bus.js.map