Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
4457d6c
feat(gamification): XP/level engine with polynomial curve
oyi77 May 19, 2026
5164b11
feat(gamification): DB migration and gamification module
oyi77 May 19, 2026
954c9eb
feat(gamification): badge system with 20+ definitions and streak tracker
oyi77 May 19, 2026
3fd342f
feat(gamification): leaderboard engine, SSE stream, and anti-cheat
oyi77 May 19, 2026
bccb7ae
feat(gamification): token sharing, invite tokens, and API routes
oyi77 May 19, 2026
9ef1ac1
feat(gamification): community server federation and connection manage…
oyi77 May 19, 2026
0ca87c3
feat(gamification): dashboard UI — leaderboard, profile, and tokens p…
oyi77 May 19, 2026
81d3522
test(gamification): unit tests for XP, badges, and streaks
oyi77 May 19, 2026
7c9334a
test(gamification): comprehensive tests for leaderboard, sharing, inv…
oyi77 May 19, 2026
5564e25
feat(gamification): wire pipeline events, MCP tools, and dashboard nav
oyi77 May 19, 2026
98ea8ae
fix(gamification): address all code review feedback
oyi77 May 19, 2026
4313ce5
docs(gamification): system design document
oyi77 May 19, 2026
0288024
feat(gamification): badge unlock notifications, admin anomaly dashboa…
oyi77 May 19, 2026
3fcf615
feat(gamification): badge unlock notifications, admin anomaly dashboa…
oyi77 May 19, 2026
f33aa36
fix(gamification): address all code review feedback
oyi77 May 19, 2026
af5f0ab
fix(triage): prefer currently checked-out release branch + sort by ve…
diegosouzapw May 19, 2026
409228a
chore(ideia): add YAML frontmatter to legacy idea files
diegosouzapw May 19, 2026
3e648d5
Merge branch 'release/v3.8.0' into feat/gamification-leaderboard
diegosouzapw May 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,082 changes: 1,082 additions & 0 deletions docs/frameworks/GAMIFICATION.md

Large diffs are not rendered by default.

