commit 40479ea5b1cd84c7eb90194f0f9be2e2a7e081f7
parent 491782f827dc7c0ed4cf946b8614f3353deff992
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 15:23:27 +0000
Execute complete Trader health-drain contracts
Diffstat:
13 files changed, 1185 insertions(+), 10 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -2152,6 +2152,12 @@ introduction and starting-item gameplay remain open below.
Healing, shows its native icon, preserves the spare and withdraws a companion
through the same window. Page replay/cold loading retain the exact remaining
items and one program; see [contained uploads](docs/nano-learning.md#learning-from-carried-backpacks).
+- [x] [P1] Execute complete Trader health-drain programs, including the issued
+ Weak Health Funnel crystal. All30 original pairs/crystals now preserve the
+ caster heal, hostile Hit and target-scoped maximum-HP gate. Both HP changes,
+ cost and recharge commit together. Catalog, rejection, clamping, cancellation,
+ rollback/retry and two-client WASM page/cold recovery pass. Shared PvE and
+ resistance/lifecycle limits remain; see [health drains](docs/nano-health-drains.md).
- [x] [P1] Cast one self-heal. Check: cast time, nano cost, health gain and recharge
agree with the chosen program and appear correctly in the native client.
Complete contracts admit 85 ordinary programs/crystals, with authored gates,
diff --git a/docs/nano-direct-damage.md b/docs/nano-direct-damage.md
@@ -6,6 +6,9 @@ endpoints and damage stat, uses the program's own cost, attack delay, recharge,
range and requirements, and commits the result through the existing atomic
nano outcome transaction. There is no program-ID switch for damage delivery.
+The same execution path also supports the 30 complete paired caster-heal and
+hostile-Hit contracts described in [Trader health drains](nano-health-drains.md).
+
This extends the existing PvE reconstruction policy: visible living creatures,
an inclusive uniform damage roll, and range checks at admission and completion.
Original resistance/fumble rolls, AC/modifier ordering, reflect/absorb, PvP,
diff --git a/docs/nano-health-drains.md b/docs/nano-health-drains.md
@@ -0,0 +1,102 @@
+# Trader health drains
+
+The shared direct-damage path now admits all 30 complete ordinary Trader
+health-drain programs and their 30 original crystals. This includes the issued
+Weak Health Funnel crystal78417, which learns program76742. The complete set is
+in [the original-record fixture](../server/testdata/health-drain-nanos.json).
+Weak Delayed Health Payment43374 is a separate team-heal/self-damage contract
+and remains unsupported.
+
+## Original contract
+
+Each admitted program has exactly two unconditional, one-shot HP Hit53002
+functions, in this order:
+
+1. Target1 heals the caster, with damage-type argument0.
+2. Target3 damages the selected recipient, with energy argument92.
+
+All 30 pairs have fixed authored amounts. Weak Health Funnel heals4 and hits10;
+Greater Health Funnel76717 heals63 and hits119; Sophisticated Health
+Plunder77195 heals577 and hits580. Healing and damage clamp independently to
+the caster's maximum and victim's current HP. The unconditional positive Hit
+does not become a percentage of clipped damage. Full caster health still allows
+the hostile Hit. Neither effect may execute alone after a failed transaction.
+
+The programs have flags0x8000, medical school2, positive ordinary cost/range and
+casting/recharge metadata, and no timed effect or strain. Attack/defense
+dictionaries retain their authored BM/TimeSpace weights and NanoResist defense.
+Conditional, repeated, opaque, differently scoped or extra effects reject the
+whole program.
+
+The action's postfix OnTarget18 marker switches subsequent attribute tests
+from caster to selected recipient. These contracts require the target's maximum
+HP stat1 to exceed damage-1. This is not a current-HP test or a caster-HP test;
+a target with one remaining HP can still qualify. The marker's authored operands
+are both zero. Skill and profession tests before it continue to use the caster.
+Missing targets and unsupported criteria reject without a reservation.
+
+The source census reopens the shipped14.9.1 ResourceDatabase and reparses all
+60 records using the maintained format-aware decoder. Program payload hashes,
+full effects/criteria, crystal uploaders, index identity and parser identity are
+retained in `local/health-drain-nanos/original-records.json`. Each program's
+payload hash matches the decoded catalog. These are authored-resource facts;
+they do not recover unavailable original-server resistance or PvP policy.
+
+## Execution and delivery
+
+Crystal learning uses the existing complete-program upload and atomic
+consumption path. Casting uses the shared learned-program, action, range,
+visibility and creature-target admission, reservation, cancellation and recharge.
+The existing PvE subset and no-resistance-roll reconstruction remain in force.
+Original charging/refund and completion-gate policies remain open in TODO.md.
+
+Completion stages the caster heal and target Hit together. The same transaction
+commits caster HP, reserved nano consumption, recharge and NPC state, including
+ordinary damage contributions, death, loot and XP when applicable. Required
+caster-health writes check their returned row; failed/ignored writes or failed
+commit publish neither effect. Existing cancellation/refund permits a fresh
+complete retry. A clamped zero caster gain causes no unnecessary HP write.
+
+After commit, the caster receives the same received-hit-aware absolute health
+snapshot used by direct healing. Observers and team resources use the shared
+delivery paths. Normal heal feedback reports the actual clamped gain. The
+target receives the existing nano damage result and retaliation/death handling;
+the caster does not start a weapon attack.
+
+Weak Health Funnel's raw cost16 produces debit15 under the recovered floating
+operation order; see [nano cost](nano-cost.md). Its original attack/recharge are
+300/400 centiseconds. No bespoke cost or timing is attached to this program.
+
+## Verification
+
+Public-handler tests cover all30 crystal uploads and complete paired outcomes,
+exact resource metadata/costs, repeated completion, cold state and source
+consumption. A controlled higher-HP NPC profile isolates the stronger catalog
+contracts; it does not establish original creature balance. Focused cases cover
+target maximum-HP equality, a one-HP victim, full/partly full caster, missing
+target, cancellation, range/death invalidation, unsupported partial pairs,
+failed/ignored writes, failed commit and complete retry.
+
+The two-client WASM fixture uses cap-checked level2 Traders, one issued crystal
+and an ordinary full-health level1 Leet at a controlled starting position. Real
+inventory upload and native program-icon casting produce caster HP20->24,
+nano30->15 and target HP100->90 on both replicas. Both page replays carry the
+stored NPC HP90; cold loading retains both HP changes, learned program, consumed
+crystal and recharge. The other character's authoritative HP/nano stay20/30.
+The accepted capture is `local/health-drain-nanos/20261104-071103`,35.37s.
+
+This fixture advances the nano scheduler, with no gameplay farming. Owner
+disconnect stops retaliation; the reloaded idle Leet can predict normal quiet
+recovery before capture. Replay checks the actual SimpleChar maximum/current
+HP pair100/90 and records later predicted HP separately. The earlier strict
+constant-90 replay assertion exposed that established prediction phase, not a
+lost drain outcome. The shared [NPC recovery](npc-regeneration.md) and broader
+HP/cadence audits remain separate. All four accepted traces have no native
+exceptions or dropped events; no client rewrite was needed.
+
+Related regressions pass 49 roots/1,033 results in216.631s, including the ordinary
+damage/healing catalogs, self-only target forms, signed requirements and atomic
+outcomes. Focused race checks pass 11 roots/97 results in154.750s. Maintained
+Go packages pass vet, and JavaScript syntax/whitespace checks pass. Independent
+packet/state checks and exact source hashes are in that folder's
+`verification.json`; these are scoped runs, not a new full-server-suite result.
diff --git a/server/browser_combat_health_refresh_test.go b/server/browser_combat_health_refresh_test.go
@@ -74,7 +74,7 @@ func TestBrowserHealthBuffRefreshDuringIncomingHit(t *testing.T) {
t.Fatal("controlled raw skill exceeds native cap", stat, base, player.trainingMaximum(stat))
}
}
- if index == 0 && !player.nanoRequirementsMet(scenario.program) {
+ if index == 0 && !player.nanoRequirementsMet(scenario.program, player) {
t.Fatal("controlled caster lacks its program requirements")
}
if err := world.saveUser_locked(player); err != nil {
diff --git a/server/browser_health_drain_test.go b/server/browser_health_drain_test.go
@@ -0,0 +1,109 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserHealthDrain(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the Trader health-drain contract")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/health-drain-nanos", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ var enemy *character
+ for _, actor := range world.characters {
+ if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (enemy == nil || actor.id < enemy.id) {
+ enemy = actor
+ }
+ }
+ if enemy == nil {
+ t.Fatal("no controlled level-one Leet")
+ }
+ var players []*character
+ for index := range 2 {
+ player := world.newCharacter()
+ player.level, player.profession = 2, 7
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 6, 8
+ player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 10, 10
+ for _, trained := range [][2]uint32{{128, 6}, {131, 8}, {152, 10}, {132, 10}} {
+ if player.trainingMaximum(trained[0]) < trained[1] {
+ t.Fatal("health-drain fixture exceeds native training caps")
+ }
+ }
+ player.position = enemy.position
+ player.position[2] -= float32(4 + index*3)
+ player.health, player.nano = 20, 30
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("health-drain-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ players = append(players, player)
+ }
+ if granted, err := world.grantItem_locked(players[0], 78417); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ 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()
+ json.NewEncoder(w).Encode(map[string]any{"owner": players[0].id, "observer": players[1].id, "enemy": enemy.id,
+ "health": players[0].health, "nano": players[0].nano, "targetHealth": enemy.health,
+ "reserved": players[0].nanoReserved, "recharge": players[0].nanoRechargeUntil,
+ "inventory": players[0].inventory, "peerHealth": players[1].health, "peerNano": players[1].nano})
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ world.advanceNanos(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_health_drain.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ cancel()
+ <-stopped
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ if players[0].health != 24 || players[0].nano != 15 || enemy.health != 90 ||
+ cold.characters[players[0].id].health != 24 || cold.characters[players[0].id].nano != 15 || cold.characters[enemy.id].health != 90 ||
+ !slices.Equal(cold.characters[players[0].id].inventory.LearnedNanos, []uint32{76742}) ||
+ len(cold.characters[players[0].id].inventory.Items) != 0 ||
+ !cold.characters[players[0].id].nanoRechargeUntil.Equal(players[0].nanoRechargeUntil) ||
+ players[1].health != 20 || players[1].nano != 30 {
+ t.Fatal("native drain lost an effect, cost, upload or peer isolation through cold recovery")
+ }
+}
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -84,8 +84,38 @@ func (player *character) nanoCastDelay(program uint32) time.Duration {
return time.Duration(float64(delay) * float64(time.Second))
}
-func (player *character) nanoRequirementsMet(program uint32) bool {
- return (directDamageNano(program) != nil || directHealingNano(program) != nil || healingOverTimeNano(program) != nil || damageOverTimeNano(program) != nil || controlNano(program) != nil || statBuffNano(program) || petSummonNano(program)) && player.templateUseRequirementsMet(gamedata.NanoTemplates[program])
+func (player *character) nanoRequirementsMet(program uint32, target *character) bool {
+ if directDamageNano(program) == nil && directHealingNano(program) == nil && healingOverTimeNano(program) == nil &&
+ damageOverTimeNano(program) == nil && controlNano(program) == nil && !statBuffNano(program) && !petSummonNano(program) {
+ return false
+ }
+ for _, section := range gamedata.NanoTemplates[program].Sections {
+ if section.Actions == nil {
+ continue
+ }
+ for _, action := range *section.Actions {
+ if action.Type != 3 {
+ continue
+ }
+ subject := player
+ if !requirementsMet(action.Requirements, func(requirement gamedata.ItemRequirement) (bool, bool) {
+ if requirement.Operator == 18 {
+ if requirement.Stat != 0 || requirement.Value != 0 {
+ return false, false
+ }
+ subject = target
+ return subject != nil, true
+ }
+ if requirement.Stat == 1 && requirement.Operator == 2 {
+ return int32(subject.maximumHealth()) > requirement.Value, true
+ }
+ return subject.meetsStatRequirement(requirement)
+ }) {
+ return false
+ }
+ }
+ }
+ return true
}
func (server *server) nanoTarget_locked(player, target *character, client *worldClient, program uint32, now time.Time) bool {
@@ -157,7 +187,7 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error {
target = player
}
accepted := targetType == 50000 && binary.BigEndian.Uint32(body[28:32]) == 53019 &&
- slices.Contains(player.inventory.LearnedNanos, program) && player.nanoRequirementsMet(program) &&
+ slices.Contains(player.inventory.LearnedNanos, program) && player.nanoRequirementsMet(program, target) &&
!player.sitting && !player.driving() && player.movement.forward == 0 && player.movement.strafe == 0 && player.movement.turn == 0 && client.equipment == nil &&
player.movement.velocity == [3]float32{} &&
server.nanoTarget_locked(player, target, client, program, now)
@@ -285,9 +315,15 @@ func (server *server) advanceNanos(now time.Time) {
var damage uint32
hit := directDamageNano(program)
heal := directHealingNano(program)
+ var casterHealing *gamedata.ItemFunction
effectProgram := program
removedHealthBonus := false
if hit != nil {
+ casterHealing = damageNanoCasterHealing(program)
+ if casterHealing != nil {
+ minimum, maximum := uint32(*casterHealing.Arguments[1].Integer), uint32(*casterHealing.Arguments[2].Integer)
+ caster.health = min(caster.maximumHealth(), caster.health+minimum+rand.Uint32N(maximum-minimum+1))
+ }
minimum, maximum := uint32(-*hit.Arguments[1].Integer), uint32(-*hit.Arguments[2].Integer)
damage = min(minimum+rand.Uint32N(maximum-minimum+1), target.health)
victim = prepareDamage(player, target, damage, now)
@@ -352,9 +388,15 @@ func (server *server) advanceNanos(now time.Time) {
continue
}
previous := *target
+ previousCasterHealth := player.health
*player, *target = caster, victim
client.nanoCast = nil
server.queueCombat_locked(updates, player, target, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program}))
+ if casterHealing != nil {
+ server.queueHealthSnapshot_locked(updates, player)
+ server.queueTeamResources_locked(updates, player)
+ updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{130, 50000, player.id, 0, player.health - previousCasterHealth}))
+ }
if effectProgram != 0 && target.health != 0 {
server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{177, 53019, effectProgram, player.id, nanoStat(effectProgram, 8)}))
}
diff --git a/server/nano_damage.go b/server/nano_damage.go
@@ -90,7 +90,45 @@ func hostileHitNano(program uint32, periodic bool) *gamedata.ItemFunction {
requirements.Type != 22 || requirements.Subtype != 36 || requirements.Actions == nil || len(*requirements.Actions) != 1 || (*requirements.Actions)[0].Type != 3 {
return nil
}
- hit := &(*effects.Functions)[0]
+ functions := *effects.Functions
+ hitIndex := 0
+ if !periodic && itemStat(definition, 0) == 0x8000 && itemStat(definition, 405) == 2 && len(functions) == 2 &&
+ functions[0].ID == 53002 && functions[0].Target == 1 {
+ // Health drains pair an unconditional caster heal with a selected-target hit.
+ heal := functions[0]
+ if heal.HeaderWords != [2]uint32{0, 4} || heal.ArgumentHeader != 9 || len(heal.Requirements) != 0 ||
+ heal.TickCount != 1 || heal.TickInterval != 0 || len(heal.Arguments) != 4 ||
+ itemStat(definition, 8) != 0 || itemStat(definition, 75) != 0 {
+ return nil
+ }
+ for _, argument := range heal.Arguments {
+ if argument.Integer == nil {
+ return nil
+ }
+ }
+ if *heal.Arguments[0].Integer != 27 || *heal.Arguments[1].Integer <= 0 ||
+ *heal.Arguments[2].Integer < *heal.Arguments[1].Integer || *heal.Arguments[3].Integer != 0 {
+ return nil
+ }
+ for _, requirement := range (*requirements.Actions)[0].Requirements {
+ switch requirement.Operator {
+ case 3, 4, 42:
+ case 18:
+ if requirement.Stat != 0 || requirement.Value != 0 {
+ return nil
+ }
+ default:
+ if requirement.Stat == 1 && requirement.Operator == 2 {
+ continue
+ }
+ if _, known := (&character{}).meetsStatRequirement(requirement); !known {
+ return nil
+ }
+ }
+ }
+ hitIndex = 1
+ }
+ hit := &functions[hitIndex]
if hit.ID != 53002 || hit.HeaderWords != [2]uint32{0, 4} || hit.ArgumentHeader != 9 || hit.Target != 3 ||
len(hit.Requirements) != 0 || len(hit.Arguments) != 4 {
return nil
@@ -114,7 +152,7 @@ func hostileHitNano(program uint32, periodic bool) *gamedata.ItemFunction {
return nil
}
taunt := false
- if len(*effects.Functions) == 2 {
+ if len(*effects.Functions) == 2 && hitIndex == 0 {
secondary := (*effects.Functions)[1]
if secondary.HeaderWords != [2]uint32{0, 4} || secondary.ArgumentHeader != 9 || secondary.Target != 3 ||
len(secondary.Requirements) != 0 || secondary.TickCount != 1 || secondary.TickInterval != 0 {
@@ -140,12 +178,21 @@ func hostileHitNano(program uint32, periodic bool) *gamedata.ItemFunction {
(itemStat(definition, 405) != 1 && itemStat(definition, 405) != 4) {
return nil
}
- } else if itemStat(definition, 30) != 0 || defense[0][1] == 0 || !periodic && itemStat(definition, 0) != 0x80008000 {
+ } else if itemStat(definition, 30) != 0 || defense[0][1] == 0 || !periodic && hitIndex == 0 && itemStat(definition, 0) != 0x80008000 {
return nil
}
return hit
}
+func damageNanoCasterHealing(program uint32) *gamedata.ItemFunction {
+ // Called only after admitting the complete direct-damage contract.
+ functions := *gamedata.NanoTemplates[program].Sections[2].Functions
+ if len(functions) == 2 && functions[0].ID == 53002 && functions[0].Target == 1 {
+ return &functions[0]
+ }
+ return nil
+}
+
func damageNanoSecondary(program uint32) uint32 {
// Called only after admission of the complete direct-damage contract.
functions := *gamedata.NanoTemplates[program].Sections[2].Functions
diff --git a/server/nano_damage_test.go b/server/nano_damage_test.go
@@ -72,12 +72,12 @@ func TestDirectDamageNanoCatalogMatchesCompleteOriginalContracts(t *testing.T) {
}
for program := range gamedata.NanoTemplates {
- if directDamageNano(program) != nil && damageNanoSecondary(program) == 0 && nanoTaunt(program) == 0 {
+ if directDamageNano(program) != nil && damageNanoCasterHealing(program) == nil && damageNanoSecondary(program) == 0 && nanoTaunt(program) == 0 {
programs = append(programs, program)
}
}
for crystal := range gamedata.ItemTemplates {
- if program := nanoCrystalProgram(crystal); directDamageNano(program) != nil && damageNanoSecondary(program) == 0 && nanoTaunt(program) == 0 {
+ if program := nanoCrystalProgram(crystal); directDamageNano(program) != nil && damageNanoCasterHealing(program) == nil && damageNanoSecondary(program) == 0 && nanoTaunt(program) == 0 {
crystals = append(crystals, crystal)
}
}
diff --git a/server/nano_health_drain_test.go b/server/nano_health_drain_test.go
@@ -0,0 +1,371 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ _ "embed"
+ "encoding/binary"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "testing"
+ "time"
+)
+
+//go:embed testdata/health-drain-nanos.json
+var healthDrainNanoData []byte
+
+type healthDrainFixture struct {
+ Program, Crystal, Quality, Damage, Healing uint32
+ Cost, Debit, Attack, Recharge, Range uint32
+ TargetMaximum uint32
+}
+
+func healthDrainFixtures(t *testing.T) []healthDrainFixture {
+ t.Helper()
+ var fixtures []healthDrainFixture
+ if err := json.Unmarshal(healthDrainNanoData, &fixtures); err != nil {
+ t.Fatal(err)
+ }
+ return fixtures
+}
+
+func TestHealthDrainCatalogMatchesCompleteOriginalContracts(t *testing.T) {
+ fixtures := healthDrainFixtures(t)
+ var expectedPrograms, expectedCrystals, programs, crystals []uint32
+ for _, fixture := range fixtures {
+ expectedPrograms = append(expectedPrograms, fixture.Program)
+ expectedCrystals = append(expectedCrystals, fixture.Crystal)
+ }
+
+ for program := range gamedata.NanoTemplates {
+ if directDamageNano(program) != nil && damageNanoCasterHealing(program) != nil {
+ programs = append(programs, program)
+ }
+ }
+ for crystal := range gamedata.ItemTemplates {
+ if program := nanoCrystalProgram(crystal); directDamageNano(program) != nil && damageNanoCasterHealing(program) != nil {
+ crystals = append(crystals, crystal)
+ }
+ }
+ for _, values := range [][]uint32{expectedPrograms, expectedCrystals, programs, crystals} {
+ slices.Sort(values)
+ }
+
+ if len(fixtures) != 30 || !slices.Equal(expectedPrograms, programs) || !slices.Equal(expectedCrystals, crystals) {
+ t.Fatal("health-drain admission differs from the complete original census", programs, crystals)
+ }
+ for _, fixture := range fixtures {
+ hit, heal := directDamageNano(fixture.Program), damageNanoCasterHealing(fixture.Program)
+ if uint32(-*hit.Arguments[1].Integer) != fixture.Damage || uint32(-*hit.Arguments[2].Integer) != fixture.Damage ||
+ uint32(*hit.Arguments[3].Integer) != 92 || uint32(*heal.Arguments[1].Integer) != fixture.Healing ||
+ uint32(*heal.Arguments[2].Integer) != fixture.Healing || nanoStat(fixture.Program, 407) != fixture.Cost ||
+ nanoStat(fixture.Program, 294) != fixture.Attack || nanoStat(fixture.Program, 210) != fixture.Recharge ||
+ nanoStat(fixture.Program, 287) != fixture.Range {
+ t.Fatal("authored health-drain effects or metadata changed", fixture.Program)
+ }
+ }
+}
+
+func TestHealthDrainCrystalsLearnCastAndRetainBothOutcomes(t *testing.T) {
+ for _, fixture := range healthDrainFixtures(t) {
+ t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
+ world, _ := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: fixture.Crystal, Profession: 7})
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.health = 1
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ original := gamedata.NPCCombatProfiles[17655][1]
+ profile := *original
+ profile.Health = 1000
+ gamedata.NPCCombatProfiles[17655][1] = &profile
+ t.Cleanup(func() { gamedata.NPCCombatProfiles[17655][1] = original })
+ target.health, target.combatProfile = 1000, &profile
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ if player.inventory.Items[0].Quality != fixture.Quality {
+ t.Fatal("original crystal quality changed")
+ }
+
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(player.inventory.LearnedNanos, []uint32{fixture.Program}) || len(player.inventory.Items) != 0 {
+ t.Fatal("complete drain crystal did not upload")
+ }
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, fixture.Program})[20:]); err != nil || client.nanoCast == nil {
+ t.Fatal("complete drain did not start", err)
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ world.advanceNanos(at)
+ world.advanceNanos(at.Add(time.Nanosecond))
+ cold := newTestInventoryServer(t)
+
+ if player.health != 1+fixture.Healing || target.health != 1000-fixture.Damage || player.nano != 50000-fixture.Debit ||
+ player.nanoReserved != 0 || client.nanoCast != nil || !slices.Equal(player.inventory.LearnedNanos, []uint32{fixture.Program}) ||
+ cold.characters[1].health != player.health || cold.characters[1].nano != player.nano ||
+ cold.characters[1000000].health != target.health || !cold.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) ||
+ player.savedVitals.Health != player.health || len(player.inventory.Items) != 0 ||
+ player.fighting != 0 || target.fighting != 1 || len(target.activeNanos) != 0 {
+ t.Fatal("health drain lost a complete effect, cost, recharge or learned state", fixture.Program, player.health, player.nano, target.health)
+ }
+ })
+ }
+}
+
+func TestHealthDrainStartupUploadsAndCastsBothHits(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.profession, player.level, player.health, player.nano = 7, 2, 1, 30
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7
+ player.inventory.LearnedNanos = nil
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 78417); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(player.inventory.LearnedNanos, []uint32{76742}) || len(player.inventory.Items) != 0 {
+ t.Fatal("eligible Trader startup crystal did not upload its complete health-drain program")
+ }
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]); err != nil || client.nanoCast == nil {
+ t.Fatal("learned health drain did not start", err)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ cold := newTestInventoryServer(t)
+
+ if player.health != 5 || player.nano != 15 || player.nanoReserved != 0 || target.health != 90 || client.nanoCast != nil ||
+ cold.characters[1].health != 5 || cold.characters[1].nano != 15 || cold.characters[1000000].health != 90 ||
+ !cold.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) || !slices.Equal(cold.characters[1].inventory.LearnedNanos, []uint32{76742}) {
+ t.Fatal("health drain did not atomically retain healing, damage, cost, recharge and learning", player.health, player.nano, target.health)
+ }
+}
+
+func TestHealthDrainClampsBothHitsAndKeepsTargetRequirementsScoped(t *testing.T) {
+ for _, scenario := range []string{"target equality", "target passes", "lethal", "full caster", "partial healing", "missing target"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.profession, player.health, player.nano = 7, 1, 30
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7
+ player.inventory.LearnedNanos = []uint32{76742}
+ profile := *gamedata.NPCCombatProfiles[17655][1]
+ target.combatProfile = &profile
+ if scenario == "target equality" {
+ profile.Health, target.health = 9, 9
+ } else if scenario == "target passes" {
+ profile.Health, target.health = 10, 10
+ } else if scenario == "lethal" {
+ target.health = 1
+ } else if scenario == "full caster" {
+ player.health = player.maximumHealth()
+ } else if scenario == "partial healing" {
+ player.health = player.maximumHealth() - 2
+ }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]
+ if scenario == "missing target" {
+ binary.BigEndian.PutUint32(request[24:28], 999999)
+ }
+ before := player.health
+
+ err := world.handleNanoCast(client, request)
+ started := client.nanoCast != nil
+ if started {
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ }
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "target equality" || scenario == "missing target" {
+ if started || player.health != before || player.nano != 30 || player.nanoReserved != 0 {
+ t.Fatal("invalid target bypassed the scoped requirement or charged the caster")
+ }
+ return
+ }
+ if !started || player.health != min(player.maximumHealth(), before+4) || player.nano != 15 ||
+ (scenario == "lethal" || scenario == "target passes") && target.health != 0 {
+ t.Fatal("drain did not clamp its independent authored hits", player.health, target.health)
+ }
+ })
+ }
+}
+
+func TestHealthDrainFailedOutcomeRollsBackBothRecipients(t *testing.T) {
+ for _, phase := range []string{"healing", "ignored healing", "NPC", "ignored NPC", "commit"} {
+ t.Run(phase, func(t *testing.T) {
+ world, output := newNanoCastingWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.profession, player.health, player.nano = 7, 1, 30
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7
+ player.inventory.LearnedNanos = []uint32{76742}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushWorld(); err != nil {
+ t.Fatal(err)
+ }
+ request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("drain admission failed", err)
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ statement := "CREATE TRIGGER fail_drain BEFORE UPDATE OF health ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'healing'); END"
+ switch phase {
+ case "ignored healing":
+ statement = "CREATE TRIGGER fail_drain BEFORE UPDATE OF health ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END"
+ case "NPC":
+ statement = "CREATE TRIGGER fail_drain BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'NPC'); END"
+ case "ignored NPC":
+ statement = "CREATE TRIGGER fail_drain BEFORE UPDATE ON npcs BEGIN SELECT RAISE(IGNORE); END"
+ case "commit":
+ statement = "CREATE TABLE pending_drain (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_drain AFTER UPDATE OF health ON characters WHEN NEW.id=1 BEGIN INSERT INTO pending_drain VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ world.advanceNanos(at)
+ cold := newTestInventoryServer(t)
+
+ if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || target.health != 100 || client.nanoCast != nil ||
+ !player.nanoRechargeUntil.IsZero() || cold.characters[1].health != 1 || cold.characters[1].nano != 30 || cold.characters[1000000].health != 100 {
+ t.Fatal("failed drain published or retained a partial heal, damage, cost or recharge")
+ }
+ for _, packet := range output.packets {
+ if bytes.Equal(packet[16:20], []byte{0x47, 0x27, 0x21, 0x3e}) ||
+ binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 107 {
+ t.Fatal("failed drain sent a result before its complete transaction")
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_drain"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("drain could not retry", err)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ cold = newTestInventoryServer(t)
+ if player.health != 5 || player.nano != 15 || target.health != 90 || cold.characters[1].health != 5 || cold.characters[1000000].health != 90 {
+ t.Fatal("drain retry did not commit exactly one full paired outcome")
+ }
+ })
+ }
+}
+
+func TestHealthDrainRejectsPartialOrUnverifiedPairs(t *testing.T) {
+ for _, scenario := range []string{"missing heal", "missing damage", "extra effect", "reversed effects", "other heal resource", "other heal target", "conditional heal", "periodic heal", "periodic damage", "opaque healing", "reversed healing", "positive damage", "unknown target criterion"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 78417, Profession: 7})
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.health = 1
+ original := gamedata.NanoTemplates[76742]
+ definition := *original
+ definition.Sections = slices.Clone(original.Sections)
+ functions := slices.Clone(*definition.Sections[2].Functions)
+ functions[0].Arguments = slices.Clone(functions[0].Arguments)
+ functions[1].Arguments = slices.Clone(functions[1].Arguments)
+ switch scenario {
+ case "missing heal":
+ functions = functions[1:]
+ case "missing damage":
+ functions = functions[:1]
+ case "extra effect":
+ functions = append(functions, gamedata.ItemFunction{ID: 53051})
+ case "reversed effects":
+ functions[0], functions[1] = functions[1], functions[0]
+ case "other heal resource":
+ value := int32(214)
+ functions[0].Arguments[0].Integer = &value
+ case "other heal target":
+ functions[0].Target = 2
+ case "conditional heal":
+ functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 20, Operator: 2}}
+ case "periodic heal":
+ functions[0].TickCount = 2
+ case "periodic damage":
+ functions[1].TickCount = 2
+ case "opaque healing":
+ functions[0].Arguments[1].Integer = nil
+ case "reversed healing":
+ value := int32(3)
+ functions[0].Arguments[2].Integer = &value
+ case "positive damage":
+ value := int32(10)
+ functions[1].Arguments[1].Integer = &value
+ case "unknown target criterion":
+ actions := slices.Clone(*definition.Sections[3].Actions)
+ actions[0].Requirements = slices.Clone(actions[0].Requirements)
+ actions[0].Requirements[len(actions[0].Requirements)-2].Stat = 455
+ definition.Sections[3].Actions = &actions
+ }
+ definition.Sections[2].Functions = &functions
+ gamedata.NanoTemplates[76742] = &definition
+ t.Cleanup(func() { gamedata.NanoTemplates[76742] = original })
+
+ err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:])
+ if len(player.inventory.LearnedNanos) != 0 {
+ t.Fatal("partial health-drain contract uploaded")
+ }
+ player.inventory.LearnedNanos = []uint32{76742}
+ if err == nil {
+ err = world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:])
+ }
+
+ if err != nil || client.nanoCast != nil || player.health != 1 || player.nano != 50000 || target.health != 100 ||
+ len(player.inventory.Items) != 1 || len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 ||
+ binary.BigEndian.Uint32(output.packets[1][29:33]) != 108 {
+ t.Fatal("unsupported pair consumed a crystal, healed or damaged a recipient, or reserved a cost", err)
+ }
+ })
+ }
+}
+
+func TestHealthDrainCancelledOrUnavailableTargetAppliesNeitherHit(t *testing.T) {
+ for _, scenario := range []string{"cancel", "range", "target death"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ player.profession, player.health, player.nano = 7, 1, 30
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7
+ player.inventory.LearnedNanos = []uint32{76742}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]); err != nil || client.nanoCast == nil {
+ t.Fatal("drain admission failed", err)
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ if scenario == "range" {
+ target.position[0] += 100
+ } else if scenario == "target death" {
+ target.health = 0
+ }
+ before := target.health
+
+ if scenario == "cancel" {
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{108})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ world.advanceNanos(at)
+ world.advanceNanos(at.Add(time.Second))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || client.nanoCast != nil || target.health != before ||
+ !player.nanoRechargeUntil.IsZero() || cold.health != 1 || cold.nano != 30 {
+ t.Fatal("cancelled drain applied one hit or retained a cost/recharge")
+ }
+ })
+ }
+}
diff --git a/server/npc_outcome.go b/server/npc_outcome.go
@@ -218,6 +218,12 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time
if changed != 1 {
return nil, fmt.Errorf("caster %d nano update affected %d rows", player.id, changed)
}
+ casterHealthChanged := player.id != target.id && player.health != server.characters[player.id].health
+ if casterHealthChanged {
+ if err := updateRecord(tx, "characters", player.id, "health", []any{player.health}); err != nil {
+ return nil, err
+ }
+ }
var state npcState
healthChanged := !target.npc && target.health != server.characters[target.id].health
if target.npc {
@@ -241,6 +247,9 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time
player.savedVitals.Nano, player.savedVitals.NanoRechargeUntil = player.nano, player.nanoRechargeUntil
player.savedVitals.NanoReserved = player.nanoReserved
+ if casterHealthChanged {
+ player.savedVitals.Health = player.health
+ }
if target.npc {
server.rememberNPCOutcome_locked(target, state, now)
} else if target.id == player.id {
diff --git a/server/signed_stats_test.go b/server/signed_stats_test.go
@@ -95,7 +95,7 @@ func TestSignedNegativeAbilitiesDoNotPassEquipmentRequirements(t *testing.T) {
t.Fatalf("positive requirement control rejected template %d", item.Template)
}
}
- if player.nanoRequirementsMet(29618) || player.nanoRequirementsMet(27169) {
+ if player.nanoRequirementsMet(29618, player) || player.nanoRequirementsMet(27169, player) {
t.Fatal("negative effective skills admitted a nano")
}
}
diff --git a/server/testdata/health-drain-nanos.json b/server/testdata/health-drain-nanos.json
@@ -0,0 +1,392 @@
+[
+ {
+ "Program": 76475,
+ "Crystal": 78443,
+ "Quality": 169,
+ "Damage": 541,
+ "Healing": 528,
+ "Cost": 300,
+ "Debit": 299,
+ "Attack": 348,
+ "Recharge": 448,
+ "Range": 20,
+ "TargetMaximum": 540
+ },
+ {
+ "Program": 76478,
+ "Crystal": 78451,
+ "Quality": 175,
+ "Damage": 560,
+ "Healing": 553,
+ "Cost": 300,
+ "Debit": 299,
+ "Attack": 349,
+ "Recharge": 449,
+ "Range": 20,
+ "TargetMaximum": 559
+ },
+ {
+ "Program": 76481,
+ "Crystal": 78442,
+ "Quality": 159,
+ "Damage": 500,
+ "Healing": 479,
+ "Cost": 297,
+ "Debit": 296,
+ "Attack": 345,
+ "Recharge": 445,
+ "Range": 20,
+ "TargetMaximum": 499
+ },
+ {
+ "Program": 76484,
+ "Crystal": 78441,
+ "Quality": 156,
+ "Damage": 483,
+ "Healing": 449,
+ "Cost": 298,
+ "Debit": 297,
+ "Attack": 342,
+ "Recharge": 442,
+ "Range": 20,
+ "TargetMaximum": 482
+ },
+ {
+ "Program": 76487,
+ "Crystal": 78440,
+ "Quality": 162,
+ "Damage": 520,
+ "Healing": 504,
+ "Cost": 298,
+ "Debit": 297,
+ "Attack": 346,
+ "Recharge": 446,
+ "Range": 20,
+ "TargetMaximum": 519
+ },
+ {
+ "Program": 76491,
+ "Crystal": 78439,
+ "Quality": 149,
+ "Damage": 467,
+ "Healing": 423,
+ "Cost": 298,
+ "Debit": 297,
+ "Attack": 339,
+ "Recharge": 439,
+ "Range": 20,
+ "TargetMaximum": 466
+ },
+ {
+ "Program": 76494,
+ "Crystal": 78438,
+ "Quality": 146,
+ "Damage": 449,
+ "Healing": 396,
+ "Cost": 297,
+ "Debit": 296,
+ "Attack": 336,
+ "Recharge": 436,
+ "Range": 20,
+ "TargetMaximum": 448
+ },
+ {
+ "Program": 76499,
+ "Crystal": 78436,
+ "Quality": 142,
+ "Damage": 430,
+ "Healing": 369,
+ "Cost": 295,
+ "Debit": 294,
+ "Attack": 333,
+ "Recharge": 433,
+ "Range": 20,
+ "TargetMaximum": 429
+ },
+ {
+ "Program": 76503,
+ "Crystal": 78437,
+ "Quality": 123,
+ "Damage": 382,
+ "Healing": 310,
+ "Cost": 283,
+ "Debit": 282,
+ "Attack": 325,
+ "Recharge": 425,
+ "Range": 20,
+ "TargetMaximum": 381
+ },
+ {
+ "Program": 76571,
+ "Crystal": 78435,
+ "Quality": 132,
+ "Damage": 409,
+ "Healing": 341,
+ "Cost": 292,
+ "Debit": 291,
+ "Attack": 329,
+ "Recharge": 429,
+ "Range": 20,
+ "TargetMaximum": 408
+ },
+ {
+ "Program": 76614,
+ "Crystal": 78434,
+ "Quality": 103,
+ "Damage": 328,
+ "Healing": 250,
+ "Cost": 265,
+ "Debit": 264,
+ "Attack": 319,
+ "Recharge": 419,
+ "Range": 20,
+ "TargetMaximum": 327
+ },
+ {
+ "Program": 76651,
+ "Crystal": 78433,
+ "Quality": 113,
+ "Damage": 355,
+ "Healing": 279,
+ "Cost": 274,
+ "Debit": 273,
+ "Attack": 321,
+ "Recharge": 421,
+ "Range": 20,
+ "TargetMaximum": 354
+ },
+ {
+ "Program": 76653,
+ "Crystal": 78432,
+ "Quality": 86,
+ "Damage": 272,
+ "Healing": 195,
+ "Cost": 241,
+ "Debit": 240,
+ "Attack": 316,
+ "Recharge": 416,
+ "Range": 20,
+ "TargetMaximum": 271
+ },
+ {
+ "Program": 76656,
+ "Crystal": 78431,
+ "Quality": 93,
+ "Damage": 300,
+ "Healing": 222,
+ "Cost": 253,
+ "Debit": 252,
+ "Attack": 318,
+ "Recharge": 418,
+ "Range": 20,
+ "TargetMaximum": 299
+ },
+ {
+ "Program": 76679,
+ "Crystal": 78430,
+ "Quality": 80,
+ "Damage": 247,
+ "Healing": 172,
+ "Cost": 228,
+ "Debit": 227,
+ "Attack": 315,
+ "Recharge": 415,
+ "Range": 20,
+ "TargetMaximum": 246
+ },
+ {
+ "Program": 76681,
+ "Crystal": 78428,
+ "Quality": 70,
+ "Damage": 222,
+ "Healing": 150,
+ "Cost": 214,
+ "Debit": 213,
+ "Attack": 314,
+ "Recharge": 414,
+ "Range": 20,
+ "TargetMaximum": 221
+ },
+ {
+ "Program": 76684,
+ "Crystal": 78429,
+ "Quality": 60,
+ "Damage": 198,
+ "Healing": 128,
+ "Cost": 200,
+ "Debit": 199,
+ "Attack": 312,
+ "Recharge": 412,
+ "Range": 20,
+ "TargetMaximum": 197
+ },
+ {
+ "Program": 76686,
+ "Crystal": 78426,
+ "Quality": 50,
+ "Damage": 177,
+ "Healing": 110,
+ "Cost": 187,
+ "Debit": 186,
+ "Attack": 310,
+ "Recharge": 410,
+ "Range": 20,
+ "TargetMaximum": 176
+ },
+ {
+ "Program": 76688,
+ "Crystal": 78427,
+ "Quality": 40,
+ "Damage": 136,
+ "Healing": 74,
+ "Cost": 157,
+ "Debit": 156,
+ "Attack": 305,
+ "Recharge": 405,
+ "Range": 20,
+ "TargetMaximum": 135
+ },
+ {
+ "Program": 76691,
+ "Crystal": 78425,
+ "Quality": 47,
+ "Damage": 156,
+ "Healing": 91,
+ "Cost": 172,
+ "Debit": 171,
+ "Attack": 308,
+ "Recharge": 408,
+ "Range": 20,
+ "TargetMaximum": 155
+ },
+ {
+ "Program": 76715,
+ "Crystal": 78424,
+ "Quality": 30,
+ "Damage": 103,
+ "Healing": 53,
+ "Cost": 129,
+ "Debit": 128,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 102
+ },
+ {
+ "Program": 76717,
+ "Crystal": 78423,
+ "Quality": 33,
+ "Damage": 119,
+ "Healing": 63,
+ "Cost": 143,
+ "Debit": 142,
+ "Attack": 302,
+ "Recharge": 402,
+ "Range": 20,
+ "TargetMaximum": 118
+ },
+ {
+ "Program": 76720,
+ "Crystal": 78422,
+ "Quality": 24,
+ "Damage": 87,
+ "Healing": 42,
+ "Cost": 114,
+ "Debit": 113,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 86
+ },
+ {
+ "Program": 76722,
+ "Crystal": 78421,
+ "Quality": 20,
+ "Damage": 70,
+ "Healing": 32,
+ "Cost": 96,
+ "Debit": 95,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 69
+ },
+ {
+ "Program": 76724,
+ "Crystal": 78420,
+ "Quality": 17,
+ "Damage": 57,
+ "Healing": 25,
+ "Cost": 81,
+ "Debit": 80,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 56
+ },
+ {
+ "Program": 76727,
+ "Crystal": 78418,
+ "Quality": 10,
+ "Damage": 43,
+ "Healing": 18,
+ "Cost": 64,
+ "Debit": 63,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 42
+ },
+ {
+ "Program": 76729,
+ "Crystal": 78419,
+ "Quality": 7,
+ "Damage": 30,
+ "Healing": 12,
+ "Cost": 46,
+ "Debit": 45,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 29
+ },
+ {
+ "Program": 76732,
+ "Crystal": 78416,
+ "Quality": 4,
+ "Damage": 17,
+ "Healing": 7,
+ "Cost": 27,
+ "Debit": 26,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 16
+ },
+ {
+ "Program": 76742,
+ "Crystal": 78417,
+ "Quality": 1,
+ "Damage": 10,
+ "Healing": 4,
+ "Cost": 16,
+ "Debit": 15,
+ "Attack": 300,
+ "Recharge": 400,
+ "Range": 20,
+ "TargetMaximum": 9
+ },
+ {
+ "Program": 77195,
+ "Crystal": 78415,
+ "Quality": 182,
+ "Damage": 580,
+ "Healing": 577,
+ "Cost": 296,
+ "Debit": 295,
+ "Attack": 353,
+ "Recharge": 453,
+ "Range": 20,
+ "TargetMaximum": 579
+ }
+]
diff --git a/tools/client/test_health_drain.mjs b/tools/client/test_health_drain.mjs
@@ -0,0 +1,94 @@
+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 = {};
+try {
+ // Load the caster last to keep independent native recovery outside this check.
+ for (const index of [1, 0]) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'health-drain-' + index, url}]);
+ const page = await context.newPage();
+ games[index] = await GameTest.attach(page);
+ await page.goto(url);
+ await games[index].ready();
+ }
+ const [owner, observer] = games;
+ const server = async () => (await owner.page.request.get(url + '/test-state')).json();
+ const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+ evidence.before = await server();
+ const {owner: id, enemy} = evidence.before;
+ await Promise.all(games.map(game => game.wait('caster and exact Leet visible', () => actor(game, id) && actor(game, enemy))));
+ await owner.key('KeyI');
+ const crystal = owner.state.grids.flatMap(grid => grid.cells).find(cell => cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy);
+ assert(crystal, 'issued Trader crystal is visible');
+ await owner.click((crystal.bounds[0] + crystal.bounds[2]) / 2, (crystal.bounds[1] + crystal.bounds[3]) / 2, 'right');
+ await owner.wait('startup crystal uploaded once', state => owner.local(state).inventory.length === 0);
+ evidence.learned = await server();
+ assert.deepEqual(evidence.learned.inventory.LearnedNanos, [76742]);
+ await owner.page.keyboard.press('Control+8');
+ await owner.click(974, 76);
+ await owner.wait('native health-drain program icon', state => state.grids.some(grid => grid.cells.some(cell =>
+ cell.identity[0] === 53019 && cell.identity[1] === 76742 && !cell.dummy)));
+ await owner.click(...await owner.pick(50000, enemy));
+ await owner.wait('exact hostile recipient selected', state => state.selected[0] === 50000 && state.selected[1] === enemy);
+ const program = owner.state.grids.flatMap(grid => grid.cells).find(cell => cell.identity[0] === 53019 && cell.identity[1] === 76742 && !cell.dummy);
+ const sequence = owner.sequence;
+ await owner.click((program.bounds[0] + program.bounds[2]) / 2, (program.bounds[1] + program.bounds[3]) / 2, 'right');
+ await owner.wait('actual native health-drain cast', () => owner.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '5e477770' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 19 && Buffer.from(event.hex, 'hex').readUInt32BE(45) === 76742));
+ await Promise.all(games.map(game => game.wait('both authored effects agree on both native clients', () =>
+ actor(game, id).stats[27] === 24 && actor(game, enemy).stats[27] === 90)));
+ await owner.wait('native nano cost retained', state => owner.local(state).stats[214] === 15);
+ evidence.after = await server();
+ assert.equal(evidence.after.health, 24);
+ assert.equal(evidence.after.targetHealth, 90);
+ assert.equal(evidence.after.nano, 15);
+ assert.equal(evidence.after.reserved, 0);
+ assert.equal(evidence.after.peerHealth, 20);
+ assert.equal(evidence.after.peerNano, 30);
+ await Promise.all(games.map((game, index) => game.save(output + '/effects-' + index)));
+
+ // Both page replays must preserve the same complete paired outcome.
+ evidence.replayClients = [];
+ for (const game of [observer, owner]) {
+ await game.page.reload();
+ await game.ready();
+ await game.wait('retained caster and replayed target', () => actor(game, id)?.stats[27] === 24 && actor(game, enemy) &&
+ game.events.some(event => event.navigation === game.navigation && event.direction === 'framereceived' &&
+ event.opcode === '271b3a6b' && event.actor?.[1] === enemy));
+ const replay = game.events.find(event => event.navigation === game.navigation && event.direction === 'framereceived' &&
+ event.opcode === '271b3a6b' && event.actor?.[1] === enemy);
+ const packet = Buffer.from(replay.hex, 'hex');
+ // SimpleChar's NPC name is followed by its auxiliary words, level and HP pair.
+ const flags = packet.readUInt32BE(30);
+ assert((flags & 1) !== 0 && (flags & 0x1000) === 0);
+ const health = 65 + packet[64] + 12 + 1;
+ assert.equal(packet.readUInt32BE(health), 100);
+ assert.equal(packet.readUInt32BE(health + 4), 90);
+ const predicted = actor(game, enemy).stats[27];
+ assert(predicted >= 90 && predicted <= 100);
+ evidence.replayClients.push({owner: actor(game, id).stats[27], targetWire: 90,
+ targetPredicted: predicted, targetCounter: actor(game, enemy).stats[58]});
+ }
+ evidence.replayed = await server();
+ assert.deepEqual(evidence.replayed, evidence.after);
+ const requests = owner.events.filter(event => event.direction === 'framesent' && event.opcode === '5e477770' &&
+ Buffer.from(event.hex, 'hex').readUInt32BE(29) === 19);
+ assert.equal(requests.length, 1);
+ assert(games.every(game => game.errors.length === 0 && game.dropped === 0));
+ console.log('PASS: Trader startup upload, both health-drain effects, exact cost and peer isolation agree across two clients and page/cold recovery');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ await Promise.all(games.map((game, index) => game.save(output + '/final-' + index)));
+ } finally { await browser.close(); }
+}