// engine/clarification-gate/gate.ts — SPEC-584: Enforcement middleware
// checkGate blocks a tool call when a pending clarification token exists and
// no clarificationAnswers have been provided.
import { findToken, clearToken } from './token-store.js';
import { buildGateError } from './error-builder.js';
/**
 * Check whether the tool is allowed to proceed.
 *
 * Flow:
 *  - No pending token → allow.
 *  - Pending token + answers provided → clear token, allow.
 *  - Pending token + no answers → block with isError mandate.
 *
 * Fails open: if token storage is unavailable, the gate allows the call
 * to proceed rather than blocking the entire tool.
 */
export async function checkGate(ctx) {
    let token;
    try {
        token = await findToken(ctx.projectId, ctx.toolName, ctx.specId);
    }
    catch {
        // Storage unavailable — fail open so the tool is not blocked
        return { allow: true };
    }
    if (!token) {
        return { allow: true };
    }
    const hasAnswers = ctx.clarificationAnswers !== undefined && Object.keys(ctx.clarificationAnswers).length > 0;
    if (hasAnswers) {
        try {
            await clearToken(ctx.projectId, ctx.toolName, ctx.specId);
        }
        catch {
            /* best-effort — token may have already expired */
        }
        return { allow: true };
    }
    return { allow: false, error: buildGateError(token) };
}
//# sourceMappingURL=gate.js.map