-
-
DRAFT state on page load — formal 6-state FSM lifecycle visualized at top...
-
System architecture — Next.js 16 frontend orchestrating...
-
Formal 6-state Finite State Machine governing contract lifecycle...
-
Autonomous Audit Trail — color-coded chronological ledger...
-
Reasoning Memorandum of Arbitration (RMA) — Gemini Flash-Lite's structured verdict...
-
27/27 automated assertions passing across 5 suites..
💡 Inspiration
Over $2 billion is lost annually to freelance, agency, and B2B milestone disputes. Traditional escrow has two systemic flaws:
- Custodial honeypots. Platforms pool client funds into omnibus bank accounts — regulatory overhead and counterparty risk.
- The 3-week deadlock. When a deliverable is defective, human dispute queues freeze accounts for 14–21 days, halting project momentum.
We asked: what if the arbitrator was an AI agent operating directly on PayPal's authorization rails, issuing refunds and captures autonomously with a verifiable audit trail?
TrustLoop AI is a reference implementation of agentic commerce applied to escrow. Autonomous AI agents operate a PayPal-backed escrow ledger with mathematically provable invariants, zero platform custody during adjudication, and a live audit trail judges can watch in real time.
🚀 What It Does
TrustLoop coordinates the full lifecycle of milestone-based commercial agreements through an autonomous agent operating on PayPal's native rails:
- 🤖 Agentic Arbitration. Google Gemini Flash-Lite evaluates deliverables against schema-validated milestone criteria and autonomously triggers PayPal capture, refund, or void — zero human in the loop.
- 💳 Non-Custodial Hold via
intent=AUTHORIZE. The buyer authorizes the full contract amount via PayPal Sandbox. Funds remain in the buyer's PayPal account during adjudication; TrustLoop takes custody only at the moment of explicit milestone capture. - 🧮 Zero-Drift Financial Invariant. Every state transition provably maintains the core identity, surfaced live in the UI:
$$\text{Authorized Hold} = \text{Disbursed} + \text{Refunded} + \text{Voided} + \text{Remaining in Vault}$$
- 📜 Live Autonomous Audit Trail. Every FSM transition, every RMA, every PayPal API call streams into a persistent event ledger timeline judges can watch in real time.
- 🏷️ Domain-Aware Contract Archetyping. Turnkey contracts (interdependent hardware) trigger cascading clawback on default; Modular contracts (independent sprints) preserve captured milestones. One LLM classifier picks the archetype from a plain-English brief.
- 🔁 FSM Remedy Arc. If a deliverable is refunded, contractors can resubmit improved proof. Upon AI re-approval, the UI re-opens the milestone for capture within the authorization's remaining headroom.
- 🛡️ Prompt-Injection Hardened. Every deliverable submission passes a regex-based injection-pattern filter + length bounds + schema validator + RMA fallback before reaching the arbitrator.
🛠️ How We Built It
PayPal Integration — Full Orders v2 Authorization Lifecycle
Built against the official PayPal v2 Checkout and Payments APIs, not just checkout:
| Endpoint | TrustLoop usage |
|---|---|
POST /v2/checkout/orders with intent=AUTHORIZE |
Non-custodial fund lock |
POST /v2/checkout/orders/{id}/authorize |
PayPal authorization token issuance |
POST /v2/payments/authorizations/{id}/capture |
Per-milestone staged disbursement |
POST /v2/payments/captures/{id}/refund |
Autonomous dispute refund |
POST /v2/payments/authorizations/{id}/void |
Terminal clawback |
- Every mutation carries a deterministic
PayPal-Request-Ididempotency key, derived from{operation}:{authId}:{milestoneId}, so retry storms and redeploys cannot double-capture. - Asynchronous event sink at
POST /api/paypal/webhookcaptures PayPal callback events into a persistent ledger.
AI Arbitration — Google Gemini Flash-Lite
- Primary model:
gemini-flash-lite-latest— chosen for sub-second parsing latency and low token cost on repetitive arbitration calls. - Resilience fallbacks:
gemini-3.1-flash-lite,gemini-flash-latest. - Structured output: Schema-validated JSON via Gemini's native
responseMimeType: "application/json"+ strictresponseSchemaattemperature: 0.2. - Reasoning Memorandum of Arbitration (RMA): Every refund/release decision mints a machine-signed, exportable reasoning artifact — the AI's work is auditable, not a black box.
- Layered prompt-injection defense: regex pattern bank →
sanitizeUserInput()→ schema validation → RMA fallback on parse failure.
Full-Stack Architecture & Hosting
- Next.js 16 (App Router, React 19, Turbopack, TypeScript, Tailwind CSS).
- Deployed as a production web service on Render at https://trustloop-ai-ck4m.onrender.com/.
- Zero-config deploy, automatic HTTPS, cold-start-resilient architecture.
Quality Assurance
- 27-assertion automated test harness (
test-suite-complete.mjs) runnable vianpm test, covering:- Prompt sanitization (6 assertions)
- Financial invariant rigor (9 assertions, ledger balance verified to < 0.001 tolerance)
- FSM state regressions (6 assertions, including the
COMPLETED_WITH_REFUNDSwedge fix) - Security hygiene (4 assertions, including dev-auth backdoor removal)
- UI audit trail mounting (2 assertions)
🚧 Challenges We Ran Into
The FSM Prerequisite Deadlock. An initial design treated
REFUNDEDas immutable — if an upstream milestone was refunded, all downstream stages were permanently blocked. We restructured the FSM to support an Approved Remedy Arc, allowing freelancers to submit improved deliverables, pass an AI re-evaluation, and transition the milestone back to actionable status.The
PARTIALLY_SETTLEDWedge. A naive FSM wedges forever after the sequence M1 capture → M2 capture → M1 refund → M3 capture (allCapturedFinalis false because M1 is now REFUNDED, not CAPTURED). We introduced aCOMPLETED_WITH_REFUNDSterminal state so every legal transaction history has a defined exit.Idempotency Correctness Under Retries. PayPal's
PayPal-Request-Idmust be stable across client retries but unique across logical operations. We built a deterministic key-derivation function ({operation}:{authId}:{milestoneId}) to guarantee both — preventing double-capture during network hiccups or redeploys.Invariant-Preserving Refunds Across Nested PayPal Payloads. PayPal returns refund amounts as nested currency objects (
{ value: "50.00", currency_code: "USD" }). Naive string coercion producedNaNbugs mid-transaction. We moved every ledger operation through a type-safe cents-integer boundary and now provably balance to the penny across 3-way splits (capture + refund + void coexisting on one authorization).Prompt Injection via Free-Text Deliverable Notes. Buyers and sellers can smuggle instructions into proof fields. We built a layered defense: regex pattern bank → sanitization pass → strict JSON schema validation → RMA fallback on parse failure. Validated by 6 unit tests against known injection vectors.
🏆 Accomplishments We're Proud Of
- Live financial invariant proof — the UI surfaces
Authorized == Disbursed + Refunded + Voided + Remainingon every FSM transition, in real time. A judge can watch the identity hold through complex partial-refund flows. - Live Autonomous Audit Trail panel — every FSM event (initialization, capture, refund, void, RMA artifact) streams into a judge-visible event ledger with timestamps and signed RMA IDs.
- Full PayPal Orders v2 lifecycle coverage — AUTHORIZE, CAPTURE, REFUND, VOID — not just a checkout button. Deployed live against PayPal Sandbox;
POST /api/paypal/create-orderreturns real PayPal order IDs on demand. - 27 genuine test assertions passing via
npm test— security, financial, FSM, and UI invariants all verified pre-submission. - Zero-trust LLM boundary — injection sanitization + schema validation + deterministic fallback make Gemini safe to operate on financial decisions.
- Live production deployment on Render with zero-config CI/CD.
🧠 What We Learned
- State machines are unforgiving in finance. Declarative invariant assertions are far safer than imperative if/else when every path moves real money.
- LLMs are usable in finance if you cage them. Strict schemas, low temperature, sanitized inputs, and deterministic fallbacks turn a stochastic model into a bounded, auditable component.
- "Agentic" is earned, not claimed. An autonomous agent needs a visible audit trail — otherwise it's just a chatbot with API keys. The RMA artifact and Audit Trail panel exist specifically so a human can verify the agent did the right thing after the fact.
- Non-custodial payment orchestration via PayPal authorizations lets platforms coordinate multi-party agreements without taking on money-transmitter custody requirements — a materially better risk posture than omnibus-account escrow.
🔮 What's Next for TrustLoop AI — V2 Roadmap
- Event-Sourced Persistence. PostgreSQL + Prisma with FSM replay streams for perfect state reconstruction across sessions and horizontal scale.
- Cryptographic Webhook Verification. Upgrade the webhook event sink with PayPal certificate extraction and
PAYPAL-TRANSMISSION-SIGHMAC-SHA256 signature verification for production-grade async reconciliation ofPAYMENT.AUTHORIZATION.VOIDEDandCUSTOMER.DISPUTE.CREATEDevents. - Multi-Arbitrator Consensus. N-of-M LLM voting (Gemini Flash-Lite + Claude Sonnet + GPT-4) to remove single-model bias on high-value escrows (>$10,000), supplemented by an escrow-bonded human appeal window.
- Multi-Currency FX-Locked Escrow. Support PayPal's 25+ global settlement currencies (EUR, GBP, JPY, AUD) using spot-rate locking at authorization creation to prevent cross-border FX drift during clawbacks.
- Tiered Partial Payouts. Extend the arbitration schema so Gemini can authorize proportional disbursements (e.g., 70% release on partial milestone delivery) rather than strict binary CAPTURE/REFUND outcomes.
- Signed RMA Export. Court-admissible JSON-LD audit artifacts with cryptographic signatures for formal dispute escalation outside the TrustLoop UI.
Built With
- agentic-ai
- autonomous-agents
- escrow
- finite-state-machine
- gemini-flash-lite
- google-gemini
- json-schema
- next.js
- node.js
- paypal
- paypal-orders-v2
- paypal-sandbox
- prompt-injection-defense
- react
- react-19
- render
- tailwind-css
- typescript