aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 1d41bd899e17fa05f2dbd90bcc2b722191ad691a
parent 2ebdd3875f33a8d377688b4b9ce17d82f154d812
Author: anon <anon@example.com>
Date:   Fri,  6 Nov 2026 00:17:22 +0000

Enable Trader starter team healing and persistent health debt

Diffstat:
MTODO.md | 12++++++++++++
Mdocs/early-shop-stock.md | 8+++++---
Mdocs/nano-health-drains.md | 4++--
Adocs/trader-health-payment.md | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_health_payment_test.go | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_buffs.go | 10+++++++---
Mserver/nano_casting.go | 18++++++++++++++++--
Aserver/nano_health_payment.go | 124+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/nano_health_payment_test.go | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/nano_learning.go | 2+-
Mserver/nano_periodic.go | 31++++++++++++++++++++++++++++---
Atools/client/test_health_payment.mjs | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 739 insertions(+), 14 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -133,6 +133,9 @@ research separately. More screenshots and test cases do not count as new gamepla provisional profile. Their original requirements, costs and lifetimes remain intact; purchase/use and recovery checks are described in [the stock ledger](docs/early-shop-stock.md#meta-physicist-pet-upgrades). + Trader's issued Weak Delayed Health Payment now supports its complete team + heal and non-removable caster debt, with atomic settlement, expiry and + recovery; see [the contract and provisional targeting rules](docs/trader-health-payment.md). Remaining profession essentials and the bounded ordinary-play affordability check stay open. New mission offers now pay an explicit provisional 500 credits per selected mission level; @@ -210,6 +213,15 @@ rewriting this document does not close them. ## P1: bounded follow-up work +- [ ] **Update the pending-cast admin item-edit regression for live inventory edits.** + `TestNanoReservationItemEditCommitsRefundWithActorReload` still expects an + actor reload and refund when changing a carried kit's count. The current + `liveInventoryEdit_locked` path deliberately preserves the actor and cast. + November 5: both subcases fail identically in the pre-Trader-change binary + and the current nano regression batch. Cover reservation preservation and + later settlement for a live edit, while retaining a real actor-reload/refund + case and rejected-write checks. Completion: both edit paths have passing + assertions for exactly one cost or refund and no partial item mutation. - [ ] **Keep account UI changes in the browser source when publishing.** November 5: publishing the door-observation client exposed existing drift between `client/browser/index.html` and the checked-in served page: regeneration diff --git a/docs/early-shop-stock.md b/docs/early-shop-stock.md @@ -311,9 +311,11 @@ model/balance rules. Meta-Physicist [Mind Pain](nano-initiative-debuffs.md#meta-physicist-starter-mind-pain) (29193 -> 29114) now supports its complete damage and linked six-skill debuff. [Lesser Anger Manifestation](pet-attack.md) now supports pet attack commands, -owner rewards and retaliation as well as summon/follow/removal. Trader Weak -Delayed Health Payment (43378 -> 43374) is also unsupported, though its separate starter Weak -Health Funnel is supported. None of those incomplete crystals is sold here. +owner rewards and retaliation as well as summon/follow/removal. Trader +[Weak Delayed Health Payment](trader-health-payment.md) (43378 -> 43374) now +supports its complete team heal and caster debt, alongside the separate starter +Weak Health Funnel. These startup crystals are issued rather than added to this +upgrade catalog. Symbol Helper (29192 -> 29113) was considered for Meta-Physicist stock but rejected: its Psychological Modification/Sensory Improvement requirements exceed the diff --git a/docs/nano-health-drains.md b/docs/nano-health-drains.md @@ -4,8 +4,8 @@ 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. +[Weak Delayed Health Payment 43374](trader-health-payment.md) is a separate +supported team-heal/self-damage contract. ## Original contract diff --git a/docs/trader-health-payment.md b/docs/trader-health-payment.md @@ -0,0 +1,84 @@ +# Trader starter team healing + +The issued Weak Delayed Health Payment crystal 43378 now uploads program 43374. +Its team heal and caster debt execute together. This resolves the A5 starter +crystal rejection; it does not add the broader Trader team-heal catalog or prove +ordinary-play affordability. + +## Original records and alpha policy + +The complete records are in `server/gamedata/items/items_002.yaml` (crystal) and +`items_167.yaml` (parent and both children): + +| Record | Contract | +| --- | --- | +| 43378 | QL1 crystal, uploads 43374; Biological Metamorphosis >9 and Time & Space >8, Trader | +| 43374 | Caster-scoped functions 53066 -> 43373 and 53051 -> 43372; 15m range, 1.5s base cast, 1s recharge, base nano cost 10 | +| 43373 | Team effect: one HP hit of +11 to +15 | +| 43372 | Caster effect: five energy HP hits of -10 at two-second intervals; 15s lifetime, strain 258, rank 999 | + +The existing cost conversion debits 9 nano without cost modifiers. The debt's +hostile flag excludes its rank from used NCU and prevents manual removal. Its +rank blocks another rank-1 parent cast until the full 15-second effect expires, +including the five seconds after its last damage tick. The parent, heal child +and debt child must all match their supported effect contracts for upload and +casting to be admitted. The instant heal and hostile debt need no free NCU. + +**Team recipient scope and raw self-damage are provisional server policy.** +The caster is always healed, including when solo. Other recipients must be living, +online, ready members of the same team, in the same playfield, within the +parent's modified range and line of sight. Team membership permits mixed-faction +healing; selected nonmembers cannot redirect the formula. Each recipient gets +an independent 11-15 roll, capped at maximum health. The debt deals the recorded +10 HP directly without armor or a PvP reduction. Original server code for the +team recipient selection and self-damage mitigation has not been recovered. +These rules provide a complete bounded implementation, not a claim of exact +historical server behavior. No additional historical search was needed here. + +## Persistence and lifecycle + +All healed HP, the debt, the reserved nano settlement and recharge commit in one +transaction before any success is published. A failed write heals nobody and +refunds the reservation. Debt ticks save HP and tick progress together; rejected +writes retry without skipping or doubling damage. Lethal debt uses the existing +player death/reclaim transaction and grants no combat rewards. + +The player periodic-nano path orders debt and healing ticks by deadline. Debt +pauses with other player nanos on logout, resumes on login, and restores its +remaining duration and tick delay after cold startup. Reconnection cannot remove +the debt or turn the team heal into a free repeatable heal. + +## Verification + +`TestHealthPaymentStarterCrystalHealsAndSchedulesDebt` first reproduced the +issued crystal's rejection. The focused checks cover upload, solo healing, +eligible/ineligible teammates and bystanders, mixed factions, exact tick timing, +removal/recast refusal, expiry, lethal debt, cold state, and rejected/ignored +cast and tick writes with retry. Altering any linked effect rejects the formula. +The full-NCU case also passes without charging NCU for the instant heal. + +`TestBrowserHealthPayment` uses a controlled two-player team and real native +crystal upload and program clicks. It compares both clients' healed HP with the +server, checks self-damage across reconnect, waits for expiry, casts again and +checks cold recovery with another debt still pending. This uses seeded health, +skills and nano; it is not earned progression or an affordability sample. + +The final focused batch passes 22 roots and 132 results, including existing +healing-over-time and player-death regressions. The broader batch passes 143 +roots and 2,677 results, with one unrelated failing root: +`TestNanoReservationItemEditCommitsRefundWithActorReload`. Its two failures also +reproduce in the retained pre-change binary. That test expects item edits to +reload the actor, while the current live inventory-edit path preserves the +pending cast; the separate P1 TODO records the required regression update. +Logs are `local/alpha-health-payment/final-focused.log`, `regressions.log` and +`baseline-admin-reservation.log`. `go vet ./server/...`, JavaScript syntax and +diff checks pass. + +The final native run passes in 36.50 seconds, with captures and authoritative +snapshots under `local/health-payment/20261105-161622/` and the log at +`local/alpha-health-payment/browser-final.log`. From 100 HP each, the first cast +healed the caster to 112 and teammate to 113; the caster then paid exactly 50 HP. +After expiry, the second cast healed them to 73/127. Its first tick left the +caster at 63 HP with four ticks pending and 82 nano. Cold startup retained those +values and the paused interval. Native heal/damage feedback and both recipient +views were inspected. Test servers and Chromium processes were closed. diff --git a/server/browser_health_payment_test.go b/server/browser_health_payment_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserHealthPayment(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for native Trader team healing and debt") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/health-payment", time.Now().Format("20060102-150405")) + world := newBrowserPetWorld(t) + for _, id := range []uint32{1, 2} { + player := world.characters[id] + player.profession, player.level = 7, 10 + player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 55, 50 + player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 10, 9 + player.health, player.nano, player.inventory.LearnedNanos = 100, 100, nil + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + world.clients[id] = &worldClient{id: id, conn: &combatTestConn{}, ready: true, target: true} + } + formTestTeam(t, world, 1, 2) + delete(world.clients, 1) + delete(world.clients, 2) + if ok, err := world.grantItem_locked(world.characters[1], 43378); err != nil || !ok { + t.Fatal(ok, 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() + owner, member := world.characters[1], world.characters[2] + var ticks uint32 + if len(owner.activeNanos) != 0 { + ticks = owner.activeNanos[0].ticksLeft + } + json.NewEncoder(w).Encode(map[string]any{"health": owner.health, "memberHealth": member.health, + "nano": owner.nano, "reserved": owner.nanoReserved, "ticks": ticks, "active": len(owner.activeNanos), + "learned": owner.inventory.LearnedNanos, "items": len(owner.inventory.Items)}) + }) + host := httptest.NewServer(mux) + defer host.Close() + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + 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_payment.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + cancel() + <-stopped + closeTestSessions(t, world) + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } + + // Pending debt, healed teammates and two exact debits survive cold recovery. + cold := newServerForTest(t) + owner, saved := world.characters[1], cold.characters[1] + if saved.health != owner.health || saved.nano != 82 || saved.nanoReserved != 0 || len(saved.inventory.Items) != 0 || + len(saved.activeNanos) != 1 || saved.activeNanos[0].program != 43372 || saved.activeNanos[0].ticksLeft != owner.activeNanos[0].ticksLeft || + saved.activeNanos[0].tickDelay != owner.activeNanos[0].tickDelay || cold.characters[2].health != world.characters[2].health { + t.Fatal("native team heal or pending debt changed on cold recovery") + } +} diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -320,7 +320,8 @@ func (server *server) loadActiveNanos() error { } periodic := damageOverTimeNano(effect.program) healing := healingOverTimeNano(effect.program) - if effect.program != 157490 && !statBuffNano(effect.program) && !passiveDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil { + payment := effect.program == 43372 && delayedHealthPaymentNano(43374) + if effect.program != 157490 && !payment && !statBuffNano(effect.program) && !passiveDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil { return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program) } if periodic != nil { @@ -330,8 +331,11 @@ func (server *server) loadActiveNanos() error { if effect.ticksLeft != 0 { effect.nextTick = now.Add(delay) } - } else if healing != nil { - if server.characters[id].npc || server.characters[effect.caster] == nil || effect.ticksLeft > healing.TickCount { + } else if healing != nil || payment { + if payment { + healing = &(*gamedata.NanoTemplates[43372].Sections[2].Functions)[0] + } + if server.characters[id].npc || server.characters[effect.caster] == nil || effect.ticksLeft > healing.TickCount || payment && effect.caster != id { return fmt.Errorf("character %d has invalid healing nano %d", id, effect.program) } effect.tickDelay = delay diff --git a/server/nano_casting.go b/server/nano_casting.go @@ -86,7 +86,7 @@ func (player *character) nanoCastDelay(program uint32) time.Duration { 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) && !engineerShellNano(program) { + damageOverTimeNano(program) == nil && controlNano(program) == nil && !statBuffNano(program) && !petSummonNano(program) && !engineerShellNano(program) && !delayedHealthPaymentNano(program) { return false } for _, section := range gamedata.NanoTemplates[program].Sections { @@ -125,6 +125,10 @@ func (server *server) nanoTarget_locked(player, target *character, client *world if petSummonNano(program) { return target == player && len(player.pets) == 0 } + if delayedHealthPaymentNano(program) { + // The instant team heal uses no NCU; only its existing debt blocks recasting. + return target == player && !slices.ContainsFunc(player.activeNanos, func(effect activeNano) bool { return effect.program == 43372 }) + } if engineerShellNano(program) { return target == player && player.inventory.Credits >= 4 && player.inventory.freeSlot() < 94 && !player.inventory.carriesUnique(ownedItem{Type: 51005, Template: 43328, Quality: 1}) @@ -185,7 +189,7 @@ func (server *server) handleNanoCast(client *worldClient, body []byte) error { program := binary.BigEndian.Uint32(body[32:36]) targetType := binary.BigEndian.Uint32(body[20:24]) target := server.characters[binary.BigEndian.Uint32(body[24:28])] - if petSummonNano(program) || engineerShellNano(program) || statBuffNano(program) && selfOnlyNano(program) { + if petSummonNano(program) || engineerShellNano(program) || delayedHealthPaymentNano(program) || statBuffNano(program) && selfOnlyNano(program) { // Native admission 100646a0 replaces both identity words with the caster. targetType = 50000 target = player @@ -296,6 +300,16 @@ func (server *server) advanceNanos(now time.Time) { caster.nanoReserved = 0 recharge := float64(nanoStat(program, 210)) * float64(float32(0.01)) caster.nanoRechargeUntil = now.Add(time.Duration(recharge * float64(time.Second))) + if delayedHealthPaymentNano(program) { + if err := server.applyHealthPayment_locked(&caster, now, updates); err != nil { + log.Printf("Team health payment: %v", err) + server.abortNano_locked(client, now, updates) + continue + } + client.nanoCast = nil + server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{107, 0, 0, 0, program})) + continue + } if engineerShellNano(program) { item, err := server.createEngineerShell_locked(&caster) if err != nil { diff --git a/server/nano_health_payment.go b/server/nano_health_payment.go @@ -0,0 +1,124 @@ +package main + +import ( + "ao/server/gamedata" + "math/rand/v2" + "slices" + "time" +) + +func delayedHealthPaymentNano(program uint32) bool { + if program != 43374 { + return false + } + // Admit both linked children with the parent; never execute just the heal. + for _, contract := range []struct { + program, flags, sections, effectIndex uint32 + ids, targets, ticks, intervals []uint32 + arguments [][]int32 + }{ + {43374, 16386, 4, 2, []uint32{53066, 53051}, []uint32{1, 1}, []uint32{1, 1}, []uint32{0, 0}, [][]int32{{43373}, {43372}}}, + {43373, 524290, 1, 0, []uint32{53002}, []uint32{3}, []uint32{1}, []uint32{0}, [][]int32{{27, 11, 15, 0}}}, + {43372, 9027586, 3, 2, []uint32{53002}, []uint32{2}, []uint32{5}, []uint32{200}, [][]int32{{27, -10, -10, 92}}}, + } { + definition := gamedata.NanoTemplates[contract.program] + if definition == nil || definition.RecordType != 1040005 || definition.HeaderWords[0] != 51051 || definition.Undecoded != nil || + itemStat(definition, 0) != contract.flags || len(definition.Sections) != int(contract.sections) { + return false + } + section := definition.Sections[contract.effectIndex] + if section.Type != 2 || section.Subtype != 0 || section.Functions == nil || len(*section.Functions) != len(contract.ids) { + return false + } + for index, function := range *section.Functions { + if function.ID != contract.ids[index] || function.HeaderWords != [2]uint32{0, 4} || function.Target != contract.targets[index] || + function.TickCount != contract.ticks[index] || function.TickInterval != contract.intervals[index] || + function.ArgumentHeader != 9 || len(function.Requirements) != 0 || len(function.Arguments) != len(contract.arguments[index]) { + return false + } + for argument, value := range contract.arguments[index] { + if function.Arguments[argument].Integer == nil || *function.Arguments[argument].Integer != value { + return false + } + } + } + } + parent, debt := gamedata.NanoTemplates[43374], gamedata.NanoTemplates[43372] + return itemStat(parent, 75) == 258 && itemStat(parent, 54) == 1 && + itemStat(debt, 75) == 258 && itemStat(debt, 54) == 999 && itemStat(debt, 8) == 1500 && + parent.Sections[3].Type == 22 && parent.Sections[3].Subtype == 36 && parent.Sections[3].Actions != nil && + len(*parent.Sections[3].Actions) == 1 && (*parent.Sections[3].Actions)[0].Type == 3 +} + +func (server *server) applyHealthPayment_locked(caster *character, now time.Time, updates map[*worldClient][][]byte) error { + // Provisional team scope: online living members in the authored 15m range and LOS. + // The caster always participates, including when not in a team. + recipients := []character{*caster} + if caster.team != nil { + for _, id := range caster.team.members { + if id == caster.id { + continue + } + target, client := server.characters[id], server.clients[id] + if client == nil || !client.ready || client.loading || target.health == 0 || target.playfield != caster.playfield { + continue + } + first, second := predictedPosition_locked(caster, now), predictedPosition_locked(target, now) + x, y, z := first[0]-second[0], first[1]-second[1], first[2]-second[2] + distance := float32(caster.nanoRange(43374)) + if x*x+y*y+z*z <= distance*distance && server.combatVisible_locked(caster, target, now) { + recipients = append(recipients, *target) + } + } + } + for index := range recipients { + recipients[index].health = min(recipients[index].maximumHealth(), recipients[index].health+11+rand.Uint32N(5)) + } + recipients[0].activeNanos = append(slices.Clone(caster.activeNanos), activeNano{ + program: 43372, caster: caster.id, remaining: 15 * time.Second, expiresAt: now.Add(15 * time.Second), + ticksLeft: 5, nextTick: now.Add(2 * time.Second), + }) + + // All recipients, the non-removable debt and the cast cost commit as one result. + db, err := server.database() + if err != nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if err := updateRecord(tx, "characters", caster.id, "nano, nano_reserved, nano_recharge_until", []any{caster.nano, caster.nanoReserved, caster.nanoRechargeUntil}); err != nil { + return err + } + if err := writeActiveNanos(tx, &recipients[0], now); err != nil { + return err + } + for _, recipient := range recipients { + if err := updateRecord(tx, "characters", recipient.id, "health", []any{recipient.health}); err != nil { + return err + } + } + if err := tx.Commit(); err != nil { + return err + } + + for _, recipient := range recipients { + player := server.characters[recipient.id] + restored := recipient.health - player.health + *player = recipient + player.savedVitals.Health = player.health + if player.id == caster.id { + player.savedVitals.Nano, player.savedVitals.NanoReserved, player.savedVitals.NanoRechargeUntil = player.nano, player.nanoReserved, player.nanoRechargeUntil + } + server.queueHealthSnapshot_locked(updates, player) + server.queueTeamResources_locked(updates, player) + updates[server.clients[caster.id]] = append(updates[server.clients[caster.id]], characterActionPacket(caster.id, [5]uint32{130, 50000, player.id, 0, restored})) + if player.id != caster.id { + updates[server.clients[player.id]] = append(updates[server.clients[player.id]], characterActionPacket(player.id, [5]uint32{129, 50000, caster.id, 0, restored})) + } + } + server.queueCombat_locked(updates, caster, caster, characterActionPacket(caster.id, [5]uint32{177, 53019, 43372, caster.id, 1500})) + return nil +} diff --git a/server/nano_health_payment_test.go b/server/nano_health_payment_test.go @@ -0,0 +1,284 @@ +package main + +import ( + "ao/server/gamedata" + "slices" + "testing" + "time" +) + +func newHealthPaymentWorld(t *testing.T) *server { + t.Helper() + world, _ := newTeamWorld(t) + for _, player := range world.characters { + player.profession, player.level = 7, 10 + player.stats.Body.BodyDevelopment = 55 + player.stats.NanoAiding.BiologicalMetamorphosis = 10 + player.stats.NanoAiding.TimeAndSpace = 9 + player.health, player.nano = 100, 30 + player.inventory.LearnedNanos = []uint32{43374} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + } + formTestTeam(t, world, 1, 2) + return world +} + +func TestHealthPaymentStarterCrystalHealsAndSchedulesDebt(t *testing.T) { + world, _ := newNanoCastingWorld(t) + player, client := world.characters[1], world.clients[1] + player.profession = 7 + player.stats.NanoAiding.BiologicalMetamorphosis = 10 + player.stats.NanoAiding.TimeAndSpace = 9 + player.health, player.nano, player.inventory.LearnedNanos = 20, 30, nil + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if granted, err := world.grantItem_locked(player, 43378); 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{43374}) { + t.Fatal("issued Weak Delayed Health Payment crystal was not learned") + } + if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 0, 0, 53019, 43374})[20:]); err != nil || client.nanoCast == nil { + t.Fatal("starter team heal was not admitted", err) + } + completed := client.nanoCast.readyAt.Add(time.Nanosecond) + world.advanceNanos(completed) + + if player.health < 31 || player.health > 35 || player.nano != 21 || len(player.activeNanos) != 1 || + player.activeNanos[0].program != 43372 || player.activeNanos[0].ticksLeft != 5 || player.usedNCU() != 0 { + t.Fatal("team heal or caster debt changed", player.health, player.nano, player.activeNanos) + } +} + +func TestHealthPaymentHealsOnlyEligibleTeamMembers(t *testing.T) { + for _, scenario := range []string{"nearby", "other faction", "far", "vertical", "zone", "dead", "offline", "loading"} { + t.Run(scenario, func(t *testing.T) { + world := newHealthPaymentWorld(t) + patient := world.characters[2] + switch scenario { + case "other faction": + patient.appearance = 0x515 + case "far": + patient.position[0] += 16 + case "vertical": + patient.position[1] += 16 + case "zone": + patient.playfield++ + case "dead": + patient.health = 0 + case "offline": + delete(world.clients, 2) + case "loading": + world.clients[2].loading = true + } + before := patient.health + + // A selected nonmember cannot redirect the self-scoped team formula. + castTestBuff(t, world, 1, 3, 43374) + + if scenario == "nearby" || scenario == "other faction" { + if patient.health < 111 || patient.health > 115 { + t.Fatal("eligible teammate did not receive the authored heal", patient.health) + } + } else if patient.health != before { + t.Fatal("ineligible teammate was healed", patient.health) + } + if world.characters[3].health != 100 || len(patient.activeNanos) != 0 || world.characters[1].health < 111 || world.characters[1].health > 115 { + t.Fatal("team heal selected a bystander, omitted caster or charged teammate") + } + }) + } +} + +func TestHealthPaymentDebtTicksAndBlocksRecastUntilExpiry(t *testing.T) { + world := newHealthPaymentWorld(t) + player, client := world.characters[1], world.clients[1] + at := castTestBuff(t, world, 1, 1, 43374) + health := player.health + + world.advanceNanos(at.Add(2*time.Second - time.Nanosecond)) + if player.health != health { + t.Fatal("debt ticked before the authored interval") + } + world.advanceNanos(at.Add(2 * time.Second)) + cold := newTestInventoryServer(t).characters[1] + if player.health != health-10 || cold.health != player.health || cold.activeNanos[0].ticksLeft != 4 { + t.Fatal("debt tick or durable progress differs", player.health, cold.activeNanos) + } + world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 43372})[20:]) + world.advanceNanos(at.Add(10 * time.Second)) + player.nanoRechargeUntil = time.Time{} + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 43374})[20:]) + + if player.health != health-50 || player.nano != 21 || len(player.activeNanos) != 1 || player.activeNanos[0].ticksLeft != 0 || client.nanoCast != nil { + t.Fatal("debt was removable, repeated ticks or allowed early recast") + } + world.advanceNanos(at.Add(15*time.Second - time.Nanosecond)) + if len(player.activeNanos) != 1 { + t.Fatal("recast restriction expired before 15 seconds") + } + world.advanceNanos(at.Add(15 * time.Second)) + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 43374})[20:]) + if len(player.activeNanos) != 0 || client.nanoCast == nil { + t.Fatal("debt did not expire or a new cast stayed blocked") + } +} + +func TestHealthPaymentDebtDeathPersistsWithoutRewards(t *testing.T) { + world := newHealthPaymentWorld(t) + player := world.characters[1] + player.health = 1 + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + at := castTestBuff(t, world, 1, 1, 43374) + + world.advanceNanos(at.Add(4 * time.Second)) + cold := newTestInventoryServer(t).characters[1] + + if player.health != 0 || cold.health != 0 || player.experience != 0 || cold.experience != 0 || + len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || world.characters[2].health < 111 { + t.Fatal("self-damage death lost debt, granted XP or undid the team heal") + } +} + +func TestHealthPaymentDoesNotRequireFreeNCU(t *testing.T) { + world := newHealthPaymentWorld(t) + player := world.characters[1] + // Pre-existing buffs occupy the ordinary eight NCU slots. + player.activeNanos = []activeNano{ + {program: 26342, caster: 1, remaining: time.Minute}, + {program: 27086, caster: 1, remaining: time.Minute}, + {program: 26360, caster: 1, remaining: time.Minute}, + } + if player.usedNCU() != 8 || player.maximumNCU() != 8 { + t.Fatal("fixture has free NCU") + } + + castTestBuff(t, world, 1, 1, 43374) + + if player.health < 111 || player.nano != 21 || len(player.activeNanos) != 4 || player.usedNCU() != 8 { + t.Fatal("instant team heal required free NCU") + } +} + +func TestHealthPaymentOutcomeFailureIsAtomic(t *testing.T) { + for _, failure := range []string{"debt", "ignored debt", "member", "ignored member", "commit"} { + t.Run(failure, func(t *testing.T) { + world := newHealthPaymentWorld(t) + player, client := world.characters[1], world.clients[1] + world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 43374})[20:]) + at := client.nanoCast.readyAt.Add(time.Nanosecond) + statement := "CREATE TRIGGER fail_payment BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(FAIL, 'debt'); END" + switch failure { + case "ignored debt": + statement = "CREATE TRIGGER fail_payment BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(IGNORE); END" + case "member": + statement = "CREATE TRIGGER fail_payment BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'member'); END" + case "ignored member": + statement = "CREATE TRIGGER fail_payment BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(IGNORE); END" + case "commit": + statement = "CREATE TABLE invalid_payment (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_payment AFTER UPDATE OF health ON characters WHEN NEW.id=2 BEGIN INSERT INTO invalid_payment VALUES (999999); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + world.advanceNanos(at) + cold := newTestInventoryServer(t) + + if player.health != 100 || world.characters[2].health != 100 || player.nano != 30 || player.nanoReserved != 0 || + len(player.activeNanos) != 0 || cold.characters[1].health != 100 || cold.characters[2].health != 100 || cold.characters[1].nano != 30 { + t.Fatal("failed team cast published a partial outcome") + } + if _, err := world.db.Exec("DROP TRIGGER fail_payment"); err != nil { + t.Fatal(err) + } + castTestBuff(t, world, 1, 1, 43374) + if player.health < 111 || world.characters[2].health < 111 || player.nano != 21 || len(player.activeNanos) != 1 { + t.Fatal("retry failed or charged twice") + } + }) + } +} + +func TestHealthPaymentRejectsIncompleteLinkedEffects(t *testing.T) { + for _, program := range []uint32{43374, 43373, 43372} { + original := gamedata.NanoTemplates[program] + clone := *original + clone.Sections = slices.Clone(original.Sections) + index := 2 + if program == 43373 { + index = 0 + } + functions := slices.Clone(*clone.Sections[index].Functions) + functions[0].TickCount++ + clone.Sections[index].Functions = &functions + gamedata.NanoTemplates[program] = &clone + + admitted := nanoCrystalProgram(43378) + + gamedata.NanoTemplates[program] = original + if admitted != 0 { + t.Fatal("changed linked contract admitted a partial formula", program) + } + } +} + +func TestHealthPaymentFailedDebtTickRetriesWithoutLosingProgress(t *testing.T) { + for _, failure := range []string{"health", "ignored health", "ticks", "ignored ticks", "death"} { + t.Run(failure, func(t *testing.T) { + world := newHealthPaymentWorld(t) + player := world.characters[1] + at := castTestBuff(t, world, 1, 1, 43374).Add(2 * time.Second) + if failure == "death" { + player.health = 1 + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + } + before := player.health + statement := "CREATE TRIGGER fail_debt BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(FAIL, 'health'); END" + switch failure { + case "ignored health": + statement = "CREATE TRIGGER fail_debt BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(IGNORE); END" + case "ticks": + statement = "CREATE TRIGGER fail_debt BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(FAIL, 'ticks'); END" + case "ignored ticks": + statement = "CREATE TRIGGER fail_debt BEFORE UPDATE ON active_nanos BEGIN SELECT RAISE(IGNORE); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + world.advanceNanos(at) + cold := newTestInventoryServer(t).characters[1] + + if player.health != before || cold.health != before || player.activeNanos[0].ticksLeft != 5 || cold.activeNanos[0].ticksLeft != 5 { + t.Fatal("failed debt tick changed HP or consumed progress") + } + if _, err := world.db.Exec("DROP TRIGGER fail_debt"); err != nil { + t.Fatal(err) + } + world.advanceNanos(at) + world.advanceNanos(at) + if failure == "death" { + if player.health != 0 || len(player.activeNanos) != 0 { + t.Fatal("lethal debt retry did not settle death") + } + } else if player.health != before-10 || player.activeNanos[0].ticksLeft != 4 { + t.Fatal("debt retry lost or duplicated a tick") + } + }) + } +} diff --git a/server/nano_learning.go b/server/nano_learning.go @@ -42,7 +42,7 @@ func nanoCrystalProgram(template uint32) uint32 { return 0 } program = uint32(*function.Arguments[0].Integer) - if !petSummonNano(program) && !engineerShellNano(program) && !statBuffNano(program) && directDamageNano(program) == nil && directHealingNano(program) == nil && healingOverTimeNano(program) == nil && damageOverTimeNano(program) == nil && controlNano(program) == nil { + if !delayedHealthPaymentNano(program) && !petSummonNano(program) && !engineerShellNano(program) && !statBuffNano(program) && directDamageNano(program) == nil && directHealingNano(program) == nil && healingOverTimeNano(program) == nil && damageOverTimeNano(program) == nil && controlNano(program) == nil { return 0 } } diff --git a/server/nano_periodic.go b/server/nano_periodic.go @@ -79,7 +79,8 @@ func (server *server) advanceHealingNanos_locked(now time.Time, updates map[*wor // Commit all due recovery and tick progress before publishing an HP snapshot. candidate := *target candidate.activeNanos = slices.Clone(target.activeNanos) - for { + var packets [][]byte + for candidate.health != 0 { index := -1 for next, effect := range candidate.activeNanos { if effect.ticksLeft != 0 && !effect.nextTick.IsZero() && !effect.nextTick.After(now) && @@ -91,18 +92,42 @@ func (server *server) advanceHealingNanos_locked(now time.Time, updates map[*wor break } effect := &candidate.activeNanos[index] + if effect.program == 43372 { + // The authored debt is five energy hits; raw self-damage is alpha policy. + damage := min(uint32(10), candidate.health) + effect.ticksLeft-- + effect.nextTick = effect.nextTick.Add(2 * time.Second) + candidate = server.prepareDamage_locked(target, &candidate, damage, now) + body := binary.BigEndian.AppendUint32(nil, uint32(-int32(damage))) + body = binary.BigEndian.AppendUint32(body, 92) + packets = append(packets, n3Packet(0x4727213e, 50000, target.id, body)) + continue + } hit := healingOverTimeNano(effect.program) minimum, maximum := uint32(*hit.Arguments[1].Integer), uint32(*hit.Arguments[2].Integer) candidate.health += min(minimum+rand.Uint32N(maximum-minimum+1), candidate.maximumHealth()-candidate.health) effect.ticksLeft-- effect.nextTick = effect.nextTick.Add(time.Duration(hit.TickInterval) * 10 * time.Millisecond) } - if err := server.saveActiveNanos_locked(&candidate, now); err != nil { - log.Printf("Periodic healing outcome: %v", err) + var err error + if candidate.health == 0 { + _, err = server.saveDamageOutcome_locked(&candidate, now) + } else { + err = server.saveActiveNanos_locked(&candidate, now) + } + if err != nil { + log.Printf("Periodic player nano outcome: %v", err) continue } previous := *target *target = candidate + if len(packets) != 0 { + server.queueCombat_locked(updates, target, target, packets...) + server.finishDamageEffects_locked(target, target, previous, now, updates) + if target.health == 0 { + server.queueCombat_locked(updates, target, target, characterActionPacket(target.id, [5]uint32{153, 0, 0, 0, 5})) + } + } if target.health != previous.health { server.queueHealthSnapshot_locked(updates, target) server.queueTeamResources_locked(updates, target) diff --git a/tools/client/test_health_payment.mjs b/tools/client/test_health_payment.mjs @@ -0,0 +1,79 @@ +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 { + for (const index of [1, 0]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'pet-cast-' + index, url}]); + const page = await context.newPage(); + games[index] = await GameTest.attach(page); + await page.goto(url); + await games[index].ready(); + } + const [owner] = games; + const state = async () => (await owner.page.request.get(url + '/test-state')).json(); + const waitState = (label, predicate) => owner.waitFor(label, async () => predicate(await state())); + const cell = (type, id) => owner.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === type && cell.identity[1] === id && !cell.dummy); + const use = async entry => { + assert(entry, 'expected native cell'); + await owner.click((entry.bounds[0] + entry.bounds[2]) / 2, (entry.bounds[1] + entry.bounds[3]) / 2, 'right'); + }; + await owner.key('KeyI'); + await owner.wait('issued crystal in inventory', () => cell(104, 48)); + await use(cell(104, 48)); + await waitState('starter crystal uploaded', state => state.items === 0 && state.learned?.includes(43374)); + await owner.page.keyboard.press('Control+8'); + await owner.click(974, 76); + await owner.wait('team heal in medical programs', () => cell(53019, 43374)); + await owner.key('F1'); + await use(cell(53019, 43374)); + await waitState('heal and debt committed', state => state.active === 1 && state.nano === 91 && state.reserved === 0); + evidence.healed = await state(); + assert(evidence.healed.health >= 111 && evidence.healed.health <= 115); + assert(evidence.healed.memberHealth >= 111 && evidence.healed.memberHealth <= 115); + await Promise.all(games.map((game, index) => game.wait('native recipient HP', snapshot => + game.local(snapshot).stats[27] === (index === 0 ? evidence.healed.health : evidence.healed.memberHealth)))); + await Promise.all(games.map((game, index) => game.save(output + '/healed-' + index))); + await waitState('first self-damage tick', state => state.ticks === 4); + evidence.firstTick = await state(); + assert.equal(evidence.firstTick.health, evidence.healed.health - 10); + + // Real reconnect retains debt. Its expiry permits another ordinary native cast. + await owner.page.reload(); + await owner.ready(); + await waitState('all five debt ticks', state => state.ticks === 0); + evidence.paid = await state(); + assert.equal(evidence.paid.health, evidence.healed.health - 50); + assert.equal(evidence.paid.memberHealth, evidence.healed.memberHealth); + await owner.wait('native caster HP agrees after reconnect', snapshot => owner.local(snapshot).stats[27] === evidence.paid.health); + await waitState('15-second debt expires', state => state.active === 0); + await owner.page.keyboard.press('Control+8'); + await owner.click(974, 76); + await owner.wait('learned team heal after reconnect', () => cell(53019, 43374)); + await owner.key('F1'); + await use(cell(53019, 43374)); + await waitState('second heal starts a new debt', state => state.active === 1 && state.nano === 82 && state.reserved === 0); + evidence.recast = await state(); + assert(evidence.recast.health >= evidence.paid.health + 11 && evidence.recast.health <= evidence.paid.health + 15); + assert(evidence.recast.memberHealth >= evidence.paid.memberHealth + 11 && evidence.recast.memberHealth <= evidence.paid.memberHealth + 15); + await waitState('new debt first tick', state => state.ticks === 4); + evidence.pending = await state(); + assert.equal(evidence.pending.health, evidence.recast.health - 10); + assert(games.every(game => game.errors.length === 0)); + console.log('PASS: native Trader upload, two-recipient heal, exact self-damage, reconnect, expiry and recast'); +} 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(); } +}