Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 3 additions & 1 deletion KNOWLEDGE_BASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,11 @@ Commit counts include replies and quotes. Commit-based badges and XP use non-del

Badges are calculated from current account data, not permanently recorded awards. Removing qualifying activity can reduce progress or lock a badge again; for example, unstarring a commit can remove **stargazer**. **Shell shocked** depends only on when the account was created, so deleting activity does not remove it. When a commit posted on the web unlocks a badge, a toast names it and confetti drops; clicking an unlocked badge drops confetti again. Unlocking a badge does not normally give bonus XP; **shell shocked** contributes **100 XP** once. XP otherwise comes from **10 per commit**, **15 per day in the longest streak**, **5 per star received**, **5 per reply to another developer**, and **2 per star given to another developer**. The **luddite** penalty applies once while the badge is unlocked, not once per unfollow, and total XP cannot fall below zero. A qualifying reply contributes both commit XP and reply XP; pastéis do not add XP.

The achievements dialog's **XP log** tab lists where the XP of the last 90 days came from, a day at a time: commits, replies to other developers, streak days, stars received and given, and the shell shocked bonus. It is read from the same activity as the total, with the same visibility, and loads only when opened. The luddite penalty has no date, so it appears in the breakdown but not in the log.

XP also determines your Unix rank: **user** at 0 XP, **daemon** at 50, **operator** at 150, **maintainer** at 400, **wheel** at 1,000, and **root** at 2,500. The achievements dialog's **Ranks** tab shows the levels and progress. Level-up notifications use your public progress, so pending or rejected commits do not trigger them. Each level above the starting rank can notify you only once, even if you lose and regain the XP; jumping ahead does not send a notification for every skipped level.

Sources: [badge definitions](app/Enums/Achievement.php), [unlock conditions and XP calculation](app/Queries/UserAchievementsQuery.php), [streak calculation](app/Queries/UserStreakQuery.php), [Unix ranks](app/Enums/UnixRank.php), [level-up notifications](app/Actions/CreateLevelNotification.php), [achievements dialog](resources/js/components/achievements-dialog.tsx).
Sources: [badge definitions](app/Enums/Achievement.php), [unlock conditions and XP calculation](app/Queries/UserAchievementsQuery.php), [XP log](app/Queries/UserXpLogQuery.php), [streak calculation](app/Queries/UserStreakQuery.php), [Unix ranks](app/Enums/UnixRank.php), [level-up notifications](app/Actions/CreateLevelNotification.php), [achievements dialog](resources/js/components/achievements-dialog.tsx).

### Following developers and suggestions

