Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

7.1 KB
Raw Blame
// GET/POST /api/cron/reconcile-decisions — resolve open ledger predictions
// against real on-chain outcomes, then anchor each agent's chain head.
//
// The Reasoning Ledger captures a snipe as a tamper-evident DECISION at entry
// time (workers/agent-sniper/executor.js → recordDecision). This cron closes the
// loop: when the linked position settles on-chain (agent_sniper_positions.status =
// 'closed', realized P&L proven by the sell signature), it writes the OUTCOME —
// was the call right, and by how much. Idempotent: a decision already reconciled
// is skipped, so re-runs over late/again data never double-count.
//
// After reconciling, it commits each agent's new chain head on-chain via an
// SPL-Memo anchor (best-effort), making the history independently verifiable at
// GET /api/ledger/verify/:agentId. Anomalies (a sudden hit-rate collapse) raise an
// ops alert.

import { json, method, wrapCron } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { sendOpsAlert } from '../_lib/alerts.js';
import { recordOutcome, linkOutcomeToMemories, computeReputation, getReputationRecords } from '../_lib/reasoning-ledger.js';
import { anchorLedgerHead, latestAnchoredAnchor } from '../_lib/ledger-anchor.js';
import { requireCron } from '../_lib/cron-auth.js';
import { solPriceUsd } from '../_lib/sol-price.js';

const LAMPORTS_PER_SOL = 1e9;
const MAX_RECONCILE = 1000;   // decisions resolved per run
const MAX_ANCHOR_AGENTS = 25; // agents whose head is committed on-chain per run
const ANOMALY_MIN_SAMPLE = 10;
const ANOMALY_HIT_RATE = 0.25;

