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.

docs(guards): register the vendored-worker guard and spec the skill royalty split

nirholas285c458ca7d2
diff --git a/CLAUDE.md b/CLAUDE.md
index 541d9d54f..047427bd6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -310,6 +310,8 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.
- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
- **Orientation:** `STRUCTURE.md` maps every product surface to its directory. Read it before exploring the 60+ top-level dirs.
+- **Shared worker code is vendored, and `npm run check:vendored` keeps the copies honest.** Each worker's Docker build context is its own directory, so `../` is unreachable and shared modules (`worker_security.py`, `oin.py`, `oin_upload.py`, `gltf_meshopt.py`, `test_gltf_meshopt.py`) live as a byte-identical copy inside every worker that needs them. Fix the canonical copy, mirror it to every worker, then rerun the check (`scripts/check-vendored-workers.mjs`, wired into `npm run gate`). It prints the exact `cp` command for each drifted copy.
+- **Caller-supplied glTF is meshopt-decoded before it is read.** Most three.ws avatars ship with `EXT_meshopt_compression`, which trimesh cannot decode, so a worker that loads a caller's mesh must route it through `gltf_meshopt.decode_if_meshopt` first (stylize, remesh, texture, segment, rig already do) and ship the pinned `gltfpack` binary in its image. A new mesh-consuming worker inherits that requirement.
- **Avatar animation is universal: no rig allowlist.** Any humanoid avatar drives the pre-baked clip library: `src/glb-canonicalize.js` maps its bone names (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L`, simple `shoulderL` rigs) to the canonical set, and `src/animation-retarget.js` retargets idle/walk onto them, legs included. A rig that genuinely can't be skeleton-driven (no skin, non-humanoid prop) falls back to the default rig (`AnimationManager.supportsCanonicalClips()` gate), never a bind-pose T-pose. Hit a new skeleton convention? Add its bone-name mapping to `glb-canonicalize.js` (cover it with a case in `tests/glb-canonicalize.test.js`); don't hardcode a curated rig list.
## Known traps
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 17e9a6fbe..0274d48bb 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -144,6 +144,7 @@ bottom.
| Production server (Google Cloud Run) | [server/](server) + [Dockerfile](Dockerfile) | Live | Single Express container serving the static frontend, the vercel.json route table, and all `api/**` handlers with Vercel-parity routing; deploy via `npm run deploy:gcp` ([server/cloudbuild.yaml](server/cloudbuild.yaml)), crons via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs) · see [server/README.md](server/README.md) |
| Multiplayer 3D world (world.three.ws) | [deploy/world/](deploy/world) — [Dockerfile](deploy/world/Dockerfile), [cloudrun.yaml](deploy/world/cloudrun.yaml), [apply-hardening.sh](deploy/world/apply-hardening.sh), patches in [deploy/world/patches/](deploy/world/patches); health monitor [api/cron/world-health.js](api/cron/world-health.js) | Live · `hyperfy-world` on Cloud Run | [Hyperfy](https://github.com/hyperfy-xyz/hyperfy) pinned to an exact upstream commit and rebuilt with three local patches (server-side upload cap, `/status` blueprint-asset enumeration, fail-closed-without-`ADMIN_CODE`). World state (SQLite + uploaded assets) lives in the GCS bucket `world-three-ws-data` mounted at `/app/world`, so the container is stateless. **The world is gated:** without `ADMIN_CODE` Hyperfy's `effectiveRank` falls back to `Ranks.ADMIN` and every anonymous visitor gets server-side build rights — the fail-open default that emptied the world on 2026-06-12. Deploy + verify with `bash deploy/world/apply-hardening.sh`; builders unlock in-world with `/admin <code>`. See [deploy/world/README.md](deploy/world/README.md) |
| On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 |
+| Reputation Staking Market | spec [specs/REPUTATION_STAKING_MARKET.md](specs/REPUTATION_STAKING_MARKET.md), engine [src/shared/reputation-staking.js](src/shared/reputation-staking.js), server [api/_lib/reputation-market.js](api/_lib/reputation-market.js) + [api/reputation/market*.js](api/reputation), surface [public/reputation/market/](public/reputation/market) `→ /reputation/market` | In-repo · devnet open, mainnet owner-gated | Phase 3 roadmap: stake conviction on an agent and earn from its attested action history. A stake is a staker-signed Solana transfer to the market escrow carrying an `rsm.v1` SPL-Memo, so the chain (not the database) defines a position; the server only verifies it by reading the transaction back. Yield comes from a fixed per-epoch pool split by `principal × time × agentWeight`, where the weight is derived purely from the agent's signed `threews.*` attestations (work concave in `log2`, faults charged double), so conviction never pays itself. Principal is never slashed and settlement clamps earnings to the escrow surplus. Extends the SPL-Memo attestation layer in [docs/solana-reputation.md](docs/solana-reputation.md). Storage: [reputation_staking_market migration](api/_lib/migrations/20260811140000_reputation_staking_market.sql). Walkthrough: [docs/reputation-staking-market.md](docs/reputation-staking-market.md). Devnet proof: `node scripts/reputation-market-proof.mjs`. Tests: [tests/reputation-staking.test.js](tests/reputation-staking.test.js) |
| On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |
| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`), signed ledger provenance [api/_lib/asset-provenance.js](api/_lib/asset-provenance.js), launch directory [api/v1/tokenized/launches.js](api/v1/tokenized/launches.js) `→ GET /api/v1/tokenized/launches`, public gallery [pages/minted.html](pages/minted.html) + [src/minted.js](src/minted.js) `→ /minted` | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Every generated avatar AND every mint also appends an ERC-191-signed record to the `agent_actions` ledger (verifiable via `@three-ws/provenance-mcp`'s `query_action`). A mint naming `parent_mint` (a remix) routes the parent creator's royalty out of the mint fee as a real on-chain USDC transfer (mainnet, x402-collected calls only) — [api/_lib/remix-royalty.js](api/_lib/remix-royalty.js) split math, [api/_lib/remix-settlement.js](api/_lib/remix-settlement.js) payout wallet. Premium/token-gated generation: the Forge High tier (200k poly + PBR) is $THREE hold-or-pay gated — [api/forge.js](api/forge.js) `requireFeatureAccess('forge.high')` + [api/_lib/three-tier.js](api/_lib/three-tier.js) tier ladder, x402 pay-per-use or credits fallback; Draft/Standard stay free and ungated. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql) + [remix-royalty columns](api/_lib/migrations/20260708130000_tokenized_3d_remix_royalty.sql). Public gallery: `/minted` renders the launch directory live (model-viewer thumbnails, network toggle, royalty + remix badges) — the NFT counterpart of `/launches`. Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs). Tests: [tests/tokenize-3d.test.js](tests/tokenize-3d.test.js), [tests/tokenize-3d-remix-royalty.test.js](tests/tokenize-3d-remix-royalty.test.js), [tests/asset-provenance.test.js](tests/asset-provenance.test.js) |
| Token-gated 3D embeds (holder-only interactive scenes) | Gate config + on-chain verify [api/_lib/embed-gate.js](api/_lib/embed-gate.js), access tokens [api/_lib/embed-gate-token.js](api/_lib/embed-gate-token.js), endpoints [api/embed/gate-create.js](api/embed/gate-create.js) + [api/embed/gate-verify.js](api/embed/gate-verify.js), gate-aware resolver [api/embed/resolve.js](api/embed/resolve.js), MCP tool [api/_mcp/tools/embed.js](api/_mcp/tools/embed.js) (`create_gated_embed`), widget [public/embed/v1.js](public/embed/v1.js) (`<three-d>`) + standalone host [public/embed/v1/gated.html](public/embed/v1/gated.html) `→ /embed/v1/gated` | In-repo | `create_gated_embed(asset_id, gate)` turns an avatar or on-chain agent you own into a holder-only interactive `<three-d>` embed — visitors must prove a real, server-verified SPL balance (SIWS challenge → nonce → signature → Solana RPC read, never a client-reported number) before the live scene renders; below the bar they see a designed locked teaser + connect-wallet CTA. `mint` defaults to $THREE but is a runtime parameter (coin-agnostic plumbing). Anti-abuse: short-lived signed access tokens (auto re-verify on expiry) + per-IP/per-wallet rate limits. Storage: [embed_gates + embed_gate_nonces](api/_lib/migrations/20260708120000_embed_gates.sql). Spec: [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md#token-gating). Docs: [docs/token-gated-3d-embeds.md](docs/token-gated-3d-embeds.md). Tests: [tests/embed-gate.test.js](tests/embed-gate.test.js) |
diff --git a/data/guards.json b/data/guards.json
index d65af2422..cab946798 100644
--- a/data/guards.json
+++ b/data/guards.json
@@ -78,6 +78,27 @@
"expect": "guard-proof-nonexistent"
}
},
+ {
+ "id": "check-vendored-workers",
+ "script": "scripts/check-vendored-workers.mjs",
+ "npm": "check:vendored",
+ "title": "Vendored worker modules stay identical",
+ "protects": "Every copy of a shared worker module (worker_security.py, oin.py, oin_upload.py, gltf_meshopt.py and its test) is byte-identical across all workers.",
+ "why": "A worker's Docker build context is its own directory, so `../` is unreachable and shared code lives as a copy in each worker that needs it. Nothing enforced that, so a fix applied to one copy could leave the other sixteen on the old behaviour, which is the shape of bug this repo has already paid for once. The guard compares every copy against the most common one and names the divergent files and the command that resyncs them.",
+ "stages": [
+ "gate"
+ ],
+ "needs": "none",
+ "proof": {
+ "summary": "One worker's copy of worker_security.py edited so it no longer matches the other sixteen.",
+ "violation": {
+ "append": {
+ "workers/stylize/worker_security.py": "\n# Proof fixture: this line exists in one copy only, so the copies have drifted.\n"
+ }
+ },
+ "expect": "worker_security.py"
+ }
+ },
{
"id": "sync-studio-openapi",
"script": "scripts/sync-studio-openapi.mjs",
diff --git a/docs/guards.md b/docs/guards.md
index 3740b7c26..0e25eb5af 100644
--- a/docs/guards.md
+++ b/docs/guards.md
@@ -90,6 +90,7 @@ Run `npm run audit:guards` to print the current count and per-stage breakdown. T
|---|---|---|
| Merge-conflict markers | `npm run check:conflicts` | No unresolved conflict marker can be built or deployed. |
| CLAUDE.md truth check | `npm run check:claude` | Every script, path, count, and runbook step named in CLAUDE.md matches the repo. |
+| Vendored worker modules | `npm run check:vendored` | Every copy of a shared worker module (`worker_security.py`, `oin.py`, `oin_upload.py`, `gltf_meshopt.py` and its test) is byte-identical across all workers. |
| Hard rules, diff scoped | `npm run check:rules` | The CLAUDE.md hard rules on the lines you changed. |
| The guard registry | `npm run audit:guards` | Every guard is registered and every stage claim is true. |
| Design-token ratchet | `npm run audit:tokens` | Hardcoded colour hexes cannot creep back past a committed baseline. |
diff --git a/scripts/agent-token-market-proof.mjs b/scripts/agent-token-market-proof.mjs
index fde318e46..d98d20a4c 100644
--- a/scripts/agent-token-market-proof.mjs
+++ b/scripts/agent-token-market-proof.mjs
@@ -111,11 +111,38 @@ async function mintsFromCluster() {
return found;
}
+/**
+ * The widget calls `/api/pump/curve` as a same-origin relative URL. There is no
+ * HTTP server in a script run, so route that one path to the handler the real
+ * route relays verbatim (api/pump/curve.js is a thin shell over getCurveView).
+ * Same code, same body, same cluster — only the transport is skipped. Every
+ * other request falls through to the network untouched.
+ */
+function routeApiCallsInProcess() {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (input, init) => {
+ const href = String(input?.url || input);
+ if (href.startsWith('/api/pump/curve')) {
+ const params = new URLSearchParams(href.split('?')[1] || '');
+ const result = await getCurveView({
+ mint: params.get('mint') || '',
+ network: params.get('network') === 'devnet' ? 'devnet' : 'mainnet',
+ });
+ return new Response(JSON.stringify(result.body), {
+ status: result.httpStatus,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ return realFetch(input, init);
+ };
+}
+
async function main() {
// The renderer is browser code; give it a real DOM to render into.
const dom = new JSDOM('<!doctype html><body></body>');
globalThis.window = dom.window;
globalThis.document = dom.window.document;
+ routeApiCallsInProcess();
const { mapCurve, mountCoinStatus } = await import('../src/pump/coin-status-card.js');
console.log(`\nAgent-token market proof — ${network}`);
diff --git a/scripts/inference-receipt-verify.mjs b/scripts/inference-receipt-verify.mjs
index c36b55b3d..7866a8b5e 100644
--- a/scripts/inference-receipt-verify.mjs
+++ b/scripts/inference-receipt-verify.mjs
@@ -66,8 +66,8 @@ const SOLANA_LANES = {
'solana:etwtrabzayq6imfeykouru166vu2xqa1': { label: 'Solana devnet', defaultRpc: 'https://api.devnet.solana.com' },
};
-function laneOf(lowercaseNetwork) {
- return SOLANA_LANES[lowercaseNetwork] || { label: lowercaseNetwork, defaultRpc: null };
+function laneOf(lowercaseNetwork, network) {
+ return SOLANA_LANES[lowercaseNetwork] || { label: String(network), defaultRpc: null };
}
// Read-only on-chain confirmation of the settlement transaction. Solana and
@@ -86,7 +86,7 @@ async function confirmOnchain(receipt, rpcUrl) {
// Name the lane from the receipt's own CAIP-2 id. Reporting anything that is
// not devnet as "mainnet" would tell an operator their payment settled on a
// chain it never touched, which is the one thing a verifier must never do.
- const { label, defaultRpc } = laneOf(n);
+ const { label, defaultRpc } = laneOf(n, network);
const url = rpcUrl || defaultRpc;
if (!url) {
return {
diff --git a/specs/README.md b/specs/README.md
index 103eb1b9f..bb8393085 100644
--- a/specs/README.md
+++ b/specs/README.md
@@ -21,6 +21,8 @@ The specifications that define the three.ws embodied-agent platform: on-chain id
- [`PROVENANCE_3D.md`](./PROVENANCE_3D.md): Verifiable 3D Provenance v1. C2PA-style signed content credentials for AI-generated 3D: creator, prompt, model, lineage and the GLB's content hash, ed25519-signed and anchored on Solana. Verification is free and public.
- [`SIM_READINESS.md`](./SIM_READINESS.md): Simulation Readiness v1. The physics grade a 3D asset carries: watertightness, metric scale, mass and inertia, and a convex collision proxy, in four verdicts. Everything is derived from the mesh; anything unknowable from the geometry is reported as unknown rather than invented. Rides the provenance credential when signed.
+- [`SKILL_ROYALTY_SPLIT.md`](./SKILL_ROYALTY_SPLIT.md): Skill Royalty Split v1. How a paid skill call divides between the author and the platform, and how that division is recorded: exact integer arithmetic that conserves value and rounds toward the creator, who the author of record is, which wallet a payout resolves to, and the ledger invariants both earning lanes must hold. The contract the x402 rail, the accrual writer, the settle cron and the earnings surface all read from.
+
- [`OPEN_INFERENCE_PROTOCOL.md`](./OPEN_INFERENCE_PROTOCOL.md): Open Inference Protocol (OIN) v0.1. The vendor-neutral wire protocol for agent inference: a job envelope, a signed capability advertisement, and an Ed25519-signed response anyone can verify against the node's published key, so inference decouples from any single provider. Reference verifier in `api/_lib/oin-verify.js`; reference node in `workers/stylize`.
- [`inference-receipts.md`](./inference-receipts.md): Inference Receipt v1. The settlement half of the same story: what a paid inference call hands back as proof (job, model, input/output hashes, node and issuer signatures, the settlement transaction) and how to verify it offline.
diff --git a/specs/SKILL_ROYALTY_SPLIT.md b/specs/SKILL_ROYALTY_SPLIT.md
new file mode 100644
index 000000000..36bc2fa0a
--- /dev/null
+++ b/specs/SKILL_ROYALTY_SPLIT.md
@@ -0,0 +1,91 @@
+# Skill Royalty Split v1
+
+The rules for dividing a paid skill call between the skill's author and the
+platform, and for recording that division.
+
+This is a contract, not a tutorial. Four independent code paths must agree on it
+and will drift apart if they each re-derive it: the x402 rail that quotes and
+settles a call ([`api/x402/skill-call.js`](../api/x402/skill-call.js)), the
+accrual writer ([`api/_lib/skill-royalty.js`](../api/_lib/skill-royalty.js)),
+the settle cron ([`api/_lib/royalty.js`](../api/_lib/royalty.js)), and the author
+earnings surface (`MonetizationService.getCreatorSalesData`). For the
+author-facing guide, read [docs/skill-royalties.md](../docs/skill-royalties.md).
+
+Invariant ids are permanent. A retired id is never reused, so an audit citing
+`SR-4` still resolves later.
+
+## Units
+
+All amounts are **USDC atomic units**: integers, 6 decimals, no floats. A price
+of $0.25 is `250000`. Arithmetic is exact integer arithmetic; USD figures exist
+only for display and for the `numeric(10,6)` ledger columns.
+
+## The split
+
+Given a settled price and a platform rate in basis points:
+
+```
+platform = floor(price × platformBps / 10000)
+author = price − platform
+```
+
+| Id | Invariant |
+|---|---|
+| SR-1 | **Conservation.** `author + platform === price` for every input. No value is created or destroyed by the split. |
+| SR-2 | **Creator-favoring rounding.** The author's share is the remainder, so the platform absorbs the odd atomic. The author is never rounded down to give the platform a whole unit. |
+| SR-3 | **Bounded platform rate.** `platformBps` is clamped to `[0, 5000]`. A misconfiguration can never take more than half of a call. The default is `250` (2.5%), matching the marketplace fee. |
+| SR-4 | **No accrual without value.** A split whose author share is `<= 0` writes no ledger row. A free skill (`price_per_call_usd = 0`) is rejected before payment with `409 skill_not_priced`, never accrued as a zero row. |
+| SR-5 | **Purity.** The split function touches no database, no network, and no clock. Given the same `(price, platformBps)` it returns the same result forever, which is what makes SR-1 and SR-2 provable in isolation. |
+
+## Attribution
+
+| Id | Invariant |
+|---|---|
+| SR-6 | The author of record is `marketplace_skills.author_id`, set from the authenticated session at publish time. Nothing in a request can override it. |
+| SR-7 | Payouts resolve to that author's **primary** wallet for the settlement chain (`user_wallets.is_primary`, one per `chain_type`). A skill whose author has no wallet for a chain does not advertise that chain. |
+| SR-8 | With no routable author wallet at all, the call still settles to the platform receiver. A missing wallet degrades the payout, it never fails the payment or silently drops the call. |
+| SR-9 | Solana is advertised first whenever the author can receive on it. Chain order is a platform decision, not a caller's. |
+
+## Accrual
+
+One settled call produces at most one `royalty_ledger` row.
+
+| Id | Invariant |
+|---|---|
+| SR-10 | Accrual is **fire-and-forget after settlement**. It runs from the `onSettled` hook, never in the request path, and never throws: a ledger failure cannot fail, delay, or reverse a payment that already settled on-chain. |
+| SR-11 | The row records the **author's share**, not the gross price. The platform's cut is recorded separately in `platform_fee_usd`. Reading `price_usd` as revenue and subtracting a fee again would double-count. |
+| SR-12 | `source` names the rail that earned the row: `x402` (per-call, paid to the author's wallet at settlement) or `skill-runtime` (in-process, settled later). Every consumer distinguishes lanes by this column, never by whether `agent_id` happens to be set. |
+| SR-13 | An `x402` row lands `settled` with `settled_at` and the rail's transaction, because the funds have already moved. A `skill-runtime` row lands `pending` and awaits redemption. |
+| SR-14 | `agent_id` is **NULL** for every `x402` row: the caller is a paying wallet, not a registered agent. Any query that joins `agent_identities` to read royalties must LEFT JOIN, or it discards the entire per-call lane. |
+
+## Settlement of pending rows
+
+| Id | Invariant |
+|---|---|
+| SR-15 | The EIP-7710 redeem leg is flag-gated on `SKILL_ROYALTIES_EVM_7710_ENABLED`. With the flag off, settlement is provably inert: pending rows are left untouched and reported as skipped. It never partially redeems. |
+| SR-16 | Rows are claimed atomically (`pending → settling`, conditional on still being `pending`) before any redeem. A concurrent pass claiming the same rows gets an empty set, so an on-chain payout runs at most once per row. |
+| SR-17 | A claim that lands below the dust threshold is released back to `pending` rather than paid, so a race can never trigger a payout whose gas exceeds its value. |
+| SR-18 | A failed redeem marks its claimed rows `failed`, never silently back to `pending`. A failure is visible state, not a retry loop. |
+
+## Reporting
+
+| Id | Invariant |
+|---|---|
+| SR-19 | `pending`, `settling` and `settled` are reported as three separate totals. Collapsing `settling` into either one overstates that total. |
+| SR-20 | Both lanes reach the author's earnings surface. An author sees every row where they are `author_user_id`, whether or not they own an agent, because royalties are author-scoped. |
+
+## Test coverage
+
+Each invariant is covered by at least one positive and one negative test. The
+suites that prove them:
+
+- [`tests/skill-royalty.test.js`](../tests/skill-royalty.test.js) — the split math (SR-1 … SR-5) and the flag gate (SR-15).
+- [`tests/skill-royalty-earnings.test.js`](../tests/skill-royalty-earnings.test.js) — the read side, including the LEFT JOIN regression guard (SR-14) and separated totals (SR-19).
+- [`scripts/royalty-proof.mjs`](../scripts/royalty-proof.mjs) — an end-to-end proof against a real Postgres, asserting SR-1, SR-4, SR-11, SR-12, SR-13, SR-14 and SR-20 in one run, moving no funds.
+
+## Change control
+
+Changing the split, the rounding direction, the clamp, or the meaning of a
+ledger column is a spec change: update the invariant here in the same change,
+with tests citing its id. Weakening an invariant needs the same review as the
+code that weakens it.