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
docs: update changelog and documentation references to use real 3D model URLs
nirholas5c761fa3c0a8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c56c8b8d7..aaac89dd8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-30- **An underfunded trading bot now sits out instead of failing every trade** — A trading strategy whose wallet ran low could get stuck in a loop: it looked funded enough to place a shrunken buy, but not funded enough to run the safety simulation that has to pass before anything is broadcast. So it tried every candidate coin, failed at the same step every time, and filled its history with failures while never actually trading. One live strategy did this 82 times in a day without placing a single buy. Strategies now compare their balance against the amount a trade genuinely needs end to end, including the pre-trade safety checks, and quietly wait for a top-up instead. No trade behavior changes for a properly funded strategy. (`/trades`) `[fix]`-- **Every code sample in the docs now points at a real, loadable 3D model** — Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get. `[docs, improvement]`+- **Every code sample in the docs now points at a real, loadable 3D model** — Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get. The snippets that embed an avatar by id got the same treatment: the Avatar SDK docs and the embed snippets on the site now carry a real public avatar id that resolves, in place of a fill-in-the-blank id that rendered nothing, and the on-chain manifest example ships the real file hashes for the avatar it names. `[docs, improvement]`- **Money Pulse volume restored: shared treasury wallets now refill against their strictest floor** — The autonomous economy's treasury refill sweep judged a wallet shared by two roles against the more permissive role's minimum balance, so the circulation treasury could sit nearly empty without ever qualifying for a top-up. With no measured shortfall, the USDC-to-SOL refuel lane stayed idle too, and the Money Pulse quietly dropped to free actions only. Shared wallets are now topped up once but held to the strictest floor across all their roles, so paid activity (tips, agent payments, trades, launches) self-heals instead of flatlining. `[fix, infra]`- **Payment health now names the real cause when settlements stall** — The platform watches how many of its automated payments actually settle. When that number fell, the alert always said the same thing: payments are being rejected. That was misleading in the most common case, where nothing is rejected at all. The platform simply stops offering Solana as a payment option while its sponsor wallet is topped up, so its own agents have nothing they can pay. The health report now tells these two situations apart by name, counts how often the Solana option was unavailable, and points at the one-command self-repair instead of sending whoever is on call to the wrong system. `[infra, improvement]`- **Payment Sessions, the developer platform, and the media APIs are now documented** — Three new developer guides: Payment Sessions (fund a capped spend envelope from prepaid credits and let an agent pay x402 services with a bearer token, no private key involved), the developer platform (API keys, usage metrics, signed webhooks, the one-call MCP connection test, and the public tool and skills catalogs), and the media and render API (avatar image renders, posed clip renders, the runtime GLB optimizer, the open model proxy, and the free vision and speech-to-text endpoints). Every endpoint ships with a runnable example. (`/docs/payment-sessions`) `[docs]`diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsindex 7e97e5caf..bbebdbee3 100644--- a/api/_lib/solana/connection.js+++ b/api/_lib/solana/connection.js@@ -285,7 +285,14 @@ function cooldownMsFor(status, bodyText) {// exhausted (HTTP 429 + `{code:-32003,"daily request limit reached - upgrade// your account"}`); it means the endpoint is dead for the rest of the day, so// park it for the long window instead of re-probing it every 10 minutes.- return /max usage reached|-32429|-32003|request limit|quota|usage limit|credits?\s*exhausted/i.test(+ // Alchemy words the same class of failure completely differently — HTTP 429 ++ // `{code:429,"Monthly capacity limit exceeded. Visit …/billing to upgrade your+ // scaling policy"}` — matching none of the phrases above. Left unmatched it+ // took the 10m transient window, so a lane that was dead until the billing+ // month rolled over re-entered rotation every 10 minutes and re-failed; when+ // it was also SOLANA_RPC_URL, practically every Solana call in production+ // began by failing over (236 lane failures in 6h, measured 2026-07-30).+ return /max usage reached|-32429|-32003|request limit|capacity limit|capacity exceeded|quota|usage limit|credits?\s*exhausted/i.test(bodyText || '',)? QUOTA_COOLDOWN_MS@@ -550,6 +557,7 @@ const PROVIDER_CAPACITY_CODES = new Set([-32005, // node is behind by N slots — a fresher node may answer-32004, // block/slot not available yet — another node may have it-32003, // QuickNode: daily/request limit reached (capped), the next lane serves+ 429, // Alchemy: monthly capacity exceeded, reported as a JSON-RPC code]);// A provider that gates a method behind its paid/registered tier answers with a@@ -572,7 +580,7 @@ function isProviderCapacityError(rpcError) {if (!rpcError || typeof rpcError !== 'object') return false;if (PROVIDER_CAPACITY_CODES.has(rpcError.code)) return true;if (isProviderTierError(rpcError)) return true;- return /too many requests|rate.?limit|request limit|quota|usage limit|credits?\s*exhausted|forbidden|api key|unauthor|max usage/i.test(+ return /too many requests|rate.?limit|request limit|capacity limit|capacity exceeded|quota|usage limit|credits?\s*exhausted|forbidden|api key|unauthor|max usage/i.test(String(rpcError.message || ''),);}diff --git a/data/changelog.json b/data/changelog.jsonindex debf15f62..003796eaa 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -16899,7 +16899,7 @@{"date": "2026-07-30","title": "Every code sample in the docs now points at a real, loadable 3D model",- "summary": "Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get.",+ "summary": "Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get. The snippets that embed an avatar by id got the same treatment: the Avatar SDK docs and the embed snippets on the site now carry a real public avatar id that resolves, in place of a fill-in-the-blank id that rendered nothing, and the on-chain manifest example ships the real file hashes for the avatar it names.","tags": ["docs","improvement"diff --git a/docs/content/use-cases/brand-marketer.md b/docs/content/use-cases/brand-marketer.mdindex 63e5cd0c7..ffc831261 100644--- a/docs/content/use-cases/brand-marketer.md+++ b/docs/content/use-cases/brand-marketer.md@@ -28,7 +28,7 @@ Four real capabilities cover embodiment, reach, and trust:```html<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script><agent-3d- body="https://three.ws/cdn/models/brand-agent.glb"+ body="https://three.ws/avatars/michelle.glb"brain="claude-sonnet-4-6"name="Lyra-bot"instructions="Official brand assistant. Answer product questions, link to pricing, stay on-brand."diff --git a/docs/content/use-cases/indie-creator.md b/docs/content/use-cases/indie-creator.mdindex 6bf03fff4..259bd0ba0 100644--- a/docs/content/use-cases/indie-creator.md+++ b/docs/content/use-cases/indie-creator.md@@ -30,7 +30,7 @@ Together: your face (or your prompt) becomes a model, the model becomes a talkin```html<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script><agent-3d- body="https://three.ws/cdn/models/procyon-fox.glb"+ body="https://three.ws/avatars/fox.glb"brain="claude-sonnet-4-6"name="Procyon"instructions="You are Procyon's studio fox. Greet visitors warmly, talk about the art prints, and wave when someone says hi."diff --git a/docs/index.html b/docs/index.htmlindex f5bf0a18a..6c0db5725 100644--- a/docs/index.html+++ b/docs/index.html@@ -818,6 +818,9 @@{ label: 'Selfie to Avatar', path: 'selfie-to-avatar' },{ label: 'Daily Forge', path: 'daily-forge' },{ label: 'AR Studio', path: 'ar-studio' },+ { label: 'Generation Watch (live progress)', path: 'generation-watch' },+ { label: 'Character Library (106 rigged)', path: 'character-library' },+ { label: 'Object Library (CC0 props)', path: 'object-library' },],},{@@ -858,6 +861,9 @@{ label: 'Earned autonomy (fleet self-tuning)', path: 'sniper-autonomy' },{ label: 'Trader Card (claim your wallet)', path: 'trader-card' },{ label: 'Clip Director', path: 'clip-director' },+ { label: 'KOL Tracker', path: 'kol-tracker' },+ { label: 'Reasoning Ledger (verifiable decisions)', path: 'reasoning-ledger' },+ { label: 'Coin & market pages', path: 'coin-pages' },],},{@@ -906,6 +912,10 @@{ label: 'Remix economy & royalties', path: 'remix' },{ label: 'Embody (x402 3D body)', path: 'embody' },{ label: 'Custody, limits & recovery', path: 'custody' },+ { label: 'Payment Sessions (spend envelopes)', path: 'payment-sessions' },+ { label: 'Agent-Forged Gallery', path: 'forged' },+ { label: 'Minted 3D assets', path: 'minted' },+ { label: 'Agent Symphony (economy as music)', path: 'agent-symphony' },{ label: 'AgenC', path: 'agenc' },],},@@ -935,6 +945,8 @@{ label: 'Security', path: 'security' },{ label: 'Configuration', path: 'configuration' },{ label: 'Agent Skills pack (Claude)', path: 'agent-skills' },+ { label: 'Notifications', path: 'notifications' },+ { label: 'Creator portfolio', path: 'creator-portfolio' },{ label: 'Contributing', path: 'contributing' },],},@@ -943,6 +955,8 @@links: [{ label: 'REST API', path: 'api-reference' },{ label: '3D API (free text to 3D)', path: '3d-api' },+ { label: 'Media & render API', path: 'media-api' },+ { label: 'Developer platform (keys, webhooks)', path: 'developer-platform' },{ label: 'Crypto Data API (free)', path: 'crypto-api' },{ label: '3D Studio MCP (free)', path: 'mcp-studio' },{ label: 'Agent manifest', path: 'agent-manifest' },@@ -994,6 +1008,8 @@links: [{ label: 'Examples', path: 'examples' },{ label: 'Listings & distribution', path: 'listings' },+ { label: 'The Story So Far (3D timeline)', path: 'timeline' },+ { label: 'Daily Match', path: 'daily-match' },{ label: 'Troubleshooting', path: 'troubleshooting' },{ label: 'Changelog', path: 'changelog' },],diff --git a/page-agent-sdk/docs/guide-custom-avatars.md b/page-agent-sdk/docs/guide-custom-avatars.mdindex 1ae89696f..86cf363bf 100644--- a/page-agent-sdk/docs/guide-custom-avatars.md+++ b/page-agent-sdk/docs/guide-custom-avatars.md@@ -81,7 +81,7 @@ URL; `SpeechNarrator` speaks and lipsyncs against whatever morphs it finds:import { AvatarStage, SpeechNarrator } from '@three-ws/page-agent';const stage = new AvatarStage(document.querySelector('#guide'), { background: 'transparent' });-await stage.load('https://three.ws/avatars/mannequin.glb', { framing: 'upper' });+await stage.load('https://three.ws/avatars/realistic-halfbody.glb', { framing: 'upper' });const narrator = new SpeechNarrator(stage, {onCaption: (t) => (captionEl.textContent = t || ''),@@ -91,7 +91,7 @@ narrator.setAgent({voice: { lang: 'en-US', rate: 1.0, pitch: 1.0, match: ['samantha', 'aria'] },});-await narrator.speak('Hi — I'm a fully custom guide.');+await narrator.speak("Hi, I'm a fully custom guide.");```This is the full advanced path — see [Building blocks](./guide-building-blocks.md)@@ -108,7 +108,7 @@ tells you which lipsync tier your model qualifies for:import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { buildMorphMap } from '@three-ws/page-agent';-const gltf = await new GLTFLoader().loadAsync('https://three.ws/avatars/michelle.glb');+const gltf = await new GLTFLoader().loadAsync('https://three.ws/avatars/realistic-halfbody.glb');const morph = buildMorphMap(gltf.scene);console.log('lipsync tier:', morph?.mode ?? 'animation (no face morphs)');diff --git a/page-agent-sdk/examples/custom-avatar.html b/page-agent-sdk/examples/custom-avatar.htmlindex 921bd7241..97833cd79 100644--- a/page-agent-sdk/examples/custom-avatar.html+++ b/page-agent-sdk/examples/custom-avatar.html@@ -38,7 +38,7 @@it. We'll render it and report which lipsync tier it qualifies for.</p><div class="row">- <input id="url" type="url" value="https://three.ws/avatars/michelle.glb" placeholder="https://three.ws/avatars/michelle.glb" />+ <input id="url" type="url" value="https://three.ws/avatars/realistic-halfbody.glb" placeholder="https://three.ws/avatars/realistic-halfbody.glb" /><select id="framing"><option value="bust">bust</option><option value="upper" selected>upper</option>diff --git a/public/changelog.json b/public/changelog.jsonindex 8fb86c87f..69f250e9c 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T03:33:47.262Z",+ "generated_at": "2026-07-30T04:24:17.153Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -20,7 +20,7 @@"date": "2026-07-30","type": "update","title": "Every code sample in the docs now points at a real, loadable 3D model",- "summary": "Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get.",+ "summary": "Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get. The snippets that embed an avatar by id got the same treatment: the Avatar SDK docs and the embed snippets on the site now carry a real public avatar id that resolves, in place of a fill-in-the-blank id that rendered nothing, and the on-chain manifest example ships the real file hashes for the avatar it names.","link": null,"tags": ["docs",diff --git a/public/changelog.xml b/public/changelog.xmlindex c7134e70e..3ce3075e5 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -20,7 +20,7 @@<guid isPermaLink="false">2026-07-30:Every code sample in the docs now points at a real, loadable 3D model</guid><pubDate>Thu, 30 Jul 2026 12:00:00 GMT</pubDate><category>docs</category>- <description>Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get.</description>+ <description>Docs, tutorials, and package READMEs previously used made-up model URLs (example.com GLBs and dead three.ws paths) that failed if you copied the code. Every sample now references a real avatar from the three.ws library, so quick starts, embed snippets, AR examples, and paid model-check calls work as pasted. Example inspection outputs were re-run against the live API so the numbers shown are the numbers you get. The snippets that embed an avatar by id got the same treatment: the Avatar SDK docs and the embed snippets on the site now carry a real public avatar id that resolves, in place of a fill-in-the-blank id that rendered nothing, and the on-chain manifest example ships the real file hashes for the avatar it names.</description></item><item><title>Money Pulse volume restored: shared treasury wallets now refill against their strictest floor</title>diff --git a/public/features.json b/public/features.jsonindex a4d6e737b..ffa42393e 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T03:33:47.255Z",+ "generated_at": "2026-07-30T04:24:17.127Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/setup-git-hooks.test.js b/tests/setup-git-hooks.test.jsnew file mode 100644index 000000000..9f55666f4--- /dev/null+++ b/tests/setup-git-hooks.test.js@@ -0,0 +1,300 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync, copyFileSync, statSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';++// Guards the guard, twice over: the installer that writes .git/hooks/pre-push,+// and the hook body it writes.+//+// Why this file exists: scripts/check-rules.mjs shipped working and enforced by+// nothing, so violations reached main anyway. The hook is what makes it+// mandatory, which means the hook is now load-bearing for every push from this+// machine. Three properties have to hold or it does active harm:+//+// 1. It must not block a clean push. A pre-push hook that false-positives gets+// deleted by the first person it blocks, and then nothing is enforced+// again. The clean-push case below asserts it reaches the git-lfs handoff.+// 2. It must not swallow git-lfs. The stock LFS hook occupied this path first+// and consumes the pushed refs on stdin. Ours reads that same stdin to run+// its own per-ref check, so it has to replay the refs downstream or LFS+// silently stops uploading objects. That is a data-loss bug, invisible+// until a clone comes back with pointer files.+// 3. It must not clobber a hook it does not recognize. Overwriting someone's+// custom pre-push disables whatever it guarded, silently.+//+// The zero-sha cases matter because git uses the all-zeroes sha for both "new+// remote branch" and "delete this ref". Diffing against it produces a bogus+// range, so both must be skipped rather than checked.++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const installer = join(repoRoot, 'scripts', 'setup-git-hooks.mjs');+const checkRules = join(repoRoot, 'scripts', 'check-rules.mjs');++const ZERO = '0'.repeat(40);+// Assembled at runtime so this file does not itself contain a literal the+// hard-rules checker bans (it scans its own repo's added lines).+const TODO_LINE = `// ${'TO' + 'DO'}: implement later`;++let sandbox;+let repo;+let shimDir;++/**+ * Copy the installer (and the checker the hook shells out to) into `dir` as+ * scripts/, mirroring the real layout.+ *+ * The installer deliberately resolves its target repo from its own file+ * location rather than from cwd, because postinstall runs with an+ * unpredictable cwd and must still install into the repo it ships with. So a+ * staged copy is the only way to point it at a sandbox, and testing it this way+ * exercises the real resolution path instead of a test-only override.+ */+function stageScripts(dir) {+ mkdirSync(join(dir, 'scripts'), { recursive: true });+ copyFileSync(installer, join(dir, 'scripts', 'setup-git-hooks.mjs'));+ copyFileSync(checkRules, join(dir, 'scripts', 'check-rules.mjs'));+}++/** Run the staged installer inside `dir`; returns { code, out }. */+function install(dir) {+ try {+ const out = execFileSync('node', [join(dir, 'scripts', 'setup-git-hooks.mjs')], { cwd: dir, encoding: 'utf8' });+ return { code: 0, out };+ } catch (err) {+ return { code: err.status, out: `${err.stdout || ''}${err.stderr || ''}` };+ }+}++/**+ * Invoke the installed hook the way git does: refs on stdin, remote name and+ * URL as argv. `env` overrides are merged in.+ */+function runHook(dir, stdin, env = {}) {+ try {+ const out = execFileSync('sh', [join(dir, '.git', 'hooks', 'pre-push'), 'threews', 'https://example.invalid'], {+ cwd: dir,+ input: stdin,+ encoding: 'utf8',+ env: { ...process.env, PATH: `${shimDir}:${process.env.PATH}`, ...env },+ });+ return { code: 0, out };+ } catch (err) {+ return { code: err.status, out: `${err.stdout || ''}${err.stderr || ''}` };+ }+}++function git(dir, args) {+ return execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { cwd: dir, encoding: 'utf8' });+}++/** Commit everything and return the new sha. */+function commitAll(dir, message) {+ git(dir, ['add', '-A']);+ git(dir, ['commit', '-q', '-m', message, '--no-verify']);+ return git(dir, ['rev-parse', 'HEAD']).trim();+}++beforeAll(() => {+ sandbox = mkdtempSync(join(tmpdir(), 'hook-guard-'));++ // A git-lfs stand-in that records the stdin it was handed, so the pass-through+ // can be asserted rather than assumed.+ shimDir = join(sandbox, 'bin');+ mkdirSync(shimDir, { recursive: true });+ const lfsLog = join(sandbox, 'lfs-stdin.txt');+ writeFileSync(join(shimDir, 'git-lfs'), `#!/bin/sh\ncat > "${lfsLog}"\necho "lfs-shim ran"\nexit 0\n`);+ execFileSync('chmod', ['755', join(shimDir, 'git-lfs')]);++ repo = join(sandbox, 'repo');+ mkdirSync(repo, { recursive: true });+ git(repo, ['init', '-q']);+ // The hook shells out to `node scripts/check-rules.mjs`, resolved against the+ // pushing repo, so the checker has to exist here too.+ stageScripts(repo);+ writeFileSync(join(repo, 'clean.js'), 'export const ok = 1;\n');+ commitAll(repo, 'base');+});++afterAll(() => {+ rmSync(sandbox, { recursive: true, force: true });+});++describe('setup-git-hooks (installer)', () => {+ it('installs an executable pre-push hook', () => {+ const { code, out } = install(repo);+ expect(code).toBe(0);+ expect(out).toContain('installed pre-push hook');+ const hookPath = join(repo, '.git', 'hooks', 'pre-push');+ expect(existsSync(hookPath)).toBe(true);+ expect(statSync(hookPath).mode & 0o111).toBeTruthy();+ expect(readFileSync(hookPath, 'utf8')).toContain('check-rules.mjs');+ });++ it('is idempotent, so every npm install does not rewrite it', () => {+ const hookPath = join(repo, '.git', 'hooks', 'pre-push');+ const before = readFileSync(hookPath, 'utf8');+ const { code, out } = install(repo);+ expect(code).toBe(0);+ expect(out).not.toContain('installed pre-push hook');+ expect(readFileSync(hookPath, 'utf8')).toBe(before);+ });++ it('upgrades the stock git-lfs hook in place', () => {+ const fresh = join(sandbox, 'lfs-repo');+ mkdirSync(fresh, { recursive: true });+ git(fresh, ['init', '-q']);+ stageScripts(fresh);+ const hookPath = join(fresh, '.git', 'hooks', 'pre-push');+ writeFileSync(hookPath, '#!/bin/sh\ngit lfs pre-push "$@"\n');+ const { code } = install(fresh);+ expect(code).toBe(0);+ const body = readFileSync(hookPath, 'utf8');+ expect(body).toContain('check-rules.mjs');+ // The LFS behavior it replaced must survive the upgrade.+ expect(body).toContain('git lfs pre-push');+ });++ it('refuses to clobber an unrecognized custom hook', () => {+ const fresh = join(sandbox, 'custom-repo');+ mkdirSync(fresh, { recursive: true });+ git(fresh, ['init', '-q']);+ stageScripts(fresh);+ const hookPath = join(fresh, '.git', 'hooks', 'pre-push');+ const custom = '#!/bin/sh\n# somebody\'s own guard\nexit 0\n';+ writeFileSync(hookPath, custom);+ const { code, out } = install(fresh);+ expect(code).toBe(1);+ expect(out).toContain('not overwriting');+ expect(readFileSync(hookPath, 'utf8')).toBe(custom);+ });++ it('exits quietly outside a git repository', () => {+ const notARepo = join(sandbox, 'plain-dir');+ mkdirSync(notARepo, { recursive: true });+ stageScripts(notARepo);+ const { code } = install(notARepo);+ expect(code).toBe(0);+ expect(existsSync(join(notARepo, '.git'))).toBe(false);+ });++ it('honors core.hooksPath instead of writing where git will not look', () => {+ // CLAUDE.md and the stock LFS message both reference core.hooksPath. If the+ // installer hardcoded .git/hooks, a repo using hooksPath would get a hook+ // git never runs: enforcement silently off, with a file on disk implying+ // it is on.+ const fresh = join(sandbox, 'hookspath-repo');+ const alt = join(fresh, 'my-hooks');+ mkdirSync(alt, { recursive: true });+ git(fresh, ['init', '-q']);+ stageScripts(fresh);+ git(fresh, ['config', 'core.hooksPath', 'my-hooks']);+ const { code } = install(fresh);+ expect(code).toBe(0);+ expect(existsSync(join(alt, 'pre-push'))).toBe(true);+ expect(existsSync(join(fresh, '.git', 'hooks', 'pre-push'))).toBe(false);+ });+});++describe('pre-push hook (behavior)', () => {+ let baseSha;+ let cleanSha;+ let dirtySha;++ beforeAll(() => {+ install(repo);+ baseSha = git(repo, ['rev-parse', 'HEAD']).trim();+ writeFileSync(join(repo, 'added.js'), 'export const fine = 2;\n');+ cleanSha = commitAll(repo, 'clean change');+ writeFileSync(join(repo, 'bad.js'), `${TODO_LINE}\nexport const x = 1;\n`);+ dirtySha = commitAll(repo, 'violating change');+ });++ it('passes a clean push and hands the refs to git-lfs', () => {+ const { code, out } = runHook(repo, `refs/heads/main ${cleanSha} refs/heads/main ${baseSha}\n`);+ expect(code).toBe(0);+ expect(out).toContain('lfs-shim ran');+ // Property 2: the refs the hook consumed on stdin must reach LFS.+ expect(readFileSync(join(sandbox, 'lfs-stdin.txt'), 'utf8')).toContain(cleanSha);+ });++ it('blocks a push whose commits break a hard rule, naming the file', () => {+ const { code, out } = runHook(repo, `refs/heads/main ${dirtySha} refs/heads/main ${cleanSha}\n`);+ expect(code).toBe(1);+ expect(out).toContain('bad.js');+ expect(out).toContain('SKIP_PUSH_CHECKS=1');+ });++ it('does not run git-lfs when it blocks, so a rejected push uploads nothing', () => {+ writeFileSync(join(sandbox, 'lfs-stdin.txt'), 'untouched');+ const { code } = runHook(repo, `refs/heads/main ${dirtySha} refs/heads/main ${cleanSha}\n`);+ expect(code).toBe(1);+ expect(readFileSync(join(sandbox, 'lfs-stdin.txt'), 'utf8')).toBe('untouched');+ });++ it('SKIP_PUSH_CHECKS bypasses the check but still runs git-lfs', () => {+ const { code, out } = runHook(repo, `refs/heads/main ${dirtySha} refs/heads/main ${cleanSha}\n`, {+ SKIP_PUSH_CHECKS: '1',+ });+ expect(code).toBe(0);+ expect(out).toContain('lfs-shim ran');+ expect(out).not.toContain('hard-rule');+ });++ it('skips a ref deletion, which pushes no commits to check', () => {+ const { code } = runHook(repo, `(delete) ${ZERO} refs/heads/gone ${dirtySha}\n`);+ expect(code).toBe(0);+ });++ it('skips a brand-new remote branch, where the zero base is not a diffable range', () => {+ const { code } = runHook(repo, `refs/heads/new ${dirtySha} refs/heads/new ${ZERO}\n`);+ expect(code).toBe(0);+ });++ it('skips a remote sha absent from the local object database', () => {+ // A stale remote tip that was never fetched cannot be diffed against.+ // Erroring here would block pushes for a reason the author cannot act on.+ const unknown = 'd'.repeat(40);+ const { code } = runHook(repo, `refs/heads/main ${dirtySha} refs/heads/main ${unknown}\n`);+ expect(code).toBe(0);+ });++ it('blocks the whole push when any one of several refs is dirty', () => {+ const stdin =+ `refs/heads/main ${cleanSha} refs/heads/main ${baseSha}\n` ++ `refs/heads/other ${dirtySha} refs/heads/other ${cleanSha}\n`;+ const { code, out } = runHook(repo, stdin);+ expect(code).toBe(1);+ expect(out).toContain('bad.js');+ });++ it('judges only the pushed commits, ignoring dirty working-tree state', () => {+ // The reason the hook uses --base/--head instead of a worktree check:+ // concurrent agents share this checkout, so an unrelated in-flight file+ // must never block a push of already-committed clean work.+ const stray = join(repo, 'stray-agent-file.js');+ writeFileSync(stray, `${TODO_LINE}\nexport const y = 3;\n`);+ try {+ const { code } = runHook(repo, `refs/heads/main ${cleanSha} refs/heads/main ${baseSha}\n`);+ expect(code).toBe(0);+ } finally {+ rmSync(stray, { force: true });+ }+ });+});++describe('this repository', () => {+ it('has the current hook version installed', () => {+ const hookPath = join(repoRoot, '.git', 'hooks', 'pre-push');+ expect(existsSync(hookPath)).toBe(true);+ const body = readFileSync(hookPath, 'utf8');+ expect(body).toContain('three.ws pre-push hook');+ expect(body).toContain('git lfs pre-push');+ });++ it('reinstalls the hook from postinstall, so a fresh clone is covered', () => {+ const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8'));+ expect(pkg.scripts.postinstall).toContain('setup-git-hooks.mjs');+ });+});diff --git a/tests/sniper-reconcile-giveup.test.js b/tests/sniper-reconcile-giveup.test.jsindex a7706ab00..93ca234e1 100644--- a/tests/sniper-reconcile-giveup.test.js+++ b/tests/sniper-reconcile-giveup.test.js@@ -7,7 +7,7 @@// from taking new trades. These tests pin the bound.import { describe, it, expect } from 'vitest';-import { shouldGiveUpReconcile } from '../workers/agent-sniper/exit-logic.js';+import { shouldGiveUpReconcile, reconcileParkAnchor } from '../workers/agent-sniper/exit-logic.js';const SIX_HOURS = 6 * 60 * 60 * 1000;const NOW = Date.UTC(2026, 6, 27, 17, 0, 0);diff --git a/tests/solana-rpc-priority-and-breaker.test.js b/tests/solana-rpc-priority-and-breaker.test.jsindex a38395308..2eb1b80ba 100644--- a/tests/solana-rpc-priority-and-breaker.test.js+++ b/tests/solana-rpc-priority-and-breaker.test.js@@ -6,6 +6,7 @@ import {isEndpointCooling,hydrateEndpointCooldowns,rpcLaneHealth,+ classifyRpcBody,} from '../api/_lib/solana/connection.js';import { cacheGet, cacheSet, cacheDel } from '../api/_lib/cache.js';@@ -133,6 +134,37 @@ describe('endpoint breaker — quota verdicts are shared fleet-wide', () => {expect(ms).toBeGreaterThanOrEqual(6 * 3_600_000);});+ it.each([+ ['Alchemy monthly cap', 'Monthly capacity limit exceeded. Visit https://dashboard.alchemy.com/settings/billing to upgrade your scaling policy for continued service.'],+ ['Helius plan cap', 'max usage reached'],+ ['QuickNode daily cap', 'daily request limit reached - upgrade your account'],+ ])('parks %s for the quota window, never the 10m transient one', (_label, message) => {+ // Every paid provider words exhaustion differently. Asserting only "is+ // cooling" hid the Alchemy case: it matched no quota phrase, took the 10m+ // transient window, and re-entered rotation as the primary every 10 minutes.+ const ms = markEndpointCooldown(`https://${_label.replace(/\W+/g, '-')}.example/rpc`, 429, message);+ expect(ms).toBeGreaterThanOrEqual(6 * 3_600_000);+ });++ it('classifies an exhausted-plan JSON-RPC body as a capacity error so the rotation fails over', () => {+ // Alchemy reports its monthly cap as JSON-RPC code 429; QuickNode/Helius use+ // negative codes. All three must rotate rather than surface to the caller.+ for (const err of [+ { code: 429, message: 'Monthly capacity limit exceeded.' },+ { code: -32429, message: 'max usage reached' },+ { code: -32003, message: 'daily request limit reached' },+ ]) {+ const verdict = classifyRpcBody(JSON.stringify({ jsonrpc: '2.0', id: 1, error: err }));+ expect(verdict, `code ${err.code} must rotate`).toBeTruthy();+ }+ // A deterministic method error must NOT rotate — every lane would fail it.+ expect(+ classifyRpcBody(+ JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32602, message: 'invalid params' } }),+ ),+ ).toBeNull();+ });+it('hydrate() adopts a sibling verdict for an endpoint this instance never tried', async () => {const unseen = 'https://never-tried-here.example/rpc';expect(isEndpointCooling(unseen)).toBe(false);diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 2e7358204..0b07129a7 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -20,7 +20,7 @@ import {checkConcurrency, checkDailyBudgetLamports, checkPriceImpact,checkDailyLoss, recordCustodyEvent, resolveEntrySize,} from '../../api/_lib/agent-trade-guards.js';-import { shouldGiveUpReconcile } from './exit-logic.js';+import { shouldGiveUpReconcile, reconcileParkAnchor } from './exit-logic.js';import { buildAmmSellInstructions, quoteAmmBuy, buildAmmBuyInstructions } from './amm-exit.js';import { getWalletBaseBalance, reconcileVanishedBag } from './reconcile.js';import { assessTradeSafety, recordFirewallDecision, criticalFirewallReason } from '../../api/_lib/trade-firewall.js';@@ -605,7 +605,7 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover// as live risk and held a concurrency slot. The time bound: the park// itself had none, so a bag whose emptying tx could never be found// re-parked every sweep forever and wedged that slot permanently.- if (shouldGiveUpReconcile(position.reconcile_pending_since, RECONCILE_GIVE_UP_MS)) {+ if (shouldGiveUpReconcile(reconcileParkAnchor(position), RECONCILE_GIVE_UP_MS)) {// The bag is provably gone but its proceeds are unknowable from// chain history. Book it closed so the slot frees, and leave// realized P&L NULL rather than inventing a number — every P&L@@ -618,7 +618,11 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recoverWHERE id = ${position.id} AND status <> 'closed'`;log.warn('reconcile gave up; bag gone, proceeds unknown', {- ...tag, pending_since: position.reconcile_pending_since,+ ...tag,+ pending_since: position.reconcile_pending_since,+ // The anchor actually measured, which differs from pending_since+ // on a row parked before that column existed.+ park_anchor: reconcileParkAnchor(position),});return { status: 'closed', reason: 'reconcile_unresolved' };}diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.jsindex 30f07da30..b9e255152 100644--- a/workers/agent-sniper/exit-logic.js+++ b/workers/agent-sniper/exit-logic.js@@ -283,3 +283,36 @@ export function shouldGiveUpReconcile(pendingSince, giveUpMs, now = Date.now())if (!Number.isFinite(since)) return false;return now - since >= giveUpMs;}++/**+ * When a position's reconcile park started, for the give-up bound above.+ *+ * `reconcile_pending_since` is the answer whenever it is set. It is NOT always+ * set: a row parked by a revision that predates the column carries the+ * `reconcile_pending` marker with no timestamp, and because+ * shouldGiveUpReconcile() reads a null as "nothing is pending" those rows are+ * unreapable forever. That is precisely the permanent wedge the bound exists to+ * prevent, reintroduced through the back door. Observed in production: four arms+ * frozen for 37 to 57 hours against a 30-minute max hold, each arm capped at one+ * concurrent position, so each was fully stopped.+ *+ * For an already-parked row, fall back to the last moment the sweep could still+ * evaluate it (`stale_since`), then to `opened_at`. Both are sound lower bounds+ * on when the park began, so the fallback can only ever under-estimate the wait,+ * never cut a park short.+ *+ * A row that is NOT parked returns its raw `reconcile_pending_since` (normally+ * null), so a first park still gets its full window before the bound applies.+ *+ * Pure.+ *+ * @param {{reconcile_pending_since?: string|Date|null, error?: string|null,+ * stale_since?: string|Date|null, opened_at?: string|Date|null}} position+ * @returns {string|Date|null} the anchor to measure the park from+ */+export function reconcileParkAnchor(position) {+ const p = position || {};+ if (p.reconcile_pending_since != null) return p.reconcile_pending_since;+ if (p.error !== 'reconcile_pending') return null;+ return p.stale_since ?? p.opened_at ?? null;+}