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: update changelog with recent fixes and improvements; add unit tests for cache circuit breaker and HTTP HEAD method handling

udvkdce87ab4be44
diff --git a/.gitignore b/.gitignore
index 64ce92c5e..50e2a1a72 100644
--- a/.gitignore
+++ b/.gitignore
@@ -264,10 +264,14 @@ three.ws-log-export-*.json
# Local prompt working set (not shared)
prompts/nvidia/
-# Embodiment / digital-human work — kept local, never shared to the mirrors
+# Embodiment / digital-human work — kept local, never shared to the mirrors.
+# Exception: emotion.js is a pure emotion/gesture descriptor that committed,
+# deployed MCP routes (api/mcp-3d.js → _mcp3d/tools/studio.js) and the embodiment
+# stage import, so it MUST be in the tree or the Vercel bundle fails to resolve it.
api/_lib/embodiment.js
api/embodiment/
-src/embodiment/
+src/embodiment/*
+!src/embodiment/emotion.js
src/embody.js
pages/embody.html
api/_lib/migrations/20260623170000_agent_bodies.sql
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d407d4b96..efa73bb76 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-26
+- **Default avatars render again everywhere** — Avatars stopped appearing across the site — the homepage hero, guest avatars, and any embed that falls back to the default character all showed an empty frame. The default avatar was being loaded from an asset host that had gone offline. It now loads from three.ws itself, so default avatars render again on every page and in every embed. `[fix]`
+- **Mission Control's live launch feed never goes dark** — The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins. (`/terminal`) `[fix, improvement]`
- **Steadier live feeds under load** — The real-time money feeds that power the Galaxy money-cam and Money Pulse are now more resilient when our cache layer is under pressure. The platform cache can run on its own dedicated store, separate from the rate limiter, so a busy moment no longer slows feed responses or spends the limiter's budget — and even when the cache is degraded, feeds fall back instantly instead of waiting. You'll see the live maps stay smooth during traffic spikes. `[infra, improvement]`
- **The trader leaderboard is never empty: live top Solana traders until agents take over** — The leaderboard ranks three.ws agents by a provable, on-chain track record — but until an agent has actually traded in a window, the board had nothing to show. Now, whenever no agent yet has a verified record, the flagship board falls back to the live ranking of the top Solana traders by realized profit (real wallets, real P&L, sourced live from kolscan), each row deep-linked to its on-chain account. The moment an agent earns a record it takes precedence again. Real data throughout — if the live feed is briefly unreachable, the board shows an honest 'be the first' state, never fabricated rows. (`/leaderboard`) `[feature, improvement]`
- **Trading Swarms: pool capital with other agents and split the profits** — A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms. (`/swarms`) `[feature]`
diff --git a/data/changelog.json b/data/changelog.json
index 3742214c8..bb59f8104 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,19 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-26",
+ "title": "Mission Control's live launch feed never goes dark",
+ "summary": "The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins.",
+ "tags": ["fix", "improvement"],
+ "link": "/terminal"
+ },
+ {
+ "date": "2026-06-26",
+ "title": "Default avatars render again everywhere",
+ "summary": "Avatars stopped appearing across the site — the homepage hero, guest avatars, and any embed that falls back to the default character all showed an empty frame. The default avatar was being loaded from an asset host that had gone offline. It now loads from three.ws itself, so default avatars render again on every page and in every embed.",
+ "tags": ["fix"]
+ },
{
"date": "2026-06-26",
"title": "The trader leaderboard is never empty: live top Solana traders until agents take over",
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index 5bf128c91..a4b3e55f5 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -421,13 +421,13 @@ a:focus-visible{outline-offset:3px}
<link rel="canonical" href="https://three.ws/ibm/hello">
<meta property="og:site_name" content="three.ws">
<meta property="og:url" content="https://three.ws/ibm/x402-demo">
- <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="x402 Live Demo (IBM × three.ws) · three.ws">
<meta name="twitter:description" content="A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.">
- <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=IBM+%C3%97+three.ws+partnership&amp;d=The+IBM+%C3%97+three.ws+partnership+page%3A+how+three.ws%27s+agent+identity%2C+x402+payment+rails%2C+and+MCP+servers+integrate+with+IBM+watsonx+and+the+IBM+x402+ecosystem.+A&amp;p=%2Fibm%2Fhello">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Live+Demo+%28IBM+%C3%97+three.ws%29&amp;d=A+self-contained+x402+micropayment+demo%3A+pay+%240.001+USDC+from+your+own+wallet+%E2%80%94+MetaMask+on+Base+or+Phantom+on+Solana+%E2%80%94+to+call+a+real+three.ws+data+API.+Watch+&amp;p=%2Fibm%2Fx402-demo">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"x402 Live Demo (IBM × three.ws)","description":"A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.","url":"https://three.ws/ibm/x402-demo","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<!-- model-viewer renders the GLB returned by the paid Forge demo (Demo 01).
Self-hosted (travels with this file under ./vendor/) so the page needs no
diff --git a/public/changelog.json b/public/changelog.json
index 0a78aa531..15c24dca2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,32 @@
{
- "generated_at": "2026-06-26T00:06:48.020Z",
+ "generated_at": "2026-06-26T00:12:52.909Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Default avatars render again everywhere",
+ "summary": "Avatars stopped appearing across the site — the homepage hero, guest avatars, and any embed that falls back to the default character all showed an empty frame. The default avatar was being loaded from an asset host that had gone offline. It now loads from three.ws itself, so default avatars render again on every page and in every embed.",
+ "link": null,
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-06-26",
+ "type": "update",
+ "title": "Mission Control's live launch feed never goes dark",
+ "summary": "The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins.",
+ "link": "/terminal",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-26",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index dbdac9120..5bc7b596d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Default avatars render again everywhere</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-26:Default avatars render again everywhere</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Avatars stopped appearing across the site — the homepage hero, guest avatars, and any embed that falls back to the default character all showed an empty frame. The default avatar was being loaded from an asset host that had gone offline. It now loads from three.ws itself, so default avatars render again on every page and in every embed.</description>
+ </item>
+ <item>
+ <title>Mission Control's live launch feed never goes dark</title>
+ <link>https://three.ws/terminal</link>
+ <guid isPermaLink="false">2026-06-26:Mission Control's live launch feed never goes dark</guid>
+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins.</description>
+ </item>
<item>
<title>Steadier live feeds under load</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 9c14750bd..4154b4f31 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-26T00:06:48.003Z",
+ "generated_at": "2026-06-26T00:12:52.882Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/element.js b/src/element.js
index 245af9c40..d2c42b1fe 100644
--- a/src/element.js
+++ b/src/element.js
@@ -2062,7 +2062,7 @@ class Agent3DElement extends HTMLElement {
spec: 'agent-manifest/0.1',
_baseURI: '',
name: this.getAttribute('name') || 'Agent',
- body: { uri: 'https://assets.three.ws/models/avatars/Default.glb', format: 'gltf-binary' },
+ body: { uri: 'https://three.ws/avatars/default.glb', format: 'gltf-binary' },
brain: { provider: 'none' },
voice: { tts: { provider: 'browser' }, stt: { provider: 'browser' } },
skills: [],
diff --git a/src/embodiment/emotion.js b/src/embodiment/emotion.js
new file mode 100644
index 000000000..dc95edfd1
--- /dev/null
+++ b/src/embodiment/emotion.js
@@ -0,0 +1,230 @@
+/**
+ * Lightweight emotion classifier + face/gesture descriptor for embodied agents.
+ *
+ * A persona speaks a turn of text; this module reads the text, picks the
+ * emotion it most plausibly carries, and returns a renderable descriptor: an
+ * idle loop to sit in, a body gesture to fire, and a set of ARKit-style face
+ * blendshape weights scaled by intensity. The embodiment stage and the MCP
+ * `speak` tool both consume this so a reply lip-syncs *and* emotes in one pass.
+ *
+ * Every idle/gesture clip this module can ask for MUST exist in
+ * public/animations/manifest.json. `referencedClipNames()` enumerates them and
+ * tests/embodiment-emotion.test.js asserts the manifest contains each one, so a
+ * clip rename can't silently leave a persona reaching for a clip that isn't
+ * baked.
+ */
+
+/** The emotions the classifier and descriptor table understand. */
+export const EMOTIONS = Object.freeze(['neutral', 'joy', 'sad', 'angry', 'surprised', 'thinking']);
+
+/** Above this intensity an emotion escalates from its base gesture to its peak gesture. */
+const HIGH_INTENSITY_THRESHOLD = 0.66;
+
+/**
+ * Per-emotion descriptor table. `idle` is the loop to rest in; `low` is the
+ * gesture for a mild read of the emotion, `high` the escalated one. `face` is
+ * the blendshape set at full (intensity = 1) strength — every weight is scaled
+ * down linearly by the turn's intensity. All clip names are baked clips in the
+ * animation manifest.
+ */
+const EMOTION_MAP = Object.freeze({
+ neutral: {
+ idle: 'idle',
+ low: null,
+ high: null,
+ face: {},
+ },
+ joy: {
+ idle: 'av-idle-breath',
+ low: 'av-joy',
+ high: 'av-celebrating',
+ face: {
+ mouthSmileLeft: 0.9,
+ mouthSmileRight: 0.9,
+ cheekSquintLeft: 0.5,
+ cheekSquintRight: 0.5,
+ eyeSquintLeft: 0.3,
+ eyeSquintRight: 0.3,
+ },
+ },
+ sad: {
+ idle: 'xbot-sad-pose',
+ low: 'xbot-sad-pose',
+ high: 'defeated',
+ face: {
+ mouthFrownLeft: 0.8,
+ mouthFrownRight: 0.8,
+ browInnerUp: 0.7,
+ eyeLookDownLeft: 0.3,
+ eyeLookDownRight: 0.3,
+ },
+ },
+ angry: {
+ idle: 'idle',
+ low: 'angry',
+ high: 'taunt',
+ face: {
+ browDownLeft: 0.9,
+ browDownRight: 0.9,
+ noseSneerLeft: 0.5,
+ noseSneerRight: 0.5,
+ mouthPressLeft: 0.4,
+ mouthPressRight: 0.4,
+ },
+ },
+ surprised: {
+ idle: 'av-waiting',
+ low: 'reaction',
+ high: 'jump',
+ face: {
+ eyeWideLeft: 0.9,
+ eyeWideRight: 0.9,
+ browInnerUp: 0.6,
+ browOuterUpLeft: 0.6,
+ browOuterUpRight: 0.6,
+ jawOpen: 0.5,
+ },
+ },
+ thinking: {
+ idle: 'av-leaning-wall',
+ low: 'lookdown',
+ high: 'facepalm',
+ face: {
+ browInnerUp: 0.3,
+ browDownLeft: 0.3,
+ eyeLookUpLeft: 0.4,
+ eyeLookUpRight: 0.4,
+ mouthPressLeft: 0.3,
+ },
+ },
+});
+
+/**
+ * Lexical cues per emotion. Single words are matched on word boundaries;
+ * multi-word phrases and emoji are matched as substrings. Order is irrelevant —
+ * the emotion with the most cue hits wins, neutral on a tie of zero.
+ */
+const CUES = Object.freeze({
+ joy: ['congratulations', 'congrats', 'amazing', 'awesome', 'great', 'wonderful', 'excellent', 'love', 'happy', 'yay', 'fantastic', 'brilliant', '🎉', '🥳', '😄', '😊'],
+ sad: ['sorry', 'unfortunately', 'failed', 'sad', 'disappointed', 'regret', 'apologies', 'apologize', 'unable', 'lost', '😢', '😔', '💔'],
+ angry: ['unacceptable', 'frustrating', 'frustrated', 'angry', 'furious', 'terrible', 'hate', 'annoyed', 'outrageous', 'ridiculous', 'broken', '😠', '😡'],
+ surprised: ['whoa', 'no way', 'incredible', 'unbelievable', 'wow', 'omg', 'shocked', 'really?!', 'surprised', '😮', '😲', '🤯'],
+ thinking: ['hmm', 'let me think', 'let me', 'think', 'thinking', 'analyze', 'analyse', 'consider', 'wondering', 'perhaps', 'maybe', 'figure out', '🤔'],
+});
+
+const WORD_CHAR = /[a-z0-9]/i;
+
+function countCue(text, cue) {
+ // Phrases and emoji can't be word-bounded; match them as substrings.
+ if (!WORD_CHAR.test(cue[0]) || !WORD_CHAR.test(cue[cue.length - 1]) || cue.includes(' ')) {
+ let count = 0;
+ let idx = text.indexOf(cue);
+ while (idx !== -1) {
+ count += 1;
+ idx = text.indexOf(cue, idx + cue.length);
+ }
+ return count;
+ }
+ const escaped = cue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const matches = text.match(new RegExp(`\\b${escaped}\\b`, 'g'));
+ return matches ? matches.length : 0;
+}
+
+function clamp01(n) {
+ if (Number.isNaN(n)) return 0;
+ return Math.max(0, Math.min(1, n));
+}
+
+/**
+ * Classify the emotion carried by a turn of text.
+ *
+ * @param {string} text
+ * @returns {{ emotion: string, intensity: number, scores: Record<string, number> }}
+ */
+export function detectEmotion(text) {
+ const scores = { neutral: 0, joy: 0, sad: 0, angry: 0, surprised: 0, thinking: 0 };
+ const raw = typeof text === 'string' ? text : '';
+ const lower = raw.toLowerCase();
+
+ if (!raw.trim()) {
+ return { emotion: 'neutral', intensity: 0, scores };
+ }
+
+ let topEmotion = 'neutral';
+ let topScore = 0;
+ for (const emotion of Object.keys(CUES)) {
+ let score = 0;
+ for (const cue of CUES[emotion]) score += countCue(lower, cue);
+ scores[emotion] = score;
+ if (score > topScore) {
+ topScore = score;
+ topEmotion = emotion;
+ }
+ }
+
+ if (topScore === 0) {
+ return { emotion: 'neutral', intensity: 0, scores };
+ }
+
+ // Intensity blends how many cues fired with how "loud" the text reads:
+ // exclamation marks and the ratio of shouted (uppercase) letters.
+ const exclamations = (raw.match(/!/g) || []).length;
+ const letters = raw.replace(/[^a-zA-Z]/g, '');
+ const uppers = raw.replace(/[^A-Z]/g, '').length;
+ const shout = letters.length ? uppers / letters.length : 0;
+ const intensity = clamp01(0.35 * topScore + 0.12 * exclamations + 0.35 * shout);
+
+ return { emotion: topEmotion, intensity, scores };
+}
+
+/**
+ * Build a renderable descriptor for an explicit emotion + intensity. Unknown
+ * emotions clamp to neutral. Face weights are scaled by intensity; the gesture
+ * escalates from the emotion's base clip to its peak clip past the threshold.
+ *
+ * @param {string} emotion
+ * @param {number} [intensity=0.6]
+ * @returns {{ emotion: string, intensity: number, idle: string, gesture: string|null, face: Record<string, number> }}
+ */
+export function expressionFor(emotion, intensity = 0.6) {
+ const key = EMOTION_MAP[emotion] ? emotion : 'neutral';
+ const entry = EMOTION_MAP[key];
+ const strength = clamp01(intensity);
+
+ const face = {};
+ for (const [shape, weight] of Object.entries(entry.face)) {
+ face[shape] = weight * strength;
+ }
+
+ const escalated = strength >= HIGH_INTENSITY_THRESHOLD;
+ const gesture = (escalated ? entry.high : entry.low) || entry.low || entry.high || null;
+
+ return { emotion: key, intensity: strength, idle: entry.idle, gesture, face };
+}
+
+/**
+ * Classify `text` and thread the result straight into a full descriptor.
+ *
+ * @param {string} text
+ * @returns {{ emotion: string, intensity: number, idle: string, gesture: string|null, face: Record<string, number>, scores: Record<string, number> }}
+ */
+export function expressionForText(text) {
+ const { emotion, intensity, scores } = detectEmotion(text);
+ return { ...expressionFor(emotion, intensity), scores };
+}
+
+/**
+ * Every clip name this module can ask the renderer to play, deduped. The
+ * manifest-contract test asserts each one is a baked clip.
+ *
+ * @returns {string[]}
+ */
+export function referencedClipNames() {
+ const names = new Set();
+ for (const entry of Object.values(EMOTION_MAP)) {
+ if (entry.idle) names.add(entry.idle);
+ if (entry.low) names.add(entry.low);
+ if (entry.high) names.add(entry.high);
+ }
+ return [...names];
+}
diff --git a/tests/cache-circuit-breaker.test.js b/tests/cache-circuit-breaker.test.js
new file mode 100644
index 000000000..d942bb484
--- /dev/null
+++ b/tests/cache-circuit-breaker.test.js
@@ -0,0 +1,61 @@
+/**
+ * cache.js circuit breaker — unit test.
+ *
+ * A degraded Upstash store (commands timing out at REDIS_CMD_TIMEOUT_MS rather
+ * than rejecting promptly) otherwise makes EVERY request pay a full 3s stall
+ * before falling back to memory, and emits one identical warning per request —
+ * the flood seen in production on hot endpoints like /api/galaxy/flows. After a
+ * run of consecutive failures the cache OPENS a circuit and serves straight from
+ * memory without touching the network. This pins that behavior.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { cacheSet, cacheGet } from '../api/_lib/cache.js';
+
+const SHARED = 'https://ratelimit-store.upstash.io';
+const ENV_KEYS = ['UPSTASH_CACHE_REST_URL', 'UPSTASH_CACHE_REST_TOKEN', 'UPSTASH_REDIS_REST_URL', 'UPSTASH_REDIS_REST_TOKEN'];
+let saved;
+
+beforeEach(() => {
+ saved = {};
+ for (const k of ENV_KEYS) { saved[k] = process.env[k]; delete process.env[k]; }
+ process.env.UPSTASH_REDIS_REST_URL = SHARED;
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'shared-token';
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ vi.restoreAllMocks();
+});
+
+describe('cache circuit breaker', () => {
+ it('opens after consecutive failures and then serves from memory without calling fetch', async () => {
+ // Every command times out (the production failure mode).
+ const fetchMock = vi.fn(async () => { throw new Error('The operation was aborted due to timeout'); });
+ globalThis.fetch = fetchMock;
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ // Drive enough consecutive failures to trip the breaker (threshold is 5).
+ for (let i = 0; i < 5; i++) {
+ await cacheSet(`circuit:open:${i}`, { v: i }, 30);
+ }
+ const callsAtOpen = fetchMock.mock.calls.length;
+ expect(callsAtOpen).toBe(5); // each attempt hit the network while the circuit was closed
+
+ // Circuit is now open — further commands must short-circuit to memory and
+ // NOT touch the network at all.
+ await cacheSet('circuit:after', { v: 'x' }, 30);
+ await cacheGet('circuit:after-get');
+ expect(fetchMock).toHaveBeenCalledTimes(callsAtOpen); // no new fetches
+
+ // The value written while open is still readable from the in-memory fallback.
+ expect(await cacheGet('circuit:after')).toEqual({ v: 'x' });
+
+ // Exactly one "circuit opened" notice is logged — not one warning per request.
+ const openWarnings = warn.mock.calls.filter((c) => String(c[0]).includes('circuit opened'));
+ expect(openWarnings).toHaveLength(1);
+ });
+});
diff --git a/tests/http-method-head.test.js b/tests/http-method-head.test.js
new file mode 100644
index 000000000..e86aff6a3
--- /dev/null
+++ b/tests/http-method-head.test.js
@@ -0,0 +1,59 @@
+/**
+ * http.js method() — HEAD handling.
+ *
+ * Regression guard for a production 504: a HEAD probe to an endpoint that allows
+ * GET passed method()'s allowlist (HEAD is GET per RFC 9110 §9.3.2) but the
+ * downstream handler dispatched on `req.method === 'GET'` (exact equality), so the
+ * HEAD request fell through every branch, never responded, and hung until the
+ * function's hard timeout. method() now normalizes an admitted HEAD to GET on the
+ * request object so that equality dispatch runs. Safe because Node's ServerResponse
+ * already captured the HEAD-ness at construction and strips the body regardless.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { method } from '../api/_lib/http.js';
+
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 0,
+ body: undefined,
+ ended: false,
+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ _headers: headers,
+ };
+}
+
+describe('method() HEAD normalization', () => {
+ it('admits a HEAD where GET is allowed and rewrites req.method to GET', () => {
+ const req = { method: 'HEAD' };
+ const res = fakeRes();
+ expect(method(req, res, ['GET', 'PUT', 'PATCH', 'DELETE'])).toBe(true);
+ // The load-bearing fix: downstream `if (req.method === 'GET')` must now run.
+ expect(req.method).toBe('GET');
+ expect(res.ended).toBe(false); // no 405 written
+ });
+
+ it('rejects HEAD where GET is not allowed, advertising the allowed methods', () => {
+ const req = { method: 'HEAD' };
+ const res = fakeRes();
+ expect(method(req, res, ['POST'])).toBe(false);
+ expect(req.method).toBe('HEAD'); // untouched — not normalized
+ expect(res.statusCode).toBe(405);
+ expect(res.getHeader('allow')).toBe('POST');
+ });
+
+ it('leaves a real GET untouched and advertises HEAD alongside it on rejection', () => {
+ const req = { method: 'GET' };
+ const res = fakeRes();
+ expect(method(req, res, ['GET'])).toBe(true);
+ expect(req.method).toBe('GET');
+
+ const req2 = { method: 'DELETE' };
+ const res2 = fakeRes();
+ expect(method(req2, res2, ['GET'])).toBe(false);
+ expect(res2.getHeader('allow')).toBe('GET, HEAD');
+ });
+});