commit 9879ecc39251c9222d94738e0d6403fa8e36744c
parent 151bf26765beff011a7bd3e7997a2aa2149bb768
Author: anon <anon@example.com>
Date: Sat, 24 Oct 2026 19:03:22 +0000
Persist scanner insurance and commit XP loss with death
Diffstat:
19 files changed, 593 insertions(+), 69 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -306,6 +306,13 @@ Historical outdoor give-up timing and obstacle navigation remain open.
can be recovered once, including after reconnect.
- [ ] Apply the classic insurance/XP-loss policy. Check: recorded before/after
XP and save-point cases match the documented 14.9.1 rule.
+ Scanner snapshots and uninsured loss now commit atomically with death, with
+ the shipped below-level-20 protection and no-level-loss floor. Thirty focused
+ cases cover rollback/retry, output failure, concurrency, resurrection, native
+ initialization and checkpoint cadence. Confirm the original treatment of a
+ level-up award's remainder before closing the full policy check; the current
+ implementation protects the new level's lower boundary. Insurance timestamps
+ and fees remain separate gaps. See [classic XP protection](docs/insurance.md#classic-xp-protection).
The Leet's replacement lifecycle and explicitly provisional delay are recorded
in [creature respawn](docs/npc-respawn.md).
@@ -1120,6 +1127,11 @@ and server restarts. Turn every reproduced bug into a focused regression test.
- [ ] Audit death, resurrection, insurance and reclaim. Cover each supported
item policy, saved/unsaved locations, repeated return/retrieval, full inventory,
failed persistence and restart at each transition.
+ Replace the world-entry shortcut in `server/main.go` that revives a zero-health
+ player at full health without completing the scanner return. Cover disconnect
+ and restart between the killing hit and native action 152; retain the already
+ committed XP loss, removed effects and reclaim state while completing exactly
+ one legitimate resurrection at the saved location.
Ability-buff deaths now cover nonlethal retention, zero-health durability,
pending-cast refunds, resource clamps, reclaim, ignored/failed SQL and COMMIT
rollback, shared ranged outcomes and resurrection without replay. Two native
diff --git a/docs/character-progression.md b/docs/character-progression.md
@@ -4,6 +4,8 @@ Character XP persists in SQLite and initializes the native experience bar.
A [provisional solo kill path](kill-experience.md) now advances XP, levels and
IP atomically; original reward balance and eligibility remain unresolved. Native
[IP spending](ip-training.md) persists validated skill/ability purchases.
+Classic [insurance](insurance.md#classic-xp-protection) stores a cumulative
+protected snapshot and commits uninsured XP loss with death.
The packet replay values below are test inputs, not historical creature rewards.
## Durable experience state
diff --git a/docs/insurance.md b/docs/insurance.md
@@ -2,7 +2,8 @@
The shipped Omni-Med scanner `51005:0xc00202c1` in Omni Entertainment can now
save a player's resurrection location through native right-click Use. Its
-identity persists in `player.yaml` as `resurrection_terminal`. Death returns
+identity persists in SQLite as `resurrection_terminal`, also exposed in the
+control editor. Death returns
the player beside that scanner, including after reconnect or server restart.
Unsaved characters keep the provisional starter return described in
[player resurrection](player-resurrection.md).
@@ -65,17 +66,75 @@ The profile is saved atomically before live state changes or success packets.
A failed write leaves the saved point unchanged and sends no success.
Socket writes occur outside the shared state mutex.
-A successful use completes GenericCmd and sends CharacterAction 79. Its saved
-XP fields are zero because durable XP progression and insurance snapshots are
-not implemented. This feature saves the return location; XP loss, fees and
-shock stat penalties remain separate work. [Private reclaim](reclaim.md) now
+A successful use completes GenericCmd and sends CharacterAction 79. Its last
+word now carries the saved cumulative XP into native stat 236. The preceding
+stat-49 word remains zero; its original time representation has not been
+recovered. Fees and shock stat penalties remain separate work. [Private reclaim](reclaim.md) now
handles ordinary inventory items from level 10 and prevents saving until all
reclaim items are collected. Ordinary profile edits
and teleports preserve the saved scanner. Unknown scanner identities in saved
profiles fail loading rather than silently selecting another location.
+## Classic XP protection
+
+`insured_experience` stores the cumulative XP protected by the last scanner
+save. It differs from `experience`, which stores progress within the current
+level. The editor and profile loader reject an insured total above current
+cumulative XP. Ordinary movement checkpoints do not write either progression
+field. Teleports, unrelated profile edits and reconnects preserve the snapshot.
+
+The selected template 117665 explicitly protects characters below level 20.
+At level 20 and above, a death retains the greater of the scanner snapshot and
+the current level's lower cumulative boundary. The latter follows the shipped
+help's no-level-loss rule. IP and trained skills are retained. This implements
+classic XP loss without importing Shadowlands' recoverable XP pool.
+
+The lower boundary protects a newly reached level even when the last scanner
+save was earlier. It does not automatically insure the kill's remainder above
+that boundary. Whether the original server also saved that remainder needs
+independent confirmation. The level-up and initial-state packets supply the
+effective saved-XP marker at or above the current level's lower boundary.
+
+XP loss commits in the same death transaction as health, canceled nano
+reservations, removed temporary nanos and reclaim placements. Ignored writes
+and failed commits leave the complete outcome unchanged. Live XP and its
+saved-profile cache change only after commit. The owner then receives an
+absolute stat-52 update, producing the native loss feedback once; observers
+receive no private XP update. Resurrection and initialization do not replay it.
+
## Verification
+`server/insurance_experience_test.go` and
+`server/insurance_experience_failure_test.go` add 30 cases for scanner snapshots,
+level-19/20 protection, no-level-loss boundaries, native saved markers, private
+feedback, resurrection, output failure, concurrent uses, invalid editor values,
+checkpoint cadence, ignored/failed SQL writes, failed commits and retries. The
+death cases retain or remove their temporary nanos and reclaim items atomically
+with the XP outcome. The full Go suite, repeated focused race run and vet pass;
+logs are retained under `local/insurance-xp-research/`.
+
+Two headed Chromium clients using the GPU tested the same published WASM
+against the single shared HTTPS preview. Native right-click insured 1000 of
+level 20's 15400 required XP. An administrative fixture then supplied 1500
+progress; an actual Leet attack killed the player, and the native UI displayed
+one 500-XP loss before returning to the saved scanner with 1000 progress.
+An uninsured level-20 death removed 1500 progress without losing the level.
+A level-19 death retained all 1500 progress without a loss update. These are
+controlled XP/resource fixtures, not historical creature reward measurements.
+
+The packet and SQLite comparisons, native snapshots, screenshots and owned
+fixture cleanup are retained under `local/insurance-xp-smoke/`. The independent
+observer received no private XP loss. Page reconnect retained the first saved
+outcome. The native insurance packet's stat-49 word stays zero throughout.
+After another real scanner save, a cold restart retained 1500 current-level
+progress and cumulative insured XP 140850. The restarted native Stats window
+showed EXP 1500/15400, without an award, loss or insurance replay. Twelve native
+and SQLite comparisons covered three actual deaths and three automatic native
+resurrection requests. Both browser error captures were empty. The two owned
+visitors and their encounter contributions were removed, with unrelated database
+rows preserved and foreign-key/integrity checks passing. The shared preview
+continues on the normal ports.
+
`server/insurance_test.go` covers native use followed by restart and death,
preservation through ordinary teleport/profile updates, faction and range
checks, invalid sessions/identities/actions, repeated concurrent uses, shared
diff --git a/docs/kill-experience.md b/docs/kill-experience.md
@@ -63,7 +63,9 @@ Higher XP thresholds remain provisional as documented in character progression.
Health and nano maxima use the new level/title and the recovered resource
formula. Current health and nano are retained. Original level-up refill policy
is unresolved; the native level-up handler alone does not prove a refill.
-Classic insurance/XP loss on death is also still TODO.
+Classic [scanner insurance and XP loss](insurance.md#classic-xp-protection) now
+persist with the death outcome; fees and level-up insurance remainder semantics
+remain unresolved.
The owner receives one absolute XP-52 update for a same-level award, or one
`NewLevelIIR_t` with the new level, IP, cumulative XP, boundaries and net gain.
diff --git a/docs/player-resurrection.md b/docs/player-resurrection.md
@@ -64,11 +64,14 @@ redirect sequence. The departing session is removed before another request can
take effect. The replacement world session initializes the same character,
equipment and inventory at the saved return point.
-Health and nano remain runtime state. Ordinary reconnect behavior still revives
-a defeated player with full health, and server restart initializes resources
-from the saved character profile. One insurance terminal and its saved return
-are now supported; other scanners, insurance fees, XP loss and resurrection
-shock stat penalties remain unimplemented. Ordinary inventory items now enter
+Death and resurrection persist their resources immediately; ordinary simulation
+uses periodic checkpoints. Startup restores the durable state, but world entry
+still revives a pending dead player at full health in `server/main.go` instead
+of completing the scanner return. That shortcut remains an explicit audit gap;
+it does not restore lost XP. The supported scanner also protects saved
+XP, with classic uninsured loss committed alongside death; see
+[XP protection](insurance.md#classic-xp-protection). Other scanners, insurance fees
+and resurrection shock stat penalties remain unimplemented. Ordinary inventory items now enter
[private reclaim](reclaim.md) from level 10; equipment and NoDrop items remain
with the player. See the [scanner evidence and limits](insurance.md).
@@ -90,8 +93,8 @@ encounter used a low-health fixture adjustment. Neither death required a
client adapter change.
Restarting the isolated server and reloading afterward retained the arrival
-position and both item identities. As expected for the existing runtime
-resource policy, restart initialized 37 HP/0 nano rather than retaining 1/1.
+position and both item identities. Current durable resource and XP restart
+checks are recorded in the [insurance verification](insurance.md#verification).
There were zero page errors and 15 expected connection-refused console messages
during intentional restart. Evidence is under `local/resurrection-smoke/`:
`verification.json`, `encounter-packets.log`, `arrival-position.yaml`, and
diff --git a/server/combat.go b/server/combat.go
@@ -393,6 +393,11 @@ func prepareDamage(attacker, target *character, damage uint32, now time.Time) ch
candidate := *target
candidate.health -= damage
if candidate.health == 0 && !candidate.npc {
+ // Classic insurance cannot remove a level; the shipped scanner protects levels below 20.
+ if candidate.level >= 20 {
+ lower, _ := candidate.experienceBounds()
+ candidate.experience = max(lower, candidate.insuredExperience) - lower
+ }
candidate.activeNanos = nil
candidate.nano = min(candidate.nano+candidate.nanoReserved, candidate.maximumNano())
candidate.nanoReserved = 0
@@ -450,6 +455,14 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr
target.roaming.returning = false
}
server.queueCombat_locked(updates, target, target, deathPacket(target))
+ if !target.npc && target.experience != previous.experience {
+ if owner := server.clients[target.id]; owner != nil && owner.ready && !owner.loading {
+ lower, _ := target.experienceBounds()
+ body := binary.BigEndian.AppendUint32(nil, 52)
+ body = binary.BigEndian.AppendUint32(body, lower+target.experience)
+ updates[owner] = append(updates[owner], n3Packet(0x2b333d6e, 50000, target.id, body))
+ }
+ }
if !target.npc && len(previous.activeNanos) != 0 {
// StopFight drains queued weapon hits before modifiers and maxima change.
for _, effect := range previous.activeNanos {
diff --git a/server/control.go b/server/control.go
@@ -77,6 +77,7 @@ func (server *server) userPage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<form method='post' action='control/users/%d'><p><label>Character:<br><textarea name='data' rows='40' cols='100' required>%s</textarea></label></p><button>Save character</button></form>", data.ID, html.EscapeString(string(contents)))
fmt.Fprint(w, "<p>Inventory uses inventory_slot_1 through inventory_slot_30; equipment uses named weapons, clothes and implants positions. Slots contain item IDs or null. Clearing a slot unassigns its item. <a href='control/items'>Browse and create item instances</a>. Container slots are edited on the container's item page. experience is progress within the current level, below its next-level requirement; level 200 requires zero. improvement_points is the available IP balance. Native skill spending deducts IP and enforces training caps; editing stats here sets their values directly.</p>")
fmt.Fprint(w, itemTables.String())
+ fmt.Fprint(w, "<p>insured_experience is the cumulative XP protected by the last insurance save. It cannot exceed current cumulative XP. Death below level 20 preserves XP; later deaths preserve the greater of insured XP and the current level's lower boundary.</p>")
fmt.Fprint(w, "</body></html>")
}
diff --git a/server/database.go b/server/database.go
@@ -66,7 +66,7 @@ type playerVitals struct {
func (character *character) profile() playerProfile {
return playerProfile{character.id, character.name, unpackAppearance(character.appearance), character.monsterData,
- character.level, character.experience, max(1, character.profession), character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
+ character.level, character.experience, character.insuredExperience, max(1, character.profession), character.baseStats(), character.running, character.browserTokenHash, character.resurrectionTerminal,
character.implantChangesUntil, character.treatmentLockedUntil}
}
@@ -135,7 +135,7 @@ func (record *characterRecord) fields() []any {
func (record characterRecord) character() *character {
profile, position := record.Profile, record.Position.editor()
data := userData{profile.ID, profile.Name, position.Playfield, position.Position, position.Rotation,
- profile.Appearance.packed(), profile.MonsterData, profile.Level, profile.Experience, profile.Profession, profile.Stats, profile.Running, position.ReturnDoor, profile.BrowserTokenHash}
+ profile.Appearance.packed(), profile.MonsterData, profile.Level, profile.Experience, profile.InsuredExperience, profile.Profession, profile.Stats, profile.Running, position.ReturnDoor, profile.BrowserTokenHash}
player := data.character()
player.applyVitals(record.Vitals)
player.resurrectionTerminal = profile.ResurrectionTerminal
diff --git a/server/insurance.go b/server/insurance.go
@@ -66,12 +66,15 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error
// Persist the scanner before acknowledging use or changing live state.
updated := *player
updated.resurrectionTerminal = 0xc00202c1
+ lower, _ := updated.experienceBounds()
+ updated.insuredExperience = lower + updated.experience
if err := server.saveUser_locked(&updated); err != nil {
server.mutex.Unlock()
return err
}
*player = updated
}
+ insuredExperience := player.insuredExperience
server.mutex.Unlock()
// Complete native Use before its effect or insurance confirmation.
@@ -88,7 +91,7 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error
}
if accepted && !reclaim {
var action []byte
- for _, value := range []uint32{79, 0, 0, 0, 0} {
+ for _, value := range []uint32{79, 0, 0, 0, insuredExperience} {
action = binary.BigEndian.AppendUint32(action, value)
}
return client.send(n3Packet(0x5e477770, 50000, client.id, action))
diff --git a/server/insurance_experience_failure_test.go b/server/insurance_experience_failure_test.go
@@ -0,0 +1,173 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func TestInsuranceExperienceFailedSaveRollsBackThenRetries(t *testing.T) {
+ for _, fault := range []struct{ name, statement string }{
+ {"abort", "CREATE TRIGGER reject_insurance BEFORE UPDATE OF insured_experience ON characters BEGIN SELECT RAISE(ABORT, 'insurance'); END"},
+ {"ignored", "CREATE TRIGGER reject_insurance BEFORE UPDATE OF insured_experience ON characters BEGIN SELECT RAISE(IGNORE); END"},
+ {"commit", "CREATE TABLE pending_insurance (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_insurance AFTER UPDATE OF insured_experience ON characters BEGIN INSERT INTO pending_insurance VALUES (999999); END"},
+ } {
+ t.Run(fault.name, func(t *testing.T) {
+ world, output := newReclaimWorld(t)
+ player := world.characters[1]
+ player.level, player.experience = 20, 1000
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec(fault.statement); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err == nil || player.insuredExperience != 0 || player.savedProfile.InsuredExperience != 0 || restored.insuredExperience != 0 ||
+ player.resurrectionTerminal != 0 || restored.resurrectionTerminal != 0 || len(output.packets) != 0 {
+ t.Fatal("failed insurance was partially published")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_insurance"); err != nil {
+ t.Fatal(err)
+ }
+
+ err = world.handleTerminalUse(world.clients[1], insuranceUseRequest(2)[20:])
+ if err == nil {
+ err = world.handleTerminalUse(world.clients[1], insuranceUseRequest(2)[20:])
+ }
+ restored = newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.insuredExperience != 140850 || restored.insuredExperience != 140850 || restored.experience != 1000 || len(output.packets) != 2 {
+ t.Fatal("insurance retry was lost or replayed", err)
+ }
+ })
+ }
+}
+
+func TestInsuranceExperienceFailedDeathRollsBackThenRetries(t *testing.T) {
+ for _, fault := range []struct{ name, statement string }{
+ {"experience", "CREATE TRIGGER reject_insured_death BEFORE UPDATE OF experience ON characters WHEN NEW.health=0 BEGIN SELECT RAISE(ABORT, 'experience'); END"},
+ {"ignored experience", "CREATE TRIGGER reject_insured_death BEFORE UPDATE OF experience ON characters WHEN NEW.health=0 BEGIN SELECT RAISE(IGNORE); END"},
+ {"buff removal", "CREATE TRIGGER reject_insured_death BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(ABORT, 'nano'); END"},
+ {"ignored buff removal", "CREATE TRIGGER reject_insured_death BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(IGNORE); END"},
+ {"reclaim", "CREATE TRIGGER reject_insured_death BEFORE UPDATE OF reclaim_at ON item_locations WHEN NEW.reclaim_at IS NOT NULL BEGIN SELECT RAISE(ABORT, 'reclaim'); END"},
+ {"ignored reclaim", "CREATE TRIGGER reject_insured_death BEFORE UPDATE OF reclaim_at ON item_locations WHEN NEW.reclaim_at IS NOT NULL BEGIN SELECT RAISE(IGNORE); END"},
+ {"commit", "CREATE TABLE pending_insured_death (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_insured_death AFTER UPDATE OF experience ON characters WHEN NEW.health=0 BEGIN INSERT INTO pending_insured_death VALUES (999999); END"},
+ } {
+ t.Run(fault.name, func(t *testing.T) {
+ world, output := newBuffedDeathWorld(t)
+ player := world.characters[1]
+ player.level, player.experience, player.insuredExperience = 20, 1500, 140850
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec(fault.statement); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ defeatReclaimPlayer(t, world)
+ restored := newTestInventoryServer(t).characters[1]
+
+ if player.health != 1 || restored.health != 1 || player.experience != 1500 || player.savedProfile.Experience != 1500 || restored.experience != 1500 ||
+ player.insuredExperience != 140850 || restored.insuredExperience != 140850 || len(player.activeNanos) != 3 || len(restored.activeNanos) != 3 ||
+ len(player.inventory.Reclaim) != 0 || len(restored.inventory.Reclaim) != 0 {
+ t.Fatal("failed death lost XP, insurance, effects or items")
+ }
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 {
+ t.Fatal("failed death published an XP loss")
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER reject_insured_death"); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ fatal := defeatReclaimPlayer(t, world)
+ world.advanceCombat(fatal.Add(time.Minute))
+ restored = newTestInventoryServer(t).characters[1]
+
+ if player.health != 0 || restored.health != 0 || player.experience != 1000 || restored.experience != 1000 ||
+ player.insuredExperience != 140850 || restored.insuredExperience != 140850 || len(player.activeNanos) != 0 || len(restored.activeNanos) != 0 ||
+ len(player.inventory.Reclaim) != 1 || len(restored.inventory.Reclaim) != 1 {
+ t.Fatal("death retry did not commit one complete insured outcome")
+ }
+ var changes int
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 {
+ changes++
+ if binary.BigEndian.Uint32(packet[33:37]) != 140850 {
+ t.Fatal("death retry sent the wrong cumulative XP")
+ }
+ }
+ }
+ if changes != 1 {
+ t.Fatalf("death retry replayed the loss: %d", changes)
+ }
+ })
+ }
+}
+
+func TestInsuranceExperienceNonlethalCheckpointDoesNotWriteProgress(t *testing.T) {
+ world, _ := newBuffedDeathWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ world.nextCharacter = 1
+ player.level, player.experience, player.insuredExperience = 20, 1500, 140850
+ player.health = 10
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TABLE insurance_writes (id INTEGER); CREATE TRIGGER audit_insurance AFTER UPDATE OF experience, insured_experience ON characters BEGIN INSERT INTO insurance_writes VALUES(NEW.id); END"); err != nil {
+ t.Fatal(err)
+ }
+ npc.playfield, npc.position = player.playfield, player.position
+ if err := world.handleCombat(world.clients[1], attackPacket(1, npc.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(player.nextAttack)
+
+ world.advanceCombat(npc.nextAttack)
+ player.position[0]++
+ err := world.flushPositions(time.Now().Add(20 * time.Second))
+ restored := newTestInventoryServer(t).characters[1]
+ var writes int
+ if err := world.db.QueryRow("SELECT count(*) FROM insurance_writes").Scan(&writes); err != nil {
+ t.Fatal(err)
+ }
+
+ if err != nil || writes != 0 || player.health != 5 || restored.health != 5 || restored.position[0] != 919 ||
+ player.experience != 1500 || restored.experience != 1500 || restored.insuredExperience != 140850 {
+ t.Fatalf("nonlethal checkpoint changed insurance or did not checkpoint: %v, writes=%d HP=%d/%d X=%f", err, writes, player.health, restored.health, restored.position[0])
+ }
+}
+
+func TestInsuranceExperienceLevelGainRaisesNativeFloor(t *testing.T) {
+ world, output := newKillExperienceWorld(t, "unarmed")
+ player, npc := world.characters[1], world.characters[1000000]
+ player.level, player.experience, player.insuredExperience = 20, 15350, 140850
+ npc.level = 20
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+
+ attackForExperience(t, world, "unarmed")
+ restored := newTestInventoryServer(t).characters[1]
+
+ if player.level != 21 || player.experience != 50 || player.insuredExperience != 140850 || restored.level != 21 || restored.experience != 50 || restored.insuredExperience != 140850 {
+ t.Fatal("level gain lost the last scanner snapshot or its new progress")
+ }
+ var markers []uint32
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 236 {
+ markers = append(markers, binary.BigEndian.Uint32(packet[33:37]))
+ }
+ }
+ if len(markers) != 1 || markers[0] != 155250 {
+ t.Fatalf("native saved-XP marker stayed below the new level: %v", markers)
+ }
+}
diff --git a/server/insurance_experience_test.go b/server/insurance_experience_test.go
@@ -0,0 +1,240 @@
+package main
+
+import (
+ "context"
+ "database/sql"
+ "encoding/binary"
+ "fmt"
+ "net"
+ "net/http"
+ "net/url"
+ "sync"
+ "testing"
+ "time"
+)
+
+type insuranceCommitConn struct {
+ combatTestConn
+ db *sql.DB
+ observed bool
+ experience, insured, terminal uint32
+ err error
+}
+
+func (conn *insuranceCommitConn) Write(packet []byte) (int, error) {
+ if !conn.observed {
+ conn.observed = true
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ conn.err = conn.db.QueryRowContext(ctx, "SELECT experience, insured_experience, resurrection_terminal FROM characters WHERE id=1").Scan(&conn.experience, &conn.insured, &conn.terminal)
+ }
+ return conn.combatTestConn.Write(packet)
+}
+
+func TestInsuranceExperienceCommitsBeforeAcknowledgement(t *testing.T) {
+ world, _ := newReclaimWorld(t)
+ player := world.characters[1]
+ player.level, player.experience = 20, 1000
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ output := &insuranceCommitConn{db: world.db}
+ world.clients[1].conn = output
+
+ err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || output.err != nil || !output.observed || output.experience != 1000 || output.insured != 140850 || output.terminal != 0xc00202c1 {
+ t.Fatalf("insurance was not durable at first acknowledgement: %v / %v, %d %d %x", err, output.err, output.experience, output.insured, output.terminal)
+ }
+ if player.insuredExperience != 140850 || player.savedProfile.InsuredExperience != 140850 || restored.insuredExperience != 140850 || restored.experience != 1000 {
+ t.Fatal("insurance snapshot or current experience was lost")
+ }
+ if len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 1 ||
+ binary.BigEndian.Uint32(output.packets[1][29:33]) != 79 || binary.BigEndian.Uint32(output.packets[1][41:45]) != 0 ||
+ binary.BigEndian.Uint32(output.packets[1][45:49]) != 140850 {
+ t.Fatal("native acknowledgement lost its saved cumulative XP")
+ }
+}
+
+func TestInsuranceExperienceLostAcknowledgementKeepsTheSave(t *testing.T) {
+ world, _ := newReclaimWorld(t)
+ player := world.characters[1]
+ player.level, player.experience = 20, 1000
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ connection, peer := net.Pipe()
+ defer connection.Close()
+ peer.Close()
+ world.clients[1].conn = connection
+
+ err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err == nil || player.insuredExperience != 140850 || restored.insuredExperience != 140850 || restored.resurrectionTerminal != 0xc00202c1 {
+ t.Fatal("lost acknowledgement lost its already committed insurance")
+ }
+ output := &combatTestConn{}
+ world.clients[1].conn = output
+
+ err = world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:])
+
+ if err != nil || len(output.packets) != 0 || player.insuredExperience != 140850 {
+ t.Fatal("duplicate use replayed after output failure", err)
+ }
+}
+
+func TestInsuranceExperienceConcurrentUseSavesOneSnapshot(t *testing.T) {
+ world, output := newReclaimWorld(t)
+ player := world.characters[1]
+ player.level, player.experience = 20, 1000
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ var uses sync.WaitGroup
+
+ for range 8 {
+ uses.Add(1)
+ go func() {
+ defer uses.Done()
+ if err := world.handleTerminalUse(world.clients[1], insuranceUseRequest(1)[20:]); err != nil {
+ t.Error(err)
+ }
+ }()
+ }
+ uses.Wait()
+ restored := newTestInventoryServer(t).characters[1]
+
+ if player.insuredExperience != 140850 || restored.insuredExperience != 140850 || len(output.packets) != 2 {
+ t.Fatal("concurrent repeated use lost or replayed insurance")
+ }
+}
+
+func TestInsuranceExperienceDeathPreservesProtectedProgress(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ level uint16
+ progress, insured, want uint32
+ }{
+ {"new player", 1, 1400, 0, 1400},
+ {"level nineteen", 19, 1500, 127150, 1500},
+ {"uninsured", 20, 1500, 0, 0},
+ {"partially insured", 20, 1500, 140850, 1000},
+ {"fully insured", 20, 1500, 141350, 1500},
+ {"previous level save", 21, 1500, 140850, 0},
+ {"level two hundred", 200, 0, 0, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, output := newBuffedDeathWorld(t)
+ player := world.characters[1]
+ player.level, player.experience, player.insuredExperience = scenario.level, scenario.progress, scenario.insured
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 705, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ output.packets = nil
+
+ fatal := defeatReclaimPlayer(t, world)
+ world.advanceCombat(fatal.Add(time.Minute))
+ restored := newTestInventoryServer(t).characters[1]
+
+ if player.health != 0 || restored.health != 0 || player.level != scenario.level || restored.level != scenario.level ||
+ player.experience != scenario.want || restored.experience != scenario.want || player.savedProfile.Experience != scenario.want ||
+ player.insuredExperience != scenario.insured || restored.insuredExperience != scenario.insured || player.stats.ImprovementPoints != 1500 {
+ t.Fatalf("death changed protected progression: level=%d progress=%d insured=%d; restored=%d/%d/%d", player.level, player.experience, player.insuredExperience, restored.level, restored.experience, restored.insuredExperience)
+ }
+ var changes []uint32
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 {
+ changes = append(changes, binary.BigEndian.Uint32(packet[33:37]))
+ }
+ }
+ if scenario.want == scenario.progress && len(changes) != 0 || scenario.want != scenario.progress && len(changes) != 1 {
+ t.Fatalf("wrong number of private loss updates: %v", changes)
+ }
+ lower, _ := player.experienceBounds()
+ if len(changes) != 0 && changes[0] != lower+scenario.want {
+ t.Fatalf("loss update was not absolute cumulative XP: %v", changes)
+ }
+ for _, packet := range observer.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 {
+ t.Fatal("observer received private loss feedback")
+ }
+ }
+ })
+ }
+}
+
+func TestInsuranceExperienceSurvivesResurrectionWithoutAnotherLoss(t *testing.T) {
+ world, output := newBuffedDeathWorld(t)
+ player := world.characters[1]
+ player.level, player.experience, player.insuredExperience = 20, 1500, 140850
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ defeatReclaimPlayer(t, world)
+ output.packets = nil
+
+ err := world.handleResurrection(world.clients[1], resurrectionRequest(1)[20:])
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.health != 1 || restored.health != 1 || player.experience != 1000 || restored.experience != 1000 ||
+ player.insuredExperience != 140850 || restored.insuredExperience != 140850 || len(restored.inventory.Reclaim) != 1 {
+ t.Fatal("resurrection lost insurance or replayed a death outcome", err)
+ }
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 52 {
+ t.Fatal("resurrection replayed the loss")
+ }
+ }
+}
+
+func TestInsuranceExperienceEditorAndNativeInitialization(t *testing.T) {
+ for _, insured := range []uint32{0, 1450, 1490, 1500} {
+ t.Run(fmt.Sprint(insured), func(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ player := world.newCharacter()
+ data := player.userData()
+ data.Level, data.Experience, data.InsuredExperience = 2, 50, insured
+
+ err := world.updateUser(data)
+ restored := newTestInventoryServer(t).characters[1]
+ packet := targetPacket(fullCharacterPacket(restored))
+ count := int(binary.BigEndian.Uint32(packet[61:])/1009 - 1)
+ stats := make(map[uint32]uint32)
+ for cursor := 65; cursor < 65+count*8; cursor += 8 {
+ stats[binary.BigEndian.Uint32(packet[cursor:])] = binary.BigEndian.Uint32(packet[cursor+4:])
+ }
+
+ if err != nil || restored.experience != 50 || restored.insuredExperience != insured || stats[52] != 1500 || stats[236] != max(1450, insured) {
+ t.Fatalf("insurance persistence/native initialization: %v, XP=%d saved=%d", err, stats[52], stats[236])
+ }
+ })
+ }
+}
+
+func TestInsuranceExperienceEditorRejectsImpossibleSnapshots(t *testing.T) {
+ for _, contents := range []string{"insured_experience: -1\n", "insured_experience: 4294967296\n", "insured_experience: 1501\n"} {
+ t.Run(contents, func(t *testing.T) {
+ useNPCData(t, testNPCData())
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.level, player.experience, player.insuredExperience = 2, 50, 1490
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+
+ response := postControlForm(world, "/control/users/1", url.Values{"data": {contents}})
+ restored := newTestInventoryServer(t).characters[1]
+
+ if response.Code != http.StatusBadRequest || player.experience != 50 || player.insuredExperience != 1490 || restored.insuredExperience != 1490 {
+ t.Fatalf("invalid insurance edit changed state: HTTP %d", response.Code)
+ }
+ })
+ }
+}
diff --git a/server/player_death.go b/server/player_death.go
@@ -8,7 +8,7 @@ import (
func (server *server) writePlayerDeath_locked(tx *sql.Tx, player *character) error {
// Death, canceled cast reservations and removed modifiers form one outcome.
- result, err := tx.Exec("UPDATE characters SET health=0, nano=?, nano_reserved=0 WHERE id=?", player.nano, player.id)
+ result, err := tx.Exec("UPDATE characters SET health=0, nano=?, nano_reserved=0, experience=? WHERE id=?", player.nano, player.experience, player.id)
if err != nil {
return err
}
@@ -53,6 +53,7 @@ func (server *server) writePlayerDeath_locked(tx *sql.Tx, player *character) err
}
func (server *server) rememberPlayerDeath_locked(player *character) {
+ player.savedProfile.Experience = player.experience
player.savedVitals.Health, player.savedVitals.Nano, player.savedVitals.NanoReserved = 0, player.nano, 0
for _, entry := range player.inventory.Reclaim {
placement := server.itemPlacements[entry.Item.ID]
diff --git a/server/profile_database.go b/server/profile_database.go
@@ -2,7 +2,7 @@ package main
// These columns are shared by players and NPCs; the pointers serve SQL scans and writes.
const profileColumns = "name, appearance_race, appearance_fatness, appearance_breed, appearance_sex, appearance_side, appearance_head, " +
- "monster_data, level, experience, profession, improvement_points, abilities_strength, abilities_agility, abilities_stamina, " +
+ "monster_data, level, experience, insured_experience, profession, improvement_points, abilities_strength, abilities_agility, abilities_stamina, " +
"abilities_intelligence, abilities_sense, abilities_psychic, body_martial_arts, body_brawling, body_riposte, body_dimach, " +
"body_adventuring, body_swimming, body_body_development, body_nano_pool, melee_one_hand_blunt, melee_one_hand_edged, " +
"melee_piercing, melee_two_hand_blunt, melee_two_hand_edged, melee_melee_energy, melee_parry, melee_sneak_attack, " +
@@ -24,7 +24,7 @@ func (profile *playerProfile) fields() []any {
return []any{
&profile.Name, &profile.Appearance.Race, &profile.Appearance.Fatness, &profile.Appearance.Breed,
&profile.Appearance.Sex, &profile.Appearance.Side, &profile.Appearance.Head, &profile.MonsterData,
- &profile.Level, &profile.Experience, &profile.Profession, &profile.Stats.ImprovementPoints, &profile.Stats.Abilities.Strength,
+ &profile.Level, &profile.Experience, &profile.InsuredExperience, &profile.Profession, &profile.Stats.ImprovementPoints, &profile.Stats.Abilities.Strength,
&profile.Stats.Abilities.Agility, &profile.Stats.Abilities.Stamina, &profile.Stats.Abilities.Intelligence, &profile.Stats.Abilities.Sense,
&profile.Stats.Abilities.Psychic, &profile.Stats.Body.MartialArts, &profile.Stats.Body.Brawling, &profile.Stats.Body.Riposte,
&profile.Stats.Body.Dimach, &profile.Stats.Body.Adventuring, &profile.Stats.Body.Swimming, &profile.Stats.Body.BodyDevelopment,
diff --git a/server/progression.go b/server/progression.go
@@ -108,6 +108,12 @@ func (server *server) applyExperienceAward_locked(award *experienceAward, now ti
body = binary.BigEndian.AppendUint32(body, value)
}
updates[client] = append(updates[client], n3Packet(0x7f405a16, 50000, player.id, body))
+ // A previous level's insurance cannot place the saved marker below this level's floor.
+ if player.insuredExperience < lower {
+ body := binary.BigEndian.AppendUint32(nil, 236)
+ body = binary.BigEndian.AppendUint32(body, lower)
+ updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, player.id, body))
+ }
visible := [][2]uint32{{54, uint32(player.level)}}
if title != 0 {
visible = append(visible, [2]uint32{37, title})
diff --git a/server/state.go b/server/state.go
@@ -13,35 +13,36 @@ import (
)
type character struct {
- id uint32
- name string
- playfield uint32
- position [3]float32
- rotation [4]float32
- appearance uint16
- monsterData uint32
- level uint16
- experience uint32
- profession uint16
- stats characterStats
- inventory playerInventory
- corpse *npcCorpse
- combatProfile *gamedata.NPCCombatProfile
- team *playerTeam
- buddies map[uint32]string
- health uint32
- nano uint32
- nanoReserved uint32
- sitting bool
- aggDef int32
- fighting uint32
- nextAttack time.Time
- rechargeUntil time.Time
- running bool
- returnDoor *doorOrigin
- npc bool
- npcDefinitionID string
- roaming *npcRoaming
+ id uint32
+ name string
+ playfield uint32
+ position [3]float32
+ rotation [4]float32
+ appearance uint16
+ monsterData uint32
+ level uint16
+ experience uint32
+ insuredExperience uint32
+ profession uint16
+ stats characterStats
+ inventory playerInventory
+ corpse *npcCorpse
+ combatProfile *gamedata.NPCCombatProfile
+ team *playerTeam
+ buddies map[uint32]string
+ health uint32
+ nano uint32
+ nanoReserved uint32
+ sitting bool
+ aggDef int32
+ fighting uint32
+ nextAttack time.Time
+ rechargeUntil time.Time
+ running bool
+ returnDoor *doorOrigin
+ npc bool
+ npcDefinitionID string
+ roaming *npcRoaming
damageContributors map[damageContributor]uint32
leadingContributor damageContributor
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -98,8 +98,8 @@ initialized:
if hex.EncodeToString(npc[60:89]) != "000001cb0b456469746564204e50430000000000000000000000000007" {
t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89])
}
- if hex.EncodeToString(full[57:97]) != "000003f10001727e0000003600000001000000340000000000000039000000000000015e000005aa" {
- t.Fatalf("target seventh list and initial progression stats: %x", full[57:97])
+ if hex.EncodeToString(full[57:105]) != "000003f10001766f0000003600000001000000340000000000000039000000000000015e000005aa000000ec00000000" {
+ t.Fatalf("target seventh list and initial progression/insurance stats: %x", full[57:105])
}
}
diff --git a/server/users.go b/server/users.go
@@ -17,19 +17,20 @@ import (
// User IDs are stable; each local user currently owns one character.
type userData struct {
- ID uint32
- Name string
- Playfield uint32
- Position [3]float32
- Rotation [4]float32
- Appearance uint16
- MonsterData uint32
- Level uint16
- Experience uint32
- Profession uint16
- Stats characterStats
- Running bool
- ReturnDoor *doorOrigin
+ ID uint32
+ Name string
+ Playfield uint32
+ Position [3]float32
+ Rotation [4]float32
+ Appearance uint16
+ MonsterData uint32
+ Level uint16
+ Experience uint32
+ InsuredExperience uint32
+ Profession uint16
+ Stats characterStats
+ Running bool
+ ReturnDoor *doorOrigin
BrowserTokenHash string
}
@@ -41,6 +42,7 @@ type playerProfile struct {
MonsterData uint32 `yaml:"monster_data"`
Level uint16 `yaml:"level"`
Experience uint32 `yaml:"experience"`
+ InsuredExperience uint32 `yaml:"insured_experience"`
Profession uint16 `yaml:"profession"`
Stats characterStats `yaml:"stats"`
Running bool `yaml:"running"`
@@ -59,16 +61,17 @@ type playerPosition struct {
func (character *character) userData() userData {
return userData{character.id, character.name, character.playfield, character.position,
- character.rotation, character.appearance, character.monsterData, character.level, character.experience, max(1, character.profession), character.baseStats(), character.running, character.returnDoor, character.browserTokenHash}
+ character.rotation, character.appearance, character.monsterData, character.level, character.experience, character.insuredExperience, max(1, character.profession), character.baseStats(), character.running, character.returnDoor, character.browserTokenHash}
}
func (data userData) character() *character {
character := &character{id: data.ID, name: data.Name, playfield: data.Playfield, position: data.Position,
rotation: data.Rotation, appearance: data.Appearance, monsterData: data.MonsterData, level: data.Level, experience: data.Experience,
- profession: max(1, data.Profession),
- running: data.Running,
- stats: data.Stats,
- returnDoor: data.ReturnDoor, browserTokenHash: data.BrowserTokenHash}
+ insuredExperience: data.InsuredExperience,
+ profession: max(1, data.Profession),
+ running: data.Running,
+ stats: data.Stats,
+ returnDoor: data.ReturnDoor, browserTokenHash: data.BrowserTokenHash}
character.stats = character.baseStats()
character.health = character.maximumHealth()
return character
@@ -91,6 +94,10 @@ func (data userData) validate() error {
if data.Level == 200 && data.Experience != 0 || data.Level < 200 && data.Experience >= gamedata.ExperienceLevels[data.Level-1] {
return fmt.Errorf("experience must be below the current level's requirement")
}
+ lower, _ := (&character{level: data.Level}).experienceBounds()
+ if data.InsuredExperience > lower+data.Experience {
+ return fmt.Errorf("insured experience cannot exceed cumulative experience")
+ }
if data.Profession > 12 {
return fmt.Errorf("profession must be one of the twelve original professions")
}
diff --git a/server/world.go b/server/world.go
@@ -195,7 +195,7 @@ func fullCharacterPacket(character *character) []byte {
body = binary.BigEndian.AppendUint32(body, 1009)
}
lowerXP, upperXP := character.experienceBounds()
- stats := [][2]uint32{{54, uint32(character.level)}, {52, lowerXP + character.experience}, {57, lowerXP}, {350, upperXP}}
+ stats := [][2]uint32{{54, uint32(character.level)}, {52, lowerXP + character.experience}, {57, lowerXP}, {350, upperXP}, {236, max(lowerXP, character.insuredExperience)}}
stats = append(stats, character.baseStats().nativeStats()...)
stats = append(stats,
[2]uint32{4, uint32(character.appearance >> 4 & 7)},
diff --git a/server/world.sql b/server/world.sql
@@ -19,6 +19,7 @@ CREATE TABLE IF NOT EXISTS characters (
monster_data INTEGER NOT NULL DEFAULT 0,
level INTEGER NOT NULL DEFAULT 1,
experience INTEGER NOT NULL DEFAULT 0 CHECK (experience BETWEEN 0 AND 4294967295),
+ insured_experience INTEGER NOT NULL DEFAULT 0 CHECK (insured_experience BETWEEN 0 AND 4294967295),
profession INTEGER NOT NULL DEFAULT 1,
improvement_points INTEGER NOT NULL DEFAULT 1500,
abilities_strength INTEGER NOT NULL DEFAULT 6,