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.

feat: generalized money-safety monitoring — all-wallet leak scan, enabled-but-silent tripwire, unified health board

nrpo8cbcc46d3dfd
diff --git a/api/_lib/financial-tripwire.js b/api/_lib/financial-tripwire.js
new file mode 100644
index 000000000..bdcac9dcb
--- /dev/null
+++ b/api/_lib/financial-tripwire.js
@@ -0,0 +1,92 @@
+// Generalized "enabled but silent" tripwire.
+//
+// The original x402 ring outage went unnoticed for days because a money loop was
+// configured-active yet producing zero volume and NOTHING alarmed on the silence.
+// The ring now has a dedicated tripwire (ring-reconciliation.js); this generalizes
+// the pattern so ANY money subsystem can declare "if I'm enabled and I've been
+// silent past my window, page ops". Pure decision + a thin DB/alert wrapper.
+
+import { sql } from './db.js';
+import { sendOpsAlert } from './alerts.js';
+
+/**
+ * Pure: is a subsystem enabled-but-silent right now?
+ *
+ * @param {{ configured: boolean, lastActivityMs: number|null, windowMs: number, now: number }} p
+ * @returns {{ silent: boolean, ageMinutes: number|null }}
+ */
+export function evaluateTripwire({ configured, lastActivityMs, windowMs, now }) {
+ if (!configured) return { silent: false, ageMinutes: null };
+ if (lastActivityMs == null) {
+ // Configured but has NEVER produced activity — that is the strongest silent
+ // signal, not an exemption.
+ return { silent: true, ageMinutes: null };
+ }
+ const ageMs = Math.max(0, now - lastActivityMs);
+ return { silent: ageMs >= windowMs, ageMinutes: Math.round(ageMs / 60_000) };
+}
+
+/**
+ * Run a tripwire and, when silent, write a WARN verdict + page ops (throttled by
+ * sendOpsAlert's per-signature 1/hour dedup). Never throws into a caller.
+ *
+ * @param {object} p
+ * @param {string} p.subsystem short id, e.g. 'launcher' | 'buyback'
+ * @param {boolean} p.configured is the subsystem armed/enabled?
+ * @param {number|null} p.lastActivityMs epoch ms of the last real activity, or null
+ * @param {number} [p.windowMinutes] silence threshold (default 60)
+ * @param {number} p.now epoch ms (pass explicitly; the cron clock)
+ * @param {string} [p.runId]
+ * @returns {Promise<{ silent: boolean, ageMinutes: number|null }>}
+ */
+export async function runTripwire({ subsystem, configured, lastActivityMs, windowMinutes = 60, now, runId = null }) {
+ const windowMs = Math.max(1, windowMinutes) * 60_000;
+ const verdict = evaluateTripwire({ configured, lastActivityMs, windowMs, now });
+ try {
+ if (verdict.silent) {
+ await upsertTripwireVerdict({
+ subsystem, reconciled: false, runId,
+ detail: `${subsystem} is enabled but has produced no activity ${verdict.ageMinutes == null ? 'ever' : `in ${verdict.ageMinutes} min`} (window ${windowMinutes} min).`,
+ });
+ await sendOpsAlert(
+ `🔕 ${subsystem} enabled but SILENT`,
+ `The ${subsystem} money loop is configured active but has been silent ${verdict.ageMinutes == null ? '(no activity on record)' : `for ~${verdict.ageMinutes} min`}. Something may have quietly stopped — investigate before it goes unnoticed for days.`,
+ { signature: `tripwire-silent:${subsystem}` },
+ );
+ } else if (configured) {
+ // Self-heal: clear a prior silent verdict once activity resumes.
+ await upsertTripwireVerdict({ subsystem, reconciled: true, runId, detail: `${subsystem} active (last activity ${verdict.ageMinutes ?? 0} min ago).` });
+ }
+ } catch (err) {
+ console.warn('[tripwire] write failed', { subsystem, message: err?.message });
+ }
+ return verdict;
+}
+
+async function upsertTripwireVerdict({ subsystem, reconciled, runId, detail }) {
+ await sql`
+ INSERT INTO payment_reconciliation
+ (source, source_ref, tx_signature, network, amount_atomic,
+ db_status, chain_status, reconciled, discrepancy, detail, run_id, checked_at)
+ VALUES
+ ('financial_tripwire', ${`silent:${subsystem}`}, null, 'mainnet', null,
+ 'enabled', ${reconciled ? 'active' : 'silent'}, ${reconciled},
+ ${reconciled ? null : detail}, ${JSON.stringify({ subsystem })}, ${runId}, now())
+ ON CONFLICT (source, source_ref) DO UPDATE SET
+ db_status = EXCLUDED.db_status, chain_status = EXCLUDED.chain_status,
+ reconciled = EXCLUDED.reconciled, discrepancy = EXCLUDED.discrepancy,
+ detail = EXCLUDED.detail, run_id = EXCLUDED.run_id, checked_at = now()
+ `;
+}
+
+/** Last-activity epoch ms from a table's newest timestamp column, or null. */
+export async function lastActivityMs(table, tsColumn = 'created_at') {
+ try {
+ // table/column are internal literals, never user input.
+ const rows = await sql.query(`SELECT extract(epoch from max(${tsColumn})) * 1000 AS ms FROM ${table}`);
+ const ms = rows?.[0]?.ms;
+ return ms != null ? Number(ms) : null;
+ } catch {
+ return null; // table absent / empty → treat as no activity on record
+ }
+}
diff --git a/api/cron/wallets-leak-scan.js b/api/cron/wallets-leak-scan.js
index 360b15fca..7bc9350f2 100644
--- a/api/cron/wallets-leak-scan.js
+++ b/api/cron/wallets-leak-scan.js
@@ -23,6 +23,7 @@ import { sendOpsAlert } from '../_lib/alerts.js';
import { SOLANA_SIGNERS, resolveSignerPubkey } from '../_lib/solana-signers.js';
import { ringAllowedAddresses } from '../_lib/x402/ring-allowlist.js';
import { classifyWalletDebits } from './x402-ring-leak-scan.js';
+import { runTripwire, lastActivityMs } from '../_lib/financial-tripwire.js';
const SIG_LIMIT = 100;
const CANONICAL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
@@ -206,5 +207,17 @@ export default wrapCron(async (req, res) => {
perWallet.push({ name, wallet: pubkey, scanned: r.scannedDelta, leaks: r.leaksDelta, error: !!r.error });
}
- return json(res, 200, { ok: true, run_id: runId, wallets: wallets.length, scanned, leaks, rpc_errors: errors, per_wallet: perWallet });
+ // Zero-activity tripwire for the always-active x402 autonomous loop — the same
+ // "enabled but silent" alarm that was missing when the ring quietly died. The
+ // ring's own settle-silence is covered by ring-reconciliation; this covers the
+ // loop that DRIVES it (pipelines + tick), which should never be idle when on.
+ const now = Date.now();
+ const autoConfigured = String(env.X402_AUTONOMOUS_ENABLED ?? '').toLowerCase() !== 'false';
+ const autoLast = await lastActivityMs('x402_autonomous_log', 'created_at');
+ const tripwire = await runTripwire({
+ subsystem: 'x402_autonomous_loop', configured: autoConfigured,
+ lastActivityMs: autoLast, windowMinutes: 60, now, runId,
+ });
+
+ return json(res, 200, { ok: true, run_id: runId, wallets: wallets.length, scanned, leaks, rpc_errors: errors, per_wallet: perWallet, tripwire });
});
diff --git a/api/ops/money-health.js b/api/ops/money-health.js
new file mode 100644
index 000000000..087859b40
--- /dev/null
+++ b/api/ops/money-health.js
@@ -0,0 +1,93 @@
+// GET /api/ops/money-health — ONE board for every money subsystem's health.
+//
+// Financial monitoring was fragmented across /admin/ring (ring-only), raw
+// payment_reconciliation queries, and per-wallet balance logs — so "is the whole
+// money system healthy right now?" had no single answer. This composes it: per
+// subsystem, its open CRITICAL/WARN verdicts and last-activity, plus the leak-scan
+// and tripwire state. Admin-authed, read-only, one aggregate query set (no N+1).
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { env } from '../_lib/env.js';
+
+// Admin gate: CRON_SECRET bearer OR the admin token, matching api/admin/*.
+function isAdmin(req) {
+ const auth = req.headers['authorization'] || '';
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ const admin = process.env.ADMIN_TOKEN || env.ADMIN_TOKEN;
+ const presented = bearer || req.headers['x-admin-token'] || '';
+ if (secret && constantTimeEquals(presented, secret)) return true;
+ if (admin && constantTimeEquals(presented, admin)) return true;
+ return false;
+}
+
+// The verdict sources each money subsystem writes into payment_reconciliation.
+const SUBSYSTEMS = [
+ { key: 'economy_master', label: 'Economy master (funding root)', sources: ['economy_master_chain', 'economy_master_onchain', 'economy_master_ledger'], activity: { table: 'economy_master_ledger', ts: 'ts' } },
+ { key: 'x402_ring', label: 'x402 ring economy', sources: ['ring_facilitator_settle', 'ring_ledger_sweep', 'ring_log_coherence', 'ring_fee_coherence', 'ring_tripwire', 'x402_ring_onchain'], activity: { table: 'x402_self_facilitator_log', ts: 'created_at' } },
+ { key: 'x402_revenue', label: 'x402 revenue', sources: ['autonomous_log', 'payment_intent'], activity: { table: 'x402_autonomous_log', ts: 'created_at' } },
+ { key: 'all_wallets', label: 'All controlled wallets (leak scan)', sources: ['wallets_onchain'], activity: null },
+ { key: 'tripwires', label: 'Enabled-but-silent tripwires', sources: ['financial_tripwire'], activity: null },
+];
+
+async function lastActivity(table, ts) {
+ if (!table) return null;
+ try {
+ const rows = await sql.query(`SELECT extract(epoch from max(${ts})) * 1000 AS ms FROM ${table}`);
+ return rows?.[0]?.ms != null ? Number(rows[0].ms) : null;
+ } catch { return null; }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+ if (!isAdmin(req)) return error(res, 401, 'unauthorized', 'admin token required');
+
+ // One grouped query for all open (unreconciled) verdicts by source + severity.
+ let verdictRows = [];
+ try {
+ verdictRows = await sql`
+ SELECT source,
+ count(*) FILTER (WHERE db_status IN ('onchain_leak','delegation_risk')
+ OR chain_status ILIKE '%missing%' OR chain_status ILIKE '%mismatch%'
+ OR chain_status ILIKE '%failed%') AS critical,
+ count(*) AS open_total,
+ max(checked_at) AS last_checked
+ FROM payment_reconciliation
+ WHERE reconciled = false
+ GROUP BY source
+ `;
+ } catch (err) {
+ if (!/relation .*payment_reconciliation.* does not exist/i.test(err?.message || '')) throw err;
+ }
+ const bySource = new Map(verdictRows.map((r) => [r.source, r]));
+
+ const now = Date.now();
+ const subsystems = [];
+ for (const s of SUBSYSTEMS) {
+ let critical = 0, open = 0, lastChecked = null;
+ for (const src of s.sources) {
+ const r = bySource.get(src);
+ if (!r) continue;
+ critical += Number(r.critical || 0);
+ open += Number(r.open_total || 0);
+ if (r.last_checked && (!lastChecked || r.last_checked > lastChecked)) lastChecked = r.last_checked;
+ }
+ const actMs = await lastActivity(s.activity?.table, s.activity?.ts);
+ subsystems.push({
+ key: s.key, label: s.label,
+ open_critical: critical, open_warn: Math.max(0, open - critical),
+ last_activity_at: actMs ? new Date(actMs).toISOString() : null,
+ minutes_since_activity: actMs ? Math.round((now - actMs) / 60_000) : null,
+ last_checked_at: lastChecked,
+ status: critical > 0 ? 'critical' : open > 0 ? 'warn' : 'ok',
+ });
+ }
+
+ const overall = subsystems.some((s) => s.status === 'critical') ? 'critical'
+ : subsystems.some((s) => s.status === 'warn') ? 'warn' : 'ok';
+
+ return json(res, 200, { ok: true, overall, subsystems, generated_at: new Date(now).toISOString() });
+});
diff --git a/docs/money-map.md b/docs/money-map.md
index 8849fe967..7cd3ebe20 100644
--- a/docs/money-map.md
+++ b/docs/money-map.md
@@ -153,6 +153,26 @@ recurring payout crons that forward the flows above:
---
+## Monitoring coverage
+
+Every wallet that moves money is watched on-chain, and every always-active loop is
+watched for silence. One board rolls it all up.
+
+| Layer | What it watches | Where |
+|---|---|---|
+| **All-wallet leak scan** | Every mainnet `SOLANA_SIGNERS` wallet (masters, all treasuries, ring wallets) — any SOL/token debit to an address outside the controlled set, or an SPL Approve | `api/cron/wallets-leak-scan.js` (`*/15`), verdict source `wallets_onchain` |
+| **Ring leak scan** | The x402 ring role wallets specifically | `api/cron/x402-ring-leak-scan.js` (`*/10`), source `x402_ring_onchain` |
+| **Economy-master breach/tamper** | Unrecorded outbound + hash-chain integrity of the funding root | `api/cron/economy-reconcile.js` (`*/30`) |
+| **Zero-activity tripwire** | Enabled-but-silent money loops (the alarm the ring outage lacked) | `api/_lib/financial-tripwire.js`, wired for `x402_autonomous_loop` in the leak-scan cron |
+| **Reconciliation** | Ring settlements/sweeps + revenue vs chain | `ring-reconciliation.js`, `revenue-reconciliation.js` |
+| **Unified board** | Per-subsystem open critical/warn verdicts + last activity, one call | `GET /api/ops/money-health` (admin) |
+
+Guardrails on outflow: the economy master is funder-only with reserve/per-transfer/
+per-run caps and a registry allowlist; the ring can only settle to allowlisted
+wallets (anti-drain gate); the sniper auto-funder moves money only for strategies
+that set `auto_fund_enabled = true` (default off). See
+[financial-controls.md](financial-controls.md) for the full register.
+
## Related
- [Financial controls & audit register](financial-controls.md) — every ledger's integrity, reconciliation, retention, monitoring, and the ranked gap list.
diff --git a/tests/financial-tripwire.test.js b/tests/financial-tripwire.test.js
new file mode 100644
index 000000000..743202d1c
--- /dev/null
+++ b/tests/financial-tripwire.test.js
@@ -0,0 +1,41 @@
+import { describe, it, expect } from 'vitest';
+import { evaluateTripwire } from '../api/_lib/financial-tripwire.js';
+
+// The alarm that was missing when the ring quietly died: a money loop that is
+// configured-active but has gone silent past its window must be flagged.
+
+const WINDOW = 60 * 60_000; // 60 min
+const NOW = 1_000_000_000_000;
+
+describe('evaluateTripwire', () => {
+ it('is not silent when the subsystem is disabled (no false alarms)', () => {
+ expect(evaluateTripwire({ configured: false, lastActivityMs: null, windowMs: WINDOW, now: NOW }))
+ .toEqual({ silent: false, ageMinutes: null });
+ });
+
+ it('is SILENT when configured but never active (strongest signal)', () => {
+ expect(evaluateTripwire({ configured: true, lastActivityMs: null, windowMs: WINDOW, now: NOW }))
+ .toEqual({ silent: true, ageMinutes: null });
+ });
+
+ it('is not silent when activity is within the window', () => {
+ const v = evaluateTripwire({ configured: true, lastActivityMs: NOW - 10 * 60_000, windowMs: WINDOW, now: NOW });
+ expect(v.silent).toBe(false);
+ expect(v.ageMinutes).toBe(10);
+ });
+
+ it('is SILENT when activity is older than the window', () => {
+ const v = evaluateTripwire({ configured: true, lastActivityMs: NOW - 90 * 60_000, windowMs: WINDOW, now: NOW });
+ expect(v.silent).toBe(true);
+ expect(v.ageMinutes).toBe(90);
+ });
+
+ it('fires exactly at the window boundary', () => {
+ expect(evaluateTripwire({ configured: true, lastActivityMs: NOW - WINDOW, windowMs: WINDOW, now: NOW }).silent).toBe(true);
+ });
+
+ it('clamps a future timestamp to age 0 (not silent)', () => {
+ const v = evaluateTripwire({ configured: true, lastActivityMs: NOW + 5000, windowMs: WINDOW, now: NOW });
+ expect(v).toEqual({ silent: false, ageMinutes: 0 });
+ });
+});