commit fbff0f312053714b2ec21c3764bec4e63cca3670
parent 3991f4dc08abd2690771974dc90f5998ff3aaac3
Author: anon <anon@example.com>
Date: Mon, 2 Nov 2026 20:31:25 +0000
Enable complete ordinary direct-healing nano contracts
Diffstat:
12 files changed, 1773 insertions(+), 32 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1823,18 +1823,22 @@ introduction and starting-item gameplay remain open below.
- [x] Learn one nano program. Check: consuming its crystal adds a persistent
native program entry and cannot learn or consume it twice accidentally.
The Doctor startup crystal now uploads Improved Healing with its exact
- skill/profession gates; healing execution remains separate and unfinished.
+ skill/profession gates; learned execution uses the shared direct-heal path below.
See [Doctor healing](docs/nano-healing.md).
-- [ ] [P1] Cast one self-heal. Check: cast time, nano cost, health gain and recharge
+- [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.
- The common-message scheduling lead is now ruled out: AttackInfo and
- HealthDamage activate immediately, without an impact clock or weapon fence.
- Expanded holder/producer audits find no neutral state-6 drain or ordinary
- impact receipt; player and NPC result/animation clocks differ. See
- [combat healing delivery](docs/combat-healing-delivery.md).
- Resolve combat health delivery rather than limiting healing to idle use.
-- [ ] [P1] Cancel an in-progress cast. Check: the applicable cancellation/refund rule
+ Complete contracts admit 85 ordinary programs/crystals, with authored gates,
+ HP endpoints, timing/range and atomic cost/health/recharge. A focused two-client
+ WASM check casts Improved Healing during a real queued Leet hit; both clients
+ retain healed HP after impact through the maintained First Aid reconciliation.
+ No idle-only restriction or synthetic weapon result is used. See
+ [direct healing](docs/nano-healing.md#direct-heal-verification).
+- [x] [P1] Cancel an in-progress cast. Check: the applicable cancellation/refund rule
is followed and no delayed heal or duplicate result occurs.
+ Native movement cancels Improved Healing and refunds its reservation once;
+ 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
diff --git a/docs/nano-healing.md b/docs/nano-healing.md
@@ -1,4 +1,11 @@
-# Doctor startup healing research
+# Doctor startup and direct healing
+
+Ordinary immediate HP heals now use the shared timed casting path. The complete
+reviewed group contains 85 programs and 85 individual crystals: 50 Doctor,
+26 Adventurer, seven Martial Artist and two without a profession gate. Admission
+requires the whole unconditional selected-target HP Hit contract, including
+ordinary friendly flags, the attack dictionary and understood requirements.
+Mixed effects, pet/script context, team effects and periodic heals remain separate.
The QL 1 Doctor startup crystal 28778 uploads Improved Healing 28665. Upload
uses the same atomic learned-program/consumption path as the other supported
@@ -15,17 +22,29 @@ execution 294 is 250 centiseconds, recharge 210 is 250 centiseconds and range
roll or debit policy. `tools/data/extract_nano_learning.py` retains both exact
records and their payload hashes in the local nano-learning report.
-Only learning is implemented. Healing casts remain disabled until health
-updates work during incoming weapon combat. The unresolved delivery issue
-and rejected approaches are in [First Aid](first-aid.md); the self-heal TODO
-remains open. A crystal's upload effects do not apply its learned heal.
+Casting uses the program's requirements, range, initiative-adjusted execution
+and recharge. Improved Healing reserves 13 nano under the existing native
+float cost arithmetic, restores an inclusive uniform 16..30 HP, clamps to the
+recipient's maximum and consumes no NCU. Cost, health and recharge commit
+atomically. An aborted cast refunds its reservation without a delayed heal.
+Friendly recipient validation and charging/refund rules retain the existing
+reconstruction policy; the definitions do not prove the original server's policy.
+
+HealthDamage publishes authoritative HP through the shared
+[First Aid reconciliation](first-aid.md#maintained-client-reconciliation).
+The maintained client preserves queued weapon feedback and animation without
+debiting damage already included in that snapshot a second time. No client
+change was needed for this spell extension. Actions 130/129 provide private
+healer/recipient feedback, and completion 107 releases the native effect gate.
+A crystal's upload effects do not apply its learned heal.
The [additional-module and capture audit](combat-healing-delivery.md) extends
the delivery investigation beyond KKR's named classes. The seven additional
classes and JJR `Heal` export supply no suitable client HP operation. Historical
archives, later live-capture reports and sampled period footage do not establish
-the missing combat-heal exchange. These bounded negative results leave casting
-unfinished and preserve the existing native behavior.
+the missing combat-heal exchange. These bounded negative results leave the
+historical publication exchange unresolved; current casting uses the maintained
+reconciliation above.
## Common message scheduling
@@ -86,7 +105,8 @@ no established current-HP addition or neutral AttackInfo drain. Common authored
execution still rejects Hit53002. The full bounded audit, source hashes, raw
RTTI and 23 new complete evidence records are under
`local/combat-heal-derived-item-research/`. Its owned analysis session was closed.
-This narrows the unresolved delivery search; it does not enable healing casts.
+This narrows the historical delivery search; it does not supply an additive
+current-HP operation in the original client.
## Periodic healing contracts
@@ -118,7 +138,7 @@ HP portion. Ten passive HealDelta programs were retained separately. Their
stat343 modifiers are not periodic Hit effects. Bulk TESTITEM uploaders are
also separate from the forty individual crystals.
-The implementation dependency remains the combat HP delivery problem above.
+The maintained client reconciliation also applies to HP snapshots during combat.
The current hostile periodic scheduler handles NPC damage and kill outcomes;
friendly healing must use living-player resource transactions and an explicit
timer/logout policy. It must not inherit NPC retaliation, damage credit or
@@ -130,7 +150,7 @@ an independent verifier are under `local/nano-hot-research/catalog/`. The
verifier reparsed 413 retained original resources, including all 312 programs
with repeated Hit, relevant uploaders and wrapper/reference candidates.
-## Verification
+## Upload milestone verification
Go tests cover exact BM/MM boundaries, profession and quality rejection,
duplicate use, failed writes, failed COMMIT, concurrent uploads, private
@@ -149,3 +169,39 @@ Screenshots, native probes, wire verification, SQL snapshots and cleanup
checks are retained under `local/healing-upload-smoke/`. Only owned test
characters and items were removed; unrelated rows were unchanged. The
published WASM bundle was unchanged.
+
+## Direct-heal verification
+
+The independent census reparsed every original nano and item record, retained
+the 227 single positive selected-target HP Hit candidates, then separated the
+85 complete ordinary contracts and their individual uploaders. Exact decoded
+records and hashes are in `local/direct-healing/original-census.json`; the
+checked-in `server/testdata/direct-healing-nanos.json` supplies independent
+expected endpoints, cost, timing, range, profession and crystal quality.
+The implementation admits complete contracts without a program-ID list.
+
+Go tests upload, cast and cold-load all 85. Focused tests cover exact Doctor
+requirements, insufficient nano, invalid targets, completion gates, clamping,
+friendly healing with full NCU, recharge, cancellation without a delayed result,
+and failed health writes, ignored updates and failed COMMIT followed by retry.
+The shared First Aid snapshot helper keeps its existing combat behavior.
+
+`TestBrowserImprovedHealingQueuedHit` uses two controlled level 10 Doctors and
+one ordinary Leet swing. Real browser input uploads crystal 28778, selects the
+Medical program, cancels the first cast by moving, then completes a second cast
+while the incoming result is pending. Both clients must display authoritative
+healed HP before impact and retain it afterwards, with one genuine weapon result,
+unchanged enemy deadlines, one completed nano and durable cost/recharge. This is
+a controlled fixture, not earned progression. Native traces, screenshots and
+server comparisons are retained in `local/direct-healing/`.
+Only the nano scheduler and one combat swing advance; the caster loads last
+to keep its unrelated regeneration phase outside this short sample.
+
+```sh
+go test ./server -run '^Test(DirectHealing|ImprovedHealing|HealingCrystal)' -count=1
+AO_GAME_TEST=1 go test ./server -run '^TestBrowserImprovedHealingQueuedHit$' -count=1 -timeout=5m -v
+```
+
+Original-server heal distribution, cross-faction/PvP permissions, interruption
+rolls and charging/refund timing are not established by this implementation.
+Periodic healing retains its separate scheduling and persistence work above.
diff --git a/server/browser_healing_test.go b/server/browser_healing_test.go
@@ -0,0 +1,119 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestBrowserImprovedHealingQueuedHit(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for the focused native healing cast")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/direct-healing", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ world.combatRoll = landedCombatRoll
+ 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")
+ }
+ players := []*character{}
+ for index := 0; index < 2; index++ {
+ player := world.newCharacter()
+ player.name, player.level, player.profession = fmt.Sprint("Healing", index), 10, 10
+ player.stats = testCharacterStats()
+ player.stats.Body.BodyDevelopment = 55
+ player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.MatterMetamorphosis = 7, 5
+ player.position, player.rotation = enemy.position, [4]float32{0, 0, 0, 1}
+ player.position[2] -= float32(2 + index*3)
+ player.health, player.nano = 200, 50
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("healing-", index))))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ players = append(players, player)
+ }
+ if granted, err := world.grantItem_locked(players[0], 28778); 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()
+ var cast any
+ if client := world.clients[players[0].id]; client != nil && client.nanoCast != nil {
+ cast = map[string]any{"readyAt": client.nanoCast.readyAt}
+ }
+ 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, "reserved": players[0].nanoReserved, "cast": cast,
+ "recharge": players[0].nanoRechargeUntil, "inventory": players[0].inventory,
+ "fighting": enemy.fighting, "nextAttack": enemy.nextAttack, "weaponRecharge": enemy.rechargeUntil})
+ })
+ // One controlled production swing near spell completion isolates queued-hit reconciliation.
+ 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(enemy, players[0], time.Now(), updates)
+ deadline := enemy.nextAttack
+ world.mutex.Unlock()
+ world.sendCombatUpdates(updates)
+ world.updateMutex.Unlock()
+ world.advanceCombat(deadline)
+ w.WriteHeader(http.StatusNoContent)
+ })
+ host := httptest.NewServer(mux)
+ defer 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_healing.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).characters[players[0].id]
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if cold.health != players[0].health || cold.nano != 37 || cold.nanoReserved != 0 || !cold.nanoRechargeUntil.Equal(players[0].nanoRechargeUntil) {
+ t.Fatal("completed native heal did not persist health, cost and recharge together")
+ }
+}
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -85,7 +85,7 @@ func (player *character) nanoCastDelay(program uint32) time.Duration {
}
func (player *character) nanoRequirementsMet(program uint32) bool {
- return (directDamageNano(program) != nil || damageOverTimeNano(program) != nil || controlNano(program) != nil || statBuffNano(program)) && player.templateUseRequirementsMet(gamedata.NanoTemplates[program])
+ return (directDamageNano(program) != nil || directHealingNano(program) != nil || damageOverTimeNano(program) != nil || controlNano(program) != nil || statBuffNano(program)) && player.templateUseRequirementsMet(gamedata.NanoTemplates[program])
}
func (server *server) nanoTarget_locked(player, target *character, client *worldClient, program uint32, now time.Time) bool {
@@ -102,7 +102,8 @@ func (server *server) nanoTarget_locked(player, target *character, client *world
}
} else {
recipient := server.clients[target.id]
- if target.npc || target.appearance>>9&3 != player.appearance>>9&3 || recipient == nil || !recipient.ready || recipient.loading || !target.acceptsNano(program) {
+ if target.npc || target.appearance>>9&3 != player.appearance>>9&3 || recipient == nil || !recipient.ready || recipient.loading ||
+ directHealingNano(program) == nil && !target.acceptsNano(program) {
return false
}
second = predictedPosition_locked(target, now)
@@ -262,6 +263,7 @@ func (server *server) advanceNanos(now time.Time) {
}
var damage uint32
hit := directDamageNano(program)
+ heal := directHealingNano(program)
effectProgram := program
removedHealthBonus := false
if hit != nil {
@@ -273,6 +275,11 @@ func (server *server) advanceNanos(now time.Time) {
}
effectProgram = damageNanoSecondary(program)
}
+ if heal != nil {
+ minimum, maximum := uint32(*heal.Arguments[1].Integer), uint32(*heal.Arguments[2].Integer)
+ victim.health = min(victim.maximumHealth(), victim.health+minimum+rand.Uint32N(maximum-minimum+1))
+ effectProgram = 0
+ }
if controlNano(program) != nil {
server.breakNanos_locked(&victim, 386)
}
@@ -326,6 +333,18 @@ func (server *server) advanceNanos(now time.Time) {
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)}))
}
+ if heal != nil {
+ // HealthDamage includes received weapon outcomes; the native client reconciles their later impacts.
+ server.queueHealthSnapshot_locked(updates, target)
+ server.queueTeamResources_locked(updates, target)
+ restored := target.health - previous.health
+ updates[client] = append(updates[client], characterActionPacket(player.id, [5]uint32{130, 50000, target.id, 0, restored}))
+ if target != player {
+ recipient := server.clients[target.id]
+ updates[recipient] = append(updates[recipient], characterActionPacket(target.id, [5]uint32{129, 50000, player.id, 0, restored}))
+ }
+ continue
+ }
if hit == nil {
if damageOverTimeNano(program) != nil || controlNano(program) != nil {
// A hostile cast starts retaliation before its first scheduled tick.
diff --git a/server/nano_heal_cast_test.go b/server/nano_heal_cast_test.go
@@ -0,0 +1,249 @@
+package main
+
+import (
+ "encoding/binary"
+ "testing"
+ "time"
+)
+
+func TestImprovedHealingFailureRollsBackAndRetries(t *testing.T) {
+ for _, failure := range []string{"health", "ignored health", "commit"} {
+ t.Run(failure, func(t *testing.T) {
+ world, conn := newHealingCrystalWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.stats.Body.NanoPool = 20
+ player.health, player.nano = 1, 30
+ player.inventory.LearnedNanos = []uint32{28665}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 28665})[20:]
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("heal admission failed", err)
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ statement := "CREATE TRIGGER fail_heal BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(FAIL, 'test heal'); END"
+ if failure == "ignored health" {
+ statement = "CREATE TRIGGER fail_heal BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(IGNORE); END"
+ } else if failure == "commit" {
+ statement = "CREATE TABLE invalid_heal (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_heal AFTER UPDATE OF health ON characters BEGIN INSERT INTO invalid_heal VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ world.advanceNanos(at)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || client.nanoCast != nil ||
+ !player.nanoRechargeUntil.IsZero() || cold.health != 1 || cold.nano != 30 {
+ t.Fatalf("failed heal published partial health, debit or recharge: health=%d nano=%d reserved=%d cast=%v recharge=%v cold=%d/%d", player.health, player.nano, player.nanoReserved, client.nanoCast, player.nanoRechargeUntil, cold.health, cold.nano)
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c ||
+ binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 107 {
+ t.Fatal("failed heal published success")
+ }
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_heal"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("failed heal could not retry", err)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ if player.health < 17 || player.health > 31 || player.nano != 17 {
+ t.Fatal("heal retry did not apply one result")
+ }
+ })
+ }
+}
+
+func TestImprovedHealingCastRestoresHealthAndCommitsCostAndRecharge(t *testing.T) {
+ world, conn := newHealingCrystalWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ player.stats.Body.NanoPool = 20
+ player.health, player.nano = 1, 30
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 28665})[20:]
+ before := time.Now()
+ if err := world.handleNanoCast(client, request); err != nil {
+ t.Fatal(err)
+ }
+ after := time.Now()
+ if client.nanoCast == nil {
+ t.Fatal("learned Improved Healing was rejected")
+ }
+ if player.health != 1 || player.nano != 17 || player.nanoReserved != 13 {
+ t.Fatal("cast admission changed health or reserved the wrong cost")
+ }
+ at := client.nanoCast.readyAt
+ if at.Before(before.Add(2464999914*time.Nanosecond)) || at.After(after.Add(2464999914*time.Nanosecond)) {
+ t.Fatal("Improved Healing did not use its authored attack time and native initiative reduction", at.Sub(before))
+ }
+ world.advanceNanos(at)
+ if player.health != 1 || client.nanoCast == nil {
+ t.Fatal("heal completed before the native effect gate")
+ }
+ world.advanceNanos(at.Add(time.Nanosecond))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if player.health < 17 || player.health > 31 || player.nano != 17 || player.nanoReserved != 0 || client.nanoCast != nil ||
+ cold.health != player.health || cold.nano != 17 || !cold.nanoRechargeUntil.Equal(player.nanoRechargeUntil) || !player.nanoRechargeUntil.After(at) || len(player.activeNanos) != 0 {
+ t.Fatalf("heal did not commit one immediate result: health=%d nano=%d recharge=%v", player.health, player.nano, player.nanoRechargeUntil)
+ }
+ completed, snapshots := 0, 0
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 107 {
+ completed++
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c && binary.BigEndian.Uint32(packet[29:33]) == player.health {
+ snapshots++
+ }
+ }
+ if completed != 1 || snapshots != 1 {
+ t.Fatalf("heal completion/absolute health publication: %d/%d", completed, snapshots)
+ }
+}
+
+func TestImprovedHealingCancellationHasNoDelayedResult(t *testing.T) {
+ world, conn := newHealingCrystalWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.stats.Body.NanoPool = 20
+ player.health, player.nano = 1, 30
+ player.inventory.LearnedNanos = []uint32{28665}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 28665})[20:]); err != nil || client.nanoCast == nil {
+ t.Fatal("heal admission failed", err)
+ }
+ deadline := client.nanoCast.readyAt
+ conn.packets = nil
+
+ for range 2 {
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{108})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ world.advanceNanos(deadline.Add(time.Minute))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || client.nanoCast != nil ||
+ !player.nanoRechargeUntil.IsZero() || cold.health != 1 || cold.nano != 30 || cold.nanoReserved != 0 {
+ t.Fatal("cancelled heal retained cost, recharge or a delayed result")
+ }
+ if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 108 {
+ t.Fatal("cancellation published a duplicate refund or result")
+ }
+}
+
+func TestImprovedHealingRejectsInvalidAdmission(t *testing.T) {
+ for _, scenario := range []string{"unlearned", "profession", "BM", "MM", "nano", "dead", "NPC", "missing target", "moving"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newHealingCrystalWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.health, player.nano = 1, 30
+ player.inventory.LearnedNanos = []uint32{28665}
+ target := uint32(1)
+ switch scenario {
+ case "unlearned":
+ player.inventory.LearnedNanos = nil
+ case "profession":
+ player.profession = 1
+ case "BM":
+ player.stats.NanoAiding.BiologicalMetamorphosis = 6
+ case "MM":
+ player.stats.NanoAiding.MatterMetamorphosis = 4
+ case "nano":
+ player.nano = 12
+ case "dead":
+ player.health = 0
+ case "NPC":
+ target = 1000000
+ case "missing target":
+ target = 999
+ case "moving":
+ player.movement.forward = 1
+ }
+ health, nano := player.health, player.nano
+
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target, 53019, 28665})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceNanos(time.Now().Add(time.Minute))
+
+ if client.nanoCast != nil || player.health != health || player.nano != nano || player.nanoReserved != 0 || !player.nanoRechargeUntil.IsZero() {
+ t.Fatal("invalid heal changed health, nano or recharge")
+ }
+ })
+ }
+}
+
+func TestImprovedHealingRecipientClampAndRecharge(t *testing.T) {
+ world, conn := newHealingCrystalWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.stats.Body.NanoPool = 20
+ player.nano, player.inventory.LearnedNanos = 30, []uint32{28665}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ patient := *player
+ patient.id, patient.name, patient.inventory = 2, "Patient", playerInventory{}
+ // Existing ability buffs fill all eight NCU; direct healing needs no free NCU.
+ patient.activeNanos = []activeNano{
+ {program: 26342, caster: 1, expiresAt: time.Now().Add(time.Minute)},
+ {program: 27086, caster: 1, expiresAt: time.Now().Add(time.Minute)},
+ {program: 26360, caster: 1, expiresAt: time.Now().Add(time.Minute)},
+ }
+ patient.health = patient.maximumHealth() - 1
+ if patient.acceptsNano(28665) {
+ t.Fatal("fixture must reject treating the heal as an NCU buff")
+ }
+ recipient := &combatTestConn{}
+ world.characters[2], world.nextCharacter = &patient, 2
+ world.clients[2] = &worldClient{id: 2, conn: recipient, ready: true, target: true}
+ if err := world.saveUser_locked(&patient); err != nil {
+ t.Fatal(err)
+ }
+ request := characterActionPacket(1, [5]uint32{19, 50000, 2, 53019, 28665})[20:]
+
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("friendly heal was rejected for NCU", err)
+ }
+ completed := client.nanoCast.readyAt.Add(time.Nanosecond)
+ world.advanceNanos(completed)
+ world.handleNanoCast(client, request)
+ world.advanceNanos(completed.Add(time.Nanosecond))
+ cold := newTestInventoryServer(t).characters[2]
+
+ if patient.health != patient.maximumHealth() || cold.health != patient.health || player.nano != 17 || client.nanoCast != nil ||
+ player.nanoRechargeUntil.Sub(completed) != 2499999944*time.Nanosecond || len(patient.activeNanos) != 3 || len(cold.activeNanos) != 3 || patient.fighting != 0 {
+ t.Fatal("heal failed to clamp, consumed NCU, started combat or bypassed recharge")
+ }
+ for _, check := range []struct {
+ packets [][]byte
+ action uint32
+ }{{conn.packets, 130}, {recipient.packets, 129}} {
+ found := 0
+ for _, packet := range check.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == check.action {
+ found++
+ if binary.BigEndian.Uint32(packet[45:49]) != 1 {
+ t.Fatal("heal feedback reported the rolled amount instead of restored HP")
+ }
+ }
+ }
+ if found != 1 {
+ t.Fatal("missing or duplicate private healing feedback", check.action, found)
+ }
+ }
+}
diff --git a/server/nano_heal_catalog_test.go b/server/nano_heal_catalog_test.go
@@ -0,0 +1,109 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ _ "embed"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "testing"
+ "time"
+)
+
+//go:embed testdata/direct-healing-nanos.json
+var directHealingNanoData []byte
+
+type directHealingFixture struct {
+ Program, Crystal, Quality, Profession uint32
+ Minimum, Maximum, Cost uint32
+ Attack, Recharge, Range uint32
+}
+
+func directHealingFixtures(t *testing.T) []directHealingFixture {
+ t.Helper()
+ var fixtures []directHealingFixture
+ if err := json.Unmarshal(directHealingNanoData, &fixtures); err != nil {
+ t.Fatal(err)
+ }
+ return fixtures
+}
+
+func TestDirectHealingCatalogMatchesOriginalContracts(t *testing.T) {
+ fixtures := directHealingFixtures(t)
+ var expected, expectedCrystals, programs, crystals []uint32
+ for _, fixture := range fixtures {
+ expected = append(expected, fixture.Program)
+ expectedCrystals = append(expectedCrystals, fixture.Crystal)
+ }
+
+ for program := range gamedata.NanoTemplates {
+ if directHealingNano(program) != nil {
+ programs = append(programs, program)
+ }
+ }
+ for crystal := range gamedata.ItemTemplates {
+ if directHealingNano(nanoCrystalProgram(crystal)) != nil {
+ crystals = append(crystals, crystal)
+ }
+ }
+ for _, values := range [][]uint32{expected, expectedCrystals, programs, crystals} {
+ slices.Sort(values)
+ }
+
+ if len(programs) != 85 || !slices.Equal(programs, expected) || !slices.Equal(crystals, expectedCrystals) {
+ t.Fatalf("ordinary healing census differs: programs=%v crystals=%v", programs, crystals)
+ }
+ for _, fixture := range fixtures {
+ hit := directHealingNano(fixture.Program)
+ if uint32(*hit.Arguments[1].Integer) != fixture.Minimum || uint32(*hit.Arguments[2].Integer) != fixture.Maximum ||
+ 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("original healing range, cost or timing changed", fixture.Program)
+ }
+ }
+}
+
+func TestDirectHealingCrystalsLearnCastAndPersist(t *testing.T) {
+ for _, fixture := range directHealingFixtures(t) {
+ t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) {
+ world, _ := newNanoCastingWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ player.level, player.profession = 200, uint16(max(1, fixture.Profession))
+ for _, field := range player.stats.trainingStats() {
+ *field.value = 2000
+ }
+ player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1}
+ player.stats.Speed.NanoInitiative, player.stats.Body.NanoPool = 5, 30000
+ player.health, player.nano, player.inventory.LearnedNanos = 1, 50000, nil
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, fixture.Crystal); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ if player.inventory.Items[0].Quality != fixture.Quality {
+ t.Fatal("original healing 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("original healing crystal was not consumed and learned once")
+ }
+ request := characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, fixture.Program})[20:]
+ if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil {
+ t.Fatal("qualified healing cast rejected", err)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ cold := newTestInventoryServer(t).characters[1]
+
+ minimum, maximum := min(player.maximumHealth(), 1+fixture.Minimum), min(player.maximumHealth(), 1+fixture.Maximum)
+ if player.health < minimum || player.health > maximum || cold.health != player.health || player.nano != 50001-fixture.Cost ||
+ cold.nano != player.nano || player.nanoReserved != 0 || client.nanoCast != nil || len(player.activeNanos) != 0 ||
+ !slices.Equal(cold.inventory.LearnedNanos, []uint32{fixture.Program}) {
+ t.Fatal("original heal lost its effect, cost or durable learned state", player.health, player.nano)
+ }
+ })
+ }
+}
diff --git a/server/nano_healing.go b/server/nano_healing.go
@@ -0,0 +1,68 @@
+package main
+
+import "ao/server/gamedata"
+
+func directHealingNano(program uint32) *gamedata.ItemFunction {
+ definition := gamedata.NanoTemplates[program]
+ if definition == nil || definition.RecordType != 1040005 || definition.HeaderWords[0] != 51051 || definition.Undecoded != nil ||
+ (itemStat(definition, 0) != 0x80000002 && itemStat(definition, 0) != 2) || itemStat(definition, 30) != 0 || itemStat(definition, 76) != 0 ||
+ itemStat(definition, 405) != 2 || itemStat(definition, 8) != 0 || len(definition.Sections) != 4 {
+ return nil
+ }
+ for _, stat := range []uint32{210, 287, 294, 407} {
+ if value := nanoStat(program, stat); value == 0 || value >= 0x80000000 {
+ return nil
+ }
+ }
+
+ // Ordinary direct heals have one attack-rating dictionary and no defense roll.
+ weights, defaults := definition.Sections[0], definition.Sections[1]
+ if weights.Type != 4 || weights.Subtype != 4 || weights.Entries == nil || len(*weights.Entries) != 1 ||
+ defaults.Type != 6 || defaults.Subtype != 27 || defaults.Stats == nil || len(*defaults.Stats) != 1 || (*defaults.Stats)[0] != [2]uint32{12, 0} {
+ return nil
+ }
+ attack := (*weights.Entries)[0]
+ if attack.Type == nil || *attack.Type != 12 || attack.Stats == nil {
+ return nil
+ }
+ var total uint32
+ for _, weight := range *attack.Stats {
+ if weight[0] < 100 || weight[0] > 168 || weight[1] == 0 || weight[1] > 100 {
+ return nil
+ }
+ total += weight[1]
+ }
+ if total != 100 {
+ return nil
+ }
+
+ // Admit the complete immediate selected-target HP contract, not a partial effect.
+ effects, requirements := definition.Sections[2], definition.Sections[3]
+ if effects.Type != 2 || effects.Subtype != 0 || effects.Functions == nil || len(*effects.Functions) != 1 ||
+ requirements.Type != 22 || requirements.Subtype != 36 || requirements.Actions == nil || len(*requirements.Actions) != 1 || (*requirements.Actions)[0].Type != 3 {
+ return nil
+ }
+ for _, requirement := range (*requirements.Actions)[0].Requirements {
+ switch requirement.Operator {
+ case 3, 4, 42:
+ default:
+ if _, known := (&character{}).meetsStatRequirement(requirement); !known {
+ return nil
+ }
+ }
+ }
+ hit := &(*effects.Functions)[0]
+ if hit.ID != 53002 || hit.HeaderWords != [2]uint32{0, 4} || hit.ArgumentHeader != 9 || hit.Target != 3 ||
+ len(hit.Requirements) != 0 || hit.TickCount != 1 || hit.TickInterval != 0 || len(hit.Arguments) != 4 {
+ return nil
+ }
+ for _, argument := range hit.Arguments {
+ if argument.Integer == nil {
+ return nil
+ }
+ }
+ if *hit.Arguments[0].Integer != 27 || *hit.Arguments[1].Integer <= 0 || *hit.Arguments[2].Integer < *hit.Arguments[1].Integer || *hit.Arguments[3].Integer != 0 {
+ return nil
+ }
+ return hit
+}
diff --git a/server/nano_learning.go b/server/nano_learning.go
@@ -41,7 +41,7 @@ func nanoCrystalProgram(template uint32) uint32 {
return 0
}
program = uint32(*function.Arguments[0].Integer)
- if !statBuffNano(program) && directDamageNano(program) == nil && damageOverTimeNano(program) == nil && controlNano(program) == nil {
+ if !statBuffNano(program) && directDamageNano(program) == nil && directHealingNano(program) == nil && damageOverTimeNano(program) == nil && controlNano(program) == nil {
return 0
}
}
@@ -56,11 +56,6 @@ func (server *server) learnNano_locked(client *worldClient, index int, body []by
var program uint32
accepted := item.Type == 51005 && item.Slot >= 64 && item.Slot < 94
switch item.Template {
- case 28778:
- program = 28665
- accepted = accepted && item.Quality == 1 && player.profession == 10 &&
- player.effectiveSkill(128, stats.NanoAiding.BiologicalMetamorphosis, [6]uint32{0, 0, 0, 80, 0, 20}) > 8 &&
- player.effectiveSkill(127, stats.NanoAiding.MatterMetamorphosis, [6]uint32{0, 0, 0, 80, 0, 20}) > 6
case 43330:
program = 43324
accepted = accepted && item.Quality == 1 && player.profession == 12 &&
diff --git a/server/regeneration.go b/server/regeneration.go
@@ -92,7 +92,10 @@ func (server *server) queueQuietHealth_locked(updates map[*worldClient][][]byte,
if server.characterInCombat_locked(actor) {
return
}
+ server.queueHealthSnapshot_locked(updates, actor)
+}
+func (server *server) queueHealthSnapshot_locked(updates map[*worldClient][][]byte, actor *character) {
// HealthDamage assigns absolute HP; a zero change suppresses feedback.
var body []byte
for _, value := range []uint32{actor.health, 0, 0, 0} {
diff --git a/server/resource_kit.go b/server/resource_kit.go
@@ -218,11 +218,7 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body
if kit.health[1] != 0 {
if kit.lockSkill == 123 {
// The client reconciles queued weapon impacts against this absolute HP.
- var health []byte
- for _, value := range []uint32{target.health, 0, 0, 0} {
- health = binary.BigEndian.AppendUint32(health, value)
- }
- server.queueCombat_locked(updates, target, target, n3Packet(0x3710256c, 50000, target.id, health))
+ server.queueHealthSnapshot_locked(updates, target)
} else {
server.queueQuietHealth_locked(updates, target)
}
diff --git a/server/testdata/direct-healing-nanos.json b/server/testdata/direct-healing-nanos.json
@@ -0,0 +1,1022 @@
+[
+ {
+ "program": 26465,
+ "crystal": 26681,
+ "quality": 1,
+ "profession": 0,
+ "minimum": 5,
+ "maximum": 10,
+ "cost": 15,
+ "attack": 151,
+ "recharge": 100,
+ "range": 12
+ },
+ {
+ "program": 26466,
+ "crystal": 26683,
+ "quality": 4,
+ "profession": 0,
+ "minimum": 15,
+ "maximum": 25,
+ "cost": 25,
+ "attack": 186,
+ "recharge": 106,
+ "range": 15
+ },
+ {
+ "program": 26695,
+ "crystal": 28742,
+ "quality": 1,
+ "profession": 6,
+ "minimum": 15,
+ "maximum": 25,
+ "cost": 16,
+ "attack": 275,
+ "recharge": 250,
+ "range": 20
+ },
+ {
+ "program": 28645,
+ "crystal": 28758,
+ "quality": 129,
+ "profession": 10,
+ "minimum": 536,
+ "maximum": 982,
+ "cost": 198,
+ "attack": 296,
+ "recharge": 388,
+ "range": 20
+ },
+ {
+ "program": 28648,
+ "crystal": 28761,
+ "quality": 90,
+ "profession": 10,
+ "minimum": 415,
+ "maximum": 690,
+ "cost": 170,
+ "attack": 284,
+ "recharge": 351,
+ "range": 20
+ },
+ {
+ "program": 28650,
+ "crystal": 28763,
+ "quality": 169,
+ "profession": 10,
+ "minimum": 10001,
+ "maximum": 10001,
+ "cost": 1400,
+ "attack": 550,
+ "recharge": 800,
+ "range": 25
+ },
+ {
+ "program": 28654,
+ "crystal": 28767,
+ "quality": 7,
+ "profession": 10,
+ "minimum": 45,
+ "maximum": 73,
+ "cost": 33,
+ "attack": 253,
+ "recharge": 258,
+ "range": 20
+ },
+ {
+ "program": 28665,
+ "crystal": 28778,
+ "quality": 1,
+ "profession": 10,
+ "minimum": 16,
+ "maximum": 30,
+ "cost": 14,
+ "attack": 250,
+ "recharge": 250,
+ "range": 20
+ },
+ {
+ "program": 28672,
+ "crystal": 28785,
+ "quality": 37,
+ "profession": 10,
+ "minimum": 192,
+ "maximum": 266,
+ "cost": 98,
+ "attack": 264,
+ "recharge": 292,
+ "range": 20
+ },
+ {
+ "program": 28676,
+ "crystal": 28789,
+ "quality": 30,
+ "profession": 10,
+ "minimum": 161,
+ "maximum": 238,
+ "cost": 89,
+ "attack": 262,
+ "recharge": 286,
+ "range": 20
+ },
+ {
+ "program": 28677,
+ "crystal": 28790,
+ "quality": 53,
+ "profession": 10,
+ "minimum": 282,
+ "maximum": 395,
+ "cost": 128,
+ "attack": 271,
+ "recharge": 312,
+ "range": 20
+ },
+ {
+ "program": 28681,
+ "crystal": 28753,
+ "quality": 24,
+ "profession": 10,
+ "minimum": 117,
+ "maximum": 188,
+ "cost": 73,
+ "attack": 259,
+ "recharge": 276,
+ "range": 20
+ },
+ {
+ "program": 43808,
+ "crystal": 43965,
+ "quality": 152,
+ "profession": 10,
+ "minimum": 621,
+ "maximum": 1165,
+ "cost": 203,
+ "attack": 308,
+ "recharge": 424,
+ "range": 20
+ },
+ {
+ "program": 43809,
+ "crystal": 44005,
+ "quality": 136,
+ "profession": 10,
+ "minimum": 559,
+ "maximum": 1034,
+ "cost": 202,
+ "attack": 298,
+ "recharge": 395,
+ "range": 20
+ },
+ {
+ "program": 43810,
+ "crystal": 43947,
+ "quality": 132,
+ "profession": 10,
+ "minimum": 540,
+ "maximum": 1018,
+ "cost": 200,
+ "attack": 297,
+ "recharge": 392,
+ "range": 20
+ },
+ {
+ "program": 43811,
+ "crystal": 43945,
+ "quality": 142,
+ "profession": 10,
+ "minimum": 572,
+ "maximum": 1055,
+ "cost": 202,
+ "attack": 300,
+ "recharge": 400,
+ "range": 20
+ },
+ {
+ "program": 43812,
+ "crystal": 43996,
+ "quality": 86,
+ "profession": 10,
+ "minimum": 389,
+ "maximum": 650,
+ "cost": 164,
+ "attack": 282,
+ "recharge": 345,
+ "range": 20
+ },
+ {
+ "program": 43813,
+ "crystal": 43985,
+ "quality": 50,
+ "profession": 10,
+ "minimum": 269,
+ "maximum": 368,
+ "cost": 123,
+ "attack": 270,
+ "recharge": 309,
+ "range": 20
+ },
+ {
+ "program": 43814,
+ "crystal": 43979,
+ "quality": 103,
+ "profession": 10,
+ "minimum": 446,
+ "maximum": 794,
+ "cost": 180,
+ "attack": 288,
+ "recharge": 363,
+ "range": 20
+ },
+ {
+ "program": 43815,
+ "crystal": 43983,
+ "quality": 109,
+ "profession": 10,
+ "minimum": 476,
+ "maximum": 831,
+ "cost": 185,
+ "attack": 290,
+ "recharge": 369,
+ "range": 20
+ },
+ {
+ "program": 43816,
+ "crystal": 43972,
+ "quality": 123,
+ "profession": 10,
+ "minimum": 524,
+ "maximum": 929,
+ "cost": 194,
+ "attack": 294,
+ "recharge": 382,
+ "range": 20
+ },
+ {
+ "program": 43817,
+ "crystal": 43973,
+ "quality": 116,
+ "profession": 10,
+ "minimum": 506,
+ "maximum": 894,
+ "cost": 191,
+ "attack": 292,
+ "recharge": 377,
+ "range": 20
+ },
+ {
+ "program": 43818,
+ "crystal": 43959,
+ "quality": 63,
+ "profession": 10,
+ "minimum": 300,
+ "maximum": 497,
+ "cost": 141,
+ "attack": 274,
+ "recharge": 323,
+ "range": 20
+ },
+ {
+ "program": 43819,
+ "crystal": 43952,
+ "quality": 73,
+ "profession": 10,
+ "minimum": 327,
+ "maximum": 551,
+ "cost": 150,
+ "attack": 277,
+ "recharge": 330,
+ "range": 20
+ },
+ {
+ "program": 43820,
+ "crystal": 43953,
+ "quality": 93,
+ "profession": 10,
+ "minimum": 426,
+ "maximum": 706,
+ "cost": 172,
+ "attack": 284,
+ "recharge": 353,
+ "range": 20
+ },
+ {
+ "program": 43821,
+ "crystal": 43943,
+ "quality": 96,
+ "profession": 10,
+ "minimum": 439,
+ "maximum": 747,
+ "cost": 176,
+ "attack": 286,
+ "recharge": 358,
+ "range": 20
+ },
+ {
+ "program": 43822,
+ "crystal": 43924,
+ "quality": 80,
+ "profession": 10,
+ "minimum": 343,
+ "maximum": 588,
+ "cost": 155,
+ "attack": 278,
+ "recharge": 335,
+ "range": 20
+ },
+ {
+ "program": 43823,
+ "crystal": 43926,
+ "quality": 57,
+ "profession": 10,
+ "minimum": 294,
+ "maximum": 437,
+ "cost": 134,
+ "attack": 272,
+ "recharge": 317,
+ "range": 20
+ },
+ {
+ "program": 43824,
+ "crystal": 43934,
+ "quality": 83,
+ "profession": 10,
+ "minimum": 354,
+ "maximum": 631,
+ "cost": 160,
+ "attack": 280,
+ "recharge": 340,
+ "range": 20
+ },
+ {
+ "program": 43825,
+ "crystal": 43935,
+ "quality": 113,
+ "profession": 10,
+ "minimum": 490,
+ "maximum": 857,
+ "cost": 187,
+ "attack": 291,
+ "recharge": 372,
+ "range": 20
+ },
+ {
+ "program": 43826,
+ "crystal": 43995,
+ "quality": 47,
+ "profession": 10,
+ "minimum": 260,
+ "maximum": 337,
+ "cost": 118,
+ "attack": 268,
+ "recharge": 305,
+ "range": 20
+ },
+ {
+ "program": 43827,
+ "crystal": 43987,
+ "quality": 30,
+ "profession": 10,
+ "minimum": 151,
+ "maximum": 225,
+ "cost": 86,
+ "attack": 261,
+ "recharge": 284,
+ "range": 20
+ },
+ {
+ "program": 43828,
+ "crystal": 43993,
+ "quality": 10,
+ "profession": 10,
+ "minimum": 54,
+ "maximum": 88,
+ "cost": 39,
+ "attack": 254,
+ "recharge": 261,
+ "range": 20
+ },
+ {
+ "program": 43829,
+ "crystal": 43978,
+ "quality": 4,
+ "profession": 10,
+ "minimum": 27,
+ "maximum": 43,
+ "cost": 20,
+ "attack": 251,
+ "recharge": 253,
+ "range": 20
+ },
+ {
+ "program": 43830,
+ "crystal": 43981,
+ "quality": 10,
+ "profession": 10,
+ "minimum": 65,
+ "maximum": 102,
+ "cost": 45,
+ "attack": 254,
+ "recharge": 263,
+ "range": 20
+ },
+ {
+ "program": 43831,
+ "crystal": 43957,
+ "quality": 4,
+ "profession": 10,
+ "minimum": 36,
+ "maximum": 59,
+ "cost": 27,
+ "attack": 252,
+ "recharge": 255,
+ "range": 10
+ },
+ {
+ "program": 43832,
+ "crystal": 43960,
+ "quality": 1,
+ "profession": 10,
+ "minimum": 21,
+ "maximum": 37,
+ "cost": 17,
+ "attack": 250,
+ "recharge": 251,
+ "range": 20
+ },
+ {
+ "program": 43833,
+ "crystal": 43962,
+ "quality": 17,
+ "profession": 10,
+ "minimum": 86,
+ "maximum": 133,
+ "cost": 56,
+ "attack": 256,
+ "recharge": 268,
+ "range": 20
+ },
+ {
+ "program": 43834,
+ "crystal": 43963,
+ "quality": 24,
+ "profession": 10,
+ "minimum": 130,
+ "maximum": 199,
+ "cost": 78,
+ "attack": 260,
+ "recharge": 279,
+ "range": 20
+ },
+ {
+ "program": 43835,
+ "crystal": 43949,
+ "quality": 40,
+ "profession": 10,
+ "minimum": 207,
+ "maximum": 286,
+ "cost": 103,
+ "attack": 265,
+ "recharge": 296,
+ "range": 20
+ },
+ {
+ "program": 43836,
+ "crystal": 43955,
+ "quality": 33,
+ "profession": 10,
+ "minimum": 180,
+ "maximum": 255,
+ "cost": 95,
+ "attack": 263,
+ "recharge": 290,
+ "range": 20
+ },
+ {
+ "program": 43837,
+ "crystal": 43939,
+ "quality": 20,
+ "profession": 10,
+ "minimum": 99,
+ "maximum": 170,
+ "cost": 66,
+ "attack": 258,
+ "recharge": 273,
+ "range": 20
+ },
+ {
+ "program": 43838,
+ "crystal": 43941,
+ "quality": 40,
+ "profession": 10,
+ "minimum": 231,
+ "maximum": 299,
+ "cost": 109,
+ "attack": 266,
+ "recharge": 299,
+ "range": 20
+ },
+ {
+ "program": 43878,
+ "crystal": 43946,
+ "quality": 165,
+ "profession": 10,
+ "minimum": 693,
+ "maximum": 1283,
+ "cost": 201,
+ "attack": 319,
+ "recharge": 456,
+ "range": 20
+ },
+ {
+ "program": 43881,
+ "crystal": 43937,
+ "quality": 162,
+ "profession": 10,
+ "minimum": 679,
+ "maximum": 1255,
+ "cost": 201,
+ "attack": 317,
+ "recharge": 450,
+ "range": 20
+ },
+ {
+ "program": 43883,
+ "crystal": 43994,
+ "quality": 146,
+ "profession": 10,
+ "minimum": 588,
+ "maximum": 1082,
+ "cost": 203,
+ "attack": 302,
+ "recharge": 406,
+ "range": 20
+ },
+ {
+ "program": 43884,
+ "crystal": 44000,
+ "quality": 152,
+ "profession": 10,
+ "minimum": 630,
+ "maximum": 1174,
+ "cost": 202,
+ "attack": 309,
+ "recharge": 428,
+ "range": 20
+ },
+ {
+ "program": 43885,
+ "crystal": 43990,
+ "quality": 159,
+ "profession": 10,
+ "minimum": 650,
+ "maximum": 1225,
+ "cost": 200,
+ "attack": 314,
+ "recharge": 442,
+ "range": 20
+ },
+ {
+ "program": 43886,
+ "crystal": 43977,
+ "quality": 162,
+ "profession": 10,
+ "minimum": 665,
+ "maximum": 1244,
+ "cost": 200,
+ "attack": 316,
+ "recharge": 447,
+ "range": 20
+ },
+ {
+ "program": 43887,
+ "crystal": 43982,
+ "quality": 156,
+ "profession": 10,
+ "minimum": 871,
+ "maximum": 980,
+ "cost": 201,
+ "attack": 312,
+ "recharge": 437,
+ "range": 20
+ },
+ {
+ "program": 43888,
+ "crystal": 43966,
+ "quality": 149,
+ "profession": 10,
+ "minimum": 603,
+ "maximum": 1153,
+ "cost": 204,
+ "attack": 306,
+ "recharge": 418,
+ "range": 20
+ },
+ {
+ "program": 43889,
+ "crystal": 43970,
+ "quality": 146,
+ "profession": 10,
+ "minimum": 596,
+ "maximum": 1117,
+ "cost": 203,
+ "attack": 304,
+ "recharge": 412,
+ "range": 20
+ },
+ {
+ "program": 43890,
+ "crystal": 43958,
+ "quality": 156,
+ "profession": 10,
+ "minimum": 636,
+ "maximum": 1191,
+ "cost": 201,
+ "attack": 311,
+ "recharge": 432,
+ "range": 20
+ },
+ {
+ "program": 82030,
+ "crystal": 82076,
+ "quality": 142,
+ "profession": 2,
+ "minimum": 566,
+ "maximum": 1026,
+ "cost": 257,
+ "attack": 210,
+ "recharge": 829,
+ "range": 20
+ },
+ {
+ "program": 82031,
+ "crystal": 82074,
+ "quality": 129,
+ "profession": 2,
+ "minimum": 443,
+ "maximum": 981,
+ "cost": 257,
+ "attack": 200,
+ "recharge": 799,
+ "range": 20
+ },
+ {
+ "program": 82032,
+ "crystal": 82075,
+ "quality": 99,
+ "profession": 2,
+ "minimum": 350,
+ "maximum": 800,
+ "cost": 235,
+ "attack": 190,
+ "recharge": 769,
+ "range": 20
+ },
+ {
+ "program": 82033,
+ "crystal": 82070,
+ "quality": 20,
+ "profession": 2,
+ "minimum": 92,
+ "maximum": 197,
+ "cost": 98,
+ "attack": 160,
+ "recharge": 679,
+ "range": 20
+ },
+ {
+ "program": 82034,
+ "crystal": 82071,
+ "quality": 10,
+ "profession": 2,
+ "minimum": 55,
+ "maximum": 103,
+ "cost": 60,
+ "attack": 155,
+ "recharge": 564,
+ "range": 20
+ },
+ {
+ "program": 82035,
+ "crystal": 82072,
+ "quality": 43,
+ "profession": 2,
+ "minimum": 181,
+ "maximum": 379,
+ "cost": 156,
+ "attack": 170,
+ "recharge": 709,
+ "range": 20
+ },
+ {
+ "program": 82036,
+ "crystal": 82073,
+ "quality": 73,
+ "profession": 2,
+ "minimum": 291,
+ "maximum": 564,
+ "cost": 202,
+ "attack": 180,
+ "recharge": 739,
+ "range": 20
+ },
+ {
+ "program": 82059,
+ "crystal": 82084,
+ "quality": 162,
+ "profession": 6,
+ "minimum": 598,
+ "maximum": 1077,
+ "cost": 240,
+ "attack": 331,
+ "recharge": 449,
+ "range": 20
+ },
+ {
+ "program": 82060,
+ "crystal": 82090,
+ "quality": 146,
+ "profession": 6,
+ "minimum": 503,
+ "maximum": 980,
+ "cost": 243,
+ "attack": 329,
+ "recharge": 411,
+ "range": 20
+ },
+ {
+ "program": 82061,
+ "crystal": 82083,
+ "quality": 93,
+ "profession": 6,
+ "minimum": 324,
+ "maximum": 684,
+ "cost": 209,
+ "attack": 310,
+ "recharge": 356,
+ "range": 20
+ },
+ {
+ "program": 82062,
+ "crystal": 82087,
+ "quality": 43,
+ "profession": 6,
+ "minimum": 194,
+ "maximum": 303,
+ "cost": 137,
+ "attack": 293,
+ "recharge": 303,
+ "range": 20
+ },
+ {
+ "program": 82063,
+ "crystal": 82080,
+ "quality": 27,
+ "profession": 6,
+ "minimum": 126,
+ "maximum": 191,
+ "cost": 100,
+ "attack": 287,
+ "recharge": 282,
+ "range": 20
+ },
+ {
+ "program": 82064,
+ "crystal": 82082,
+ "quality": 7,
+ "profession": 6,
+ "minimum": 41,
+ "maximum": 72,
+ "cost": 43,
+ "attack": 278,
+ "recharge": 259,
+ "range": 20
+ },
+ {
+ "program": 136672,
+ "crystal": 136700,
+ "quality": 159,
+ "profession": 6,
+ "minimum": 10001,
+ "maximum": 10001,
+ "cost": 1600,
+ "attack": 1300,
+ "recharge": 1300,
+ "range": 20
+ },
+ {
+ "program": 136673,
+ "crystal": 136698,
+ "quality": 176,
+ "profession": 6,
+ "minimum": 668,
+ "maximum": 1153,
+ "cost": 241,
+ "attack": 350,
+ "recharge": 474,
+ "range": 20
+ },
+ {
+ "program": 136674,
+ "crystal": 136696,
+ "quality": 182,
+ "profession": 6,
+ "minimum": 697,
+ "maximum": 1193,
+ "cost": 234,
+ "attack": 357,
+ "recharge": 497,
+ "range": 20
+ },
+ {
+ "program": 136675,
+ "crystal": 136702,
+ "quality": 156,
+ "profession": 6,
+ "minimum": 524,
+ "maximum": 1081,
+ "cost": 241,
+ "attack": 337,
+ "recharge": 436,
+ "range": 20
+ },
+ {
+ "program": 136676,
+ "crystal": 136704,
+ "quality": 153,
+ "profession": 6,
+ "minimum": 500,
+ "maximum": 1054,
+ "cost": 243,
+ "attack": 333,
+ "recharge": 424,
+ "range": 20
+ },
+ {
+ "program": 136677,
+ "crystal": 136706,
+ "quality": 143,
+ "profession": 6,
+ "minimum": 451,
+ "maximum": 965,
+ "cost": 242,
+ "attack": 325,
+ "recharge": 400,
+ "range": 20
+ },
+ {
+ "program": 136678,
+ "crystal": 136703,
+ "quality": 130,
+ "profession": 6,
+ "minimum": 414,
+ "maximum": 907,
+ "cost": 237,
+ "attack": 321,
+ "recharge": 388,
+ "range": 20
+ },
+ {
+ "program": 136679,
+ "crystal": 136691,
+ "quality": 116,
+ "profession": 6,
+ "minimum": 392,
+ "maximum": 814,
+ "cost": 228,
+ "attack": 317,
+ "recharge": 376,
+ "range": 20
+ },
+ {
+ "program": 136680,
+ "crystal": 136705,
+ "quality": 83,
+ "profession": 6,
+ "minimum": 288,
+ "maximum": 569,
+ "cost": 191,
+ "attack": 305,
+ "recharge": 340,
+ "range": 15
+ },
+ {
+ "program": 136681,
+ "crystal": 136695,
+ "quality": 90,
+ "profession": 6,
+ "minimum": 317,
+ "maximum": 621,
+ "cost": 201,
+ "attack": 308,
+ "recharge": 348,
+ "range": 15
+ },
+ {
+ "program": 136682,
+ "crystal": 136694,
+ "quality": 107,
+ "profession": 6,
+ "minimum": 356,
+ "maximum": 746,
+ "cost": 218,
+ "attack": 313,
+ "recharge": 365,
+ "range": 15
+ },
+ {
+ "program": 136683,
+ "crystal": 136697,
+ "quality": 74,
+ "profession": 6,
+ "minimum": 253,
+ "maximum": 511,
+ "cost": 179,
+ "attack": 302,
+ "recharge": 330,
+ "range": 15
+ },
+ {
+ "program": 136684,
+ "crystal": 136693,
+ "quality": 64,
+ "profession": 6,
+ "minimum": 217,
+ "maximum": 453,
+ "cost": 166,
+ "attack": 299,
+ "recharge": 321,
+ "range": 15
+ },
+ {
+ "program": 136685,
+ "crystal": 136707,
+ "quality": 50,
+ "profession": 6,
+ "minimum": 186,
+ "maximum": 391,
+ "cost": 151,
+ "attack": 295,
+ "recharge": 311,
+ "range": 15
+ },
+ {
+ "program": 136686,
+ "crystal": 136692,
+ "quality": 41,
+ "profession": 6,
+ "minimum": 141,
+ "maximum": 288,
+ "cost": 124,
+ "attack": 290,
+ "recharge": 296,
+ "range": 15
+ },
+ {
+ "program": 136687,
+ "crystal": 136690,
+ "quality": 14,
+ "profession": 6,
+ "minimum": 66,
+ "maximum": 113,
+ "cost": 64,
+ "attack": 281,
+ "recharge": 267,
+ "range": 15
+ },
+ {
+ "program": 136688,
+ "crystal": 136701,
+ "quality": 21,
+ "profession": 6,
+ "minimum": 87,
+ "maximum": 158,
+ "cost": 83,
+ "attack": 283,
+ "recharge": 274,
+ "range": 15
+ },
+ {
+ "program": 136689,
+ "crystal": 136699,
+ "quality": 34,
+ "profession": 6,
+ "minimum": 119,
+ "maximum": 259,
+ "cost": 114,
+ "attack": 288,
+ "recharge": 290,
+ "range": 15
+ },
+ {
+ "program": 143908,
+ "crystal": 143909,
+ "quality": 169,
+ "profession": 6,
+ "minimum": 614,
+ "maximum": 1142,
+ "cost": 241,
+ "attack": 346,
+ "recharge": 462,
+ "range": 20
+ }
+]
diff --git a/tools/client/test_healing.mjs b/tools/client/test_healing.mjs
@@ -0,0 +1,101 @@
+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', headless: false,
+ 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 state = async () => (await games[0].page.request.get(url + '/test-state')).json();
+const actor = (game, id) => game.state.actors.find(actor => actor.type === 50000 && actor.id === id);
+const pending = (game, id) => actor(game, id)?.weapons.some(weapon => weapon.pending.length);
+const waitState = async (label, predicate) => {
+ const deadline = Date.now() + 10000;
+ for (;;) {
+ const current = await state();
+ if (predicate(current)) return current;
+ assert(Date.now() < deadline, 'Timed out waiting for ' + label);
+ await games[0].snapshot();
+ }
+};
+try {
+ // Load the observer first so the caster's regeneration phase stays outside this short check.
+ for (const index of [1, 0]) {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'healing-' + index, url}]);
+ const page = await context.newPage();
+ const game = await GameTest.attach(page);
+ games[index] = game;
+ await page.goto(url);
+ await game.ready();
+ }
+ const [owner] = games;
+ const initial = await state();
+ evidence.initial = initial;
+ await Promise.all(games.map(game => game.wait('both patients and the Leet', () =>
+ actor(game, initial.owner) && actor(game, initial.observer) && actor(game, initial.enemy))));
+ await owner.key('KeyI');
+ await owner.click(681, 45, 'right');
+ await owner.wait('Doctor crystal learned', snapshot => owner.local(snapshot).inventory.length === 0);
+ await owner.page.keyboard.press('Control+8');
+ await owner.click(974, 76);
+ await owner.key('F1');
+ await owner.save(output + '/ready');
+
+ // Ordinary movement cancels the first cast and refunds its reservation.
+ await owner.click(857, 128, 'right');
+ await waitState('first healing cast', state => state.cast !== null);
+ assert.equal((await state()).reserved, 13);
+ await owner.key('KeyW');
+ await waitState('movement cancellation and refund', state => state.cast === null && state.nano === 50 && state.reserved === 0);
+ assert.equal((await state()).health, 200);
+ await owner.wait('refunded native nano', snapshot => owner.local(snapshot).stats[214] === 50);
+ evidence.cancelled = await state();
+ await owner.save(output + '/cancelled');
+
+ const sequence = owner.sequence;
+ await owner.click(857, 128, 'right');
+ await waitState('second healing cast near completion', state => state.cast && Date.now() >= Date.parse(state.cast.readyAt) - 500);
+ assert.equal((await owner.page.request.post(url + '/test-attack')).status(), 204);
+ evidence.pending = {server: await state()};
+ assert(evidence.pending.server.cast !== null);
+ assert(evidence.pending.server.health < 200);
+ await Promise.all(games.map(game => game.wait('incoming result before heal completion', () => pending(game, initial.enemy))));
+ evidence.pending.clients = games.map(game => ({health: actor(game, initial.owner).stats[27], enemy: actor(game, initial.enemy)}));
+ assert(evidence.pending.clients.every(client => client.health === 200));
+ await Promise.all(games.map(async game => {
+ await game.wait('healing completes before queued impact', () => actor(game, initial.owner).stats[27] !== 200 && pending(game, initial.enemy));
+ return {health: actor(game, initial.owner).stats[27], enemy: actor(game, initial.enemy)};
+ })).then(clients => { evidence.beforeImpact = clients; });
+ const healed = await state();
+ evidence.healed = healed;
+ assert(healed.health >= evidence.pending.server.health + 16 && healed.health <= evidence.pending.server.health + 30);
+ assert.equal(healed.nano, 37);
+ assert.equal(healed.reserved, 0);
+ assert.equal(healed.cast, null);
+ assert(evidence.beforeImpact.every(client => client.health === healed.health));
+ assert.equal(healed.nextAttack, evidence.pending.server.nextAttack);
+ assert.equal(healed.weaponRecharge, evidence.pending.server.weaponRecharge);
+ await Promise.all(games.map(game => game.wait('healed health remains after impact', () =>
+ actor(game, initial.owner).stats[27] === healed.health && !pending(game, initial.enemy))));
+ evidence.afterImpact = games.map(game => ({health: actor(game, initial.owner).stats[27], enemy: actor(game, initial.enemy)}));
+ await owner.wait('native nano debit', snapshot => owner.local(snapshot).stats[214] === 37);
+ const results = owner.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' &&
+ ['46002f16', '5c654b28'].includes(event.opcode));
+ assert.equal(results.length, 1);
+ const actions = owner.events.filter(event => event.direction === 'framereceived' && event.opcode === '5e477770')
+ .map(event => Buffer.from(event.hex, 'hex').readUInt32BE(29));
+ assert.equal(actions.filter(action => action === 18).length, 2);
+ assert.equal(actions.filter(action => action === 108).length, 1);
+ assert.equal(actions.filter(action => action === 107).length, 1);
+ assert(games.every(game => game.errors.length === 0));
+ console.log('PASS: native Doctor upload, cancellation/refund, timed combat heal and both clients retain healed HP after the original impact');
+} finally {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2));
+ try { await Promise.all(games.map((game, index) => game.save(output + '/final-' + index))); }
+ finally { await browser.close(); }
+}