Expand Down
4 changes: 3 additions & 1 deletion app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use App\Queries\UserCommitsQuery;
use App\Queries\UserModerationQuery;
use App\Queries\UserStreakQuery;
use App\Queries\UserXpLogQuery;
use App\Services\PageMetadata;
use Illuminate\Container\Attributes\CurrentUser;
use Illuminate\Http\RedirectResponse;
Expand All @@ -32,7 +33,7 @@
/**
* Profiles are public, so guests and crawlers read the same page, with the profile's link preview.
*/
public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser, User $user, UserActivityQuery $activity, UserStreakQuery $streaks, UserAchievementsQuery $achievements, PushAccessQuery $pushAccess, UserCommitsQuery $commits, PinnedCommitQuery $pinned, UserModerationQuery $moderation, FollowersYouKnowQuery $followersYouKnow, GitHubReadmeQuery $readme, PageMetadata $metadata): Response
public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser, User $user, UserActivityQuery $activity, UserStreakQuery $streaks, UserAchievementsQuery $achievements, UserXpLogQuery $xpLog, PushAccessQuery $pushAccess, UserCommitsQuery $commits, PinnedCommitQuery $pinned, UserModerationQuery $moderation, FollowersYouKnowQuery $followersYouKnow, GitHubReadmeQuery $readme, PageMetadata $metadata): Response
{
$blockerId = $currentUser?->blockerIdWith($user);

Expand Down Expand Up @@ -68,6 +69,7 @@ public function show(ShowUserRequest $request, #[CurrentUser] ?User $currentUser
'activity' => fn (): array => $activity->get($user, $currentUser),
'streaks' => $getStreaks,
'achievements' => fn (): array => $achievements->get($user, $currentUser, $getStreaks()),
'xpLog' => Inertia::optional(fn (): array => $xpLog->get($user, $currentUser)),
'moderation' => fn (): ?array => $currentUser?->isAdmin() === true && ! $user->isAdmin() ? $moderation->get([$user])[$user->id] : null,
'tab' => $request->tab(...),
'pinnedCommit' => fn (): ?Commit => $request->tab() === 'commits' ? $pinned->get($user, $currentUser) : null,
Expand Down
134 changes: 134 additions & 0 deletions app/Queries/UserXpLogQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
<?php

declare(strict_types=1);

namespace App\Queries;

use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

/**
* @phpstan-type XpLogEntry array{source: string, count: int, xp: int}
* @phpstan-type XpLogDay array{date: string, xp: int, entries: list<XpLogEntry>}
*/
final readonly class UserXpLogQuery
{
private const int DAYS = 90;

/**
* Where the XP of the last 90 days came from, a day at a time, newest first. Days follow the activity graph and the
* streak: the date of `created_at`. Nothing is stored for this; it is read from the same commits and stars that make
* up the XP total, with the same visibility as the profile.
*
* @return list<XpLogDay>
*/
public function get(User $user, ?User $viewer): array
{
// Today is the first of the 90 days.
$since = CarbonImmutable::now()->subDays(self::DAYS - 1)->startOfDay();
$visible = $user->commits()->visibleTo($viewer);

/** @var Collection<int, object{day: string, commits: int|string, replies: int|string}> $commits */
$commits = (clone $visible)
->where('commits.created_at', '>=', $since)
->leftJoin('commits as parents', fn (JoinClause $join): JoinClause => $join
->on('parents.id', '=', 'commits.parent_id')
->where('parents.user_id', '!=', $user->id))
->selectRaw('date(commits.created_at) as day, count(*) as commits, count(parents.id) as replies')
->groupBy('day')
->toBase()
->get();

/** @var Collection<int, object{day: string, count: int|string}> $starsReceived */
$starsReceived = DB::table('stars')
->whereIn('commit_id', (clone $visible)->select('commits.id'))
->where('user_id', '!=', $user->id)
->where('created_at', '>=', $since)
->selectRaw('date(created_at) as day, count(*) as count')
->groupBy('day')
->get();

/** @var Collection<int, object{day: string, count: int|string}> $starsGiven */
$starsGiven = $user->starredCommits()
->where('commits.user_id', '!=', $user->id)
->where(fn (CommitBuilder $query): CommitBuilder => $query->visibleTo($viewer))
->where('stars.created_at', '>=', $since)
->selectRaw('date(stars.created_at) as day, count(*) as count')
->groupBy('day')
->toBase()
->get();

/** @var array<string, list<XpLogEntry>> $days */
$days = [];
$add = function (string $day, string $source, int $count, int $multiplier) use (&$days): void {
if ($count > 0) {
$days[$day][] = ['source' => $source, 'count' => $count, 'xp' => $count * $multiplier];
}
};

foreach ($commits as $row) {
$add($row->day, 'commits', (int) $row->commits, 10);
$add($row->day, 'replies', (int) $row->replies, 5);
}

foreach ($this->longestStreakDays($user, $viewer) as $day) {
if ($day >= $since->toDateString()) {
$add($day, 'streak', 1, 15);
}
}

foreach ($starsReceived as $row) {
$add($row->day, 'stars_received', (int) $row->count, 5);
}

foreach ($starsGiven as $row) {
$add($row->day, 'stars_given', (int) $row->count, 2);
}

if ($user->created_at->lt('2026-10-21 14:00:00 UTC') && $user->created_at->gte($since)) {
$add($user->created_at->toDateString(), 'shell_shocked', 1, 100);
}

krsort($days);

return array_map(fn (string $day, array $entries): array => [
'date' => $day,
'xp' => array_sum(array_column($entries, 'xp')),
'entries' => $entries,
], array_keys($days), $days);
}

/**
* The days of the longest streak, the ones that earn streak XP, found the way the streak itself is counted. Equal
* streaks resolve to the most recent one.
*
* @return list<string>
*/
private function longestStreakDays(User $user, ?User $viewer): array
{
/** @var list<string> $days */
$days = $user->commits()
->visibleTo($viewer)
->selectRaw('date(created_at) as day')
->distinct()
->orderBy('day')
->pluck('day')
->all();

$longest = [];
$run = [];
$previous = null;

foreach ($days as $day) {
$date = CarbonImmutable::parse($day);
$run = $previous?->addDay()->isSameDay($date) ? [...$run, $day] : [$day];
$longest = count($run) >= count($longest) ? $run : $longest;
$previous = $date;
}

return $longest;
}
}
140 changes: 136 additions & 4 deletions resources/js/components/achievements-dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { router } from '@inertiajs/react';
import {
Bomb,
BotOff,
Expand All @@ -15,7 +16,7 @@ import {
Zap,
} from 'lucide-react';
import type { CSSProperties } from 'react';
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { DragonBallIcon } from '@/components/dragon-ball-icon';
import {
Dialog,
Expand All @@ -24,11 +25,18 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { WordmarkText } from '@/components/wordmark-text';
import { dropConfetti } from '@/lib/confetti';
import { formatCount, formatExactCount } from '@/lib/numbers';
import { cn, laneTint } from '@/lib/utils';
import type { Achievements, Profile, User } from '@/types';
import { cn, formatFullDate, laneTint } from '@/lib/utils';
import type {
Achievements,
Profile,
User,
XpLogDay,
XpLogEntry,
} from '@/types';

const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
terminal: Terminal,
Expand All @@ -48,20 +56,66 @@ const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
'dragon-ball': DragonBallIcon,
};

const xpSources: Record<XpLogEntry['source'], [string, string]> = {
commits: ['commit', 'commits'],
replies: ['reply to someone else', 'replies to others'],
streak: ['streak day', 'streak days'],
stars_received: ['star received', 'stars received'],
stars_given: ['star given', 'stars given'],
shell_shocked: ['shell shocked bonus', 'shell shocked bonus'],
};

function XpLogSkeleton() {
return (
<div
aria-hidden
className="space-y-3 motion-safe:animate-in motion-safe:delay-300 motion-safe:fill-mode-backwards motion-safe:fade-in"
>
{[0, 1, 2].map((index) => (
<div key={index}>
<div className="flex items-center justify-between border-b pb-1">
<Skeleton className="h-4 w-20" />
<Skeleton className="h-4 w-12" />
</div>
<div className="mt-1 space-y-0.5">
<Skeleton className="h-4 w-2/3" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
))}
</div>
);
}

export function AchievementsDialog({
open,
onOpenChange,
achievements,
xpLog,
user,
lane,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
achievements: Achievements;
xpLog?: XpLogDay[];
user: User | Profile;
lane: string;
}) {
const [tab, setTab] = useState<'badges' | 'ranks'>('badges');
const [tab, setTab] = useState<'badges' | 'ranks' | 'xp'>('badges');
const [hasFailed, setHasFailed] = useState(false);

// The log is only loaded once someone looks at it, so a profile visit stays as light as before.
useEffect(() => {
if (open && tab === 'xp' && xpLog === undefined) {
router.reload({
only: ['xpLog'],
onStart: () => setHasFailed(false),
onError: () => setHasFailed(true),
onNetworkError: () => setHasFailed(true),
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
}, [open, tab, xpLog]);

const unlockedCount = achievements.badges.filter((b) => b.unlocked).length;
const nextRank = achievements.ranks.find(
Expand Down Expand Up @@ -162,6 +216,18 @@ export function AchievementsDialog({
>
Unix Ranks ({achievements.ranks.length})
</button>
<button
type="button"
onClick={() => setTab('xp')}
className={cn(
'border-b-2 px-3 py-1.5 font-medium transition',
tab === 'xp'
? 'border-(--lane) text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground',
)}
>
XP Log
</button>
</div>

{/* Badges Grid */}
Expand Down Expand Up @@ -338,6 +404,72 @@ export function AchievementsDialog({
</div>
)}

{/* XP Log */}
{tab === 'xp' && (
<div
className="min-h-40 font-mono text-xs"
aria-busy={xpLog === undefined && !hasFailed}
>
{hasFailed ? (
<p role="status" className="text-muted-foreground">
The XP log couldn't be loaded. Try again in a
minute.
</p>
) : xpLog === undefined ? (
<XpLogSkeleton />
) : xpLog.length === 0 ? (
<p role="status" className="text-muted-foreground">
No XP in the last 90 days.
</p>
) : (
<ol className="space-y-3">
{xpLog.map((day) => (
<li key={day.date}>
<div className="flex items-center justify-between gap-2 border-b pb-1">
<time
dateTime={day.date}
className="text-muted-foreground"
>
{formatFullDate(
`${day.date}T00:00:00`,
)}
</time>
<span className="font-medium tabular-nums">
+{formatExactCount(day.xp)} XP
</span>
</div>
<ul className="mt-1 space-y-0.5">
{day.entries.map((entry) => (
<li
key={entry.source}
className="flex items-center justify-between gap-2 text-muted-foreground"
>
<span>
{entry.count}{' '}
{
xpSources[
entry.source
][
entry.count ===
1
? 0
: 1
]
}
</span>
<span className="tabular-nums">
+{entry.xp}
</span>
</li>
))}
</ul>
</li>
))}
</ol>
)}
</div>
)}

{/* Dry Unix XP Formula Footnote */}
<p className="border-t pt-2 text-center font-mono text-[11px] text-muted-foreground">
XP: 10/commit · 15/day streak · 5/star received · 5/reply ·
Expand Down
4 changes: 4 additions & 0 deletions resources/js/pages/user/show.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import type {
CursorPaginated,
Profile,
Streaks,
XpLogDay,
} from '@/types';

function pluralize(count: number, singular: string, plural: string) {
Expand All @@ -72,6 +73,7 @@ export default function Show({
activity,
streaks,
achievements,
xpLog,
commits,
tab,
pinnedCommit,
Expand All @@ -88,6 +90,7 @@ export default function Show({
activity: Activity;
streaks: Streaks;
achievements: Achievements;
xpLog?: XpLogDay[];
commits: CursorPaginated<Commit>;
tab: 'commits' | 'replies' | 'readme';
pinnedCommit: Commit | null;
Expand Down Expand Up @@ -426,6 +429,7 @@ export default function Show({
open={isAchievementsOpen}
onOpenChange={setIsAchievementsOpen}
achievements={achievements}
xpLog={xpLog}
user={user}
lane={lane}
/>
Expand Down
Loading