28 changes: 28 additions & 0 deletions open-sse/handlers/chatCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4409,6 +4409,20 @@ export async function handleChatCore({
recordCost(apiKeyInfo.id, estimatedCost);
}

// ── Gamification event (fire-and-forget) ──
if (apiKeyInfo?.id) {
try {
const { emitGamificationEvent } = await import("@/lib/gamification/events");
emitGamificationEvent({
apiKeyId: apiKeyInfo.id,
action: "request",
metadata: { model, provider },
});
} catch (_) {
/* gamification optional */
}
}

return {
success: true,
response: new Response(JSON.stringify(translatedResponse), {
Expand Down Expand Up @@ -4728,6 +4742,20 @@ export async function handleChatCore({
})
);

// ── Gamification event (fire-and-forget) ──
if (apiKeyInfo?.id) {
try {
const { emitGamificationEvent } = await import("@/lib/gamification/events");
emitGamificationEvent({
apiKeyId: apiKeyInfo.id,
action: "request",
metadata: { model, provider },
});
} catch (_) {
/* gamification optional */
}
}

return {
success: true,
response: new Response(finalStream, {
Expand Down
29 changes: 28 additions & 1 deletion open-sse/mcp-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
import { memoryTools } from "./tools/memoryTools.ts";
import { skillTools } from "./tools/skillTools.ts";
import { compressionTools } from "./tools/compressionTools.ts";
import { gamificationTools } from "./tools/gamificationTools.ts";
import { compressMcpRegistryMetadata } from "./descriptionCompressor.ts";
import { smartFilterText } from "../services/compression/engines/mcpAccessibility/index.ts";
import {
Expand All @@ -98,7 +99,10 @@ const MCP_ALLOWED_SCOPES = new Set(
.filter(Boolean)
);
const TOTAL_MCP_TOOL_COUNT =
MCP_TOOLS.length + Object.keys(memoryTools).length + Object.keys(skillTools).length;
MCP_TOOLS.length +
Object.keys(memoryTools).length +
Object.keys(skillTools).length +
gamificationTools.length;

type JsonRecord = Record<string, unknown>;

Expand Down Expand Up @@ -1022,6 +1026,29 @@ export function createMcpServer(): McpServer {
);
});

// ── Gamification Tools ────────────────────────
gamificationTools.forEach((toolDef) => {
server.registerTool(
toolDef.name,
{
description: toolDef.description,
// @ts-ignore: dynamic zod access
inputSchema: toolDef.inputSchema,
},
withScopeEnforcement(toolDef.name, async (args) => {
try {
const parsedArgs = toolDef.inputSchema.parse(args ?? {});
// @ts-ignore: handler expected specific object
const result = await toolDef.handler(parsedArgs);
return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { content: [{ type: "text" as const, text: `Error: ${msg}` }], isError: true };
}
})
);
});

return server;
}

Expand Down
140 changes: 140 additions & 0 deletions open-sse/mcp-server/tools/gamificationTools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/**
* MCP Gamification Tools — leaderboard, badges, levels, sharing.
*
* @module mcp-server/tools/gamificationTools
*/

import { z } from "zod";

export const gamificationTools = [
{
name: "gamification_leaderboard",
description: "Get leaderboard rankings for a scope (global, weekly, monthly, tokens_shared).",
inputSchema: z.object({
scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"),
limit: z.number().min(1).max(100).default(50),
}),
handler: async (args: { scope: string; limit: number }) => {
const { getTopN } = await import("../../../src/lib/gamification/leaderboard");
const entries = await getTopN(args.scope as any, args.limit);
return { entries };
},
},
{
name: "gamification_rank",
description: "Get rank for an API key in a leaderboard scope.",
inputSchema: z.object({
apiKeyId: z.string(),
scope: z.enum(["global", "weekly", "monthly", "tokens_shared"]).default("global"),
}),
handler: async (args: { apiKeyId: string; scope: string }) => {
const { getRank } = await import("../../../src/lib/gamification/leaderboard");
const rank = await getRank(args.apiKeyId, args.scope as any);
return { rank };
},
},
{
name: "gamification_profile",
description: "Get XP, level, and badges for an API key.",
inputSchema: z.object({
apiKeyId: z.string(),
}),
handler: async (args: { apiKeyId: string }) => {
const { getXp, getBadges } = await import("../../../src/lib/db/gamification");
const { calculateLevel, getLevelTitle, getLevelTier } =
await import("../../../src/lib/gamification/xp");
const { getStreak } = await import("../../../src/lib/gamification/streaks");

const xp = getXp(args.apiKeyId);
const badges = getBadges(args.apiKeyId);
const streak = await getStreak(args.apiKeyId);
const level = xp ? calculateLevel(xp.totalXp) : 1;

return {
totalXp: xp?.totalXp || 0,
level,
title: getLevelTitle(level),
tier: getLevelTier(level),
streak: streak.currentStreak,
longestStreak: streak.longestStreak,
badges: badges.map((b) => ({ id: b.badgeId, unlockedAt: b.unlockedAt })),
};
},
},
{
name: "gamification_badges",
description: "List all badge definitions or earned badges for an API key.",
inputSchema: z.object({
apiKeyId: z.string().optional(),
category: z.string().optional(),
}),
handler: async (args: { apiKeyId?: string; category?: string }) => {
const { getBadgeDefinitions, getBadges } = await import("../../../src/lib/db/gamification");

if (args.apiKeyId) {
const badges = getBadges(args.apiKeyId);
return { earned: badges };
}

const definitions = getBadgeDefinitions(args.category);
return { definitions };
},
},
{
name: "gamification_transfer",
description: "Transfer tokens between API keys.",
inputSchema: z.object({
fromApiKeyId: z.string(),
toApiKeyId: z.string(),
amount: z.number().positive(),
reason: z.string().optional(),
}),
handler: async (args: {
fromApiKeyId: string;
toApiKeyId: string;
amount: number;
reason?: string;
}) => {
const { transferTokens } = await import("../../../src/lib/gamification/sharing");
const result = await transferTokens(
args.fromApiKeyId,
args.toApiKeyId,
args.amount,
args.reason
);
return result;
},
},
{
name: "gamification_invite",
description: "Create an invite token for server connection.",
inputSchema: z.object({
apiKeyId: z.string(),
serverUrl: z.string().optional(),
maxUses: z.number().positive().default(1),
}),
handler: async (args: { apiKeyId: string; serverUrl?: string; maxUses: number }) => {
const { createInvite } = await import("../../../src/lib/gamification/invites");
const result = await createInvite(args.apiKeyId, args.serverUrl, args.maxUses);
return result;
},
},
{
name: "gamification_servers",
description: "List connected community servers.",
inputSchema: z.object({}),
handler: async () => {
const { listServers } = await import("../../../src/lib/gamification/servers");
return { servers: await listServers() };
},
},
{
name: "gamification_anomalies",
description: "Get flagged anomalous XP activity (admin only).",
inputSchema: z.object({}),
handler: async () => {
const { getAnomalies } = await import("../../../src/lib/gamification/antiCheat");
return { anomalies: await getAnomalies() };
},
},
];
67 changes: 67 additions & 0 deletions src/app/(dashboard)/dashboard/components/BadgeToast.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"use client";

import { useState, useEffect, useCallback } from "react";

interface BadgeUnlockEvent {
badgeId: string;
badgeName: string;
badgeIcon: string;
badgeRarity: string;
}

const RARITY_COLORS: Record<string, string> = {
common: "border-gray-500 bg-gray-800",
uncommon: "border-green-500 bg-green-900/30",
rare: "border-blue-500 bg-blue-900/30",
legendary: "border-yellow-500 bg-yellow-900/30",
};

export function BadgeToast({ apiKeyId }: { apiKeyId: string }) {
const [toasts, setToasts] = useState<BadgeUnlockEvent[]>([]);

const addToast = useCallback((event: BadgeUnlockEvent) => {
setToasts((prev) => [...prev, event]);
// Auto-dismiss after 5s
setTimeout(() => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: setTimeout is never cleared on unmount — causes state update on unmounted component

If BadgeToast unmounts while toasts are still visible (e.g., user navigates away), the setTimeout callback at line 25 will still fire after 5 seconds and call setToasts() on an unmounted component. This causes a React warning and potential memory leak.

Return a cleanup function from addToast or use useRef to track timeouts and clear them in the useEffect cleanup.

setToasts((prev) => prev.slice(1));
}, 5000);
}, []);

useEffect(() => {
const es = new EventSource(`/api/gamification/notifications?apiKeyId=${apiKeyId}`);

es.addEventListener("badge_unlock", (event) => {
try {
const data = JSON.parse(event.data) as BadgeUnlockEvent;
addToast(data);
} catch {
// ignore parse errors
}
});

es.onerror = () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: No reconnect logic for EventSource — permanent disconnect on error

When es.onerror fires (network drop, server restart, proxy timeout), the EventSource is closed permanently with no reconnection attempt. Users would need to manually refresh the page to resume receiving badge notifications.

The leaderboard page (dashboard/leaderboard/page.tsx:70-78) implements reconnect with 3s delay + exponential backoff. This component should follow the same pattern for consistency and reliability.

es.close();
};

return () => es.close();
}, [apiKeyId, addToast]);

if (toasts.length === 0) return null;

return (
<div className="fixed top-4 right-4 z-50 flex flex-col gap-2">
{toasts.map((toast, i) => (
<div
key={`${toast.badgeId}-${i}`}
className={`flex items-center gap-3 px-4 py-3 rounded-lg border-2 shadow-lg animate-slide-in ${RARITY_COLORS[toast.badgeRarity] || RARITY_COLORS.common}`}
>
<span className="text-2xl">🏆</span>
<div>
<div className="font-semibold text-white">Badge Unlocked!</div>
<div className="text-sm text-text-muted">{toast.badgeName}</div>
</div>
</div>
))}
</div>
);
}
77 changes: 77 additions & 0 deletions src/app/(dashboard)/dashboard/gamification/admin/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"use client";

import { useState, useEffect } from "react";
import { Card } from "@/shared/components";

interface Anomaly {
apiKeyId: string;
xpLastHour: number;
zScore: number;
}

export default function GamificationAdminPage() {
const [anomalies, setAnomalies] = useState<Anomaly[]>([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
const fetchAnomalies = async () => {
try {
const res = await fetch("/api/gamification/anomalies");
const data = await res.json();
setAnomalies(data.anomalies || []);
} catch {
// ignore fetch errors
} finally {
setLoading(false);
}
};
fetchAnomalies();
const interval = setInterval(fetchAnomalies, 30000);
return () => clearInterval(interval);
}, []);

return (
<div className="flex flex-col gap-6">
<div>
<h1 className="text-2xl font-bold">Gamification Admin</h1>
<p className="text-sm text-text-muted mt-1">Monitor anomalies and system health</p>
</div>

<Card>
<h2 className="text-lg font-semibold mb-3">Flagged Anomalies</h2>
{loading ? (
<div className="text-text-muted">Loading...</div>
) : anomalies.length === 0 ? (
<div className="text-text-muted">No anomalies detected</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border">
<th className="text-left p-2 font-medium text-text-muted">API Key</th>
<th className="text-right p-2 font-medium text-text-muted">XP (1h)</th>
<th className="text-right p-2 font-medium text-text-muted">Z-Score</th>
<th className="text-center p-2 font-medium text-text-muted">Status</th>
</tr>
</thead>
<tbody>
{anomalies.map((a) => (
<tr key={a.apiKeyId} className="border-b border-border/50 last:border-b-0">
<td className="p-2 font-mono text-xs">{a.apiKeyId.slice(0, 16)}...</td>
<td className="p-2 text-right">{a.xpLastHour.toLocaleString()}</td>
<td className="p-2 text-right text-red-400">{a.zScore.toFixed(2)}</td>
<td className="p-2 text-center">
<span className="px-2 py-0.5 text-xs bg-red-500/20 text-red-400 rounded-full">
Suspicious
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Card>
</div>
);
}
Loading