commit 8036ffbb54b420052dd136ff515d440c2d16e6e6
parent 59ceb853e77eb880363168a5bc770aff07674a98
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 13:15:20 +0000
Correct combat HP after health buff refresh and replacement
Diffstat:
7 files changed, 350 insertions(+), 13 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1960,12 +1960,16 @@ introduction and starting-item gameplay remain open below.
action 108, repeated cancellation, delayed ticks and durable recovery are covered.
This verifies the existing reconstruction policy. Historical charging/refund
timing remains the separate open P2 item above.
-- [ ] [P2] Reconcile native HP during maximum-health buff replacement/refresh under
- incoming weapon combat. Native modifier removal can clamp to the intermediate
- maximum; idle casts now correct HP immediately after action 177. The existing quiet
- HP path deliberately waits for weapon queues to drain. Resolve the shared
- combat health-delivery contract together with healing, without disabling
- otherwise valid buffs or resetting the fight to hide the discrepancy.
+- [x] [P2] Reconcile native HP during maximum-health buff replacement/refresh under
+ incoming weapon combat. Body Boost refresh reproduced native 184 versus server 204;
+ Titan/Survivor replacement reproduced 2244 versus 2613. Publish the existing
+ received-hit-aware snapshot after refresh and actual HP changes, preserving
+ periodic quiet suppression. Handler cases cover refresh, upgrade, replacement
+ and cancellation clamps. Two qualified controlled native pairs now retain 204
+ and 2613 through their original queued impacts, unchanged attacker clocks,
+ StopFight, page replay and a final checkpoint/cold load, with exact nano costs,
+ effects and items. No buff is disabled or fight reset to hide the discrepancy;
+ see [combat health modifiers](docs/nano-health-buffs.md#combat-refresh-and-replacement).
- [x] Cast one direct-damage program on a creature. Check: target validation,
damage and death handling work without starting an unintended weapon attack.
- [x] Replace Winter's Bite's damage constants and bespoke requirements with
diff --git a/docs/nano-health-buffs.md b/docs/nano-health-buffs.md
@@ -37,11 +37,12 @@ atomically with removal. Death uses the existing ordinary-buff removal policy.
Native replacement removes the old MaxHealth modifier before applying the new
one. Its removal handler can temporarily clamp HP to the intermediate maximum,
even on refresh or an upgrade whose authoritative HP stays unchanged. Such
-casts therefore publish a quiet HP correction after action 177 and any resource
-foundation updates. This adds no database write when actual HP is unchanged.
-Health reconciliation during weapon combat retains the broader unresolved
-delivery limitation described in [Doctor healing](nano-healing.md); maximum
-foundation accounting during combat is covered separately.
+casts therefore publish an HP snapshot after action 177 and any resource
+foundation updates, including while incoming weapon results remain queued.
+Actual HP changes from replacement, cancellation or expiry use the same snapshot
+path. Native received-hit reconciliation preserves the later impact without
+applying its damage twice. Periodic quiet corrections still wait for combat to
+end. This adds no database health write when actual HP is unchanged.
## Native resource foundations
@@ -67,6 +68,47 @@ They reuse the original 14.9.1 KKR SHA-256
The separate team/inspection receiver evidence is documented in
[team resources](team-resources.md) and [inspection](character-info.md).
+## Combat refresh and replacement
+
+The previous combat guard withheld an absolute HP correction after modifier
+removal. Two controlled native clients reproduced Body Boost refresh at 184 HP
+versus authoritative 204, and Titan Physique replacement by Survivor's Resilience
+at 2244 versus 2613. Each case received one real eight-point Leet result while
+the cast completion tick was held. The pending result remained present during
+the modifier update; its later impact exposed the missing correction.
+
+Refresh now publishes the existing HealthDamage snapshot after action 177 even
+when authoritative HP stays unchanged. Actual HP changes through the shared
+resource path also publish immediately, including replacement/cancellation
+clamps. This uses the same received-hit reconciliation as recovery/healing;
+periodic quiet snapshots retain their combat guard. The attack target, next-hit
+deadline, recharge and original queued result stay intact.
+
+Public-handler cases cover refresh, upgrade, a smaller final maximum and
+cancellation, requiring exactly one correction after the modifier event,
+zero damage feedback, unchanged incoming clocks and exact cold health.
+Existing unchanged-health write refusal checks still pass.
+
+`TestBrowserHealthBuffRefreshDuringIncomingHit` checks both reproduced cases
+with real native casting input and two clients. The starter case is a level 20
+Soldier with Body Development 10. The replacement uses a level 200 Nanomage
+Soldier at breed ability caps, raw BM 537/MC 480, existing MatCrea Expertise and
+the controlled 47-NCU fixture implant. Raw skill caps and program requirements
+are checked. After the original impact both clients retain 204/2613 HP, with
+exact 10/519 nano debits and the expected active contributions. StopFight,
+both page reloads and a final world checkpoint/cold read retain health, cost,
+effects and exact items. These are controlled delivery fixtures, not earned
+progression or independent measurements of historical cast balance. Captures,
+baseline failures and independent checks are in `local/combat-health-refresh/`.
+
+The related Go selection passes 33 roots and 210 results. Focused race checks
+pass five roots and 16 results in 102.987 seconds; vet and Node syntax checks
+pass. The two native cases complete in 47.30 seconds with eight clean, complete
+traces. The independent verifier checks unchanged pending results and clocks,
+HP corrections after the modifier and before StopFight, exact impacts and page
+replay. Its source hashes and results are in
+`local/combat-health-refresh/verification.json`.
+
## Flags and remaining policies
Two exact program Flags0 variants qualify: 0x80010000 and 0x10000. All carry
diff --git a/server/browser_combat_health_refresh_test.go b/server/browser_combat_health_refresh_test.go
@@ -0,0 +1,159 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserHealthBuffRefreshDuringIncomingHit(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for health buff refresh during combat")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/combat-health-refresh", time.Now().Format("20060102-150405"))
+ for _, scenario := range []struct {
+ name string
+ initial, program, cost uint32
+ }{{"refresh", 29091, 29091, 10}, {"replace-clamp", 29254, 95693, 519}} {
+ t.Run(scenario.name, func(t *testing.T) {
+ world := newTestServer(t)
+ var npc *character
+ for _, actor := range world.characters {
+ if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) {
+ npc = actor
+ }
+ }
+ if npc == nil {
+ t.Fatal("no admitted level-one Leet")
+ }
+ npc.playfield, npc.position, npc.rotation, npc.motion = 705, [3]float32{960, 16.5, 514}, [4]float32{0, 0, 0, 1}, nil
+ world.characters = map[uint32]*character{npc.id: npc}
+ for index := 0; index < 2; index++ {
+ player := world.newCharacter()
+ player.level, player.profession = 20, 1
+ if scenario.program == 95693 {
+ player.level = 200
+ }
+ player.playfield, player.position = 705, [3]float32{960 + float32(index*2), 16.5, 511}
+ player.rotation = [4]float32{0, 0, 0, 1}
+ player.stats = testCharacterStats()
+ player.stats.Abilities = characterAbilitiesStats{20, 20, 20, 20, 20, 20}
+ player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 10, 20
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.MatterCreation = 10, 10
+ if index == 0 {
+ if scenario.program == 95693 {
+ player.appearance = 0x535
+ player.stats.Abilities = characterAbilitiesStats{464, 464, 448, 512, 480, 512}
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.MatterCreation = 537, 480
+ player.stats.Body.NanoPool = 400
+ }
+ player.inventory.LearnedNanos = []uint32{scenario.program}
+ player.activeNanos = []activeNano{{program: scenario.initial, caster: 1, remaining: 30 * time.Minute, expiresAt: time.Now().Add(30 * time.Minute)}}
+ if scenario.program == 95693 {
+ player.activeNanos = append(player.activeNanos, activeNano{program: 27098, caster: 1, remaining: 30 * time.Minute, expiresAt: time.Now().Add(30 * time.Minute)})
+ }
+ }
+ player.health, player.nano = player.maximumHealth(), player.maximumNano()
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("health-refresh-", index))))
+ for stat, base := range map[uint32]uint32{152: uint32(player.stats.Body.BodyDevelopment), 132: uint32(player.stats.Body.NanoPool),
+ 128: uint32(player.stats.NanoAiding.BiologicalMetamorphosis), 130: uint32(player.stats.NanoAiding.MatterCreation)} {
+ if base > player.trainingMaximum(stat) {
+ t.Fatal("controlled raw skill exceeds native cap", stat, base, player.trainingMaximum(stat))
+ }
+ }
+ if index == 0 && !player.nanoRequirementsMet(scenario.program) {
+ t.Fatal("controlled caster lacks its program requirements")
+ }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if scenario.program == 95693 {
+ if granted, err := world.grantItem_locked(world.characters[1], 173155); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ world.characters[1].inventory.Items[0].Slot = 35
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ player := world.characters[1]
+ initialNano := player.nano
+ initialEffects := len(player.activeNanos)
+ expectedItems := slices.Clone(player.inventory.Items)
+ mux := http.NewServeMux()
+ mux.Handle("/", world.httpHandler())
+ mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ casting := world.clients[1] != nil && world.clients[1].nanoCast != nil
+ json.NewEncoder(w).Encode(map[string]any{"health": player.health, "maximum": player.maximumHealth(), "nano": player.nano,
+ "program": scenario.program, "cost": scenario.cost, "casting": casting, "effects": len(player.activeNanos), "npc": npc.id, "target": npc.fighting,
+ "nextAttack": npc.nextAttack, "rechargeUntil": npc.rechargeUntil})
+ })
+ mux.HandleFunc("POST /test-attack", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ world.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+ world.startAttack_locked(npc, player, time.Now(), updates)
+ deadline := npc.nextAttack
+ world.mutex.Unlock()
+ world.sendCombatUpdates(updates)
+ world.updateMutex.Unlock()
+ world.advanceCombat(deadline)
+ })
+ mux.HandleFunc("POST /test-finish", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ deadline := world.clients[1].nanoCast.readyAt.Add(time.Nanosecond)
+ world.mutex.Unlock()
+ world.advanceNanos(deadline)
+ })
+ mux.HandleFunc("POST /test-stop", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ updates := make(map[*worldClient][][]byte)
+ world.stopAttack_locked(npc, updates)
+ world.queueQuietHealth_locked(updates, player)
+ world.mutex.Unlock()
+ world.sendCombatUpdates(updates)
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_combat_health_refresh.mjs"), host.URL, filepath.Join(output, scenario.name))
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ t.Logf("Browser artifacts: %s", filepath.Join(output, scenario.name))
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ if cold.characters[1].health != player.health || player.nano != initialNano-scenario.cost ||
+ cold.characters[1].nano != player.nano || !slices.Equal(cold.characters[1].inventory.Items, expectedItems) || len(player.activeNanos) != initialEffects || len(cold.characters[1].activeNanos) != initialEffects ||
+ player.nanoBonus(1) != nanoProgramBonus(scenario.program, 1) || npc.fighting != 0 {
+ t.Fatal("refresh changed real health, duplicated the buff or lost its committed cost")
+ }
+ })
+ }
+}
diff --git a/server/combat_health_refresh_test.go b/server/combat_health_refresh_test.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func TestHealthBuffCombatCorrectionFollowsEffectAndRetainsAttack(t *testing.T) {
+ for _, scenario := range []string{"refresh", "upgrade", "replace clamp", "cancel clamp"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newMaximumHealthNanoWorld(t)
+ player, npc := world.characters[1], world.characters[1000000]
+ player.inventory.LearnedNanos = []uint32{29091, 95696, 29254, 95693}
+ initial, replacement, expected := uint32(29091), uint32(29091), uint32(57)
+ switch scenario {
+ case "upgrade":
+ replacement = 95696
+ case "replace clamp":
+ initial, replacement, expected = 29254, 95693, 398
+ case "cancel clamp":
+ expected = 37
+ }
+ castTestBuff(t, world, 1, 1, initial)
+ player.health = player.maximumHealth()
+ player.nanoRechargeUntil = time.Time{}
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ updates := make(map[*worldClient][][]byte)
+ world.startAttack_locked(npc, player, time.Now(), updates)
+ attack, recharge := npc.nextAttack, npc.rechargeUntil
+ output.packets = nil
+
+ if scenario == "cancel clamp" {
+ if err := world.handleNanoRemoval(world.clients[1], characterActionPacket(1, [5]uint32{65, 0, 0, 53019, initial})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ castTestBuff(t, world, 1, 1, replacement)
+ }
+ cold := newTestInventoryServer(t)
+
+ effect, correction, snapshots := -1, -1, 0
+ for index, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 {
+ action := binary.BigEndian.Uint32(packet[29:33])
+ if action == 65 || action == 177 {
+ effect = index
+ }
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c {
+ correction, snapshots = index, snapshots+1
+ if binary.BigEndian.Uint32(packet[29:33]) != expected || binary.BigEndian.Uint32(packet[33:37]) != 0 {
+ t.Fatal("combat correction changed real HP or added damage feedback")
+ }
+ }
+ }
+ if effect < 0 || correction <= effect || snapshots != 1 || player.health != expected || cold.characters[1].health != expected ||
+ npc.fighting != 1 || npc.nextAttack != attack || npc.rechargeUntil != recharge {
+ t.Fatal("health modifier completion lacked ordered combat-safe correction or changed the incoming attack", effect, correction, snapshots, player.health)
+ }
+ })
+ }
+}
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -418,7 +418,7 @@ func (server *server) finishResourceChange_locked(updates map[*worldClient][][]b
}
}
if player.health != previous.health {
- server.queueQuietHealth_locked(updates, player)
+ server.queueHealthSnapshot_locked(updates, player)
}
if player.nano != previous.nano && server.clients[player.id] != nil {
updates[server.clients[player.id]] = append(updates[server.clients[player.id]], nanoPointsPacket(player))
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -360,7 +360,7 @@ func (server *server) advanceNanos(now time.Time) {
server.finishResourceChange_locked(updates, target, previous, now)
if removedHealthBonus && target.health == previous.health {
// Native removal can clamp HP before adding the replacement or refresh.
- server.queueQuietHealth_locked(updates, target)
+ server.queueHealthSnapshot_locked(updates, target)
}
continue
}
diff --git a/tools/client/test_combat_health_refresh.mjs b/tools/client/test_combat_health_refresh.mjs
@@ -0,0 +1,67 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium',
+ args: ['--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+const games = [], evidence = {};
+const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+try {
+ for (let index = 0; index < 2; ++index) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'health-refresh-' + index, url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner, observer] = games;
+ const server = async () => (await owner.page.request.get(url + '/test-state')).json();
+ evidence.initial = await server();
+ const npc = evidence.initial.npc;
+ const pending = game => actor(game, npc)?.weapons.some(weapon => weapon.pending.length);
+ const clients = () => games.map(game => ({health: actor(game, 1).stats[27], weapons: actor(game, npc).weapons}));
+ await Promise.all(games.map(game => game.wait('owner and attacker ready', () => actor(game, 1) && actor(game, npc))));
+ await owner.key('F1');
+ await owner.page.keyboard.press('Control+8');
+ await owner.click(975, 76);
+ const cast = owner.sequence;
+ await owner.click(857, 128, 'right');
+ await owner.wait('native health-buff request', () => owner.events.some(event => event.sequence > cast &&
+ event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 19));
+ assert.equal((await server()).casting, true);
+ assert((await owner.page.request.post(url + '/test-attack')).ok());
+ await Promise.all(games.map(game => game.wait('real incoming result remains pending', () => pending(game))));
+ evidence.pending = {server: await server(), clients: clients()};
+ assert.equal(evidence.pending.server.health, evidence.initial.health - 8);
+ assert((await owner.page.request.post(url + '/test-finish')).ok());
+ await owner.wait('health buff delivered', () => owner.events.some(event => event.sequence > cast &&
+ event.direction === 'framereceived' && event.opcode === '5e477770' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 177 && Buffer.from(event.hex, 'hex').readUInt32BE(37) === evidence.initial.program));
+ evidence.refreshed = {server: await server(), clients: clients()};
+ assert.equal(evidence.refreshed.server.health, Math.min(evidence.pending.server.health, evidence.refreshed.server.maximum));
+ assert.equal(evidence.refreshed.server.nano, evidence.initial.nano - evidence.initial.cost);
+ assert.equal(evidence.refreshed.server.nextAttack, evidence.pending.server.nextAttack);
+ assert.equal(evidence.refreshed.server.rechargeUntil, evidence.pending.server.rechargeUntil);
+ await Promise.all(games.map(game => game.wait('original impact consumed', () => !pending(game))));
+ evidence.impact = {server: await server(), clients: clients()};
+ await Promise.all(games.map((game, index) => game.save(output + '/impact-' + index)));
+ assert(evidence.impact.clients.every(client => client.health === evidence.impact.server.health),
+ 'Health-buff refresh/replacement clamped native HP below the authoritative incoming-hit result');
+ assert((await owner.page.request.post(url + '/test-stop')).ok());
+ await Promise.all(games.map(game => game.wait('attacker stopped', () => actor(game, npc).combatTarget === 0)));
+ await Promise.all(games.map(async game => { await game.page.reload(); await game.ready(); }));
+ await Promise.all(games.map(game => game.wait('replayed owner HP', () => actor(game, 1)?.stats[27] === evidence.impact.server.health)));
+ assert(games.every(game => game.errors.length === 0));
+ console.log('PASS: native health buff refresh preserves incoming hit, exact HP, clocks, cost and page/cold recovery');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ for (const [index, game] of games.entries()) await game.save(output + '/final-' + index);
+ } finally { await browser.close(); }
+}