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
feat(ops): sniper worker joins the watchdog + gains a dead-man switch
fudjia9daad7019c33
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6910df535..90bf911f4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **@three-ws/retarget — the animation engine behind every avatar, now a standalone package** — The rig-agnostic animation system that powers all three.ws avatars is now on npm as @three-ws/retarget. It maps bone names from Mixamo, VRM/VRoid, Avaturn, Daz, MakeHuman, Unreal, and Blender rigs onto one canonical skeleton, retargets any clip onto any humanoid with rest-pose and hip-axis correction, and ships the crossfading runtime that keeps characters from ever freezing in a T-pose. Only dependency: your own copy of Three.js. Same engine, same tests (2,800 lines of them) — now usable in any Three.js project. `[sdk, feature]`- **2,000+ new motion-capture animations in the library** — The animation library just grew from around 100 curated clips to over 2,000 — the full professional motion-capture set, every one retargeted to the universal three.ws skeleton so it plays on any humanoid avatar. Walks, runs, dances, combat, idles, reactions, sports, and hundreds more are all searchable in the animations gallery, previewable on a live avatar, and one click away from the pose studio or any embed. The clips are served from the CDN, so the site stays fast no matter how big the library gets. (`/animations`) `[feature, improvement]`- **The agent economy now watches itself and pages the team** — After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began. `[improvement, infra]`+- **The sniper engine now pages us when it goes down — and restarts itself** — The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing. (`/status`) `[fix, infra]`## 2026-07-04diff --git a/api/_lib/ops/subsystem-health.js b/api/_lib/ops/subsystem-health.jsindex d0425721e..d90de539b 100644--- a/api/_lib/ops/subsystem-health.js+++ b/api/_lib/ops/subsystem-health.js@@ -9,8 +9,8 @@// live in the 2026-07-03 production log export yet invisible to a reachability// probe. This module reads the in-process degradation state each subsystem// already tracks (cache circuit breaker, Helius breaker, ring invariants) plus a-// live DB ping and the world-health cron's parked outcome, and rolls them into-// one structured verdict.+// live DB ping, the world-health cron's parked outcome, and the sniper worker's+// bot_heartbeat row, and rolls them into one structured verdict.//// Consumed by:// - api/healthz.js → `subsystems` block (live, per-request)@@ -40,6 +40,13 @@ const WORLD_HEALTH_CACHE_KEY = 'world:health';// A parked world-health outcome older than this is treated as stale/unknown// rather than trusted — the 15-min cron should refresh it well within the window.const WORLD_STALE_MS = 90 * 60 * 1000;+// Sniper worker heartbeat (bot_heartbeat, worker='agent-sniper'). It beats every+// ~30s; /api/sniper/status calls it dead past 90s. For paging we use a wider+// window so a deploy blip doesn't page, but a real death pages within two ticks.+// The 2026-07-03 outage (heartbeat frozen 36h, oracle scoring flat-lined, zero+// alerts) is exactly the failure this check exists to catch.+const SNIPER_FRESH_MS = 90_000;+const SNIPER_DOWN_MS = 10 * 60 * 1000;/** Statuses that pull the overall roll-up down, worst first. */const UNHEALTHY = ['down', 'degraded'];@@ -186,6 +193,63 @@ async function checkWorld() {}}+/**+ * Classify the sniper worker's heartbeat row into a subsystem record. Pure —+ * exported for tests; checkSniper() feeds it the live bot_heartbeat row.+ * @param {{ mode?: string, last_beat_at?: string|Date, meta?: object }|null|undefined} beat+ * @param {number} [now]+ */+export function classifySniperBeat(beat, now = Date.now()) {+ const base = { name: 'sniper', label: 'Sniper worker (Cloud Run)' };+ if (!beat) {+ return { ...base, status: 'unknown', detail: 'no heartbeat reported yet' };+ }+ const lastBeatMs = beat.last_beat_at ? new Date(beat.last_beat_at).getTime() : 0;+ const ageMs = lastBeatMs ? now - lastBeatMs : Number.POSITIVE_INFINITY;+ const meta = beat.meta && typeof beat.meta === 'object' ? beat.meta : {};+ if (ageMs > SNIPER_DOWN_MS) {+ const ageNote = Number.isFinite(ageMs) ? `${Math.round(ageMs / 60_000)} min old` : 'never recorded';+ return {+ ...base,+ status: 'down',+ detail: `heartbeat ${ageNote} (mode=${beat.mode || 'unknown'}) — worker dead or its DB writes are failing; oracle scoring and all sniping are stopped`,+ hint: 'Restart the Cloud Run service: npm run deploy:sniper from a gcloud-authed machine (project aerial-vehicle-466722-p5). See deploy/sniper/README.md.',+ };+ }+ if (ageMs > SNIPER_FRESH_MS) {+ return { ...base, status: 'degraded', detail: `heartbeat ${Math.round(ageMs / 1000)}s old — worker slow or mid-restart` };+ }+ const watchdogMs = Number(meta.feedWatchdogMs) || 180_000;+ if (meta.feedConnected !== true || Number(meta.lastEventAgeMs) > watchdogMs) {+ return {+ ...base,+ status: 'degraded',+ detail: 'worker alive but the PumpPortal feed is not live — no launches are being scored',+ hint: 'The worker self-reconnects; if this persists past an hour, check PumpPortal status and the worker logs.',+ };+ }+ return {+ ...base,+ status: 'ok',+ detail: `live (mode=${beat.mode || 'unknown'}, ${meta.strategies ?? '?'} strategies armed)`,+ };+}++async function checkSniper() {+ const base = { name: 'sniper', label: 'Sniper worker (Cloud Run)' };+ try {+ const { sql } = await import('../db.js');+ const [beat] = await sql`+ SELECT mode, last_beat_at, meta FROM bot_heartbeat+ WHERE worker = 'agent-sniper'+ LIMIT 1+ `;+ return classifySniperBeat(beat);+ } catch (err) {+ return { ...base, status: 'unknown', detail: err?.message || 'heartbeat unreadable' };+ }+}+function checkX402Config() {const base = { name: 'x402_config', label: 'x402 payment config' };try {@@ -224,6 +288,7 @@ export async function gatherSubsystemHealth({ probeDb = true } = {}) {Promise.resolve(checkRing()),checkWorld(),Promise.resolve(checkX402Config()),+ probeDb ? checkSniper() : Promise.resolve({ name: 'sniper', label: 'Sniper worker (Cloud Run)', status: 'unknown', detail: 'probe skipped' }),];const subsystems = await Promise.all(checks);diff --git a/data/changelog.json b/data/changelog.jsonindex 8e673545c..d07add9c3 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -11236,6 +11236,16 @@"tags": ["fix"]+ },+ {+ "date": "2026-07-05",+ "title": "The sniper engine now pages us when it goes down — and restarts itself",+ "summary": "The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/status"}]}diff --git a/deploy/sniper/README.md b/deploy/sniper/README.mdindex 2ae2c25ee..47222de6f 100644--- a/deploy/sniper/README.md+++ b/deploy/sniper/README.md@@ -76,6 +76,7 @@ shared ops-alert credentials and may already exist for other workers — reuse t| `SNIPER_NETWORK` | `mainnet` | `mainnet` \| `devnet`. || `SNIPER_GLOBAL_KILL` | `0` | `1` halts all **new** buys; open positions still manage/exit. || `SNIPER_HEARTBEAT_MS` | `30000` | Liveness heartbeat cadence → `bot_heartbeat` → `/api/sniper/status`. |+| `SNIPER_HEARTBEAT_SELF_HEAL_MS` | `900000` | Dead-man switch: heartbeat writes failing continuously this long → `exit(1)` so Cloud Run restarts the worker with fresh connections/secrets (kills the up-but-zombie failure mode). `0` disables. || `SNIPER_FEED_WATCHDOG_MS` | `180000` | Re-subscribe + alert if the feed is silent this long. || `SNIPER_ERROR_ALERT_THRESHOLD` / `_WINDOW_MS` | `5` / `600000` | Executor/RPC errors in the window that trip an ops alert. || `SNIPER_ANNOUNCE` | `1` | Announce boot/shutdown to the ops channel. |diff --git a/docs/economy-heartbeat.md b/docs/economy-heartbeat.mdindex 346643512..31b810f67 100644--- a/docs/economy-heartbeat.md+++ b/docs/economy-heartbeat.md@@ -110,6 +110,15 @@ no-op if unset, so set them):- **Money-feed silence** — no on-chain agent activity on `/api/pulse` for 90+minutes, the end-to-end signal that catches anything the per-engine checksmiss.+- **Sniper worker dead** — the Cloud Run worker's `bot_heartbeat` row stale for+ 10+ minutes (worker crashed, crash-looping, or zombied on dead DB writes;+ oracle scoring and all sniping stop with it). Surfaced as the `sniper`+ subsystem in `/api/status` and paged through the subsystem digest. The July+ 2026 outage — heartbeat frozen 36 hours, `scored_24h` flat at 0, zero pages —+ is exactly this. The worker also carries its own dead-man switch now: if its+ heartbeat writes fail continuously for 15 minutes+ (`SNIPER_HEARTBEAT_SELF_HEAL_MS`, 0 disables), it exits so Cloud Run restarts+ it with fresh connections and freshly resolved secrets.Escalation is streak-gated like the subsystem digest: page on first sight,re-page hourly while the problem persists (so a stall can't hide behind onediff --git a/public/changelog.json b/public/changelog.jsonindex 5c6417b0f..fcd85d0c6 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T08:21:26.866Z",+ "generated_at": "2026-07-05T08:29:37.932Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -39,6 +39,17 @@"infra"]},+ {+ "date": "2026-07-05",+ "type": "update",+ "title": "The sniper engine now pages us when it goes down — and restarts itself",+ "summary": "The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing.",+ "link": "/status",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-04","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex db3f5a2b7..029e673fd 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>improvement</category><description>After weeks of the agent-to-agent economy silently stalling and being diagnosed hours late, the platform now monitors it as a system: every 5 minutes it checks that the per-minute heartbeat is alive, that no engine is failing or stuck on a fixable problem (missing config, an unfundable payment, a full database), and that real on-chain agent activity is still flowing. Any of those pages the ops channel immediately, keeps re-paging hourly until fixed, and announces recovery. The status page's JSON feed also keeps 24 hours of health history so anyone can see exactly when a stall began.</description></item>+ <item>+ <title>The sniper engine now pages us when it goes down — and restarts itself</title>+ <link>https://three.ws/status</link>+ <guid isPermaLink="false">2026-07-05:The sniper engine now pages us when it goes down — and restarts itself</guid>+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The on-chain sniper worker went quiet on July 3 and nothing noticed: the status page showed the engine offline and zero launches scored, but no alert fired. The platform's watchdog now checks the sniper's own heartbeat every 5 minutes and pages the ops channel within 10 minutes of a stall, with hourly re-pages until it recovers. The worker also gained a dead-man switch: if it loses its database for 15 minutes straight it restarts itself instead of running as a zombie that scores nothing.</description>+ </item><item><title>Markets — Live Crypto Prices</title><link>https://three.ws/coins</link>diff --git a/tests/agent-sniper-ops.test.js b/tests/agent-sniper-ops.test.jsindex 1494a1948..c5fc1492a 100644--- a/tests/agent-sniper-ops.test.js+++ b/tests/agent-sniper-ops.test.js@@ -12,6 +12,7 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { loadConfig } from '../workers/agent-sniper/config.js';import { makeErrorTracker } from '../workers/agent-sniper/error-tracker.js';+import { shouldSelfHeal } from '../workers/agent-sniper/heartbeat.js';const SNIPER_KEYS = Object.keys(process.env).filter((k) => k.startsWith('SNIPER_'));@@ -132,3 +133,25 @@ describe('agent-sniper error-spike tracker', () => {expect(t.total).toBe(2);});});++// Heartbeat dead-man switch — the worker must restart itself (Cloud Run brings+// it back with fresh connections + secrets) once heartbeat writes have failed+// continuously past the self-heal window, instead of running as a 36-hour+// zombie the way it did on 2026-07-03. Transient blips inside the window must+// NOT trigger it, and 0 disables it.+describe('agent-sniper heartbeat self-heal verdict', () => {+ const NOW = 1_800_000_000_000;++ it('does not fire inside the failure window (a Neon blip is not a death)', () => {+ expect(shouldSelfHeal(NOW - 5 * 60_000, NOW, 15 * 60_000)).toBe(false);+ });++ it('fires once writes have failed continuously past the window', () => {+ expect(shouldSelfHeal(NOW - 16 * 60_000, NOW, 15 * 60_000)).toBe(true);+ });++ it('is disabled by a non-positive window', () => {+ expect(shouldSelfHeal(NOW - 10 * 3_600_000, NOW, 0)).toBe(false);+ expect(shouldSelfHeal(NOW - 10 * 3_600_000, NOW, -1)).toBe(false);+ });+});diff --git a/tests/api/uptime-status.test.js b/tests/api/uptime-status.test.jsindex a3536e64f..4979d22b6 100644--- a/tests/api/uptime-status.test.js+++ b/tests/api/uptime-status.test.js@@ -82,6 +82,10 @@ beforeEach(() => {upstream.failIds.clear();sendOpsAlert.mockClear();process.env.CRON_SECRET = 'test-secret';+ // A fresh, healthy economy heartbeat so the economy watchdog inside the cron+ // stays quiet — its own alerting (dead heartbeat, engine problems, feed+ // silence) is covered by the watchdog cases, not the reachability ones.+ cache.set('economy:last-tick', { t: Date.now(), fired: 1, failed: 0, engines: [] });global.fetch = vi.fn(async (url) => {const u = new URL(String(url));const target = UPTIME_TARGETS.find((t) => u.pathname + u.search === t.path);diff --git a/tests/subsystem-health.test.js b/tests/subsystem-health.test.jsindex 91c720d1c..6041c0d87 100644--- a/tests/subsystem-health.test.js+++ b/tests/subsystem-health.test.js@@ -12,7 +12,7 @@*/import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { gatherSubsystemHealth } from '../api/_lib/ops/subsystem-health.js';+import { gatherSubsystemHealth, classifySniperBeat } from '../api/_lib/ops/subsystem-health.js';import { cacheSet } from '../api/_lib/cache.js';// Env the ring + x402-config checks read. Save/restore so cases don't leak.@@ -141,6 +141,11 @@ describe('gatherSubsystemHealth', () => {expect(sub(health, 'database').status).toBe('unknown');});+ it('skips the sniper heartbeat probe when probeDb is false (sniper → unknown)', async () => {+ const health = await gatherSubsystemHealth({ probeDb: false });+ expect(sub(health, 'sniper').status).toBe('unknown');+ });+it('rolls the overall verdict to the worst subsystem and lists degraded names', async () => {process.env.X402_PAY_TO_SOLANA = 'THREEsynthetic1111111111111111111111111111111';delete process.env.X402_FEE_PAYER_SOLANA; // → x402_config degraded@@ -151,3 +156,53 @@ describe('gatherSubsystemHealth', () => {expect(Object.values(health.counts).reduce((a, b) => a + b, 0)).toBe(health.subsystems.length);});});++// The sniper-worker heartbeat classifier — pins the exact failure that went+// unpaged on 2026-07-03: heartbeat frozen for 36h while /api/oracle/stats+// flat-lined at scored_24h=0. A stale beat must classify as DOWN (which the+// uptime cron escalates to Telegram), not blend into "ok".+describe('classifySniperBeat', () => {+ const NOW = 1_800_000_000_000;+ const beat = (ageMs, meta = {}, mode = 'live') => ({+ mode,+ last_beat_at: new Date(NOW - ageMs).toISOString(),+ meta,+ });+ const liveMeta = { feedConnected: true, lastEventAgeMs: 2_000, feedWatchdogMs: 180_000, strategies: 6 };++ it('reports UNKNOWN when no heartbeat row exists (fresh deploy, never started)', () => {+ expect(classifySniperBeat(null, NOW).status).toBe('unknown');+ });++ it('reports OK for a fresh beat with a live feed', () => {+ const s = classifySniperBeat(beat(30_000, liveMeta), NOW);+ expect(s.status).toBe('ok');+ expect(s.detail).toContain('mode=live');+ });++ it('reports DOWN with a redeploy hint once the heartbeat is stale (the 2026-07-03 outage)', () => {+ const s = classifySniperBeat(beat(36 * 3_600_000, liveMeta), NOW);+ expect(s.status).toBe('down');+ expect(s.detail).toContain('2160 min');+ expect(s.hint).toContain('deploy:sniper');+ });++ it('reports DEGRADED between fresh and dead (mid-restart window)', () => {+ expect(classifySniperBeat(beat(3 * 60_000, liveMeta), NOW).status).toBe('degraded');+ });++ it('reports DEGRADED when alive but the feed is disconnected', () => {+ const s = classifySniperBeat(beat(30_000, { ...liveMeta, feedConnected: false }), NOW);+ expect(s.status).toBe('degraded');+ expect(s.detail).toContain('feed');+ });++ it('reports DEGRADED when alive but the feed has been silent past its watchdog window', () => {+ const s = classifySniperBeat(beat(30_000, { ...liveMeta, lastEventAgeMs: 240_000 }), NOW);+ expect(s.status).toBe('degraded');+ });++ it('treats a row with no last_beat_at as DOWN, not ok', () => {+ expect(classifySniperBeat({ mode: 'live', last_beat_at: null, meta: {} }, NOW).status).toBe('down');+ });+});diff --git a/workers/agent-sniper/heartbeat.js b/workers/agent-sniper/heartbeat.jsindex 403e5edbe..371c58a2f 100644--- a/workers/agent-sniper/heartbeat.js+++ b/workers/agent-sniper/heartbeat.js@@ -23,11 +23,23 @@//// Best-effort: a DB blip must never crash the trade loop, so every write is// guarded. Secrets are never written here.+//+// Dead-man switch: swallowing DB errors forever creates the OTHER catastrophic+// failure mode — the 2026-07-03 outage, where the process stayed up while every+// DB write failed for 36 hours (heartbeat frozen, scores unrecorded, positions+// unmanageable, nothing paged). If heartbeat writes fail continuously past+// SNIPER_HEARTBEAT_SELF_HEAL_MS, the worker exits(1) so Cloud Run+// (minScale=1, CPU always on) restarts it with fresh connections and freshly+// resolved secrets. A restart loses nothing a dead DB hasn't already lost —+// strategies and positions live in that same DB.import { sql } from '../../api/_lib/db.js';import { log } from './log.js';const WORKER = 'agent-sniper';+// How long heartbeat writes may fail continuously before the worker restarts+// itself. Well past any transient Neon blip or brief network partition; 0 disables.+const SELF_HEAL_AFTER_MS = Number(process.env.SNIPER_HEARTBEAT_SELF_HEAL_MS ?? 15 * 60_000);/*** Upsert the sniper's heartbeat row. Fire-and-forget safe — swallows DB errors@@ -35,7 +47,8 @@ const WORKER = 'agent-sniper';* sustained DB outage is visible in the worker's own logs.** @param {string} mode simulate | live- * @param {() => object} snapshot returns the current operational meta+ * @param {object} meta the current operational meta+ * @returns {Promise<boolean>} whether the write landed*/export async function writeHeartbeat(mode, meta) {try {@@ -47,11 +60,25 @@ export async function writeHeartbeat(mode, meta) {last_beat_at = excluded.last_beat_at,meta = excluded.meta`;+ return true;} catch (err) {log.warn('heartbeat write failed', { err: err?.message });+ return false;}}+/**+ * Dead-man verdict: should the worker restart itself? True once heartbeat+ * writes have failed continuously past the self-heal window. Pure — exported+ * for tests.+ * @param {number} lastOkAt epoch ms of the last successful write+ * @param {number} now epoch ms+ * @param {number} [afterMs] continuous-failure window; <=0 disables+ */+export function shouldSelfHeal(lastOkAt, now, afterMs = SELF_HEAL_AFTER_MS) {+ return afterMs > 0 && now - lastOkAt > afterMs;+}+/*** Start a heartbeat loop. Writes immediately, then every `intervalMs`. Returns a* stop function. `getMeta` is called on every beat so the row always reflects@@ -65,7 +92,22 @@ export async function writeHeartbeat(mode, meta) {* @returns {() => void} stop*/export function startHeartbeat({ mode, intervalMs, getMeta }) {- const beat = () => writeHeartbeat(mode, safeMeta(getMeta));+ let lastOkAt = Date.now();+ const beat = async () => {+ const ok = await writeHeartbeat(mode, safeMeta(getMeta));+ if (ok) {+ lastOkAt = Date.now();+ return;+ }+ if (shouldSelfHeal(lastOkAt, Date.now())) {+ const deadMs = Date.now() - lastOkAt;+ log.error('heartbeat writes dead — exiting so Cloud Run restarts the worker', {+ deadMs,+ selfHealAfterMs: SELF_HEAL_AFTER_MS,+ });+ process.exit(1);+ }+ };beat();const timer = setInterval(beat, intervalMs);if (typeof timer.unref === 'function') timer.unref();