// Combines normalized check results with the firm's policy into one decision.
import { worst } from './checks.js';
export function decide(input, checks, policy) {
let verdict = 'ok';
const reasons = [];
const add = (v, why) => { verdict = worst(verdict, v); if (why) reasons.push(why); };
for (const c of checks) {
if (c.outcome === 'skipped') continue;
if (c.outcome !== 'ok') add(c.outcome, null);
for (const r of c.reasons) reasons.push(r);
}
const addr = String(input.payTo || '').toLowerCase();
if ((policy.denylist || []).map((a) => String(a).toLowerCase()).includes(addr)) add('block', 'payTo is on the firm denylist');
const sanc = checks.find((c) => c.check === 'sanctions');
if (sanc && sanc.outcome === 'block' && policy.sanctions?.on_match) add(policy.sanctions.on_match, null);
const amt = Number(input.amount_usd);
const ag = policy.agent_identity || {};
const idc = checks.find((c) => c.check === 'agent_identity');
if (Number.isFinite(amt) && ag.require_verified_above_usd != null && amt > ag.require_verified_above_usd) {
if (!input.agentId) add(ag.unverified_above_threshold || 'block', `Amount $${amt} is above $${ag.require_verified_above_usd}; policy requires a verified paying agent but no agentId was given`);
else if (idc && !(idc.found && idc.active && idc.verified)) add(ag.unverified_above_threshold || 'block', `Amount $${amt} is above $${ag.require_verified_above_usd}; paying agent is not verified`);
}
if (Number.isFinite(amt) && policy.amount?.manual_review_above_usd != null && amt > policy.amount.manual_review_above_usd) {
add('caution', `Amount $${amt} is above the manual-review threshold of $${policy.amount.manual_review_above_usd}`);
}
// Hard invariant (not configurable): a required check that failed or is missing can never yield ok.
for (const req of ['counterparty', 'sanctions']) {
const c = checks.find((x) => x.check === req);
if (!c) add('caution', `Required check "${req}" did not run`);
}
const sources_failed = [...new Set(checks.flatMap((c) => c.sources_failed || []))];
if (sources_failed.length && verdict === 'ok') add('caution', 'One or more upstream sources failed');
const retryable = checks.some((c) => c.retryable);
const action = verdict === 'ok' ? 'proceed' : verdict === 'caution' ? (retryable ? 'hold: retry later or send to human review' : 'hold: send to human review') : (retryable ? 'do_not_pay (provisional: some checks were incomplete; re-screen later)' : 'do_not_pay');
return { verdict, action, retryable, reasons: [...new Set(reasons)], sources_failed };
}
agentgate-source: code mirror on Cloudflare Pages. All repos