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.

fix(quest-notify): stop reporting a bell row as delivered before the insert lands

nirholas0f263832e714
diff --git a/api/internal/quest-notify.js b/api/internal/quest-notify.js
index d7f5f5ca6..5555c07c0 100644
--- a/api/internal/quest-notify.js
+++ b/api/internal/quest-notify.js
@@ -1,4 +1,4 @@
-// POST /api/internal/quest-notify — the multiplayer server → API bridge for
+// POST /api/internal/quest-notify, the multiplayer server to API bridge for
// quest/mission notifications. WalkRoom already publishes a public
// 'mission-complete' ticker event (api/_lib/feed.js) when a player finishes a
// /play job or co-op heist, but that ticker is anonymous-by-design (world-
@@ -9,8 +9,14 @@
//
// Trust model mirrors api/world/[action].js save: only a request bearing a
// valid world-service token (signed by multiplayer/src/persistence.js's
-// signServiceToken, svc:'world') is accepted — a browser can't forge a quest
+// signServiceToken, svc:'world') is accepted, a browser can't forge a quest
// completion for another account.
+//
+// The insert is awaited, not fired and forgotten: writing the bell row IS this
+// endpoint's whole job, so answering 200 before the write resolves would let the
+// game server log a delivery that never happened. The response carries the row id
+// (null when the player has muted this category, or when the insert failed and
+// notify.js swallowed it), so the caller can tell the two outcomes apart.
import { json, method, wrap, error, readJson, cors } from '../_lib/http.js';
import { extractBearer } from '../_lib/auth.js';
@@ -20,7 +26,7 @@ import { insertNotification } from '../_lib/notify.js';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export default wrap(async (req, res) => {
- // Server-to-server only — no browser origin ever calls this directly.
+ // Server-to-server only, no browser origin ever calls this directly.
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
@@ -42,7 +48,7 @@ export default wrap(async (req, res) => {
const coop = !!body?.coop;
const coin = typeof body?.coin === 'string' ? body.coin.slice(0, 32) : null;
- insertNotification(accountUid, 'quest_complete', {
+ const delivery = await insertNotification(accountUid, 'quest_complete', {
mission,
gold,
coop,
@@ -50,5 +56,5 @@ export default wrap(async (req, res) => {
link: '/play',
});
- return json(res, 200, { ok: true });
+ return json(res, 200, { ok: true, id: delivery.id ?? null });
});
diff --git a/prompts/swarm-100/api-internal-01.md b/prompts/swarm-100/api-internal-01.md
deleted file mode 100644
index af3f56d12..000000000
--- a/prompts/swarm-100/api-internal-01.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# API audit: api/internal batch 01 (2 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/internal/event-score.js
-- api/internal/quest-notify.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-internal-01.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/api-internal-event-score.test.js b/tests/api-internal-event-score.test.js
new file mode 100644
index 000000000..0d3aeb8c8
--- /dev/null
+++ b/tests/api-internal-event-score.test.js
@@ -0,0 +1,207 @@
+// POST /api/internal/event-score, the world server's write path into the live
+// event leaderboard.
+//
+// The store's own maths is covered in tests/event-leaderboard.test.js; what is
+// covered here is the endpoint's gate, the part that decides whether a reported
+// run is allowed to score at all. Four independent locks have to hold: a valid
+// world-service token, a configured event, an open window, and a mission the quest
+// engine actually marks `event: true`. A hole in any one of them lets a leaked
+// token stuff a board.
+//
+// The event window is injected through a mocked eventConfig rather than by writing
+// public/event.json, so the suite neither depends on a real event being scheduled
+// nor turns one on for every other surface that reads that file. Redis is never
+// touched: recordEventRun folds through the real applyEventRun into a local map,
+// so the record the endpoint echoes back is the record the store would have built.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { applyEventRun, emptyEventRecord } from '../multiplayer/src/event-leaderboard.js';
+
+const verifyWorldServiceTokenMock = vi.fn();
+vi.mock('../api/_lib/world-service-auth.js', () => ({
+ verifyWorldServiceToken: (...a) => verifyWorldServiceTokenMock(...a),
+}));
+
+const eventConfigMock = vi.fn();
+vi.mock('../api/_lib/event-config.js', () => ({
+ eventConfig: (...a) => eventConfigMock(...a),
+}));
+
+const board = new Map(); // account -> record
+const recordEventRunMock = vi.fn(async ({ account, name, missionId, gold, at }) => {
+ const rec = applyEventRun(board.get(account) || emptyEventRecord(account, name), {
+ missionId,
+ gold,
+ at,
+ name,
+ });
+ board.set(account, rec);
+ return { record: rec, durable: false };
+});
+vi.mock('../api/_lib/event-leaderboard-store.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ recordEventRun: (...a) => recordEventRunMock(...a),
+}));
+
+const { default: handler } = await import('../api/internal/event-score.js');
+
+function mkReq({ method = 'POST', url = '/api/internal/event-score', headers = {}, body = null } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method, url, headers: hdrs,
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') this._endCb = cb;
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+const AUTH = { authorization: 'Bearer faketoken' };
+const ACCOUNT = 'probe:runner';
+const MISSION = 'event-supply-run';
+
+function liveWindow(now = Date.now()) {
+ return { id: 'unit-event', name: 'Unit event', startsAt: now - 3600_000, endsAt: now + 3600_000 };
+}
+
+async function post(body, headers = AUTH) {
+ const res = mkRes();
+ await handler(mkReq({ headers, body }), res);
+ return res;
+}
+
+beforeEach(() => {
+ board.clear();
+ recordEventRunMock.mockClear();
+ verifyWorldServiceTokenMock.mockReset().mockResolvedValue(null);
+ eventConfigMock.mockReset().mockReturnValue(liveWindow());
+});
+
+describe('POST /api/internal/event-score', () => {
+ it('scores a run reported by the world server and echoes the updated row', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const res = await post({
+ eventId: 'unit-event',
+ account: ACCOUNT,
+ name: 'Runner',
+ missionId: MISSION,
+ gold: 250,
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({
+ ok: true,
+ durable: false,
+ eventId: 'unit-event',
+ runs: 1,
+ cash: 250,
+ });
+ expect(recordEventRunMock).toHaveBeenCalledTimes(1);
+ expect(recordEventRunMock.mock.calls[0][0]).toMatchObject({
+ eventId: 'unit-event',
+ account: ACCOUNT,
+ missionId: MISSION,
+ gold: 250,
+ });
+ });
+
+ it('counts a repeat of the same job as a separate run', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ await post({ account: ACCOUNT, name: 'Runner', missionId: MISSION, gold: 250 });
+ const res = await post({ account: ACCOUNT, name: 'Runner', missionId: MISSION, gold: 40 });
+ expect(parse(res)).toMatchObject({ runs: 2, cash: 290 });
+ });
+
+ it('takes the configured event id when the report omits one', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const res = await post({ account: ACCOUNT, missionId: MISSION });
+ expect(parse(res)).toMatchObject({ ok: true, eventId: 'unit-event' });
+ });
+
+ it('rejects a report with no valid world-service token', async () => {
+ const res = await post({ account: ACCOUNT, missionId: MISSION }, {});
+ expect(res.statusCode).toBe(401);
+ expect(parse(res).error).toBe('unauthorized');
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('scores nothing when no event is configured', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ eventConfigMock.mockReturnValue(null);
+ const res = await post({ account: ACCOUNT, missionId: MISSION });
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('no_event');
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a run reported against some other event', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const res = await post({ eventId: 'a-different-event', account: ACCOUNT, missionId: MISSION });
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('event_mismatch');
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a run reported outside the event window', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const now = Date.now();
+ eventConfigMock.mockReturnValue({ id: 'unit-event', name: 'Unit event', startsAt: now - 7200_000, endsAt: now - 3600_000 });
+ const res = await post({ account: ACCOUNT, missionId: MISSION });
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('event_closed');
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a mission the quest engine does not mark as an event job', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ for (const missionId of ['', 'not-a-mission', 'daily-sweep']) {
+ const res = await post({ account: ACCOUNT, missionId });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error_description).toBe('missionId must be an event mission');
+ }
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses an account key that could not have come from a real player', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ for (const account of ['', ' ', 'has space', 'x'.repeat(97)]) {
+ const res = await post({ account, missionId: MISSION });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error_description).toBe('account required');
+ }
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+
+ it('clamps a junk gold value instead of poisoning the row', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ for (const gold of [-500, 'lots', null, undefined]) {
+ board.clear();
+ const res = await post({ account: ACCOUNT, missionId: MISSION, gold });
+ expect(parse(res)).toMatchObject({ ok: true, runs: 1, cash: 0 });
+ }
+ });
+
+ it('truncates an oversized display name rather than storing it whole', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ await post({ account: ACCOUNT, name: 'N'.repeat(200), missionId: MISSION });
+ expect(recordEventRunMock.mock.calls[0][0].name).toHaveLength(24);
+ });
+
+ it('answers 405 to a read and never scores on one', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'GET', headers: AUTH }), res);
+ expect(res.statusCode).toBe(405);
+ expect(recordEventRunMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api-internal-quest-notify.test.js b/tests/api-internal-quest-notify.test.js
index f67da954f..3b2971a43 100644
--- a/tests/api-internal-quest-notify.test.js
+++ b/tests/api-internal-quest-notify.test.js
@@ -39,7 +39,7 @@ const ACCOUNT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
beforeEach(() => {
verifyWorldServiceTokenMock.mockReset().mockResolvedValue(null);
- insertNotificationMock.mockReset();
+ insertNotificationMock.mockReset().mockResolvedValue({ id: 'notif-1', in_app: true });
});
describe('POST /api/internal/quest-notify', () => {
@@ -60,7 +60,7 @@ describe('POST /api/internal/quest-notify', () => {
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
- expect(parse(res)).toEqual({ ok: true });
+ expect(parse(res)).toEqual({ ok: true, id: 'notif-1' });
expect(insertNotificationMock).toHaveBeenCalledWith(ACCOUNT, 'quest_complete', {
mission: 'Vault heist',
gold: 250,
@@ -81,4 +81,47 @@ describe('POST /api/internal/quest-notify', () => {
expect(res.statusCode).toBe(400);
expect(insertNotificationMock).not.toHaveBeenCalled();
});
+
+ it('waits for the insert and reports a null id when the bell row never landed', async () => {
+ // notify.js swallows a failed insert and resolves { id: null }. The endpoint
+ // must not answer before that resolves, and must not dress a dropped row up
+ // as a delivered one: the game server logs the report as landed on any 2xx.
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ let settle;
+ insertNotificationMock.mockReturnValue(new Promise((resolve) => { settle = resolve; }));
+ const req = mkReq({
+ headers: { authorization: 'Bearer faketoken' },
+ body: { accountUid: ACCOUNT, mission: 'Heist' },
+ });
+ const res = mkRes();
+ const done = handler(req, res);
+ await Promise.resolve();
+ expect(res.writableEnded).toBe(false);
+ settle({ id: null, in_app: false });
+ await done;
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: true, id: null });
+ });
+
+ it('clamps a hostile payload instead of forwarding it verbatim', async () => {
+ verifyWorldServiceTokenMock.mockResolvedValue({ svc: 'world' });
+ const req = mkReq({
+ headers: { authorization: 'Bearer faketoken' },
+ body: {
+ accountUid: ACCOUNT,
+ mission: 'M'.repeat(400),
+ gold: -9999,
+ coop: 'yes',
+ coin: 'C'.repeat(100),
+ },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ const [, , payload] = insertNotificationMock.mock.calls[0];
+ expect(payload.mission).toHaveLength(120);
+ expect(payload.gold).toBe(0);
+ expect(payload.coop).toBe(true);
+ expect(payload.coin).toHaveLength(32);
+ });
});