export default wrapCron(async (req, res) => {
	if (!method(req, res, ['GET', 'POST'])) return;
	if (!requireCron(req, res)) return;

	const report = { reconciled: 0, wins: 0, losses: 0, anchored: 0, anchor_pending: 0, anchor_failed: 0, anchor_skipped: 0, anomalies: 0, errors: 0 };
	const touchedAgents = new Set();

	// 1. Reconcile snipe decisions whose position has settled on-chain.
	let pending = [];
	try {
		pending = await sql`
			select d.id as decision_id, d.agent_id,
			       p.realized_pnl_lamports, p.realized_pnl_pct, p.sell_sig, p.exit_reason, p.closed_at, p.opened_at
			from agent_decisions d
			join agent_sniper_positions p on p.id = (d.inputs->>'position_id')::uuid
			left join decision_outcomes o on o.decision_id = d.id
			where d.kind = 'snipe' and o.decision_id is null and p.status = 'closed'
			order by p.closed_at asc
			limit ${MAX_RECONCILE}
		`;
	} catch (err) {
		report.errors++;
		report.reconcile_error = err.message;
	}

	// 0 means the price feed has never resolved: outcomes are then stored unpriced
	// (win/loss only) rather than valued with a guess.
	const solUsd = pending.length ? await solPriceUsd().catch(() => 0) : 0;

	for (const row of pending) {
		try {
			const pnlLamports = BigInt(row.realized_pnl_lamports ?? 0);
			const pnlSol = Number(pnlLamports) / LAMPORTS_PER_SOL;
			const wasCorrect = pnlLamports > 0n;
			const out = await recordOutcome({
				decisionId: row.decision_id,
				agentId: row.agent_id,
				observed: {
					pnl_sol: Number(pnlSol.toFixed(6)),
					pnl_pct: row.realized_pnl_pct != null ? Number(row.realized_pnl_pct) : null,
					sell_sig: row.sell_sig && row.sell_sig !== 'SIMULATED' ? row.sell_sig : null,
					exit_reason: row.exit_reason || null,
					closed_at: row.closed_at,
				},
				wasCorrect,
				pnlSol: Number(pnlSol.toFixed(6)),
				impact: Number(pnlSol.toFixed(6)),
			});
			if (out.reconciled) {
				report.reconciled++;
				report[wasCorrect ? 'wins' : 'losses']++;
				touchedAgents.add(row.agent_id);
			}
			// Stamp the realized result onto every memory recalled into this decision.
			// Independent of `out.reconciled` so a link that failed last run is retried.
			const heldMs = row.opened_at && row.closed_at ? new Date(row.closed_at) - new Date(row.opened_at) : null;
			const linked = await linkOutcomeToMemories({
				decisionId: row.decision_id,
				agentId: row.agent_id,
				pnlUsd: solUsd > 0 ? Number((pnlSol * solUsd).toFixed(2)) : null,
				win: wasCorrect,
				holdSeconds: heldMs != null && Number.isFinite(heldMs) ? Math.max(0, Math.round(heldMs / 1000)) : null,
				closedAt: row.closed_at,
			});
			report.memories_linked = (report.memories_linked || 0) + linked.linked;
		} catch {
			report.errors++;
		}
	}

	// 2. Anchor each agent whose chain head moved past its last on-chain commitment.
	let heads = [];
	try {
		heads = await sql`
			select agent_id, max(seq) as head_seq, count(*)::bigint as cnt
			from agent_decisions group by agent_id
		`;
	} catch (err) {
		report.errors++;
		report.heads_error = err.message;
	}

	// A broadcast rejection is never agent-specific: an unfunded or unusable
	// attester wallet fails identically for every head in the run. Stop after the
	// first one instead of re-simulating the same doomed memo for each remaining
	// agent (twelve wasted RPC round-trips and twelve rewritten rows, every ten
	// minutes), report what was skipped, and alert once so the outage is visible.
	let anchoredCount = 0;
	let anchorOutage = null;
	for (const h of heads) {
		if (anchoredCount >= MAX_ANCHOR_AGENTS) break;
		if (anchorOutage) { report.anchor_skipped++; continue; }
		try {
			const anchor = await latestAnchoredAnchor(h.agent_id);
			if (anchor && Number(anchor.through_seq) >= Number(h.head_seq)) continue; // already committed
			const [head] = await sql`
				select entry_hash, network from agent_decisions
				where agent_id = ${h.agent_id} and seq = ${Number(h.head_seq)} limit 1
			`;
			if (!head) continue;
			anchoredCount++;
			const r = await anchorLedgerHead({
				agentId: h.agent_id,
				network: head.network || 'mainnet',
				headHash: head.entry_hash,
				throughSeq: Number(h.head_seq),
				entryCount: Number(h.cnt),
			});
			if (r.status === 'anchored' || r.status === 'deduped') report.anchored++;
			else if (r.status === 'failed') {
				report.anchor_failed++;
				anchorOutage = r.detail || 'anchor broadcast rejected';
			} else report.anchor_pending++;
		} catch {
			report.errors++;
		}
	}

	if (anchorOutage) {
		report.anchor_outage = String(anchorOutage).slice(0, 280);
		sendOpsAlert(
			'Reasoning ledger: on-chain anchoring is down',
			`Ledger head anchoring was rejected on-chain and ${report.anchor_skipped} further agent(s) were skipped this run. ` +
			`Chain hashes stay tamper-evident, but no head is reaching Solana. Reason: ${report.anchor_outage}`,
			{ signature: 'ledger-anchor-broadcast-failed' },
		);
	}

	// 3. Anomaly watch: a verified track record that suddenly collapses is worth
	//    surfacing — it can mean a broken strategy or market regime change.
	for (const agentId of touchedAgents) {
		try {
			const records = await getReputationRecords(agentId);
			const rep = computeReputation(records);
			if (rep.sample_size >= ANOMALY_MIN_SAMPLE && rep.hit_rate < ANOMALY_HIT_RATE) {
				report.anomalies++;
				sendOpsAlert(
					'Reasoning ledger: hit-rate collapse',
					`Agent ${agentId} hit rate ${(rep.hit_rate * 100).toFixed(0)}% over ${rep.sample_size} reconciled calls (score ${rep.score}).`,
					{ signature: `ledger-anomaly:${agentId}` },
				);
			}
		} catch {
			report.errors++;
		}
	}

	return json(res, 200, { ok: true, ...report, t: Date.now() });
});