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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(cron): refund every payment session the sweep expires, and gate it to the methods it implements
nirholas81cca69be0cd
diff --git a/api/cron/oracle-score.js b/api/cron/oracle-score.jsindex 306f1c022..3323535a5 100644--- a/api/cron/oracle-score.js+++ b/api/cron/oracle-score.js@@ -20,7 +20,6 @@// executor) and a watch is itself armed in live mode.import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { loadConfig } from '../../workers/oracle/config.js';import { runScorePass } from '../../workers/oracle/score-loop.js';import { actOnFreshCoins, freshlyScored } from '../../workers/oracle/agent-loop.js';diff --git a/api/cron/payment-session-sweep.js b/api/cron/payment-session-sweep.jsindex 4e927a521..995aa822c 100644--- a/api/cron/payment-session-sweep.js+++ b/api/cron/payment-session-sweep.js@@ -1,14 +1,14 @@-// GET /api/cron/payment-session-sweep — expire stale sessions and refund budgets.+// GET/POST /api/cron/payment-session-sweep - expire stale sessions and refund budgets.//-// Runs on a schedule (recommended: every 5 minutes). Finds payment sessions whose-// expires_at has passed but are still 'active', marks them 'expired', and refunds-// any un-spent budget back to the creator's credit balance.+// Runs on a schedule (every 5 minutes). Finds payment sessions whose expires_at+// has passed but are still 'active', marks them 'expired', and refunds any+// un-spent budget back to the creator's credit balance.//// Design:-// • Processes up to BATCH_LIMIT sessions per tick — the next tick catches the rest.-// • Refunds are idempotent (ON CONFLICT DO NOTHING on credit_ledger) so retries-// don't double-credit.-// • All rows updated atomically per-session; a crash mid-batch leaves the+// - Claims up to BATCH_LIMIT sessions per tick; the next tick catches the rest.+// - Refunds are idempotent (credit_ledger is keyed on the idempotency key) so+// retries do not double-credit.+// - All rows updated atomically per-session; a crash mid-batch leaves the// remaining sessions to be picked up on the next tick.//// Auth: the shared, fail-closed cron gate (api/_lib/cron-auth.js), same as every@@ -17,7 +17,7 @@import { sql } from '../_lib/db.js';import { creditAccount } from '../_lib/credits.js';import { atomicsToUsd } from '../_lib/pay/spend-governor.js';-import { cors, json, wrapCron } from '../_lib/http.js';+import { cors, json, method, wrapCron } from '../_lib/http.js';import { requireCron } from '../_lib/cron-auth.js';export const maxDuration = 30;@@ -25,24 +25,37 @@ export const maxDuration = 30;const BATCH_LIMIT = Number(process.env.PAYMENT_SESSION_SWEEP_BATCH) || 100;export default wrapCron(async (req, res) => {- cors(req, res, { methods: 'GET,POST,OPTIONS' });- if (req.method?.toUpperCase() === 'OPTIONS') return;+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;if (!requireCron(req, res)) return;const t0 = Date.now();- // UPDATE ... RETURNING all expired sessions atomically. The refund step- // is idempotent (ON CONFLICT DO NOTHING in credit_ledger), so concurrent- // ticks processing the same row are safe. We slice to BATCH_LIMIT in JS- // to keep each tick bounded; the next tick handles any remainder.- const allExpired = await sql`- UPDATE payment_sessions+ // Expire and refund the SAME bounded set. The batch limit lives inside the+ // UPDATE (via a CTE, because Postgres has no LIMIT on UPDATE) rather than in a+ // JS slice of the result. An unbounded UPDATE flips every due session to+ // 'expired' but only the sliced head is ever refunded, and the remainder is+ // then invisible to the next tick, which only looks at status = 'active': the+ // un-spent budget of every session past the limit would be silently kept.+ // Whatever this tick does not claim stays active and is swept next tick.+ //+ // FOR UPDATE SKIP LOCKED keeps concurrent ticks on disjoint rows; the refund+ // is idempotent on `paysess_expire_<id>`, so a retry never double-credits.+ const expiredRows = await sql`+ WITH due AS (+ SELECT id FROM payment_sessions+ WHERE status = 'active'+ AND expires_at < now()+ ORDER BY expires_at ASC+ LIMIT ${BATCH_LIMIT}+ FOR UPDATE SKIP LOCKED+ )+ UPDATE payment_sessions sSET status = 'expired', updated_at = now()- WHERE status = 'active'- AND expires_at < now()- RETURNING id, user_id, budget_usdc, spent_usdc+ FROM due+ WHERE s.id = due.id+ RETURNING s.id, s.user_id, s.budget_usdc, s.spent_usdc`;- const expiredRows = allExpired.slice(0, BATCH_LIMIT);let refunded = 0;let refundErrors = 0;@@ -63,8 +76,12 @@ export default wrapCron(async (req, res) => {idempotencyKey: `paysess_expire_${row.id}`,});refunded++;- } catch {+ } catch (err) {+ // A refund that failed here is not lost: the idempotency key means the+ // repair is a re-credit, but the session row is already 'expired' and no+ // longer selected. Log the id so an operator can replay it.refundErrors++;+ console.error('[payment-session-sweep] refund failed', { sessionId: row.id, error: err?.message || String(err) });}}));@@ -76,7 +93,7 @@ export default wrapCron(async (req, res) => {refund_errors: refundErrors,duration_ms: durationMs,note: expiredRows.length === BATCH_LIMIT- ? `Batch limit (${BATCH_LIMIT}) reached — more sessions may remain. Next tick will continue.`+ ? `Batch limit (${BATCH_LIMIT}) reached. More sessions may remain; the next tick continues.`: null,});});diff --git a/api/cron/quality-bench.js b/api/cron/quality-bench.jsindex 9097bef4e..75780baa0 100644--- a/api/cron/quality-bench.js+++ b/api/cron/quality-bench.js@@ -110,5 +110,7 @@ export default wrapCron(async (req, res) => {console.log('[cron] quality-bench smoke run', summary);}- json(res, regressed ? 200 : 200, { ok: true, regressed, ...summary });+ // Always 200: a regression is a reported finding, not a failed invocation.+ // A non-2xx here would make Cloud Scheduler retry the (expensive) bench run.+ json(res, 200, { ok: true, regressed, ...summary });});diff --git a/api/cron/quota-check.js b/api/cron/quota-check.jsindex db2a19bc5..f17a565aa 100644--- a/api/cron/quota-check.js+++ b/api/cron/quota-check.js@@ -18,8 +18,7 @@// Kept as a concrete file to keep the import graph tiny — this cron must not// share a cold start with the heavy SDK bundles.-import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sendOpsAlert } from '../_lib/alerts.js';import { getRedis } from '../_lib/redis.js';import { requireCron } from '../_lib/cron-auth.js';diff --git a/api/cron/radar-watchlist.js b/api/cron/radar-watchlist.jsindex e5144329e..d0ccfcb0b 100644--- a/api/cron/radar-watchlist.js+++ b/api/cron/radar-watchlist.js@@ -11,7 +11,6 @@// radar's own table.import { json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { recomputeWatchlist } from '../../workers/agent-sniper/radar-watchlist.js';import { requireCron } from '../_lib/cron-auth.js';diff --git a/api/cron/reconstruct-sweep.js b/api/cron/reconstruct-sweep.jsindex 663d26d84..967a8ca0b 100644--- a/api/cron/reconstruct-sweep.js+++ b/api/cron/reconstruct-sweep.js@@ -25,7 +25,7 @@// jobs stay browser-driven and the age reaper below is their only backstop.// They are a rounding error in practice (1 of the last ~100 reconstruct jobs).-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { getRegenProviderForMode } from '../_lib/regen-provider.js';import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-finalize.js';diff --git a/api/cron/reflect-sweep.js b/api/cron/reflect-sweep.jsindex 1f727df6a..6958e338c 100644--- a/api/cron/reflect-sweep.js+++ b/api/cron/reflect-sweep.js@@ -14,8 +14,7 @@// and picked up on the next tick — never silently dropped.import { sql } from '../_lib/db.js';-import { env } from '../_lib/env.js';-import { cors, error, json, method, wrapCron } from '../_lib/http.js';+import { cors, json, method, wrapCron } from '../_lib/http.js';import { runReflection } from '../_lib/reflection.js';import { requireCron } from '../_lib/cron-auth.js';@@ -72,7 +71,14 @@ export default wrapCron(async (req, res) => {});if (result.status === 'ok') summary.dreamsCreated += result.created.length;else if (result.status === 'skipped') summary.skipped++;- else summary.errors++;+ else {+ summary.errors++;+ // runReflection reports engine failures by return value, not by throwing+ // (it records the run either way). Without this the response says+ // "errors: 1" and nothing anywhere says which agent or why.+ summary.lastError = result.reason || 'reflection failed';+ console.error(`[reflect-sweep] agent=${agent.id} reflection error:`, summary.lastError);+ }} catch (err) {summary.errors++;console.error(`[reflect-sweep] agent=${agent.id} failed:`, err?.message);diff --git a/prompts/swarm-100/api-cron-05.md b/prompts/swarm-100/api-cron-05.mddeleted file mode 100644index 0dffd9f63..000000000--- a/prompts/swarm-100/api-cron-05.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/cron batch 05 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/cron/oracle-score.js-- api/cron/payment-session-sweep.js-- api/cron/pulse-tick.js-- api/cron/quality-bench.js-- api/cron/quota-check.js-- api/cron/radar-watchlist.js-- api/cron/recompute-reputation.js-- api/cron/reconcile-decisions.js-- api/cron/reconstruct-sweep.js-- api/cron/reflect-sweep.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-cron-05.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/payment-session-sweep.test.js b/tests/payment-session-sweep.test.jsnew file mode 100644index 000000000..6ab83c9b1--- /dev/null+++ b/tests/payment-session-sweep.test.js@@ -0,0 +1,170 @@+// Regression guard for the payment-session sweep (api/cron/payment-session-sweep.js).+//+// 2026-08-10 audit: the sweep ran an UNBOUNDED `UPDATE payment_sessions SET+// status = 'expired' WHERE status = 'active' AND expires_at < now()` and then+// sliced the RETURNING rows to BATCH_LIMIT in JS before refunding. Postgres had+// already expired every due session, but only the first BATCH_LIMIT of them were+// refunded, and the next tick could never see the rest because it selects on+// `status = 'active'`. Every session past the limit silently kept the user's+// un-spent budget. The handler's own note ("the next tick will continue") was+// false. The bound now lives inside the statement, so the set that is expired and+// the set that is refunded are the same set.+//+// The sql double below models the one thing that matters for that bug: Postgres+// honours a LIMIT only if the statement carries one. A handler that goes back to+// slicing in JS fails `expires exactly what it refunds`.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const h = vi.hoisted(() => {+ process.env.CRON_SECRET = 'test-cron-secret';+ process.env.PAYMENT_SESSION_SWEEP_BATCH = '10';+ return { sql: vi.fn(), creditAccount: vi.fn() };+});++vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => h.sql(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/credits.js', () => ({ creditAccount: (...a) => h.creditAccount(...a) }));++const { default: handler } = await import('../api/cron/payment-session-sweep.js');++const BATCH = 10;++function mockRes() {+ return {+ statusCode: 0,+ headersSent: false,+ writableEnded: false,+ headers: {},+ body: null,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(payload) {+ this.writableEnded = true;+ this.body = payload ? JSON.parse(payload) : null;+ },+ };+}++const req = (over = {}) => ({+ method: 'GET',+ url: '/api/cron/payment-session-sweep',+ headers: { authorization: 'Bearer test-cron-secret' },+ ...over,+});++// Sessions still 'active' and past expiry, keyed by id.+let due;+// Ids the double actually flipped to 'expired'.+let expiredIds;++function installSql() {+ h.sql.mockImplementation((strings, ...vals) => {+ const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);+ if (!/UPDATE payment_sessions/i.test(q)) return Promise.resolve([]);++ // Postgres applies a bound only when the statement asks for one.+ const bounded = /\bLIMIT\b/i.test(q);+ const limit = bounded ? Number(vals[0]) : Infinity;+ const claimed = due.slice(0, limit);+ for (const row of claimed) expiredIds.push(row.id);+ due = due.slice(claimed.length);+ return Promise.resolve(claimed.map((r) => ({ ...r })));+ });+}++function makeSessions(n) {+ return Array.from({ length: n }, (_, i) => ({+ id: `sess-${i}`,+ user_id: `user-${i}`,+ budget_usdc: '1000000',+ spent_usdc: '250000',+ }));+}++describe('payment-session-sweep', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ due = [];+ expiredIds = [];+ installSql();+ h.creditAccount.mockResolvedValue({ ok: true });+ });++ it('expires exactly the set it refunds when more sessions are due than the batch limit', async () => {+ due = makeSessions(BATCH * 3);+ const res = mockRes();+ await handler(req(), res);++ expect(res.statusCode).toBe(200);+ expect(expiredIds.length).toBe(BATCH);+ // The invariant: nothing is marked expired without its refund being issued.+ expect(h.creditAccount).toHaveBeenCalledTimes(BATCH);+ expect(h.creditAccount.mock.calls.map(([a]) => a.refId).sort()).toEqual([...expiredIds].sort());+ expect(res.body.expired).toBe(BATCH);+ expect(res.body.refunded).toBe(BATCH);+ // The remainder is still active, so the next tick genuinely reaches it.+ expect(due.length).toBe(BATCH * 2);+ });++ it('drains the backlog across ticks instead of stranding it', async () => {+ due = makeSessions(BATCH * 3);+ for (let tick = 0; tick < 3; tick++) await handler(req(), mockRes());++ expect(due.length).toBe(0);+ expect(expiredIds.length).toBe(BATCH * 3);+ expect(h.creditAccount).toHaveBeenCalledTimes(BATCH * 3);+ });++ it('refunds the un-spent remainder under a stable idempotency key', async () => {+ due = makeSessions(1);+ await handler(req(), mockRes());++ const [arg] = h.creditAccount.mock.calls[0];+ expect(arg.amountUsd).toBeCloseTo(0.75, 6);+ expect(arg.kind).toBe('refund');+ expect(arg.idempotencyKey).toBe('paysess_expire_sess-0');+ });++ it('skips the refund when the whole budget was spent', async () => {+ due = [{ id: 'sess-full', user_id: 'u', budget_usdc: '1000000', spent_usdc: '1000000' }];+ const res = mockRes();+ await handler(req(), res);++ expect(h.creditAccount).not.toHaveBeenCalled();+ expect(res.body).toMatchObject({ expired: 1, refunded: 0, refund_errors: 0 });+ });++ it('counts a failing refund without aborting the rest of the batch', async () => {+ due = makeSessions(3);+ h.creditAccount.mockRejectedValueOnce(new Error('ledger down'));+ const res = mockRes();+ await handler(req(), res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, expired: 3, refunded: 2, refund_errors: 1 });+ });++ it('rejects a method it does not implement before touching the database', async () => {+ due = makeSessions(5);+ const res = mockRes();+ await handler(req({ method: 'DELETE' }), res);++ expect(res.statusCode).toBe(405);+ expect(h.sql).not.toHaveBeenCalled();+ expect(h.creditAccount).not.toHaveBeenCalled();+ });++ it('rejects an unauthenticated caller before touching the database', async () => {+ due = makeSessions(5);+ const res = mockRes();+ await handler(req({ headers: {} }), res);++ expect(res.statusCode).toBe(401);+ expect(h.sql).not.toHaveBeenCalled();+ expect(h.creditAccount).not.toHaveBeenCalled();+ });+});