Add character levels and permanent player titles

This commit is contained in:
dingo
2026-09-07 07:58:34 -04:00
parent 5a48a3c739
commit bc0ffbbbe5
30 changed files with 1594 additions and 62 deletions
+2 -2
View File
@@ -18,11 +18,11 @@
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items" class="inventory-items"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items" class="inventory-items"></div><h3>Stat points</h3><p id="saved-stat-points"></p><p class="progression-note">Stat allocation is coming later.</p><h3>Permanent titles</h3><div id="earned-titles"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
<div id="notice" role="status" class="notice" hidden></div>
<footer class="bottom" id="game-controls" hidden>
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div></section>
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div><div class="progression-line"><strong id="character-level">Level 1</strong><span id="character-experience">0 XP</span></div><progress id="experience-meter" class="experience-meter" aria-label="Level experience" max="1" value="0"></progress><div class="progression-bank"><span id="stat-point-bank">0 stat points saved</span><span id="title-count">0 titles</span></div></section>
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
</footer>
+2
View File
@@ -1,4 +1,5 @@
import './portal.css';
import { permanentTitles, progressionSummary } from './progression';
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type Command, type RecordCharacter, type World } from './portal-shared';
type Data = { worlds: World[]; characters: RecordCharacter[]; commands: Command[]; provisioningEnabled: boolean; characterLimit: number; auditLimit: number };
@@ -43,6 +44,7 @@ function detail(r: RecordCharacter) {
const list = el('dl', '', 'details'); const v = r.character.view;
const pairs: [string, string][] = [['Character ID', r.id], ['Account ID', r.account], ['World', r.worldId], ['State', r.state], ['Health', `${v.entity.hp} / ${v.entity.maxHp}`], ['Position', `${Math.round(v.entity.position.x)}, ${Math.round(v.entity.position.y)}, ${Math.round(v.entity.position.z)}`], ['Played today', `${Math.floor(r.character.dailySeconds / 60)} min`], ['Born', date(r.character.bornAt)], ['Died', r.character.diedAt ? date(r.character.diedAt) : '-'], ['Cause', r.character.deathReason || '-']];
for (const [key,value] of pairs) list.append(el('dt', key), el('dd', value)); parent.append(list);
parent.append(el('h3', 'Progression'), progressionSummary(v), el('h3', 'Permanent titles'), permanentTitles(v.titles));
for (const [heading, items] of [['Inventory', v.inventory], ['Skills', v.skills]] as const) { parent.append(el('h3', heading)); const section = el('div', '', 'item-list'); for (const [key,value] of Object.entries(items)) { const item = el('span', key.replaceAll('_', ' ')); item.append(el('b', String(value))); section.append(item); } if (!section.children.length) section.append(el('span', 'None', 'muted')); parent.append(section); }
$<HTMLDialogElement>('character-dialog').showModal();
}
+28 -8
View File
@@ -53,14 +53,34 @@ export interface Vec3 {
}
export interface Character {
ack: number;
entity: Entity;
hasKeystone: boolean;
inventory: { [key: string]: number };
kills: number;
playedSeconds: number;
remainingSeconds: number;
skills: { [key: string]: number };
ack: number;
entity: Entity;
experience: number;
experienceToNextLevel: number;
hasKeystone: boolean;
inventory: { [key: string]: number };
kills: number;
level: number;
playedSeconds: number;
remainingSeconds: number;
skills: { [key: string]: number };
statPoints: number;
titles: TitleAward[];
}
export interface TitleAward {
description: string;
earnedAt: string;
effects: TitleEffects;
id: string;
name: string;
scope: string;
worldId: string;
}
export interface TitleEffects {
damage: number;
moveSpeed: number;
}
export interface WorldInfo {
+9
View File
@@ -2,6 +2,7 @@ import './style.css';
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
import { WorldView } from './world-view';
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
import { experienceText, permanentTitles, statPointsText, updateExperienceMeter } from './progression';
type Recipe = { Inputs: Record<string, number>; Outputs: Record<string, number> };
type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
@@ -114,6 +115,8 @@ function showEnding(title: string, detail: string, survivor: boolean) {
$<HTMLDialogElement>('ending').show();
}
function inventory(c: Character) {
$('saved-stat-points').textContent = statPointsText(c);
$('earned-titles').replaceChildren(permanentTitles(c.titles));
const parent = $('inventory-items'); parent.replaceChildren();
for (const [item, count] of Object.entries(c.inventory).filter(([, n]) => n > 0)) {
const div = document.createElement('div'); div.className = 'item';
@@ -148,6 +151,12 @@ function updateHUD(s: Snapshot) {
const c = s.self, w = s.world;
visible('game-controls', true); visible('movement', c.entity.state === 'alive' && $('inventory').hidden && $('settings').hidden);
$('character-name').textContent = c.entity.name;
$('character-level').textContent = `Level ${c.level || 1}`;
$('character-experience').textContent = experienceText(c);
updateExperienceMeter($<HTMLProgressElement>('experience-meter'), c);
$('stat-point-bank').textContent = statPointsText(c);
const titleCount = c.titles?.length ?? 0;
$('title-count').textContent = `${titleCount} title${titleCount === 1 ? '' : 's'}`;
$('health-number').textContent = `${Math.max(0, Math.ceil(c.entity.hp))} / ${Math.ceil(c.entity.maxHp)}`;
$('health-fill').style.width = `${Math.max(0, c.entity.hp / c.entity.maxHp * 100)}%`;
$('play-time').textContent = `${time(c.remainingSeconds)} left today`;
+1
View File
@@ -8,3 +8,4 @@ dialog { width: min(510px, calc(100vw - 32px)); max-height: calc(100dvh - 40px);
@media(max-width:720px) { .site-header { padding: 16px 5%; flex-wrap: wrap; gap: 18px; } .site-header nav { gap: 17px; width: 100%; justify-content: space-between; } .site-header nav > a { font-size: 12px; } .wordmark { font-size: 17px; } .world-hero { min-height: 300px; max-height: none; height: 350px; } .hero-copy { bottom: 45px; right: 6%; } .hero-copy h1 { font-size: 47px; } .hero-copy > p:not(.eyebrow) { font-size: 14px; max-width: 260px; } .hero-caption { font-size: 8px; } .site-section { padding-top: 30px; padding-bottom: 30px; } .section-heading h2 { font-size: 23px; } .world-row { grid-template-columns: 42px minmax(0,1fr) auto; gap: 17px 12px; } .world-emblem { width: 38px; height: 42px; } .world-name h3 { font-size: 16px; } .world-row .world-stat:nth-child(4) { grid-column: 2; } .world-row > .button { grid-column: 3; font-size: 11px; padding: 9px; } .world-stat strong { font-size: 12px; } .world-stat span { margin-bottom: 4px; } .active-life { align-items: flex-start; flex-wrap: wrap; } .site-footer { flex-wrap: wrap; } .site-footer > span:nth-child(2) { order: 3; width: 100%; } .control-site { display: block; } .control-sidebar { padding: 18px; border-right: 0; border-bottom: 1px solid var(--line); } .control-sidebar .wordmark { margin-bottom: 18px; padding: 0; } .control-sidebar nav { grid-template-columns: repeat(3,minmax(0,1fr)); gap: 3px; } .nav-item { justify-content: center; padding: 11px 4px; gap: 6px; font-size: 12px; } .sidebar-bottom { display: none; } .control-main { padding: 22px 16px; } .control-header { margin-bottom: 20px; gap: 12px; } .control-header h1 { font-size: 24px; } .control-header .heading-tools { gap: 6px; } #admin-signout { display: none; } #create-world { padding: 10px; font-size: 12px; } .metrics { grid-template-columns: repeat(2,minmax(0,1fr)); gap: 20px 0; padding: 20px 0; margin-bottom: 20px; } .metrics > div { padding: 0 16px; } .metrics > div:nth-child(3) { padding-left: 0; } .metrics > div:nth-child(2) { border-right: 0; } .metrics strong { font-size: 24px; } .metrics span { font-size: 11px; } .table-tools { gap: 12px; } .search-field { flex-basis: 100%; max-width: none; } .table-tools > .muted { font-size: 11px; } .table-tools label { font-size: 11px; } .table-tools select { max-width: 135px; font-size: 12px; } th,td { padding: 12px 10px; } .access-state { padding: 65px 5px; } dialog { padding: 21px; } }
.button.secondary:hover:not(:disabled):not(.disabled), .button.light:hover:not(:disabled):not(.disabled) { background: #edf3ef; color: #253c31; }
@media(prefers-reduced-motion:reduce) { * { scroll-behavior: auto !important; } }
.active-life-summary{flex:1;min-width:0}.active-titles{padding-bottom:28px}.active-titles>h3{font-size:14px;margin-bottom:12px}.active-titles .title-list{grid-template-columns:repeat(auto-fit,minmax(min(250px,100%),1fr))}.active-life .progression-note{margin-top:4px}td .character-progression{min-width:155px;margin-top:0}dialog .earned-title p{margin-bottom:0}
+19
View File
@@ -0,0 +1,19 @@
.character-progression { width: 100%; max-width: 360px; margin-top: 15px; }
.progression-line { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 12px; font-size: 12px; }
.progression-line strong { font-size: inherit; font-weight: 600; }
.experience-meter { display: block; width: 100%; height: 4px; margin: 8px 0; border: 0; border-radius: 2px; overflow: hidden; appearance: none; background: var(--progression-track, #d9e4dd); color: var(--progression-fill, #477d62); }
.experience-meter::-webkit-progress-bar { background: var(--progression-track, #d9e4dd); }
.experience-meter::-webkit-progress-value { background: var(--progression-fill, #477d62); }
.experience-meter::-moz-progress-bar { background: var(--progression-fill, #477d62); }
.progression-note { color: var(--progression-muted, #66736d); font-size: 12px; line-height: 1.5; }
.title-list { display: grid; gap: 10px; min-width: 0; }
.earned-title { min-width: 0; padding: 13px; border: 1px solid var(--progression-border, #cfdad3); border-radius: 4px; overflow-wrap: anywhere; }
.earned-title > strong { display: block; font-size: 13px; font-weight: 600; }
.title-description { margin: 7px 0 0; font-size: 12px; line-height: 1.6; }
.title-origin { margin: 7px 0 0; color: var(--progression-muted, #66736d); font-size: 11px; line-height: 1.5; }
.title-effects { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: 9px; font-size: 12px; }
.effect-positive { color: var(--progression-positive, #28714c); }
.effect-negative { color: var(--progression-negative, #a24554); }
.title-history { min-width: 190px; }
.title-history summary { cursor: pointer; color: var(--progression-muted, #66736d); }
.title-history[open] summary { margin-bottom: 10px; }
+45
View File
@@ -0,0 +1,45 @@
import './progression.css';
import type { Character, TitleAward } from './generated';
function element<K extends keyof HTMLElementTagNameMap>(tag: K, text = '', className = '') {
const node = document.createElement(tag); node.textContent = text; node.className = className; return node;
}
export function experienceText(character: Character) {
if (!Number.isFinite(character.experienceToNextLevel)) return 'XP unavailable';
return character.experienceToNextLevel > 0 ? `${character.experience} / ${character.experienceToNextLevel} XP` : 'Level cap';
}
export function statPointsText(character: Character) {
const points = character.statPoints ?? 0;
return `${points} stat point${points === 1 ? '' : 's'} saved`;
}
export function updateExperienceMeter(meter: HTMLProgressElement, character: Character) {
meter.max = character.experienceToNextLevel || 1;
meter.value = character.experienceToNextLevel > 0 ? character.experience : character.experienceToNextLevel === 0 ? 1 : 0;
meter.setAttribute('aria-valuetext', `Level ${character.level || 1}: ${experienceText(character)}`);
}
export function progressionSummary(character: Character) {
const parent = element('div', '', 'character-progression');
const line = element('div', '', 'progression-line');
line.append(element('strong', `Level ${character.level || 1}`), element('span', experienceText(character)));
const meter = element('progress', '', 'experience-meter'); meter.setAttribute('aria-label', 'Level experience'); updateExperienceMeter(meter, character);
parent.append(line, meter, element('p', statPointsText(character), 'progression-note'), element('p', 'Stat allocation is coming later.', 'progression-note'));
return parent;
}
export function permanentTitles(titles: TitleAward[] = []) {
const parent = element('div', '', 'title-list');
if (!titles?.length) { parent.append(element('p', 'No titles earned yet.', 'progression-note')); return parent; }
const scopes: Record<string, string> = { personal: 'Personal', world: 'World first', global: 'First ever' };
for (const title of titles) {
const card = element('article', '', 'earned-title');
card.append(element('strong', title.name), element('p', title.description, 'title-description'));
const earned = new Date(title.earnedAt).toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' });
card.append(element('p', `${scopes[title.scope] || title.scope} / ${title.worldId} / ${earned}`, 'title-origin'));
const effects = element('div', '', 'title-effects');
for (const [value, label] of [[title.effects.damage, 'damage'], [title.effects.moveSpeed, 'movement speed']] as const) {
if (value) effects.append(element('span', `${value > 0 ? '+' : ''}${value} ${label}`, value > 0 ? 'effect-positive' : 'effect-negative'));
}
if (!effects.children.length) effects.append(element('span', 'No attribute effects.', 'progression-note'));
card.append(effects); parent.append(card);
}
return parent;
}
+13 -3
View File
@@ -1,4 +1,5 @@
import './portal.css';
import { permanentTitles, progressionSummary } from './progression';
import { $, api, APIError, badge, cell, date, el, gameURL, icons, icon, table, type RecordCharacter, type World } from './portal-shared';
type Account = { active: RecordCharacter | null; characters: RecordCharacter[]; admin: boolean };
@@ -30,12 +31,21 @@ function renderAccount() {
$('control-link').hidden = !account?.admin;
$('account-button').replaceChildren(icon(account ? 'log-out' : 'log-in'), el('span', account ? 'Sign out' : 'Sign in'));
if (!account) { history.append(el('p', 'Sign in to see your characters.', 'empty')); return; }
if (account.active) { const r = account.active; const summary = el('div', '', 'active-life'); const title = el('div'); title.append(el('h3', r.name), el('p', `${r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted')); const link = el('a', 'Continue journey', 'button'); link.href = gameURL(r.worldId); link.append(icon('arrow-right')); summary.append(title, link); parent.append(summary); }
if (account.active) {
const r = account.active; const summary = el('div', '', 'active-life'); const title = el('div', '', 'active-life-summary');
title.append(el('h3', r.name), el('p', `${r.worldId} / ${r.state === 'eligible' ? 'Passage earned' : `${Math.ceil(r.character.view.entity.hp)} health`}`, 'muted'), progressionSummary(r.character.view));
const link = el('a', 'Continue journey', 'button'); link.href = gameURL(r.worldId); link.append(icon('arrow-right')); summary.append(title, link);
const titles = el('section', '', 'active-titles'); titles.append(el('h3', 'Permanent titles'), permanentTitles(r.character.view.titles)); parent.append(summary, titles);
}
else parent.append(el('p', 'Your next life is waiting in an open world.', 'empty'));
if (!account.characters.length) return;
const { node, body } = table(['Character', 'World', 'State', 'Journey ended', 'Cause']);
const { node, body } = table(['Character', 'World', 'State', 'Progression', 'Permanent titles', 'Journey ended', 'Cause']);
for (const r of [...account.characters].sort((a,b) => (b.character.diedAt || b.character.bornAt).localeCompare(a.character.diedAt || a.character.bornAt))) {
const row = body.insertRow(); cell(row, r.name); cell(row, r.worldId); cell(row, badge(r.state)); cell(row, r.character.diedAt ? date(r.character.diedAt) : '-'); cell(row, r.character.deathReason || '-');
const row = body.insertRow(); cell(row, r.name); cell(row, r.worldId); cell(row, badge(r.state)); cell(row, progressionSummary(r.character.view));
const titles = r.character.view.titles ?? [];
if (titles.length) { const details = el('details', '', 'title-history'); details.append(el('summary', `${titles.length} permanent title${titles.length === 1 ? '' : 's'}`), permanentTitles(titles)); cell(row, details); }
else cell(row, 'None earned');
cell(row, r.character.diedAt ? date(r.character.diedAt) : '-'); cell(row, r.character.deathReason || '-');
}
const wrapper = el('div', '', 'table-wrap'); wrapper.append(node); history.append(wrapper);
}
+5
View File
@@ -4,3 +4,8 @@
.boss-bar>button{background:transparent;border:0;padding:0;min-height:28px;font:18px Georgia,serif;color:#ffe3d5;text-shadow:0 2px 5px #000}
@media(max-width:800px){.inventory{bottom:190px;max-height:calc(100dvh - 285px)}}
@media(max-height:520px){.season{top:85px}.bottom{bottom:10px;flex-wrap:nowrap}.location{display:none}.movement:not([hidden]){display:grid;position:absolute;grid-template-columns:repeat(4,38px);gap:3px;bottom:110px;left:18px}.movement button{padding:6px}.boss-bar{top:80px}.inventory,.settings{top:70px;bottom:auto;max-height:calc(100dvh - 90px)}dialog{max-height:calc(100dvh - 24px);overflow:auto;padding:20px}.notice{bottom:90px}}
:root{--progression-track:#ffffff20;--progression-fill:#d0bb83;--progression-muted:#b8c9b2;--progression-border:#87927950;--progression-positive:#b3ce82;--progression-negative:#efa79b}
.vitals .progression-line{margin-top:13px;font-size:11px}.progression-bank{display:flex;justify-content:space-between;flex-wrap:wrap;gap:5px 10px;font-size:10px;color:#cbd7c2}.inventory .progression-note{margin-top:5px}.inventory .earned-title .progression-note{margin:0}.inventory .earned-title{padding:11px}
@media(min-height:521px){.inventory{bottom:195px}}
@media(max-width:800px) and (min-height:521px){.movement:not([hidden]){bottom:255px}.inventory{bottom:258px;max-height:calc(100dvh - 350px)}.notice{bottom:375px}}
@media(max-height:520px){.movement:not([hidden]){bottom:178px}}
+27
View File
@@ -89,6 +89,33 @@ simulation lock and are deliberately a simple first implementation. Before publi
permadeath or large worlds, replace this with a durable event log, asynchronous
checkpoints, versioned migrations, and crash/latency fault injection.
## Progression and permanent titles
The Go simulation awards character XP for successful gathering, crafting, mob
kills, and the boss killing blow. Each crossed level threshold banks stat points;
there is no allocation intent until the stat design is defined. Levels, XP,
points, and the character's original level curve survive restart and survivor
passage. Replacement characters start at level 1. Existing snapshots receive
level 1 and the initial progression defaults once, without retroactive XP or
points, while preserving deaths and daily usage.
Title requirements are evaluated in Go and produce ordered award candidates.
The shared database resolves first-world and first-ever claims in the same
transaction as the owner/revision-checked world snapshot, character registry,
and survivor passages. A conflicting first claim is an ordinary lost race.
Only committed awards appear in the character view or affect combat/movement.
The immutable account ledger preserves title ownership after death and across
worlds; death records retain their titles and new lives inherit account awards.
This account inheritance is the initial interpretation of player-bound titles.
Awarded names, descriptions, effects, and provenance are copied at grant time;
later content changes do not remove or alter an earned title.
All earned title effects are active and additive, once per title ID. The initial
effect hooks are damage and movement speed; both accept positive and negative
values, with effective damage/speed floored at zero. They cannot alter death,
the daily play budget, or passage eligibility. The broader stat and effect
catalog remains open. See [progression configuration](PROGRESSION.md).
## Security scope
- Production login: OIDC verification (issuer, audience, signature, expiry), PKCE,
+27
View File
@@ -43,6 +43,33 @@ Configure `deploy/chart/values.yaml` (prefer an external GitOps values file):
4. Render and inspect with `helm lint` and `helm template`; validate against the
target cluster version using your normal dry-run pipeline.
## Keycloak administrator access
Create the exact realm role **`aeternalis-admin`** and assign it to your user.
The configured override is `OIDC_ADMIN_ROLE` (`control.adminRole` in Helm values);
the SRS deployment already uses `aeternalis-admin`.
The app checks the verified **ID token** for either
`realm_access.roles` or `resource_access[OIDC_CLIENT_ID].roles`. An access-token-only
role or a role belonging to a different client does not grant access.
For the realm-role approach, configure a User Realm Role mapper on the client's
dedicated scope with token claim `realm_access.roles`, no role prefix, type
String, Multivalued enabled, and **Add to ID token** enabled. If client role scope
is restricted, include `aeternalis-admin` in that scope. The SRS client is
`aeternalis-web`. Use Keycloak's token evaluation to check the ID token contains:
```json
{"realm_access":{"roles":["aeternalis-admin"]}}
```
Sign out of the game and sign back in at `/control` after assigning the role.
Existing game sessions do not gain admin privileges automatically. The admin
grant lasts ten minutes; sign in again from Control to renew it. Production
continues to require verified OIDC; `DEV_ADMIN` is restricted to loopback development.
See [Keycloak role token mappings](https://www.keycloak.org/docs/latest/server_admin/#_oidc_token_role_mappings).
## Gitea setup
Enable Actions in the repository. Use a runner with the `ubuntu-latest` label,
+92
View File
@@ -0,0 +1,92 @@
# Levels and permanent titles
Levels belong to a character. Titles belong to an account in this first pass,
so a new life inherits titles while starting at level 1 with no XP or stat
points. A dead character remains dead and keeps its historical progression.
Survivor passage preserves levels, XP, points, titles, and the daily time budget.
## Provisional level tuning
Edit `server/content/balance.yaml`. New characters start at level 1. Reaching
level 2 takes 100 XP; each following threshold costs 50 XP more. Every level
awards 5 banked stat points. The current safety cap is level 1000. All of these
values are configuration, not a settled stat or balance design.
Successful gathering gives 10 XP, crafting 20 XP, a sentinel kill 50 XP, and
the boss killing blow 500 XP. Nonlethal hits, failed actions, duplicate requests,
and actions after death give no XP. XP beyond a threshold carries into the next
level, including multiple level-ups from one reward. XP stops at the cap.
There is no stat allocation or client XP-grant API. Points remain banked until
the full stat system is designed. Character level curves and point grants are
stored with the character, so moving into differently tuned worlds cannot reset
or reprice earned progress. Activity XP rewards use the destination world's tuning.
## Title definitions
The YAML `titles` list is the initial authoring interface. Each entry needs a
stable `id`, `name`, `description`, `scope`, one or more `requirements`, and
`effects`. Requirements are ANDed and use positive integer `atLeast` thresholds.
| Requirement metric | Meaning |
| --- | --- |
| `level` | Current character level |
| `kills` | Lifetime sentinel kills for this character |
| `worldKills` | Sentinel kills since arriving in this world; resets on passage |
| `bossKills` | Boss killing blows for this character |
| `worldsSurvived` | Worlds survived when their boss dies, including offline survivors |
| `gathering`, `crafting`, `combat` | Existing character skill XP counters |
| `deaths` | 1 when this character dies, otherwise 0 |
| Scope | Award policy |
| --- | --- |
| `personal` | Any qualifying account can earn the title once |
| `world` | First qualifying account to commit the title claim in a world |
| `global` | First qualifying account to commit the title claim across the shared database |
“First ever” is determined by the first committed eligible transaction, starting
when the title is introduced. It cannot reconstruct an achievement predating
the title system. All production worlds must share the PostgreSQL database.
Within a world, candidates follow simulation event order. Simultaneous survivor
milestones break ties by character ID. An account already owning a title does
not earn it again or stack its effects by visiting another world.
The shipped starter examples are Wayfarer (level 2, +1 damage), First Hunter of
the World (first sentinel kill in a world, +2 damage), and The First Hunter
(first sentinel kill globally, +3 damage and -0.5 movement speed).
Effects are additive `damage` and `moveSpeed` values using existing game units.
Negative values are supported. Every owned title is active; effective damage
and movement speed cannot go below zero. There is no equip, remove, trade, or
revoke action. Future stat/effect hooks can extend this catalog without deciding
the final player stat list now.
```yaml
- id: burdened_survivor
name: Burdened Survivor
description: Survive a world after defeating at least ten sentinels.
scope: personal
requirements:
- { metric: worldsSurvived, atLeast: 1 }
- { metric: kills, atLeast: 10 }
effects: { damage: 4, moveSpeed: -1 }
```
Worlds persist their balance and title catalogs. YAML edits apply to new world
IDs; they do not hot-edit existing worlds or already-earned titles. Existing
worlds without progression are upgraded once with the starter defaults on
restore, with no retroactive XP or automatic historical first claims. New
definitions can match existing counters on the next qualifying gameplay event.
Treat published title IDs as permanent identities. Use a new ID for a distinct
award rather than repurposing an existing one.
## Verification and limits
Game tests cover successful-action XP, multi-level grants, caps, migration,
signed effects, death, daily limits, and survivor progress. Store tests cover
durable title claims, first-award races, retries/rollback, inheritance, and stale
source worlds. PostgreSQL integration tests require `TEST_DATABASE_URL`.
The tested world capacity is unchanged. This remains the existing checkpoint
persistence model: unacknowledged actions can be lost on a crash, and storage
failures freeze the owner before it can publish speculative progression.
+14
View File
@@ -64,6 +64,20 @@ Tracked across:
- Bad karma accrues from starting player-kills / being the aggressor.
- Good karma source — **unspecified, open question**.
## Player Progression and Titles
- Characters gain levels; every level-up awards stat points.
- The full stat list and allocation rules are still undecided. The first
implementation banks points without spending them.
- Titles have configurable requirements, a name, and positive or negative effects.
- Award scopes include personal achievements, first in a world, and first ever.
- Earned titles cannot be lost or transferred to another player.
- Initial implementation interprets player-bound titles as account-bound: they
carry to a replacement character after permanent death. Levels, XP, and banked
stat points belong to the individual character and survive survivor passage.
Account inheritance is an implementation assumption awaiting player-design confirmation.
- XP rewards, level curve, points per level, starter titles, and effect numbers
are provisional tuning in `server/content/balance.yaml`.
## Open Questions
- Good karma: what actions/behaviors generate it? — **undecided**.
- Mob scaling mechanics: does it reset on world regen? Is scaling per-node, per-server, or world-wide? — **undecided**.
+18 -1
View File
@@ -38,11 +38,28 @@
"entity": {"$ref": "#/definitions/Entity"},
"inventory": {"type": "object", "additionalProperties": {"type": "integer"}},
"skills": {"type": "object", "additionalProperties": {"type": "integer"}},
"level": {"type": "integer"}, "experience": {"type": "integer"},
"experienceToNextLevel": {"type": "integer"}, "statPoints": {"type": "integer"},
"titles": {"type": "array", "items": {"$ref": "#/definitions/TitleAward"}},
"playedSeconds": {"type": "number"}, "remainingSeconds": {"type": "number"},
"kills": {"type": "integer"}, "ack": {"type": "integer"},
"hasKeystone": {"type": "boolean"}
},
"required": ["entity", "inventory", "skills", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone"]
"required": ["entity", "inventory", "skills", "level", "experience", "experienceToNextLevel", "statPoints", "titles", "playedSeconds", "remainingSeconds", "kills", "ack", "hasKeystone"]
},
"TitleEffects": {
"type": "object", "additionalProperties": false,
"properties": {"damage": {"type": "number"}, "moveSpeed": {"type": "number"}},
"required": ["damage", "moveSpeed"]
},
"TitleAward": {
"type": "object", "additionalProperties": false,
"properties": {
"id": {"type": "string"}, "name": {"type": "string"}, "description": {"type": "string"},
"scope": {"type": "string"}, "worldId": {"type": "string"}, "earnedAt": {"type": "string"},
"effects": {"$ref": "#/definitions/TitleEffects"}
},
"required": ["id", "name", "description", "scope", "worldId", "earnedAt", "effects"]
},
"Chunk": {
"type": "object", "additionalProperties": false,
+30
View File
@@ -46,3 +46,33 @@ recipes:
inputs: { herb: 2 }
outputs: { bandage: 1 }
bandageHealing: 35
# Provisional progression tuning; stat allocation waits for the full stat design.
progression:
baseXp: 100
xpPerLevel: 50
statPointsPerLevel: 5
maxLevel: 1000
gatherXp: 10
craftXp: 20
mobKillXp: 50
bossKillXp: 500
# Starter definitions. Requirements are ANDed; awarded definitions are immutable.
titles:
- id: wayfarer
name: Wayfarer
description: Reach level 2 in one life.
scope: personal
requirements: [{ metric: level, atLeast: 2 }]
effects: { damage: 1, moveSpeed: 0 }
- id: world_first_hunter
name: First Hunter of the World
description: Be the first to defeat a sentinel in this world.
scope: world
requirements: [{ metric: worldKills, atLeast: 1 }]
effects: { damage: 2, moveSpeed: 0 }
- id: first_hunter
name: The First Hunter
description: Be the first ever to defeat a sentinel. Power comes with a heavier step.
scope: global
requirements: [{ metric: worldKills, atLeast: 1 }]
effects: { damage: 3, moveSpeed: -0.5 }
+5
View File
@@ -57,6 +57,8 @@ type Balance struct {
StartingKit map[string]int64 `yaml:"startingKit"`
Recipes map[string]Recipe `yaml:"recipes"`
BandageHealing float64 `yaml:"bandageHealing"`
Progression *Progression `yaml:"progression"`
Titles []Title `yaml:"titles"`
}
func Load() (Balance, error) { return Parse(balance) }
@@ -70,6 +72,9 @@ func Parse(data []byte) (Balance, error) {
return b, b.Validate()
}
func (b Balance) Validate() error {
if err := b.validateProgression(); err != nil {
return err
}
v := reflect.ValueOf(b)
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
+88
View File
@@ -0,0 +1,88 @@
package content
import (
"fmt"
"math"
"regexp"
)
type Progression struct {
BaseXP int64 `yaml:"baseXp"`
XPPerLevel int64 `yaml:"xpPerLevel"`
StatPointsPerLevel int64 `yaml:"statPointsPerLevel"`
MaxLevel int64 `yaml:"maxLevel"`
GatherXP int64 `yaml:"gatherXp"`
CraftXP int64 `yaml:"craftXp"`
MobKillXP int64 `yaml:"mobKillXp"`
BossKillXP int64 `yaml:"bossKillXp"`
}
type TitleRequirement struct {
Metric string `yaml:"metric"`
AtLeast int64 `yaml:"atLeast"`
}
type TitleEffects struct {
Damage float64 `yaml:"damage"`
MoveSpeed float64 `yaml:"moveSpeed"`
}
type Title struct {
ID string `yaml:"id"`
Name string `yaml:"name"`
Description string `yaml:"description"`
Scope string `yaml:"scope"`
Requirements []TitleRequirement `yaml:"requirements"`
Effects TitleEffects `yaml:"effects"`
}
var titleID = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,63}$`)
func (b Balance) validateProgression() error {
if b.Progression == nil {
return fmt.Errorf("progression configuration is required")
}
if err := b.Progression.Validate(); err != nil {
return err
}
if len(b.Titles) > 256 {
return fmt.Errorf("too many title definitions")
}
seen := map[string]bool{}
metrics := map[string]bool{"level": true, "kills": true, "worldKills": true, "bossKills": true, "worldsSurvived": true, "gathering": true, "crafting": true, "combat": true, "deaths": true}
for _, title := range b.Titles {
if !titleID.MatchString(title.ID) || seen[title.ID] || len(title.Name) < 1 || len(title.Name) > 80 || len(title.Description) > 500 {
return fmt.Errorf("invalid or duplicate title %q", title.ID)
}
seen[title.ID] = true
if title.Scope != "personal" && title.Scope != "world" && title.Scope != "global" {
return fmt.Errorf("invalid title scope %q", title.Scope)
}
if len(title.Requirements) < 1 || len(title.Requirements) > 8 {
return fmt.Errorf("title %q needs bounded requirements", title.ID)
}
for _, r := range title.Requirements {
if !metrics[r.Metric] || r.AtLeast < 1 || r.AtLeast > 1000000000 {
return fmt.Errorf("invalid title requirement for %q", title.ID)
}
}
for _, effect := range []float64{title.Effects.Damage, title.Effects.MoveSpeed} {
if math.IsNaN(effect) || math.IsInf(effect, 0) || math.Abs(effect) > 1000 {
return fmt.Errorf("invalid title effect for %q", title.ID)
}
}
}
return nil
}
func (p Progression) Validate() error {
if p.BaseXP < 1 || p.BaseXP > 1000000000 || p.XPPerLevel < 0 || p.XPPerLevel > 1000000000 || p.StatPointsPerLevel < 1 || p.StatPointsPerLevel > 1000 || p.MaxLevel < 2 || p.MaxLevel > 10000 {
return fmt.Errorf("invalid progression curve or stat point grant")
}
for _, xp := range []int64{p.GatherXP, p.CraftXP, p.MobKillXP, p.BossKillXP} {
if xp < 0 || xp > 1000000000 {
return fmt.Errorf("invalid progression XP reward")
}
}
return nil
}
+43
View File
@@ -0,0 +1,43 @@
package content
import (
"math"
"testing"
)
func TestProgressionAndTitleValidation(t *testing.T) {
for name, mutate := range map[string]func(*Balance){
"missing progression": func(b *Balance) { b.Progression = nil },
"zero threshold": func(b *Balance) { b.Progression.BaseXP = 0 },
"negative growth": func(b *Balance) { b.Progression.XPPerLevel = -1 },
"point grant": func(b *Balance) { b.Progression.StatPointsPerLevel = 0 },
"overflow curve": func(b *Balance) { b.Progression.BaseXP = math.MaxInt64 },
"unbounded cap": func(b *Balance) { b.Progression.MaxLevel = math.MaxInt64 },
"negative reward": func(b *Balance) { b.Progression.GatherXP = -1 },
"duplicate title": func(b *Balance) { b.Titles = append(b.Titles, b.Titles[0]) },
"bad scope": func(b *Balance) { b.Titles[0].Scope = "client" },
"no requirements": func(b *Balance) { b.Titles[0].Requirements = nil },
"unknown metric": func(b *Balance) { b.Titles[0].Requirements[0].Metric = "clientXp" },
"invalid threshold": func(b *Balance) { b.Titles[0].Requirements[0].AtLeast = 0 },
"infinite effect": func(b *Balance) { b.Titles[0].Effects.Damage = math.Inf(1) },
"nan effect": func(b *Balance) { b.Titles[0].Effects.MoveSpeed = math.NaN() },
} {
t.Run(name, func(t *testing.T) {
b, err := Load()
if err != nil {
t.Fatal(err)
}
mutate(&b)
if b.Validate() == nil {
t.Fatal("invalid content accepted")
}
})
}
b, _ := Load()
b.Titles[0].Effects.Damage = -5
b.Titles[0].Effects.MoveSpeed = -1
b.Progression.GatherXP = 0
if err := b.Validate(); err != nil {
t.Fatalf("valid penalty or disabled reward rejected: %v", err)
}
}
+162
View File
@@ -0,0 +1,162 @@
package game
import (
"errors"
"fmt"
"math"
"sort"
"time"
p "aeternalis/server/internal/protocol"
)
// Candidates are produced in simulation event order. Only a successful store
// transaction may turn them into permanent awards and enable their effects.
type TitleCandidate struct {
CharacterID string
Award p.TitleAward
}
func (w *World) orderedCharacters() []*Character {
ids := make([]string, 0, len(w.Characters))
for id := range w.Characters {
ids = append(ids, id)
}
sort.Strings(ids)
characters := make([]*Character, 0, len(ids))
for _, id := range ids {
characters = append(characters, w.Characters[id])
}
return characters
}
func (w *World) restoreProgression(c *Character) error {
if c.Progression == nil {
rules := *w.Balance.Progression
c.Progression = &rules
}
if err := c.Progression.Validate(); err != nil {
return err
}
if c.View.Level == 0 {
c.View.Level = 1
}
if c.View.Level < 1 || c.View.Level > c.Progression.MaxLevel || c.View.Experience < 0 || c.View.StatPoints < 0 {
return errors.New("invalid persisted character progression")
}
c.View.ExperienceToNextLevel = c.nextLevelXP()
if (c.View.ExperienceToNextLevel == 0 && c.View.Experience != 0) || (c.View.ExperienceToNextLevel > 0 && c.View.Experience >= c.View.ExperienceToNextLevel) {
return errors.New("invalid persisted level XP")
}
if c.View.Titles == nil {
c.View.Titles = []p.TitleAward{}
}
return nil
}
func (c *Character) nextLevelXP() int64 {
if c.View.Level >= c.Progression.MaxLevel {
return 0
}
return c.Progression.BaseXP + (c.View.Level-1)*c.Progression.XPPerLevel
}
func (w *World) grantXP(c *Character, amount int64) {
if amount <= 0 || c.View.Entity.State != "alive" || c.View.Level >= c.Progression.MaxLevel {
return
}
c.View.Experience += amount
before := c.View.Level
for c.View.Level < c.Progression.MaxLevel && c.View.Experience >= c.nextLevelXP() {
c.View.Experience -= c.nextLevelXP()
c.View.Level++
c.View.StatPoints += c.Progression.StatPointsPerLevel
}
c.View.ExperienceToNextLevel = c.nextLevelXP()
if c.View.ExperienceToNextLevel == 0 {
c.View.Experience = 0
}
if c.View.Level > before {
c.Message = fmt.Sprintf("Level %d reached. %d stat points banked.", c.View.Level, c.View.StatPoints)
}
w.dirty = true
}
func (w *World) evaluateTitles(c *Character) {
metric := func(name string) int64 {
switch name {
case "level":
return c.View.Level
case "kills":
return c.View.Kills
case "worldKills":
return c.WorldKills
case "bossKills":
return c.BossKills
case "worldsSurvived":
return c.WorldsSurvived
case "deaths":
if c.View.Entity.State == "dead" {
return 1
}
return 0
default:
return c.View.Skills[name]
}
}
for _, title := range w.Balance.Titles {
owned := false
for _, award := range c.View.Titles {
if award.ID == title.ID {
owned = true
break
}
}
if owned {
continue
}
for _, pending := range w.PendingTitles {
if pending.CharacterID == c.View.Entity.ID && pending.Award.ID == title.ID {
owned = true
break
}
}
if owned {
continue
}
eligible := true
for _, requirement := range title.Requirements {
if metric(requirement.Metric) < requirement.AtLeast {
eligible = false
break
}
}
if !eligible {
continue
}
w.PendingTitles = append(w.PendingTitles, TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{
ID: title.ID, Name: title.Name, Description: title.Description, Scope: title.Scope, WorldID: w.ID,
EarnedAt: w.now.UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: title.Effects.Damage, MoveSpeed: title.Effects.MoveSpeed},
}})
w.dirty = true
}
}
func (c *Character) titleEffects() p.TitleEffects {
var effects p.TitleEffects
// One effect per permanent title ID, even if legacy data contains duplicates.
seen := map[string]bool{}
for _, title := range c.View.Titles {
if seen[title.ID] {
continue
}
seen[title.ID] = true
effects.Damage += title.Effects.Damage
effects.MoveSpeed += title.Effects.MoveSpeed
}
return effects
}
func (w *World) playerSpeed(c *Character) float64 {
return math.Max(0, w.Balance.PlayerSpeed+c.titleEffects().MoveSpeed)
}
+286
View File
@@ -0,0 +1,286 @@
package game
import (
"encoding/json"
"math"
"reflect"
"sort"
"testing"
"time"
"aeternalis/server/content"
p "aeternalis/server/internal/protocol"
)
func TestLevelUpsBankPointsAndCap(t *testing.T) {
w, c := fixture(t)
if c.View.Level != 1 || c.View.StatPoints != 0 || c.View.ExperienceToNextLevel != 100 {
t.Fatal("incorrect new life progression")
}
w.grantXP(c, 99)
if c.View.Level != 1 || c.View.Experience != 99 {
t.Fatal("premature level")
}
w.grantXP(c, 151)
if c.View.Level != 3 || c.View.Experience != 0 || c.View.StatPoints != 10 || c.View.ExperienceToNextLevel != 200 {
t.Fatalf("multi-level award lost points or XP: %+v", c.View)
}
c.Progression.MaxLevel = 4
w.grantXP(c, 1000000)
if c.View.Level != 4 || c.View.StatPoints != 15 || c.View.Experience != 0 || c.View.ExperienceToNextLevel != 0 {
t.Fatal("level cap failed")
}
w.grantXP(c, 1000000)
if c.View.StatPoints != 15 {
t.Fatal("cap farming granted extra points")
}
}
func TestOnlySuccessfulActionsGrantXP(t *testing.T) {
w, c := fixture(t)
id := c.View.Entity.ID
w.now = w.now.Add(2 * time.Second)
for seq, op := range []string{"grant-xp", "level-up", "spend-stat", "grant-title", "remove-title", "gather", "craft", "attack"} {
if w.Intent(id, p.Intent{Op: op, Seq: int64(seq + 1), Target: "invalid"}) == nil {
t.Fatalf("invalid %s accepted", op)
}
}
if c.View.Experience != 0 || c.View.StatPoints != 0 || len(w.PendingTitles) != 0 {
t.Fatal("failed intent awarded progression")
}
c.View.Entity.Position = w.terrain.Position(17, 12)
if err := w.Intent(id, p.Intent{Op: "gather", Seq: 9, Target: "arrival:ore"}); err != nil {
t.Fatal(err)
}
if c.View.Experience != w.Balance.Progression.GatherXP {
t.Fatal("missing gather XP")
}
if w.Intent(id, p.Intent{Op: "gather", Seq: 10, Target: "arrival:ore"}) == nil {
t.Fatal("duplicate gather")
}
if c.View.Experience != w.Balance.Progression.GatherXP {
t.Fatal("failed gather gained XP")
}
c.View.Inventory["herb"] = 2
if err := w.Intent(id, p.Intent{Op: "craft", Seq: 11, Target: "bandage"}); err != nil {
t.Fatal(err)
}
before := c.View.Experience
if before != w.Balance.Progression.GatherXP+w.Balance.Progression.CraftXP {
t.Fatal("missing craft XP")
}
w.Mobs["test"] = &Mob{Entity: p.Entity{ID: "test", HP: w.Balance.PlayerDamage + 1, Position: c.View.Entity.Position}}
if err := w.Intent(id, p.Intent{Op: "attack", Seq: 12, Target: "test"}); err != nil {
t.Fatal(err)
}
if c.View.Experience != before {
t.Fatal("nonlethal hit granted kill XP")
}
w.now = w.now.Add(time.Second)
if err := w.Intent(id, p.Intent{Op: "attack", Seq: 13, Target: "test"}); err != nil {
t.Fatal(err)
}
if c.View.Experience != before+w.Balance.Progression.MobKillXP || c.WorldKills != 1 {
t.Fatal("missing kill XP")
}
w.now = w.now.Add(time.Second)
if w.Intent(id, p.Intent{Op: "attack", Seq: 14, Target: "test"}) == nil {
t.Fatal("dead mob killed twice")
}
if c.View.Kills != 1 || c.View.Experience != before+w.Balance.Progression.MobKillXP {
t.Fatal("duplicate kill progression")
}
}
func TestProgressionSurvivesRestartDeathAndTransfer(t *testing.T) {
w, c := fixture(t)
w.grantXP(c, 275)
c.View.Titles = []p.TitleAward{{ID: "bound", Name: "Bound", Scope: "personal", Effects: p.TitleEffects{Damage: 2}}}
c.DailySeconds = 123
c.WorldKills = 7
raw, err := json.Marshal(w)
if err != nil {
t.Fatal(err)
}
var restored World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err = restored.Restore(w.now); err != nil {
t.Fatal(err)
}
loaded := restored.Characters[c.View.Entity.ID]
if loaded.View.Level != 3 || loaded.View.Experience != 25 || loaded.View.StatPoints != 10 || !reflect.DeepEqual(loaded.View.Titles, c.View.Titles) {
t.Fatal("restart reset progression")
}
loaded.View.Entity.State = "eligible"
changed := w.Balance
rules := *changed.Progression
rules.BaseXP = 1
rules.StatPointsPerLevel = 100
changed.Progression = &rules
destination := New("destination", 999, w.now, changed)
if err = destination.Import(loaded); err != nil {
t.Fatal(err)
}
if loaded.View.ExperienceToNextLevel != 200 || loaded.Progression.StatPointsPerLevel != 5 || loaded.DailySeconds != 123 || loaded.WorldKills != 0 || loaded.View.StatPoints != 10 || len(loaded.View.Titles) != 1 {
t.Fatal("transfer altered progression, titles, or daily budget")
}
destination.kill(loaded, "test death")
destination.grantXP(loaded, 1000)
if loaded.View.StatPoints != 10 || loaded.View.Experience != 25 || len(loaded.View.Titles) != 1 {
t.Fatal("death erased progression or allowed postmortem XP")
}
replacement, err := destination.Join(loaded.Account, "Replacement")
if err != nil {
t.Fatal(err)
}
if replacement.View.Level != 1 || replacement.View.StatPoints != 0 || replacement.View.Entity.ID == loaded.View.Entity.ID {
t.Fatal("replacement inherited character levels")
}
if destination.Connect(loaded.View.Entity.ID) == nil {
t.Fatal("progression resurrected dead character")
}
}
func TestLegacySnapshotProgressionMigrationIsIdempotent(t *testing.T) {
w, c := fixture(t)
w.Balance.Progression = nil
w.Balance.Titles = nil
c.Progression = nil
c.View.Level = 0
c.View.ExperienceToNextLevel = 0
c.View.Titles = nil
c.View.Kills = 42
c.View.Skills["gathering"] = 99
c.DailySeconds = 456
c.View.Entity.State = "dead"
if err := w.Restore(w.now); err != nil {
t.Fatal(err)
}
if c.View.Level != 1 || c.View.Experience != 0 || c.View.StatPoints != 0 || c.View.Titles == nil || c.DailySeconds != 456 || c.View.Entity.State != "dead" {
t.Fatal("legacy migration changed life/budget or backfilled XP")
}
if err := w.Restore(w.now); err != nil {
t.Fatal(err)
}
if c.View.StatPoints != 0 || len(w.PendingTitles) != 0 {
t.Fatal("migration minted grants")
}
}
func TestTitleRequirementsAndPendingAwardsHaveNoEffects(t *testing.T) {
w, c := fixture(t)
w.Balance.Titles = []content.Title{{ID: "trial", Name: "Trial", Scope: "world", Requirements: []content.TitleRequirement{{Metric: "level", AtLeast: 2}, {Metric: "worldKills", AtLeast: 1}}, Effects: content.TitleEffects{Damage: 3, MoveSpeed: -2}}}
w.grantXP(c, 100)
w.evaluateTitles(c)
if len(w.PendingTitles) != 0 {
t.Fatal("requirements were not ANDed")
}
c.WorldKills = 1
w.evaluateTitles(c)
w.evaluateTitles(c)
if len(w.PendingTitles) != 1 || len(c.View.Titles) != 0 || w.playerSpeed(c) != w.Balance.PlayerSpeed {
t.Fatal("candidate duplicated or applied before durable award")
}
award := w.PendingTitles[0].Award
if award.WorldID != w.ID || award.Scope != "world" || award.Effects.MoveSpeed != -2 || award.EarnedAt == "" {
t.Fatal("candidate lost provenance or negative effect")
}
c.View.Titles = append(c.View.Titles, award)
w.PendingTitles = nil
w.Balance.Titles[0].Effects.MoveSpeed = 99
c.WorldKills = 0
w.evaluateTitles(c)
if len(w.PendingTitles) != 0 || w.playerSpeed(c) != w.Balance.PlayerSpeed-2 {
t.Fatal("lost requirement or edited catalog changed earned award")
}
}
func TestSignedTitleEffectsAreServerAuthoritative(t *testing.T) {
w, c := fixture(t)
c.View.Titles = []p.TitleAward{{ID: "blessing", Effects: p.TitleEffects{Damage: 5, MoveSpeed: 2}}, {ID: "curse", Effects: p.TitleEffects{Damage: -2, MoveSpeed: -1}}}
w.now = w.now.Add(2 * time.Second)
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "move", Seq: 1, X: 1}); err != nil {
t.Fatal(err)
}
before := c.View.Entity.Position
w.Advance(w.now.Add(50*time.Millisecond), .05)
if math.Abs(distance(before, c.View.Entity.Position)-(w.Balance.PlayerSpeed+1)*.05) > 1e-8 {
t.Fatal("title movement effect not applied")
}
w.Mobs["target"] = &Mob{Entity: p.Entity{ID: "target", HP: 100, Position: c.View.Entity.Position}}
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "target"}); err != nil {
t.Fatal(err)
}
if w.Mobs["target"].Entity.HP != 100-w.Balance.PlayerDamage-3 {
t.Fatal("signed damage effects not applied")
}
c.View.Titles = append(c.View.Titles, p.TitleAward{ID: "heavy", Effects: p.TitleEffects{Damage: -1000, MoveSpeed: -1000}})
if w.playerSpeed(c) != 0 {
t.Fatal("negative speed reversed movement")
}
w.now = w.now.Add(time.Second)
hp := w.Mobs["target"].Entity.HP
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 3, Target: "target"}); err != nil {
t.Fatal(err)
}
if w.Mobs["target"].Entity.HP != hp {
t.Fatal("negative damage healed target")
}
w.Balance.DailyPlaySeconds = 1
c.View.Entity.HP = 20
w.Advance(w.now.Add(2*time.Second), 2)
if c.Online || c.View.RemainingSeconds != 0 || c.View.Entity.HP != 50 {
t.Fatal("title effects weakened daily cap")
}
}
func TestBossXPAndSurvivalMilestoneGrantedOnce(t *testing.T) {
w, c := fixture(t)
offline, _ := w.Join("offline", "Offline")
dead, _ := w.Join("dead", "Dead")
w.kill(dead, "test")
w.now = w.now.Add(time.Second)
if err := w.TriggerBoss(); err != nil {
t.Fatal(err)
}
w.BossHP = 1
if err := w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 1, Target: "boss"}); err != nil {
t.Fatal(err)
}
if c.BossKills != 1 || c.WorldsSurvived != 1 || offline.WorldsSurvived != 1 || dead.WorldsSurvived != 0 || c.View.Level != 4 || c.View.Experience != 50 || c.View.StatPoints != 15 {
t.Fatal("incorrect boss progression")
}
if w.Intent(c.View.Entity.ID, p.Intent{Op: "attack", Seq: 2, Target: "boss"}) == nil {
t.Fatal("repeat boss kill")
}
if c.BossKills != 1 || c.View.StatPoints != 15 {
t.Fatal("duplicate boss rewards")
}
}
func TestCollapseTitleMilestonesKeepDeterministicOrderAndDeath(t *testing.T) {
w, c := fixture(t)
w.Balance.Titles = []content.Title{{ID: "worlds_fallen", Name: "World's Fallen", Scope: "world", Requirements: []content.TitleRequirement{{Metric: "deaths", AtLeast: 1}}, Effects: content.TitleEffects{Damage: -1}}}
other, err := w.Join("other", "Other")
if err != nil {
t.Fatal(err)
}
c.Online = false
ids := []string{c.View.Entity.ID, other.View.Entity.ID}
sort.Strings(ids)
w.Advance(w.CreatedAt.Add(time.Duration(w.Balance.SeasonSeconds+w.Balance.CollapseSeconds+1)*time.Second), .05)
if w.Phase != "lost" || len(w.PendingTitles) != 2 {
t.Fatal("collapse did not queue death milestones")
}
for i, id := range ids {
if w.PendingTitles[i].CharacterID != id || w.Characters[id].View.Entity.State != "dead" || len(w.Characters[id].View.Titles) != 0 {
t.Fatal("simultaneous deaths changed award order, life state, or prematurely granted title")
}
w.kill(w.Characters[id], "duplicate")
}
if len(w.PendingTitles) != 2 {
t.Fatal("duplicate death milestone")
}
}
+78 -24
View File
@@ -14,22 +14,26 @@ import (
)
type Character struct {
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
DailySeconds float64 `json:"dailySeconds"`
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
Sheltered bool `json:"sheltered"`
LastAttack float64 `json:"lastAttack"`
LastGather float64 `json:"lastGather"`
Online bool `json:"-"`
MoveX float64 `json:"-"`
MoveZ float64 `json:"-"`
LastMove time.Time `json:"-"`
Message string `json:"-"`
BornAt time.Time `json:"bornAt"`
DiedAt *time.Time `json:"diedAt,omitempty"`
DeathReason string `json:"deathReason,omitempty"`
View p.Character `json:"view"`
Account string `json:"account"`
Day string `json:"day"`
DailySeconds float64 `json:"dailySeconds"`
ReturnPosition *p.Vec3 `json:"returnPosition,omitempty"`
Sheltered bool `json:"sheltered"`
LastAttack float64 `json:"lastAttack"`
LastGather float64 `json:"lastGather"`
Online bool `json:"-"`
MoveX float64 `json:"-"`
MoveZ float64 `json:"-"`
LastMove time.Time `json:"-"`
Message string `json:"-"`
BornAt time.Time `json:"bornAt"`
DiedAt *time.Time `json:"diedAt,omitempty"`
DeathReason string `json:"deathReason,omitempty"`
Progression *content.Progression `json:"progression,omitempty"`
WorldKills int64 `json:"worldKills"`
BossKills int64 `json:"bossKills"`
WorldsSurvived int64 `json:"worldsSurvived"`
}
type Corpse struct {
Entity p.Entity `json:"entity"`
@@ -58,6 +62,7 @@ type World struct {
Depleted map[string]float64 `json:"depleted"`
Mobs map[string]*Mob `json:"mobs"`
Balance content.Balance `json:"balance"`
PendingTitles []TitleCandidate `json:"-"`
terrain *Terrain
chunks map[string]p.Chunk
now time.Time
@@ -80,6 +85,19 @@ func (w *World) Restore(now time.Time) error {
if w.Version != GeneratorVersion {
return errors.New("unsupported persisted generator version")
}
// Snapshots predating progression receive the YAML defaults once. Existing
// world tuning and character lives remain intact; old actions grant no backfill XP.
if w.Balance.Progression == nil {
defaults, err := content.Load()
if err != nil {
return err
}
w.Balance.Progression = defaults.Progression
if w.Balance.Titles == nil {
w.Balance.Titles = defaults.Titles
}
w.dirty = true
}
if err := w.Balance.Validate(); err != nil {
return err
}
@@ -89,7 +107,11 @@ func (w *World) Restore(now time.Time) error {
w.terrain = NewTerrain(w.Seed, w.Balance)
w.chunks = map[string]p.Chunk{}
w.now = now
w.PendingTitles = nil
for _, c := range w.Characters {
if err := w.restoreProgression(c); err != nil {
return err
}
c.Online = false
c.MoveX = 0
c.MoveZ = 0
@@ -177,11 +199,15 @@ func (w *World) Join(account, name string) (*Character, error) {
return nil, err
}
c := &Character{Account: account, Day: w.now.UTC().Format(time.DateOnly), View: p.Character{Entity: p.Entity{ID: ID(), Kind: "player", Name: name, Position: pos, HP: w.Balance.PlayerHp, MaxHP: w.Balance.PlayerHp, State: "alive"}, Inventory: map[string]int64{}, Skills: map[string]int64{}, RemainingSeconds: w.Balance.DailyPlaySeconds}}
if err := w.restoreProgression(c); err != nil {
return nil, err
}
for k, v := range w.Balance.StartingKit {
c.View.Inventory[k] = v
}
w.Characters[c.View.Entity.ID] = c
c.BornAt = w.now
w.evaluateTitles(c)
w.dirty = true
return c, nil
}
@@ -192,6 +218,9 @@ func (w *World) Import(c *Character) error {
if c.View.Entity.State != "eligible" || c.View.Entity.HP <= 0 {
return errors.New("character is not a living survivor")
}
if err := w.restoreProgression(c); err != nil {
return err
}
pos, err := w.spawn("")
if err != nil {
return err
@@ -207,6 +236,7 @@ func (w *World) Import(c *Character) error {
c.ReturnPosition = nil
c.Sheltered = false
c.View.HasKeystone = false
c.WorldKills = 0
w.resetDay(c)
w.Characters[c.View.Entity.ID] = c
w.dirty = true
@@ -356,6 +386,8 @@ func (w *World) gather(c *Character, target string) error {
w.Depleted[target] = w.Age() + w.Balance.ResourceRespawnSeconds
w.dirty = true
c.Message = "Gathered " + item
w.grantXP(c, w.Balance.Progression.GatherXP)
w.evaluateTitles(c)
return nil
}
}
@@ -379,6 +411,8 @@ func (w *World) craft(c *Character, name string) error {
}
c.View.Skills["crafting"] += w.Balance.SkillXpPerAction
c.Message = "Crafted " + name
w.grantXP(c, w.Balance.Progression.CraftXP)
w.evaluateTitles(c)
w.dirty = true
return nil
}
@@ -390,17 +424,24 @@ func (w *World) attack(c *Character, target string) error {
if c.View.Inventory["spear"] > 0 {
damage = w.Balance.SpearDamage
}
damage = math.Max(0, damage+c.titleEffects().Damage)
if target == "boss" {
if w.Phase != "cataclysm" || distance(c.View.Entity.Position, w.terrain.Position(0, 0)) > w.Balance.AttackRange+4 {
return errors.New("boss out of reach")
}
w.BossHP = math.Max(0, w.BossHP-damage)
if w.BossHP == 0 {
c.BossKills++
w.grantXP(c, w.Balance.Progression.BossKillXP)
w.evaluateTitles(c)
w.Phase = "won"
ended := w.now
w.EndedAt = &ended
for _, survivor := range w.Characters {
// Stable order for simultaneous survivor milestone candidates.
for _, survivor := range w.orderedCharacters() {
if survivor.View.Entity.State == "alive" {
survivor.WorldsSurvived++
w.evaluateTitles(survivor)
survivor.View.Entity.State = "eligible"
survivor.MoveX = 0
survivor.MoveZ = 0
@@ -418,11 +459,14 @@ func (w *World) attack(c *Character, target string) error {
m.Entity.State = "dead"
m.RespawnAt = w.Age() + w.Balance.MobRespawnSeconds
c.View.Kills++
c.WorldKills++
c.View.Inventory["herb"]++
w.grantXP(c, w.Balance.Progression.MobKillXP)
}
}
c.LastAttack = w.Age()
c.View.Skills["combat"] += w.Balance.SkillXpPerAction
w.evaluateTitles(c)
w.dirty = true
return nil
}
@@ -447,6 +491,7 @@ func (w *World) kill(c *Character, reason string) {
died := w.now
c.DiedAt = &died
c.DeathReason = reason
w.evaluateTitles(c)
w.dirty = true
}
@@ -464,7 +509,7 @@ func (w *World) Control(op, target, value, reason string) error {
if w.Phase == "won" || w.Phase == "lost" {
return errors.New("world has already ended")
}
for _, c := range w.Characters {
for _, c := range w.orderedCharacters() {
w.kill(c, "World ended by an operator: "+reason)
}
w.Phase = "lost"
@@ -508,7 +553,8 @@ func (w *World) Advance(now time.Time, dt float64) {
w.dirty = true
}
active := map[string]bool{}
for _, c := range w.Characters {
characters := w.orderedCharacters()
for _, c := range characters {
if c.View.Entity.State != "alive" {
continue
}
@@ -541,7 +587,8 @@ func (w *World) Advance(now time.Time, dt float64) {
c.MoveZ = 0
}
pos := c.View.Entity.Position
nx, nz := pos.X+c.MoveX*w.Balance.PlayerSpeed*dt, pos.Z+c.MoveZ*w.Balance.PlayerSpeed*dt
speed := w.playerSpeed(c)
nx, nz := pos.X+c.MoveX*speed*dt, pos.Z+c.MoveZ*speed*dt
if math.Hypot(nx, nz) < w.Balance.WorldRadius {
c.View.Entity.Position = w.terrain.Position(nx, nz)
}
@@ -561,7 +608,7 @@ func (w *World) Advance(now time.Time, dt float64) {
w.updateMobs(active, dt)
if w.Phase == "cataclysm" {
if w.Age()-w.BossLastAttack >= w.Balance.BossCooldown {
for _, c := range w.Characters {
for _, c := range characters {
if c.Online && !c.Sheltered && c.View.Entity.State == "alive" && distance(c.View.Entity.Position, w.terrain.Position(0, 0)) <= w.Balance.BossRange {
c.View.Entity.HP -= w.Balance.BossDamage
w.dirty = true
@@ -579,7 +626,7 @@ func (w *World) Advance(now time.Time, dt float64) {
}
}
if w.SafeRadius() <= 0 || (len(w.Characters) > 0 && alive == 0) {
for _, c := range w.Characters {
for _, c := range characters {
w.kill(c, "The world has been destroyed.")
}
w.Phase = "lost"
@@ -613,7 +660,14 @@ func (w *World) ensureMob(ch p.Chunk) {
w.Mobs[id] = &Mob{Entity: p.Entity{ID: id, Kind: "sentinel", Name: "Ash sentinel", Position: w.terrain.Position(x, z), HP: hp, MaxHP: hp, State: "alive"}, HomeX: int(ch.X), HomeZ: int(ch.Z)}
}
func (w *World) updateMobs(active map[string]bool, dt float64) {
for id, m := range w.Mobs {
mobIDs := make([]string, 0, len(w.Mobs))
for id := range w.Mobs {
mobIDs = append(mobIDs, id)
}
sort.Strings(mobIDs)
characters := w.orderedCharacters()
for _, id := range mobIDs {
m := w.Mobs[id]
key := Key(m.HomeX, m.HomeZ)
if !active[key] {
if m.Entity.HP == m.Entity.MaxHP || (m.Entity.HP <= 0 && w.Age() >= m.RespawnAt) {
@@ -631,7 +685,7 @@ func (w *World) updateMobs(active map[string]bool, dt float64) {
}
var target *Character
nearest := w.Balance.MobAggroRange
for _, c := range w.Characters {
for _, c := range characters {
if !c.Online || c.View.Entity.State != "alive" || c.Sheltered {
continue
}
+28 -8
View File
@@ -55,14 +55,34 @@ type Vec3 struct {
}
type Character struct {
ACK int64 `json:"ack"`
Entity Entity `json:"entity"`
HasKeystone bool `json:"hasKeystone"`
Inventory map[string]int64 `json:"inventory"`
Kills int64 `json:"kills"`
PlayedSeconds float64 `json:"playedSeconds"`
RemainingSeconds float64 `json:"remainingSeconds"`
Skills map[string]int64 `json:"skills"`
ACK int64 `json:"ack"`
Entity Entity `json:"entity"`
Experience int64 `json:"experience"`
ExperienceToNextLevel int64 `json:"experienceToNextLevel"`
HasKeystone bool `json:"hasKeystone"`
Inventory map[string]int64 `json:"inventory"`
Kills int64 `json:"kills"`
Level int64 `json:"level"`
PlayedSeconds float64 `json:"playedSeconds"`
RemainingSeconds float64 `json:"remainingSeconds"`
Skills map[string]int64 `json:"skills"`
StatPoints int64 `json:"statPoints"`
Titles []TitleAward `json:"titles"`
}
type TitleAward struct {
Description string `json:"description"`
EarnedAt string `json:"earnedAt"`
Effects TitleEffects `json:"effects"`
ID string `json:"id"`
Name string `json:"name"`
Scope string `json:"scope"`
WorldID string `json:"worldId"`
}
type TitleEffects struct {
Damage float64 `json:"damage"`
MoveSpeed float64 `json:"moveSpeed"`
}
type WorldInfo struct {
+1
View File
@@ -64,6 +64,7 @@ func (d *DB) migrate(ctx context.Context) error {
}
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS schema_migrations(version INTEGER PRIMARY KEY)`,
`CREATE TABLE IF NOT EXISTS title_awards(account_id TEXT NOT NULL, title_id TEXT NOT NULL, scope TEXT NOT NULL, scope_key TEXT NOT NULL, character_id TEXT NOT NULL, award TEXT NOT NULL, PRIMARY KEY(account_id,title_id), UNIQUE(scope,scope_key,title_id))`,
`CREATE TABLE IF NOT EXISTS character_records(character_id TEXT PRIMARY KEY, account_id TEXT NOT NULL, world_id TEXT NOT NULL, name TEXT NOT NULL, state TEXT NOT NULL, character TEXT NOT NULL)`,
`CREATE UNIQUE INDEX IF NOT EXISTS one_living_character ON character_records(account_id) WHERE state IN ('alive','eligible')`,
`CREATE INDEX IF NOT EXISTS characters_world ON character_records(world_id)`,
+27 -15
View File
@@ -135,6 +135,8 @@ func (l *Lease) Save(ctx context.Context, w *game.World, claimID string) error {
return l.SaveCommand(ctx, w, claimID, nil, "")
}
func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string, command *Command, outcome string) error {
live := w
w = stageTitleWorld(w)
data, err := json.Marshal(w)
if err != nil {
return err
@@ -167,20 +169,26 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
return errors.New("passage already redeemed or unavailable")
}
}
if w.Phase == "won" {
for _, c := range w.Characters {
if c.View.Entity.State != "eligible" {
continue
}
encoded, err := json.Marshal(c)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
if err != nil {
return err
}
}
if err = d.syncPassages(ctx, tx, w); err != nil {
return err
}
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
}
if err = d.syncTitles(ctx, tx, w); err != nil {
return err
}
// Rewrite the final payloads after the immutable award claims have resolved.
// The transaction already holds the owner, passage and character row locks.
data, err = json.Marshal(w)
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, d.q(`UPDATE worlds SET snapshot=? WHERE id=? AND owner=?`), string(data), l.WorldID, l.Owner); err != nil {
return err
}
if err = d.syncPassages(ctx, tx, w); err != nil {
return err
}
if err = d.syncCharacters(ctx, tx, w, claimID); err != nil {
return err
@@ -208,7 +216,11 @@ func (l *Lease) SaveCommand(ctx context.Context, w *game.World, claimID string,
return err
}
l.Revision++
w.Saved()
for id, c := range w.Characters {
live.Characters[id].View.Titles = c.View.Titles
}
live.PendingTitles = nil
live.Saved()
return nil
}
func (l *Lease) Release(ctx context.Context) error {
+167
View File
@@ -0,0 +1,167 @@
package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"sort"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
)
// Only title slices change in this staged view. The live simulation is untouched
// until its snapshot, claim ledger, character records and passages all commit.
func stageTitleWorld(w *game.World) *game.World {
staged := *w
staged.Characters = make(map[string]*game.Character, len(w.Characters))
for id, c := range w.Characters {
copy := *c
copy.View.Titles = append([]p.TitleAward{}, c.View.Titles...)
staged.Characters[id] = &copy
}
return &staged
}
func (d *DB) syncTitles(ctx context.Context, tx *sql.Tx, w *game.World) error {
// syncCharacters has already locked these rows. A stale source world may
// checkpoint itself, but it cannot grant titles for a transferred character.
owned := make(map[string]bool, len(w.Characters))
for id, c := range w.Characters {
var account, world string
err := tx.QueryRowContext(ctx, d.q(`SELECT account_id,world_id FROM character_records WHERE character_id=?`), id).Scan(&account, &world)
if err != nil {
return err
}
owned[id] = account == c.Account && world == w.ID
}
candidates := append([]game.TitleCandidate{}, w.PendingTitles...)
// All owners lock title IDs in the same order, even with different catalogs.
// Stable ordering preserves simulation event order for contenders for one ID.
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].Award.ID < candidates[j].Award.ID })
granted := map[string]map[string]bool{}
for _, candidate := range candidates {
c := w.Characters[candidate.CharacterID]
if c == nil || !owned[candidate.CharacterID] {
continue
}
award := candidate.Award
if award.ID == "" || award.WorldID != w.ID {
return errors.New("invalid title candidate identity")
}
key := ""
switch award.Scope {
case "personal":
key = c.Account
case "world":
key = w.ID
case "global":
key = "global"
default:
return errors.New("invalid title candidate scope")
}
raw, err := json.Marshal(award)
if err != nil {
return err
}
result, err := tx.ExecContext(ctx, d.q(`INSERT INTO title_awards(account_id,title_id,scope,scope_key,character_id,award) VALUES(?,?,?,?,?,?) ON CONFLICT DO NOTHING`), c.Account, award.ID, award.Scope, key, candidate.CharacterID, string(raw))
if err != nil {
return err
}
count, err := result.RowsAffected()
if err != nil {
return err
}
if count == 1 {
if granted[candidate.CharacterID] == nil {
granted[candidate.CharacterID] = map[string]bool{}
}
granted[candidate.CharacterID][award.ID] = true
}
}
byAccount := map[string][]p.TitleAward{}
for id, c := range w.Characters {
if !owned[id] {
continue
}
awards, loaded := byAccount[c.Account]
if !loaded {
var err error
awards, err = d.accountTitles(ctx, tx, c.Account)
if err != nil {
return err
}
byAccount[c.Account] = awards
}
if c.View.Entity.State != "dead" {
c.View.Titles = append([]p.TitleAward{}, awards...)
continue
}
// A historical dead life keeps its own record. Only awards from its death
// transaction are appended; titles from later lives do not rewrite history.
keep := map[string]bool{}
for _, award := range c.View.Titles {
keep[award.ID] = true
}
for title := range granted[id] {
keep[title] = true
}
c.View.Titles = []p.TitleAward{}
for _, award := range awards {
if keep[award.ID] {
c.View.Titles = append(c.View.Titles, award)
}
}
}
return nil
}
func (d *DB) accountTitles(ctx context.Context, tx *sql.Tx, account string) ([]p.TitleAward, error) {
rows, err := tx.QueryContext(ctx, d.q(`SELECT award FROM title_awards WHERE account_id=? ORDER BY title_id`), account)
if err != nil {
return nil, err
}
defer rows.Close()
awards := []p.TitleAward{}
for rows.Next() {
var raw string
var award p.TitleAward
if err = rows.Scan(&raw); err != nil {
return nil, err
}
if err = json.Unmarshal([]byte(raw), &award); err != nil {
return nil, err
}
awards = append(awards, award)
}
return awards, rows.Err()
}
func (d *DB) syncPassages(ctx context.Context, tx *sql.Tx, w *game.World) error {
if w.Phase != "won" {
return nil
}
// Stable row order also prevents competing owners from acquiring survivor
// passage locks in opposite map iteration order.
ids := make([]string, 0, len(w.Characters))
for id := range w.Characters {
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
c := w.Characters[id]
if c.View.Entity.State != "eligible" {
continue
}
encoded, err := json.Marshal(c)
if err != nil {
return err
}
_, err = tx.ExecContext(ctx, d.q(`INSERT INTO passages(character_id,account_id,source_world,character) VALUES(?,?,?,?) ON CONFLICT(character_id) DO UPDATE SET source_world=excluded.source_world,character=excluded.character,claimed_world=NULL WHERE passages.claimed_world=excluded.source_world OR (passages.source_world=excluded.source_world AND passages.claimed_world IS NULL)`), c.View.Entity.ID, c.Account, w.ID, string(encoded))
if err != nil {
return err
}
}
return nil
}
+292
View File
@@ -0,0 +1,292 @@
package store
import (
"context"
"encoding/json"
"os"
"path/filepath"
"reflect"
"sync"
"testing"
"time"
"aeternalis/server/content"
"aeternalis/server/internal/game"
p "aeternalis/server/internal/protocol"
)
func titleCandidate(w *game.World, c *game.Character, id, scope string) game.TitleCandidate {
return game.TitleCandidate{CharacterID: c.View.Entity.ID, Award: p.TitleAward{ID: id, Name: id, Description: "A permanent test title", Scope: scope, WorldID: w.ID, EarnedAt: time.Now().UTC().Format(time.RFC3339Nano), Effects: p.TitleEffects{Damage: 2, MoveSpeed: -.5}}}
}
func TestTitlePersistence(t *testing.T) {
runTitleTests(t, "file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "titles.db")))
}
func TestPostgresTitlePersistence(t *testing.T) {
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
t.Skip("TEST_DATABASE_URL not configured")
}
runTitleTests(t, dsn)
}
func runTitleTests(t *testing.T, dsn string) {
ctx := context.Background()
db, err := Open(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
b, err := content.Load()
if err != nil {
t.Fatal(err)
}
prefix := game.ID()
makeWorld := func(suffix string) (*game.World, *Lease, *game.Character) {
t.Helper()
w := game.New(prefix+suffix, 1, time.Now().UTC(), b)
l, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = l.Release(ctx) })
c, err := w.Join(prefix+suffix, "Traveler")
if err != nil {
t.Fatal(err)
}
return w, l, c
}
count := func(id string) int {
t.Helper()
var n int
if err := db.sql.QueryRowContext(ctx, db.q(`SELECT count(*) FROM title_awards WHERE title_id=?`), id).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
has := func(c *game.Character, id string) bool {
for _, a := range c.View.Titles {
if a.ID == id {
return true
}
}
return false
}
t.Run("permanent inheritance and immutable history", func(t *testing.T) {
w, l, c := makeWorld("-life")
id := prefix + "-personal"
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "personal")}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
original := c.View.Titles[0]
if count(id) != 1 || len(w.PendingTitles) != 0 {
t.Fatal("award not committed")
}
c.View.Titles[0].Name = "Changed"
c.View.Titles[0].Effects.Damage = 999
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "personal")}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
if count(id) != 1 || !reflect.DeepEqual(c.View.Titles, []p.TitleAward{original}) {
t.Fatal("retry changed immutable title")
}
if err := w.Control("retire", c.View.Entity.ID, "", "test"); err != nil {
t.Fatal(err)
}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
next, err := w.Join(c.Account, "Replacement")
if err != nil {
t.Fatal(err)
}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
if !has(next, id) || !has(c, id) || next.View.Level != 1 || c.View.Entity.State != "dead" {
t.Fatal("death lost title or resurrected life")
}
later := prefix + "-later"
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, next, later, "personal")}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
if has(c, later) || !has(next, later) {
t.Fatal("later life rewrote dead history")
}
if err := l.Release(ctx); err != nil {
t.Fatal(err)
}
restoredLease, raw, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
defer restoredLease.Release(ctx)
var restored game.World
if err = json.Unmarshal(raw, &restored); err != nil {
t.Fatal(err)
}
if err = restored.Restore(time.Now()); err != nil {
t.Fatal(err)
}
if !has(restored.Characters[next.View.Entity.ID], id) || restored.Characters[c.View.Entity.ID].View.Entity.State != "dead" {
t.Fatal("restart lost titles or death")
}
})
t.Run("global race and independent world firsts", func(t *testing.T) {
a, la, ca := makeWorld("-race-a")
z, lz, cz := makeWorld("-race-z")
global, world := prefix+"-global", prefix+"-world"
a.PendingTitles = []game.TitleCandidate{titleCandidate(a, ca, world, "world"), titleCandidate(a, ca, global, "global")}
z.PendingTitles = []game.TitleCandidate{titleCandidate(z, cz, global, "global"), titleCandidate(z, cz, world, "world")}
var wg sync.WaitGroup
results := make(chan error, 2)
for _, pair := range []struct {
w *game.World
l *Lease
}{{a, la}, {z, lz}} {
wg.Add(1)
go func(w *game.World, l *Lease) { defer wg.Done(); results <- l.Save(ctx, w, "") }(pair.w, pair.l)
}
wg.Wait()
close(results)
for err := range results {
if err != nil {
t.Fatal(err)
}
}
winners := 0
for _, c := range []*game.Character{ca, cz} {
if has(c, global) {
winners++
}
if !has(c, world) {
t.Fatal("first in own world denied")
}
}
if winners != 1 || count(global) != 1 || count(world) != 2 {
t.Fatal("global first duplicated or world scopes shared")
}
other, err := a.Join(prefix+"-contender", "Contender")
if err != nil {
t.Fatal(err)
}
a.PendingTitles = []game.TitleCandidate{titleCandidate(a, other, world, "world"), titleCandidate(a, other, global, "global")}
if err = la.Save(ctx, a, ""); err != nil {
t.Fatal(err)
}
if has(other, global) || has(other, world) {
t.Fatal("late contender stole first")
}
})
t.Run("event order beats character map order", func(t *testing.T) {
w, l, c := makeWorld("-order")
other, err := w.Join(prefix+"-order-other", "Other")
if err != nil {
t.Fatal(err)
}
id := prefix + "-order-title"
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, other, id, "world"), titleCandidate(w, c, id, "world")}
if err = l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
if !has(other, id) || has(c, id) {
t.Fatal("first simulation candidate lost")
}
})
t.Run("late transaction failure rolls back claims and view", func(t *testing.T) {
w, l, c := makeWorld("-rollback")
id := prefix + "-rollback-title"
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, id, "global")}
before := l.Revision
if err := l.SaveCommand(ctx, w, "", &Command{ID: "missing-command"}, ""); err == nil {
t.Fatal("missing command committed")
}
if count(id) != 0 || len(c.View.Titles) != 0 || len(w.PendingTitles) != 1 || l.Revision != before {
t.Fatal("failed save leaked title state")
}
if err := l.Save(ctx, w, ""); err != nil {
t.Fatal(err)
}
if count(id) != 1 || !has(c, id) {
t.Fatal("retry failed after rollback")
}
if err := l.Release(ctx); err != nil {
t.Fatal(err)
}
replacement, _, err := db.Acquire(ctx, w)
if err != nil {
t.Fatal(err)
}
defer replacement.Release(ctx)
stale := prefix + "-stale-title"
w.PendingTitles = []game.TitleCandidate{titleCandidate(w, c, stale, "global")}
if err = l.Save(ctx, w, ""); err == nil {
t.Fatal("stale owner saved")
}
if count(stale) != 0 || has(c, stale) {
t.Fatal("stale owner claimed title")
}
})
t.Run("victory transfer and stale source", func(t *testing.T) {
source, ls, c := makeWorld("-source")
id := prefix + "-survivor"
source.PendingTitles = []game.TitleCandidate{titleCandidate(source, c, id, "global")}
c.View.Level = 2
c.View.Experience = 20
c.View.ExperienceToNextLevel = 150
c.View.StatPoints = 5
c.DailySeconds = 123
c.View.Entity.State = "eligible"
source.Phase = "won"
if err := ls.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
survivor, err := db.ReadPassage(ctx, c.View.Entity.ID, c.Account)
if err != nil {
t.Fatal(err)
}
if !has(survivor, id) {
t.Fatal("victory passage missed same-transaction title")
}
target := game.New(prefix+"-destination", 2, time.Now().UTC(), b)
lt, _, err := db.Acquire(ctx, target)
if err != nil {
t.Fatal(err)
}
defer lt.Release(ctx)
if err = target.Import(survivor); err != nil {
t.Fatal(err)
}
if err = lt.Save(ctx, target, c.View.Entity.ID); err != nil {
t.Fatal(err)
}
if !has(survivor, id) || survivor.View.StatPoints != 5 || survivor.View.Experience != 20 || survivor.DailySeconds != 123 {
t.Fatal("passage lost progression")
}
forbidden := prefix + "-source-forbidden"
source.PendingTitles = []game.TitleCandidate{titleCandidate(source, c, forbidden, "global")}
if err = ls.Save(ctx, source, ""); err != nil {
t.Fatal(err)
}
if count(forbidden) != 0 || has(c, forbidden) {
t.Fatal("old source granted new title")
}
active, err := db.ActiveCharacter(ctx, c.Account)
if err != nil {
t.Fatal(err)
}
if active.WorldID != target.ID || !has(active.Character, id) {
t.Fatal("source overwrote destination")
}
if _, err = db.ReadPassage(ctx, c.View.Entity.ID, c.Account); err == nil {
t.Fatal("source reopened spent passage")
}
})
}
+1 -1
View File
@@ -22,7 +22,7 @@ func (h *HTTP) admin(w http.ResponseWriter, r *http.Request) (string, bool) {
return "", false
}
if !h.auth.isAdmin(r) {
fail(w, 403, "Administrator access required. Sign in again with the configured Keycloak role.")
fail(w, 403, "Administrator access required. Your Keycloak ID token must include the role \""+h.auth.AdminRole+"\". Sign in again after assigning it.")
return "", false
}
return account, true
+25
View File
@@ -115,3 +115,28 @@ func TestKeycloakRolesAndReturnURL(t *testing.T) {
t.Fatal("game return lost or untrusted query retained")
}
}
func TestAdminRoleClaimsMatchExactlyAndOnlyOwnClient(t *testing.T) {
for _, tc := range []struct {
name, raw string
want bool
}{
{"realm role", `{"realm_access":{"roles":["aeternalis-admin"]}}`, true},
{"client role", `{"resource_access":{"game":{"roles":["aeternalis-admin"]}}}`, true},
{"other client", `{"resource_access":{"other":{"roles":["aeternalis-admin"]}}}`, false},
{"player", `{"realm_access":{"roles":["player"]}}`, false},
{"case mismatch", `{"realm_access":{"roles":["Aeternalis-admin"]}}`, false},
{"substring", `{"realm_access":{"roles":["not-aeternalis-admin"]}}`, false},
{"missing", `{}`, false},
} {
t.Run(tc.name, func(t *testing.T) {
var claims roleClaims
if err := json.Unmarshal([]byte(tc.raw), &claims); err != nil {
t.Fatal(err)
}
if claims.admin("aeternalis-admin", "game") != tc.want {
t.Fatal("incorrect role access")
}
})
}
}
+1
View File
@@ -177,6 +177,7 @@ func (s *Service) join(ctx context.Context, account, name, claim string) (p.Char
view := c.View
view.Inventory = maps.Clone(view.Inventory)
view.Skills = maps.Clone(view.Skills)
view.Titles = append([]p.TitleAward{}, view.Titles...)
return view, nil
}
+58
View File
@@ -0,0 +1,58 @@
import { test, expect } from '@playwright/test';
import type { Character, Snapshot } from '../client/src/generated';
test('progression and signed permanent titles render in game, account, and admin views', async ({ page, request }) => {
const errors: string[] = []; page.on('pageerror', error => errors.push(error.message));
const character: Character = {
entity: { id: 'progression-fixture', kind: 'player', name: 'Title bearer', state: 'alive', hp: 100, maxHp: 100, position: { x: 0, y: 0, z: 0 } },
inventory: { knife: 1 }, skills: { combat: 2 }, kills: 2, ack: 0, hasKeystone: false,
playedSeconds: 120, remainingSeconds: 7080, level: 2, experience: 40, experienceToNextLevel: 150, statPoints: 5,
titles: [{ id: 'first-hunter-fixture', name: 'The First Hunter', description: 'Power comes with a heavier step.', scope: 'global', worldId: 'e2e', earnedAt: '2026-09-06T12:00:00Z', effects: { damage: 3, moveSpeed: -0.5 } }],
};
const record = { id: character.entity.id, account: 'fixture-account', worldId: 'e2e', name: character.entity.name, state: 'alive', character: { view: character, bornAt: '2026-09-06T11:00:00Z', dailySeconds: 120 } };
const worlds = await (await request.get('/api/worlds')).json();
const chunks = await (await request.get('/worlds/e2e/api/preview')).json();
await page.route('**/api/me', route => route.fulfill({ json: { character } }));
await page.route('**/api/account', route => route.fulfill({ json: { active: record, characters: [record], admin: true } }));
await page.route('**/api/control?*', route => route.fulfill({ json: { worlds, characters: [record], commands: [], provisioningEnabled: false, characterLimit: 500, auditLimit: 100 } }));
let sendSnapshot: () => void = () => {};
await page.routeWebSocket('**/ws', socket => {
sendSnapshot = () => {
const snapshot: Snapshot = { type: 'snapshot', version: 1, tick: 1, self: character, chunks, chunkKeys: chunks.map(c => c.key), entities: [], unavailableResources: [], message: '',
world: { id: 'e2e', seed: 1, phase: 'gathering', ageSeconds: 120, bossInSeconds: 3600, collapseInSeconds: 5400, safeRadius: 1024, radius: 1024, online: 1, capacity: 100, bossHp: 1200, bossMaxHp: 1200 } };
socket.send(JSON.stringify(snapshot));
};
sendSnapshot();
});
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto('/game?world=e2e');
await expect(page.locator('#character-level')).toHaveText('Level 2');
await expect(page.locator('#character-experience')).toHaveText('40 / 150 XP');
await expect(page.locator('#stat-point-bank')).toHaveText('5 stat points saved');
await page.getByRole('button', { name: 'Inventory and crafting' }).click();
await expect(page.locator('#earned-titles')).toContainText('+3 damage');
await expect(page.locator('#earned-titles')).toContainText('-0.5 movement speed');
await expect(page.locator('#earned-titles')).toContainText('First ever');
await page.screenshot({ path: 'test-results/progression-desktop.png' });
await page.setViewportSize({ width: 390, height: 844 });
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await expect(page.locator('#earned-titles .earned-title')).toBeVisible();
await page.screenshot({ path: 'test-results/progression-mobile.png' });
character.level = 1000; character.experience = 0; character.experienceToNextLevel = 0; character.statPoints = 4995;
sendSnapshot();
await expect(page.locator('#character-experience')).toHaveText('Level cap');
await expect(page.locator('#experience-meter')).toHaveAttribute('aria-valuetext', 'Level 1000: Level cap');
await page.goto('/');
await expect(page.locator('#active-character')).toContainText('4995 stat points saved');
await expect(page.locator('#active-character')).toContainText('-0.5 movement speed');
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.goto('/control');
await page.getByRole('button', { name: 'Characters', exact: true }).click();
await page.getByRole('button', { name: 'Title bearer', exact: true }).click();
await expect(page.locator('#character-detail')).toContainText('Level 1000');
await expect(page.locator('#character-detail')).toContainText('+3 damage');
await expect(page.locator('#character-detail')).toContainText('-0.5 movement speed');
await page.screenshot({ path: 'test-results/progression-control.png' });
expect(errors).toEqual([]);
});