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
test(economy): cover staking earnings, retention cohorts, and the buyback ordering they depend on
nirholasb3aac8a67f8c
diff --git a/contracts/src/AgentPayments.sol b/contracts/src/AgentPayments.solindex 4f475dff0..ed680102e 100644--- a/contracts/src/AgentPayments.sol+++ b/contracts/src/AgentPayments.sol@@ -120,9 +120,11 @@ contract AgentPayments is ReentrancyGuard, Ownable {error NoTokensBought();error NativeTransferFailed();- constructor(address initialOwner) Ownable(initialOwner) {- if (initialOwner == address(0)) revert ZeroAddress();- }+ /// @dev A zero `initialOwner` is rejected by `Ownable`'s constructor with+ /// `OwnableInvalidOwner`, which runs before this body, so there is no+ /// second check to add here: an unreachable one would only look like+ /// protection that is never exercised.+ constructor(address initialOwner) Ownable(initialOwner) {}// ── Agent registration ───────────────────────────────────────────────────diff --git a/contracts/test/AgentPayments.t.sol b/contracts/test/AgentPayments.t.solindex 69f8faf15..cbc2399e1 100644--- a/contracts/test/AgentPayments.t.sol+++ b/contracts/test/AgentPayments.t.sol@@ -385,7 +385,9 @@ contract AgentPaymentsTest is Test {}function testConstructorRejectsZeroOwner() public {- vm.expectRevert();+ // Ownable rejects it before the body runs; assert the exact error so a+ // future refactor cannot silently drop the guard.+ vm.expectRevert(abi.encodeWithSignature("OwnableInvalidOwner(address)", address(0)));new AgentPayments(address(0));}@@ -544,9 +546,10 @@ contract AgentPaymentsTest is Test {// ── AP-6: currency validation ────────────────────────────────────────────function testAcceptPaymentRejectsNativeSentinel() public {+ address sentinel = ap.NATIVE_TOKEN();vm.prank(payer);vm.expectRevert(AgentPayments.InvalidCurrency.selector);- ap.acceptPayment(address(agentTok), ap.NATIVE_TOKEN(), 1e18, 1, 0, 0);+ ap.acceptPayment(address(agentTok), sentinel, 1e18, 1, 0, 0);}function testAcceptPaymentRejectsZeroCurrency() public {@@ -688,6 +691,25 @@ contract AgentPaymentsTest is Test {assertEq(bb, 30e18);}+ function testNativeBuybackRevertsWhenTheSwapReverts() public {+ address nativeCur = ap.NATIVE_TOKEN();+ vm.deal(payer, 10 ether);+ vm.prank(payer);+ ap.acceptPaymentNative{value: 10 ether}(address(agentTok), 1, 0, 0);+ ap.distributePayments(address(agentTok), nativeCur);++ FailingRouter bad = new FailingRouter();+ vm.startPrank(owner);+ ap.setRouterAllowed(address(bad), true);+ vm.expectRevert(AgentPayments.SwapFailed.selector);+ ap.buybackTrigger(address(agentTok), nativeCur, address(bad), hex"1234");+ vm.stopPrank();++ (, uint256 bb,) = ap.getBalances(address(agentTok), nativeCur);+ assertEq(bb, 3 ether, "AP-9: a reverted native swap must leave the vault intact");+ assertEq(address(ap).balance, 10 ether);+ }+function testBuybackLeavesNoStandingRouterAllowance() public {_pay(100e18, 1);ap.distributePayments(address(agentTok), address(usdc));diff --git a/packages/copy-mcp/test/handlers.test.mjs b/packages/copy-mcp/test/handlers.test.mjsnew file mode 100644index 000000000..8e26998d7--- /dev/null+++ b/packages/copy-mcp/test/handlers.test.mjs@@ -0,0 +1,262 @@+// Handler behavior for @three-ws/copy-mcp: request shaping, the auth-exemption+// boundary, the update merge sequence, row shaping, and error normalization.+// Global fetch is stubbed for every test - nothing here touches the network.+//+// Env is pinned BEFORE the dynamic imports because src/config.js reads+// process.env at module load.+//+// Run: node --test packages/copy-mcp/test/handlers.test.mjs++import { test } from 'node:test';+import assert from 'node:assert/strict';++process.env.THREE_WS_BASE = 'https://copy.test';+process.env.THREE_WS_API_KEY = 'sk_test_copy_mcp';+delete process.env.THREE_WS_TIMEOUT_MS;++const { def: getEarnings } = await import('../src/tools/get-earnings.js');+const { def: createSubscription } = await import('../src/tools/create-subscription.js');+const { def: updateSubscription } = await import('../src/tools/update-subscription.js');+const { def: listSubscriptions } = await import('../src/tools/list-subscriptions.js');+const { shapeSubscription } = await import('../src/lib/shapes.js');+const { buildServer } = await import('../src/index.js');++const LEADER_ID = '8f3c1b2a-4d5e-4f60-8a9b-0c1d2e3f4a5b';+const SUB_ID = '11111111-2222-4333-8444-555555555555';+const WALLET = 'So11111111111111111111111111111111111111112';++// Swap globalThis.fetch for the duration of fn, always restoring it.+async function withFetch(stub, fn) {+ const original = globalThis.fetch;+ globalThis.fetch = stub;+ try {+ return await fn();+ } finally {+ globalThis.fetch = original;+ }+}++// Answer each fetch in order from `responses`, recording every invocation.+function sequencedFetch(responses, log) {+ let i = 0;+ return async (url, init) => {+ log.push({ url: String(url), init });+ const r = responses[Math.min(i++, responses.length - 1)];+ return typeof r === 'function' ? r() : r;+ };+}++function jsonResponse(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++// A realistic copy_subscriptions row: Postgres numerics arrive as strings, and+// the create/update paths return the raw row with no joined leader or counts.+function subscriptionRow(overrides = {}) {+ return {+ id: SUB_ID,+ status: 'active',+ network: 'mainnet',+ leader_agent_id: LEADER_ID,+ copier_wallet: WALLET,+ sizing_rule: 'fixed',+ fixed_sol: '0.05',+ multiplier: '0.1',+ pct_balance: null,+ per_trade_cap_sol: '0.5',+ min_order_sol: '0.02',+ daily_budget_sol: '1',+ max_open_copies: 5,+ mcap_floor_usd: null,+ mcap_ceiling_usd: null,+ copy_sells: true,+ require_safety_pass: false,+ min_oracle_score: null,+ perf_fee_bps: 1000,+ high_water_mark_sol: '0',+ telegram_chat_id: null,+ created_at: '2026-08-01T00:00:00Z',+ updated_at: '2026-08-01T00:00:00Z',+ ...overrides,+ };+}++// ── get_earnings: the auth-exemption boundary ─────────────────────────────++test('get_earnings with agent_id hits the public lane with NO authorization header', async () => {+ const log = [];+ const out = await withFetch(+ sequencedFetch([jsonResponse({ agent_id: LEADER_ID, network: 'mainnet', copiers: '3', accrued_fee_sol: '0.42', copier_profit_sol: '4.2' })], log),+ () => getEarnings.handler({ agent_id: LEADER_ID, network: 'mainnet' }),+ );+ assert.equal(log.length, 1);+ const url = new URL(log[0].url);+ assert.equal(url.pathname, '/api/copy/earnings');+ assert.equal(url.searchParams.get('agent_id'), LEADER_ID);+ assert.equal(url.searchParams.get('network'), 'mainnet');+ assert.equal(log[0].init.headers.authorization, undefined, 'public mode must not leak the bearer');+ assert.deepEqual(out, {+ ok: true,+ scope: 'leader',+ agent_id: LEADER_ID,+ network: 'mainnet',+ copiers: 3,+ accrued_fee_sol: 0.42,+ copier_profit_sol: 4.2,+ });+});++test('get_earnings without agent_id is account-scoped and sends the bearer', async () => {+ const log = [];+ const out = await withFetch(+ sequencedFetch([jsonResponse({ total_fee_owed_sol: '0.1', items: [{ subscription_id: SUB_ID }] })], log),+ () => getEarnings.handler({}),+ );+ assert.equal(log[0].init.headers.authorization, 'Bearer sk_test_copy_mcp');+ assert.equal(out.scope, 'mine');+ assert.equal(out.total_fee_owed_sol, 0.1);+ assert.equal(out.count, 1);+});++// ── create_subscription ───────────────────────────────────────────────────++test('create_subscription rejects fixed sizing without fixed_sol before any request', async () => {+ const log = [];+ await withFetch(sequencedFetch([jsonResponse({})], log), () =>+ assert.rejects(+ createSubscription.handler({ leader_agent_id: LEADER_ID, copier_wallet: WALLET }),+ (err) => {+ assert.equal(err.code, 'validation_error');+ assert.match(err.message, /fixed_sol/);+ return true;+ },+ ),+ );+ assert.equal(log.length, 0, 'must fail client-side, no round trip');+});++test('create_subscription POSTs the follow and shapes the raw row (numeric strings become numbers)', async () => {+ const log = [];+ const out = await withFetch(+ sequencedFetch([jsonResponse({ subscription: subscriptionRow() })], log),+ () =>+ createSubscription.handler({+ leader_agent_id: LEADER_ID,+ copier_wallet: WALLET,+ sizing_rule: 'fixed',+ fixed_sol: 0.05,+ }),+ );+ assert.equal(log[0].init.method, 'POST');+ const body = JSON.parse(log[0].init.body);+ assert.equal(body.leader_agent_id, LEADER_ID);+ assert.equal(body.fixed_sol, 0.05);+ assert.equal(out.ok, true);+ assert.equal(out.subscription.sizing.fixed_sol, 0.05, 'Postgres numeric string coerced');+ assert.equal(out.subscription.guards.per_trade_cap_sol, 0.5);+ assert.equal(out.subscription.leader.name, null, 'create returns the raw row: no joined leader');+ assert.equal(out.subscription.pending_count, undefined, 'counts only exist on the list read');+});++// ── update_subscription: the three fetch sequences ────────────────────────++test('update_subscription with only an id throws no_changes and fetches nothing', async () => {+ const log = [];+ await withFetch(sequencedFetch([jsonResponse({})], log), () =>+ assert.rejects(updateSubscription.handler({ id: SUB_ID }), (err) => {+ assert.equal(err.code, 'no_changes');+ assert.equal(err.status, 400);+ return true;+ }),+ );+ assert.equal(log.length, 0);+});++test('update_subscription status-only is a single POST transition', async () => {+ const log = [];+ const out = await withFetch(+ sequencedFetch([jsonResponse({ subscription: subscriptionRow({ status: 'paused' }) })], log),+ () => updateSubscription.handler({ id: SUB_ID, status: 'paused' }),+ );+ assert.equal(log.length, 1);+ assert.deepEqual(JSON.parse(log[0].init.body), { id: SUB_ID, status: 'paused' });+ assert.equal(out.subscription.status, 'paused');+});++test('update_subscription config change on a paused follow: GET, merged upsert, then status restore', async () => {+ const log = [];+ const paused = subscriptionRow({ status: 'paused', mcap_floor_usd: '50000' });+ const out = await withFetch(+ sequencedFetch(+ [+ jsonResponse({ subscriptions: [paused] }),+ jsonResponse({ subscription: subscriptionRow({ status: 'active', daily_budget_sol: '2' }) }),+ jsonResponse({ subscription: subscriptionRow({ status: 'paused', daily_budget_sol: '2' }) }),+ ],+ log,+ ),+ () => updateSubscription.handler({ id: SUB_ID, daily_budget_sol: 2, mcap_floor_usd: null }),+ );+ assert.equal(log.length, 3, 'list + upsert + restore');+ assert.equal(log[0].init.method ?? 'GET', 'GET');+ const upsert = JSON.parse(log[1].init.body);+ assert.equal(upsert.daily_budget_sol, 2, 'passed field wins');+ assert.equal(upsert.mcap_floor_usd, null, 'explicit null clears the guard');+ assert.equal(upsert.copier_wallet, WALLET, 'unpassed fields carry over from the existing row');+ assert.deepEqual(JSON.parse(log[2].init.body), { id: SUB_ID, status: 'paused' }, 'guard edits never un-pause');+ assert.equal(out.subscription.status, 'paused');+ assert.equal(out.subscription.guards.daily_budget_sol, 2);+});++test('update_subscription throws not_found when the id is not in the account list', async () => {+ await withFetch(sequencedFetch([jsonResponse({ subscriptions: [] })], []), () =>+ assert.rejects(updateSubscription.handler({ id: SUB_ID, daily_budget_sol: 2 }), (err) => {+ assert.equal(err.code, 'not_found');+ assert.equal(err.status, 404);+ return true;+ }),+ );+});++// ── error normalization ───────────────────────────────────────────────────++test('upstream errors surface error_description, not the bare error code', async () => {+ await withFetch(+ sequencedFetch([jsonResponse({ error: 'unauthorized', error_description: 'sign in required' }, 401)], []),+ () =>+ assert.rejects(listSubscriptions.handler({}), (err) => {+ assert.equal(err.code, 'upstream_error');+ assert.equal(err.status, 401);+ assert.equal(err.message, 'sign in required', 'the human-readable message wins');+ return true;+ }),+ );+});++test('the registered MCP callback converts handler throws into an isError payload', async () => {+ const server = buildServer();+ const entry = server._registeredTools.list_subscriptions;+ assert.ok(entry, 'list_subscriptions must be registered');+ const result = await withFetch(+ async () => {+ throw new TypeError('fetch failed');+ },+ () => entry.handler({}, {}),+ );+ assert.equal(result.isError, true);+ const payload = JSON.parse(result.content[0].text);+ assert.equal(payload.ok, false);+ assert.equal(payload.error, 'network_error');+});++// ── shapes ────────────────────────────────────────────────────────────────++test('shapeSubscription keeps list-only counts when present and coerces them', () => {+ const shaped = shapeSubscription(subscriptionRow({ pending_count: '2', acted_count: '7', leader_name: 'Ledger' }));+ assert.equal(shaped.pending_count, 2);+ assert.equal(shaped.acted_count, 7);+ assert.equal(shaped.leader.name, 'Ledger');+});diff --git a/packages/pose/README.md b/packages/pose/README.mdindex 11e27384f..90f7023c7 100644--- a/packages/pose/README.md+++ b/packages/pose/README.md@@ -82,9 +82,9 @@ import { poseSeed } from '@three-ws/pose';const pose = await poseSeed('wave hello');console.log(pose.presetId); // → 'wave'-console.log(pose.seed); // → '8c12…e0f9' (stable sha256-derived)+console.log(pose.seed); // → '4ae1977023a2568b' (stable sha256-derived)console.log(pose.parameters); // → { shoulderR: { x: 0, y: 0, z: -2.45 }, elbowR: { x: -1.2, … }, … }-console.log(pose.previewUrl); // → https://three.ws/pose?seed=8c12…&preset=wave+console.log(pose.previewUrl); // → https://three.ws/pose?seed=4ae1977023a2568b&preset=wave```Apply the rotations straight to a Three.js skeleton:diff --git a/src/solana-stake.js b/src/solana-stake.jsindex 13c8fe2df..f90547bb1 100644--- a/src/solana-stake.js+++ b/src/solana-stake.js@@ -98,3 +98,69 @@ export async function stakeOnSolana({await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');return sig;}++/** The market envelope tag that separates a market stake from a bare conviction memo. */+export const MARKET_TAG = 'rsm.v1';++/**+ * Open a position in the Reputation Staking Market (specs/REPUTATION_STAKING_MARKET.md §3.1).+ *+ * Same shape as stakeOnSolana, with two differences that make the stake+ * *withdrawable*: the lamports go to the market escrow rather than to the+ * agent's own wallet, and the memo carries `market` + `escrow` so the server can+ * recognise the transaction as a position it must honour. A bare stakeOnSolana+ * memo stays what it always was: a conviction signal with no principal to return.+ *+ * @param {object} opts+ * @param {string} opts.agentAsset Base58 pubkey identifying the agent+ * @param {string} opts.escrow Base58 market escrow pubkey (from GET /api/reputation/market)+ * @param {bigint} opts.lamports Stake amount (>= MIN_STAKE_LAMPORTS)+ * @param {number} opts.score 1-5 conviction rating+ * @param {'mainnet'|'devnet'} [opts.network='devnet']+ * @param {object} opts.wallet Solana wallet adapter (publicKey + signTransaction)+ * @returns {Promise<string>} the stake transaction signature, which is the position id+ */+export async function stakeOnMarket({ agentAsset, escrow, lamports, score, network = 'devnet', wallet }) {+ if (!wallet?.publicKey || typeof wallet.signTransaction !== 'function') {+ throw new Error('Solana wallet not connected');+ }+ if (!Number.isInteger(score) || score < 1 || score > 5) {+ throw new Error('score must be 1-5');+ }+ if (lamports < MIN_STAKE_LAMPORTS) {+ throw new Error(`min stake is ${Number(MIN_STAKE_LAMPORTS) * SOL_PER_LAMPORT} SOL`);+ }++ const conn = new Connection(RPC[network] || RPC.devnet, 'confirmed');+ const fromPk = wallet.publicKey;+ const escrowPk = new PublicKey(escrow);++ const memoIx = new TransactionInstruction({+ keys: [{ pubkey: fromPk, isSigner: true, isWritable: false }],+ programId: MEMO_PROGRAM_ID,+ data: Buffer.from(+ JSON.stringify({+ v: 1,+ kind: 'threews.stake.v1',+ market: MARKET_TAG,+ agent: agentAsset,+ score,+ escrow: escrowPk.toBase58(),+ }),+ 'utf8',+ ),+ });+ const transferIx = SystemProgram.transfer({+ fromPubkey: fromPk,+ toPubkey: escrowPk,+ lamports: Number(lamports),+ });++ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash();+ const tx = new Transaction({ feePayer: fromPk, blockhash, lastValidBlockHeight }).add(transferIx, memoIx);++ const signed = await wallet.signTransaction(tx);+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false });+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ return sig;+}diff --git a/tests/api/reconstruct-finalize.test.js b/tests/api/reconstruct-finalize.test.jsindex 14d00939c..cdd562aed 100644--- a/tests/api/reconstruct-finalize.test.js+++ b/tests/api/reconstruct-finalize.test.js@@ -29,6 +29,14 @@ vi.mock('../../api/_lib/glb-inspect.js', () => ({vi.mock('../../api/_lib/webhook-dispatch.js', () => ({ dispatchWebhooks: async () => {} }));+// Every terminal materialize also registers the result in the Forge store so+// galleries/share pages see reconstructions; mocked here so the control flow+// (and its never-blocks-delivery contract) is what's under test.+const registerReconstructionCreationMock = vi.fn(async () => 'creation-1');+vi.mock('../../api/_lib/forge-store.js', () => ({+ registerReconstructionCreation: (...a) => registerReconstructionCreationMock(...a),+}));+const providerMock = { name: 'replicate', instance: null };vi.mock('../../api/_lib/regen-provider.js', () => ({getRegenProvider: async () => providerMock,@@ -97,6 +105,33 @@ describe('finalizeReconstructStage', () => {expect(out.status).toBe('done');expect(createAvatarMock.mock.calls[0][0].input.tags).toContain('unrigged');});++ it('registers the delivered avatar in the Forge store with its visibility mirrored', async () => {+ inspectGlbMock.mockReturnValue(RIGGED);+ await finalizeReconstructStage({+ userId: 'u1',+ jobId: 'j1',+ job: { provider: 'gcp', params: { name: 'Me', visibility: 'unlisted' } },+ glbUrl: 'https://x/m.glb',+ });+ expect(registerReconstructionCreationMock).toHaveBeenCalledOnce();+ const reg = registerReconstructionCreationMock.mock.calls[0][0];+ expect(reg.userId).toBe('u1');+ expect(reg.avatarId).toBe('avatar-1');+ expect(reg.jobId).toBe('j1');+ expect(reg.provider).toBe('gcp');+ expect(reg.visibility).toBe('unlisted');+ expect(reg.glbUrl).toMatch(/^https:\/\/cdn\.test\/u\/u1\//);+ // The selfie lane has no prompt: the honest display line is the name.+ expect(reg.prompt).toBe('Me');+ });++ it('still delivers the avatar when Forge-store registration throws', async () => {+ inspectGlbMock.mockReturnValue(RIGGED);+ registerReconstructionCreationMock.mockRejectedValueOnce(new Error('store down'));+ const out = await finalizeReconstructStage({ userId: 'u1', jobId: 'j1', job: baseJob, glbUrl: 'https://x/m.glb' });+ expect(out).toEqual({ status: 'done', resultAvatarId: 'avatar-1' });+ });});describe('pollRiggingStage', () => {diff --git a/tests/reputation-staking.test.js b/tests/reputation-staking.test.jsnew file mode 100644index 000000000..f72bb069f--- /dev/null+++ b/tests/reputation-staking.test.js@@ -0,0 +1,354 @@+// Reputation Staking Market — the earnings engine.+//+// These tests pin the contract in specs/REPUTATION_STAKING_MARKET.md §4-§5. The+// numbers here are the ones a staker is quoted and the ones the escrow pays, so+// a change that moves any of them is a change to what people are owed.++import { describe, it, expect } from 'vitest';++import {+ EPOCH_SECONDS,+ MIN_STAKE_LAMPORTS,+ MARKET_TAG,+ NEUTRAL_QUALITY,+ epochOf,+ epochBounds,+ epochFraction,+ positionEpochs,+ foldActions,+ agentEpochWeight,+ distributeEpoch,+ accruePosition,+ realizedApr,+ clampSettlement,+ toBigInt,+ formatSol,+} from '../src/shared/reputation-staking.js';+import { KIND_MAP, validatePayload } from '../api/_lib/solana-attestations.js';++const AGENT_A = 'THREEsynthetic1111111111111111111111111111A';+const AGENT_B = 'THREEsynthetic1111111111111111111111111111B';++/** An epoch boundary far from any real date, so the maths is readable. */+const E = 20_000;+const { start: E_START } = epochBounds(E);++const feedback = (score, taskAccepted = false) => ({+ kind: 'threews.feedback.v1',+ verified: true,+ score,+ taskAccepted,+ blockTime: E_START + 10,+});+const validation = (passed) => ({+ kind: 'threews.validation.v1',+ verified: true,+ passed,+ blockTime: E_START + 10,+});+const accept = () => ({ kind: 'threews.accept.v1', verified: true, blockTime: E_START + 10 });++describe('epochs', () => {+ it('buckets a timestamp into its UTC day', () => {+ expect(EPOCH_SECONDS).toBe(86_400);+ expect(epochOf(0)).toBe(0);+ expect(epochOf(86_399)).toBe(0);+ expect(epochOf(86_400)).toBe(1);+ expect(epochBounds(1)).toEqual({ start: 86_400, end: 172_800 });+ });++ it('credits only the fraction of the epoch a position was actually open', () => {+ // Opened at noon, still open at the end of the day: half the epoch.+ const half = epochFraction({ openedAt: E_START + EPOCH_SECONDS / 2, closedAt: null }, E, E_START + EPOCH_SECONDS);+ expect(half).toBe(0.5);+ });++ it('gives no free day to a stake placed one second before midnight', () => {+ const sliver = epochFraction({ openedAt: E_START + EPOCH_SECONDS - 1, closedAt: null }, E, E_START + EPOCH_SECONDS);+ expect(sliver).toBeCloseTo(1 / 86_400, 12);+ });++ it('never accrues past `now`, even for an open position', () => {+ const now = E_START + 3_600;+ expect(epochFraction({ openedAt: E_START, closedAt: null }, E, now)).toBe(round9(3_600 / 86_400));+ });++ it('returns zero for an epoch the position did not overlap', () => {+ expect(epochFraction({ openedAt: E_START, closedAt: E_START + 10 }, E + 5, E_START + 10 * EPOCH_SECONDS)).toBe(0);+ });++ it('enumerates every epoch a position spanned, inclusive', () => {+ const epochs = positionEpochs({ openedAt: E_START, closedAt: E_START + 2 * EPOCH_SECONDS }, E_START + 3 * EPOCH_SECONDS);+ expect(epochs).toEqual([E, E + 1, E + 2]);+ });+});++describe('foldActions', () => {+ it('weights each attested action per the spec table', () => {+ const folded = foldActions([accept(), validation(true), feedback(5, true), feedback(4, false)]);+ // 1.00 accept + 1.00 passed validation + 0.75 verified feedback + 0.35 plain feedback+ expect(folded.work).toBe(3.1);+ expect(folded.faults).toBe(0);+ expect(folded.feedbackCount).toBe(2);+ });++ it('charges faults for failed validations, disputes and revocations', () => {+ const folded = foldActions([+ validation(false),+ { kind: 'threews.dispute.v1', verified: true },+ { kind: 'threews.revoke.v1', verified: true },+ ]);+ expect(folded.work).toBe(0);+ expect(folded.faults).toBe(3);+ });++ it('counts conviction as worth nothing, so the market cannot pay itself', () => {+ const folded = foldActions([+ { kind: 'threews.stake.v1', verified: true, score: 5 },+ { kind: 'threews.unstake.v1', verified: true },+ ]);+ expect(folded.work).toBe(0);+ expect(folded.faults).toBe(0);+ });++ it('ignores unverified rows and unknown kinds', () => {+ const folded = foldActions([+ { kind: 'threews.accept.v1', verified: false },+ { kind: 'threews.future-kind.v9', verified: true },+ ]);+ expect(folded.work).toBe(0);+ });+});++describe('agentEpochWeight', () => {+ it('treats an agent with no feedback as neutral quality, not as bad', () => {+ const w = agentEpochWeight([accept(), accept()]);+ expect(w.quality).toBe(NEUTRAL_QUALITY);+ expect(w.integrity).toBe(1);+ // 0.5 * log2(1 + 2)+ expect(w.weight).toBeCloseTo(0.5 * Math.log2(3), 8);+ });++ it('maps the 1-5 feedback scale onto [0, 1]', () => {+ expect(agentEpochWeight([feedback(1)]).quality).toBe(0);+ expect(agentEpochWeight([feedback(3)]).quality).toBe(0.5);+ expect(agentEpochWeight([feedback(5)]).quality).toBe(1);+ });++ it('charges a fault at double the rate work is credited', () => {+ // work 1.0 (one passed validation), faults 1.0 (one failed) => 1 / (1 + 2)+ const w = agentEpochWeight([validation(true), validation(false)]);+ expect(w.integrity).toBeCloseTo(1 / 3, 9);+ });++ it('pays nothing for an idle epoch', () => {+ expect(agentEpochWeight([]).weight).toBe(0);+ });++ it('is concave in activity, so spraying attestations does not buy proportional yield', () => {+ const ten = agentEpochWeight(Array.from({ length: 10 }, accept)).weight;+ const twenty = agentEpochWeight(Array.from({ length: 20 }, accept)).weight;+ expect(twenty).toBeGreaterThan(ten);+ expect(twenty).toBeLessThan(ten * 2);+ });+});++describe('distributeEpoch', () => {+ const positions = [+ { id: 'a', agentAsset: AGENT_A, principalLamports: 1_000_000_000n, openedAt: E_START, closedAt: null },+ { id: 'b', agentAsset: AGENT_A, principalLamports: 3_000_000_000n, openedAt: E_START, closedAt: null },+ ];++ it('splits an agent share strictly in proportion to principal', () => {+ const { payouts } = distributeEpoch({+ epoch: E,+ positions,+ agentWeights: new Map([[AGENT_A, 1]]),+ poolLamports: 4_000_000n,+ now: E_START + EPOCH_SECONDS,+ });+ expect(payouts.get('a').lamports).toBe(1_000_000n);+ expect(payouts.get('b').lamports).toBe(3_000_000n);+ });++ it('never distributes more than the pool', () => {+ const { payouts, distributed } = distributeEpoch({+ epoch: E,+ positions: [+ ...positions,+ { id: 'c', agentAsset: AGENT_A, principalLamports: 7n, openedAt: E_START, closedAt: null },+ ],+ agentWeights: new Map([[AGENT_A, 1]]),+ poolLamports: 1_000_001n,+ now: E_START + EPOCH_SECONDS,+ });+ const sum = [...payouts.values()].reduce((acc, v) => acc + v.lamports, 0n);+ expect(sum).toBe(distributed);+ expect(sum).toBeLessThanOrEqual(1_000_001n);+ });++ it('pays a staker of an idle agent nothing while a working agent still earns', () => {+ const { payouts } = distributeEpoch({+ epoch: E,+ positions: [+ { id: 'working', agentAsset: AGENT_A, principalLamports: 1_000_000_000n, openedAt: E_START, closedAt: null },+ { id: 'idle', agentAsset: AGENT_B, principalLamports: 1_000_000_000n, openedAt: E_START, closedAt: null },+ ],+ agentWeights: new Map([+ [AGENT_A, 1],+ [AGENT_B, 0],+ ]),+ poolLamports: 1_000_000n,+ now: E_START + EPOCH_SECONDS,+ });+ expect(payouts.get('working').lamports).toBe(1_000_000n);+ expect(payouts.get('idle').lamports).toBe(0n);+ });++ it('pays nothing at all when the pool is unfunded', () => {+ const { payouts } = distributeEpoch({+ epoch: E,+ positions,+ agentWeights: new Map([[AGENT_A, 1]]),+ poolLamports: 0n,+ now: E_START + EPOCH_SECONDS,+ });+ expect(payouts.get('a').lamports).toBe(0n);+ expect(payouts.get('a').posWeight).toBeGreaterThan(0);+ });++ it('halves the share of a position that was only open for half the epoch', () => {+ const { payouts } = distributeEpoch({+ epoch: E,+ positions: [+ { id: 'full', agentAsset: AGENT_A, principalLamports: 1_000_000_000n, openedAt: E_START, closedAt: null },+ {+ id: 'half',+ agentAsset: AGENT_A,+ principalLamports: 1_000_000_000n,+ openedAt: E_START + EPOCH_SECONDS / 2,+ closedAt: null,+ },+ ],+ agentWeights: new Map([[AGENT_A, 1]]),+ poolLamports: 3_000_000n,+ now: E_START + EPOCH_SECONDS,+ });+ expect(payouts.get('full').lamports).toBe(2_000_000n);+ expect(payouts.get('half').lamports).toBe(1_000_000n);+ });+});++describe('accruePosition', () => {+ it('sums a position across every epoch it overlapped', () => {+ const position = { id: 'a', agentAsset: AGENT_A, principalLamports: 1_000_000_000n, openedAt: E_START, closedAt: null };+ const cohort = [position];+ const agentWeights = new Map([[AGENT_A, 1]]);+ const epochInputs = new Map([+ [E, { poolLamports: 1_000_000n, positions: cohort, agentWeights }],+ [E + 1, { poolLamports: 1_000_000n, positions: cohort, agentWeights }],+ ]);+ const { lamports, byEpoch } = accruePosition({ position, epochInputs, now: E_START + 2 * EPOCH_SECONDS });+ expect(lamports).toBe(2_000_000n);+ expect(byEpoch.map((r) => r.epoch)).toEqual([E, E + 1]);+ });++ it('stops accruing the moment the position closes', () => {+ const position = {+ id: 'a',+ agentAsset: AGENT_A,+ principalLamports: 1_000_000_000n,+ openedAt: E_START,+ closedAt: E_START + EPOCH_SECONDS,+ };+ const agentWeights = new Map([[AGENT_A, 1]]);+ const epochInputs = new Map([+ [E, { poolLamports: 1_000_000n, positions: [position], agentWeights }],+ [E + 1, { poolLamports: 1_000_000n, positions: [position], agentWeights }],+ ]);+ const { lamports } = accruePosition({ position, epochInputs, now: E_START + 5 * EPOCH_SECONDS });+ expect(lamports).toBe(1_000_000n);+ });+});++describe('realizedApr', () => {+ it('annualises what actually accrued, never a projection', () => {+ const apr = realizedApr({+ principalLamports: 1_000_000_000n,+ earningsLamports: 10_000_000n,+ openedAt: E_START,+ closedAt: E_START + 365 * EPOCH_SECONDS,+ now: E_START + 365 * EPOCH_SECONDS,+ });+ expect(apr).toBeCloseTo(0.01, 9);+ });++ it('is zero before any time has passed', () => {+ expect(realizedApr({ principalLamports: 1n, earningsLamports: 1n, openedAt: E_START, closedAt: E_START, now: E_START })).toBe(0);+ });+});++describe('clampSettlement', () => {+ it('returns principal in full even when the reward surplus is empty', () => {+ const s = clampSettlement({ principalLamports: 5_000_000n, earningsLamports: 900n, surplusLamports: 0n });+ expect(s.principal).toBe(5_000_000n);+ expect(s.earnings).toBe(0n);+ expect(s.clamped).toBe(true);+ });++ it('pays earnings whole when the surplus covers them', () => {+ const s = clampSettlement({ principalLamports: 5_000_000n, earningsLamports: 900n, surplusLamports: 10_000n });+ expect(s.earnings).toBe(900n);+ expect(s.clamped).toBe(false);+ });+});++describe('lamport helpers', () => {+ it('parses decimal strings past Number.MAX_SAFE_INTEGER without loss', () => {+ expect(toBigInt('9007199254740993')).toBe(9007199254740993n);+ expect(toBigInt('not a number')).toBe(0n);+ });++ it('formats lamports as SOL', () => {+ expect(formatSol(1_500_000_000n)).toBe('1.5000');+ });++ it('pins the market constants the wire format depends on', () => {+ expect(MIN_STAKE_LAMPORTS).toBe(1_000_000n);+ expect(MARKET_TAG).toBe('rsm.v1');+ });+});++describe('registry extension: threews.unstake.v1', () => {+ const SIG = '5'.repeat(88);++ it('is a registered attestation kind', () => {+ expect(KIND_MAP.unstake).toBe('threews.unstake.v1');+ });++ it('accepts a well-formed unstake envelope', () => {+ expect(+ validatePayload({+ v: 1,+ kind: 'threews.unstake.v1',+ agent: AGENT_A,+ stake: SIG,+ principal: '1000000',+ }),+ ).toBe(true);+ });++ it('rejects a principal sent as a number instead of a decimal string', () => {+ expect(+ validatePayload({ v: 1, kind: 'threews.unstake.v1', agent: AGENT_A, stake: SIG, principal: 1_000_000 }),+ ).toBe(false);+ });++ it('rejects an envelope that names no stake', () => {+ expect(validatePayload({ v: 1, kind: 'threews.unstake.v1', agent: AGENT_A, principal: '1' })).toBe(false);+ });+});++function round9(n) {+ return Math.round(n * 1e9) / 1e9;+}diff --git a/tests/retention-cohorts.test.js b/tests/retention-cohorts.test.jsnew file mode 100644index 000000000..4f3420108--- /dev/null+++ b/tests/retention-cohorts.test.js@@ -0,0 +1,169 @@+// Week-2 retention on minted agents — the cohort arithmetic behind the phase-2+// roadmap metric (api/_lib/retention.js, api/cron/retention-rollup.js).+//+// The parts that can quietly produce a WRONG number rather than an error are all+// here: which Monday a mint belongs to, where the day-7..day-13 window falls, when+// a cohort has stopped moving, and how a per-week row becomes the two stored+// metrics. A retention figure that is silently off by a week is worse than no+// figure at all, because it still gets quoted.++import { describe, it, expect } from 'vitest';+import {+ isoWeekStart,+ retentionWindow,+ isCohortComplete,+ cohortRecords,+ summarizeCohorts,+ RETENTION_METRICS,+ WEEK2_TARGET_RATE,+} from '../api/_lib/retention.js';++describe('isoWeekStart', () => {+ it('maps every day of a week to the same Monday', () => {+ // 2026-08-10 is a Monday; 2026-08-16 is the Sunday that closes its week.+ const days = [+ '2026-08-10T00:00:00Z',+ '2026-08-11T13:45:00Z',+ '2026-08-14T23:59:59Z',+ '2026-08-16T23:59:59Z',+ ];+ for (const d of days) expect(isoWeekStart(d)).toBe('2026-08-10');+ });++ it('puts Sunday at the END of its week, not the start', () => {+ // The classic off-by-one: JS getUTCDay() calls Sunday 0, which would put+ // 2026-08-16 in the week starting 2026-08-16 instead of 2026-08-10.+ expect(isoWeekStart('2026-08-16T12:00:00Z')).toBe('2026-08-10');+ expect(isoWeekStart('2026-08-17T00:00:00Z')).toBe('2026-08-17');+ });++ it('accepts a bare date string and a Date alike', () => {+ expect(isoWeekStart('2026-08-13')).toBe('2026-08-10');+ expect(isoWeekStart(new Date('2026-08-13T09:00:00Z'))).toBe('2026-08-10');+ });++ it('crosses a month and a year boundary correctly', () => {+ expect(isoWeekStart('2026-03-01T00:00:00Z')).toBe('2026-02-23');+ expect(isoWeekStart('2027-01-01T00:00:00Z')).toBe('2026-12-28');+ });+});++describe('retentionWindow', () => {+ it('opens on day 7 and closes (exclusive) on day 14', () => {+ expect(retentionWindow('2026-08-11T00:00:00Z')).toEqual({+ start: '2026-08-18',+ end: '2026-08-25',+ });+ });++ it('measures from the owner\'s own mint instant, not the week boundary', () => {+ // A Monday minter and a Saturday minter in the SAME cohort week get+ // different absolute windows — that is the point of per-owner windows.+ expect(retentionWindow('2026-08-10T08:00:00Z').start).toBe('2026-08-17');+ expect(retentionWindow('2026-08-15T08:00:00Z').start).toBe('2026-08-22');+ });+});++describe('isCohortComplete', () => {+ it('is complete only once the window end has arrived', () => {+ expect(isCohortComplete('2026-08-25', '2026-08-24')).toBe(false);+ expect(isCohortComplete('2026-08-25', '2026-08-25')).toBe(true);+ expect(isCohortComplete('2026-08-25', '2026-09-01')).toBe(true);+ });+});++describe('cohortRecords', () => {+ const row = {+ cohort_week: '2026-07-27',+ minted_owners: 40,+ retained_converse: 14,+ retained_return: 22,+ window_start: '2026-08-03',+ window_end: '2026-08-17',+ is_complete: true,+ };++ it('expands one week into one record per stored metric', () => {+ const recs = cohortRecords([row], '2026-08-20');+ expect(recs.map((r) => r.metric)).toEqual([...RETENTION_METRICS]);+ expect(recs[0]).toMatchObject({+ cohortWeek: '2026-07-27',+ metric: 'week2_converse',+ mintedOwners: 40,+ retainedOwners: 14,+ windowStart: '2026-08-03',+ windowEnd: '2026-08-17',+ isComplete: true,+ });+ expect(recs[0].retentionRate).toBeCloseTo(0.35, 10);+ expect(recs[1]).toMatchObject({ metric: 'week2_return', retainedOwners: 22 });+ expect(recs[1].retentionRate).toBeCloseTo(0.55, 10);+ });++ it('drops a cohort with no minters instead of dividing by zero', () => {+ expect(cohortRecords([{ ...row, minted_owners: 0, retained_converse: 0, retained_return: 0 }], '2026-08-20'))+ .toEqual([]);+ });++ it('derives completeness from the window end when the query did not supply it', () => {+ const { is_complete, ...noFlag } = row;+ expect(cohortRecords([noFlag], '2026-08-16')[0].isComplete).toBe(false);+ expect(cohortRecords([noFlag], '2026-08-17')[0].isComplete).toBe(true);+ });++ it('coerces the string counts a driver may hand back', () => {+ const recs = cohortRecords([{ ...row, minted_owners: '40', retained_converse: '10' }], '2026-08-20');+ expect(recs[0].mintedOwners).toBe(40);+ expect(recs[0].retentionRate).toBeCloseTo(0.25, 10);+ });++ it('tolerates an empty or missing result set', () => {+ expect(cohortRecords([], '2026-08-20')).toEqual([]);+ expect(cohortRecords(undefined, '2026-08-20')).toEqual([]);+ });+});++describe('summarizeCohorts', () => {+ const cohorts = [+ { cohort_week: '2026-07-13', minted_owners: 10, retained_owners: 2, retention_rate: 0.2, is_complete: true },+ { cohort_week: '2026-07-20', minted_owners: 20, retained_owners: 9, retention_rate: 0.45, is_complete: true },+ // Still open — must not be treated as a settled number.+ { cohort_week: '2026-07-27', minted_owners: 30, retained_owners: 1, retention_rate: 0.033, is_complete: false },+ ];++ it('reports the newest CLOSED cohort, never an open one', () => {+ const s = summarizeCohorts(cohorts);+ expect(s.latestCompleteWeek).toBe('2026-07-20');+ expect(s.latestRate).toBeCloseTo(0.45, 10);+ });++ it('pools closed cohorts by owner, not by averaging the weekly rates', () => {+ // Owner-weighted: 11/30 = 0.3667. A naive mean of 0.2 and 0.45 gives 0.325+ // and would clear the 30% bar for the wrong reason.+ const s = summarizeCohorts(cohorts);+ expect(s.mintedOwners).toBe(30);+ expect(s.retainedOwners).toBe(11);+ expect(s.pooledRate).toBeCloseTo(11 / 30, 10);+ expect(s.completeCohorts).toBe(2);+ });++ it('grades against the roadmap target', () => {+ expect(summarizeCohorts(cohorts).target).toBe(WEEK2_TARGET_RATE);+ expect(summarizeCohorts(cohorts).meetsTarget).toBe(true);+ const weak = [{ cohort_week: '2026-07-20', minted_owners: 20, retained_owners: 3, retention_rate: 0.15, is_complete: true }];+ expect(summarizeCohorts(weak).meetsTarget).toBe(false);+ });++ it('answers null rather than 0% when nothing has closed yet', () => {+ const s = summarizeCohorts([cohorts[2]]);+ expect(s.latestCompleteWeek).toBeNull();+ expect(s.latestRate).toBeNull();+ expect(s.pooledRate).toBeNull();+ expect(s.meetsTarget).toBeNull();+ });++ it('tolerates an empty or missing list', () => {+ expect(summarizeCohorts([]).completeCohorts).toBe(0);+ expect(summarizeCohorts(undefined).pooledRate).toBeNull();+ });+});