aorecomp

Anarchy Online classic in the browser

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


commit 33633e67765e38f702d20e1f3f074b0b91490203
parent 8582ef2bef1b07739e5ab9f0420aad33d52f597d
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 17:24:03 +0000

Fix First Aid healing through queued weapon impacts

Diffstat:
MAGENTS.md | 21+++++++++++++++++++++
MTODO.md | 36+++++++++++++++++++-----------------
Mclient/Makefile.linux | 2+-
Mclient/game/kkr.dll/lifted-0050.c | 10+++++++++-
Mclient/game/kkr.dll/lifted-0052.c | 2++
Aclient/game/kkr.dll/weapon_health.c | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aclient/game/kkr.dll/weapon_health.h | 10++++++++++
Mclient/runtime/browser_testing.c | 18++++++++++++++++++
Mclient/tests/browser_testing.c | 23+++++++++++++++++++++++
Mclient/tests/critical_result.c | 89++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mdocs/first-aid.md | 42+++++++++++++++++++++++++++++++++++++-----
Mdocs/medical-consumables.md | 8++++++--
Aserver/browser_first_aid_test.go | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/first_aid_test.go | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/resource_kit.go | 14+++++++++++---
Mserver/resource_kit_test.go | 32++++++++++++++------------------
Atools/client/test_first_aid.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 589 insertions(+), 50 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -15,6 +15,27 @@ testing; see `DEVELOPERS.md` under "Browser game testing". Prefer observed state transitions over fixed sleeps and ad hoc WASM memory probes. Keep real browser input coverage and check significant outcomes against server state. +# Focused debugging and verification + +- Before starting work, identify the exact TODO item, the observed failure or + missing behavior, and its completion check. +- Prefer the smallest reproducible scenario. Use controlled fixtures and existing + checkpoints to reach the relevant state; clearly distinguish these from + earned-progression evidence. +- Do not spend time earning levels, farming supplies, or replaying established + gameplay merely to reach a test condition. +- Use short WASM checks to reproduce an issue and verify its fix. Reserve extended + playthroughs for explicitly scoped integration milestones after relevant known + blockers are resolved. +- Default to a 15-minute budget for exploratory manual gameplay. If it has not + reproduced a specific issue or resolved a stated uncertainty, stop that + exploration and reassess the approach. +- Keep historical research bounded to the current implementation question. Record + unresolved evidence gaps and move to another actionable issue instead of + repeating unsuccessful searches. +- Prefer milestones that fix behavior or add a necessary regression over + accumulating more verification of unchanged behavior. + # No server backward compatibility Backward compatibility with earlier development versions of this server is diff --git a/TODO.md b/TODO.md @@ -1376,24 +1376,26 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train recovery. Controlled fixtures establish use, not historical stock or earned acquisition. QL201..399, complete medical stock and combat health-stim delivery remain open. See [medical qualities](docs/medical-quality.md). -- [ ] [P0] Use one First Aid item. Check: it restores the expected health, consumes +- [x] Use one First Aid item. Check: it restores the expected health, consumes the applicable quantity/charge and cannot be reused during its skill lock. - Resolve incoming queued-hit delivery without fake weapon outcomes: two-client - WASM checks reject zero-damage backlog flushing because leftover results alter - native attack presentation. Native queue regression cases now cover the - receive-time drain and empty/nonempty ring behavior; see the research below. - The additional-module audit checked all 50 shipped PE files and seven named - IIR classes beyond KKR, including JJR's inert Heal export. No usable delivery - primitive was found. The bounded historical-capture and period-footage search - also leaves update cadence unresolved; see [combat healing delivery](docs/combat-healing-delivery.md). - The new retail capture lead targets AO18.8.x; its inspected public root - import already excludes the reported recordings. No period heal/impact - correction report was recovered, so neither lead establishes a delivery rule. - This blocks an authored starter recovery option: a normally created Atrox - with trained First Aid 7 self-targeted and used its issued kit during combat, - but retained all three charges. The current resource-kit admission explicitly - excludes health stims, including the complete startup health/nano contract; - this is not resolved by adjusting the UI click or lowering enemy health. + The focused reproduction queued real damage before an absolute heal, then + subtracted it again at impact. The maintained client now records which queued + results the snapshot already includes, preserving their damage, feedback, + animations and attack timing. Regular health stims are enabled through their + complete catalog contracts. A controlled two-client WASM regression uses a + real right-click during the pending hit, checks both clients before/after + impact against server HP, verifies one charge and lock rejection, and leaves + attack scheduling unchanged. This is fixture evidence, not earned acquisition + or recovery of historical server cadence. See [First Aid](docs/first-aid.md). +- [ ] [P0] Execute the issued startup First-Aid kit's complete delayed-use contract. + Check: kit116629 restores both health and nano by5..7 during combat, consumes + one charge, and locks the user's FirstAid123 for40 seconds with both clients + agreeing through queued impact. Its authored ItemDelay294 is2; the current + immediate-use decoder rejects nonzero delays before inspecting its effects. + The regular-kit queued-hit correction removes the prior HP-delivery blocker. + Reproduce with a controlled standing character, First Aid above5 and one + incoming hit; no leveling or supply farming is needed. Preserve both effects + and recover the activation timing instead of silently treating it as instant. - [ ] [P1] Reconcile player HP across native observers during incoming combat and target switches. Check: correlate authoritative HP, weapon queues and recovery with ordinary and increased Body Development, before/after StopFight, zoning diff --git a/client/Makefile.linux b/client/Makefile.linux @@ -689,7 +689,7 @@ build/linux/fling-result: tests/fling_result.c game/kkr.dll/lifted-0053.c runtim test: build/linux/fling-result -build/linux/critical-result: tests/critical_result.c game/kkr.dll/lifted-0034.c game/kkr.dll/lifted-0035.c game/kkr.dll/lifted-0050.c game/kkr.dll/lifted-0051.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h +build/linux/critical-result: tests/critical_result.c game/kkr.dll/weapon_health.c game/kkr.dll/weapon_health.h game/kkr.dll/lifted-0034.c game/kkr.dll/lifted-0035.c game/kkr.dll/lifted-0050.c game/kkr.dll/lifted-0051.c game/kkr.dll/lifted-0052.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h @mkdir -p $(@D) $(CC) $(CPPFLAGS) $(CFLAGS) -ffunction-sections -fdata-sections $(filter %.c,$^) -Wl,--gc-sections -lm -o $@ diff --git a/client/game/kkr.dll/lifted-0050.c b/client/game/kkr.dll/lifted-0050.c @@ -1,5 +1,6 @@ #define RECOMP_GENERATED_CODE #include "recomp_types.h" +#include "kkr.dll/weapon_health.h" #include <math.h> #include <stdio.h> #include <stdlib.h> @@ -10050,6 +10051,7 @@ L_360AACE9: MEM32(esi + 0x10) = edi; /* 0x360AACF2: mov dword ptr [esi + 0x10], edi */ MEM32(esi + 0x14) = ebx; /* 0x360AACF5: mov dword ptr [esi + 0x14], ebx */ MEM32(esi + 0x18) = ebx; /* 0x360AACF8: mov dword ptr [esi + 0x18], ebx */ + weapon_health_forget(esi); RECOMP_ICALL(0x3615FD6Au); /* 0x360AACFB: call 0x3615fd6a */ /* not lifted */ RECOMP_FLAGS_IN(); _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(4); @@ -10107,6 +10109,7 @@ L_360AACE9: MEM32(esi + 0x10) = edi; /* 0x360AACF2: mov dword ptr [esi + 0x10], edi */ MEM32(esi + 0x14) = ebx; /* 0x360AACF5: mov dword ptr [esi + 0x14], ebx */ MEM32(esi + 0x18) = ebx; /* 0x360AACF8: mov dword ptr [esi + 0x18], ebx */ + weapon_health_forget(esi); RECOMP_ICALL(0x3615FD6Au); /* 0x360AACFB: call 0x3615fd6a */ /* not lifted */ RECOMP_FLAGS_IN(); _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(4); @@ -10162,6 +10165,7 @@ L_360AACF2: MEM32(esi + 0x10) = edi; /* 0x360AACF2: mov dword ptr [esi + 0x10], edi */ MEM32(esi + 0x14) = ebx; /* 0x360AACF5: mov dword ptr [esi + 0x14], ebx */ MEM32(esi + 0x18) = ebx; /* 0x360AACF8: mov dword ptr [esi + 0x18], ebx */ + weapon_health_forget(esi); RECOMP_ICALL(0x3615FD6Au); /* 0x360AACFB: call 0x3615fd6a */ /* not lifted */ RECOMP_FLAGS_IN(); _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(4); @@ -10280,6 +10284,7 @@ void sub_360AAD70(void) { RECOMP_ENTER(0x360AAD70u); L_360AAD70: + weapon_health_forget(ecx); PUSH32(esp, ebp); /* 0x360AAD70: push ebp */ ebp = esp; /* 0x360AAD71: mov ebp, esp */ PUSH32(esp, ecx); /* 0x360AAD73: push ecx */ @@ -12291,6 +12296,7 @@ void sub_360AB4C0(void) { RECOMP_ENTER(0x360AB4C0u); L_360AB4C0: + weapon_health_take(ecx, MEM32(ecx + 0x14)); PUSH32(esp, ebp); /* 0x360AB4C0: push ebp */ ebp = esp; /* 0x360AB4C1: mov ebp, esp */ edx = MEM32(ecx + 0x10); /* 0x360AB4C3: mov edx, dword ptr [ecx + 0x10] */ @@ -12477,6 +12483,7 @@ L_360AB580: } void sub_360AB5A0(void) { + int health_included = 0; int _fpu_cmp = 0; uint32_t _cf = 0; int _df = 1; @@ -12510,6 +12517,7 @@ L_360AB5B9: L_360AB5BD: esi = MEM32(ebp + (-0x8)); /* 0x360AB5BD: mov esi, dword ptr [ebp - 8] */ L_360AB5C0: + health_included = weapon_health_take(esi, MEM32(esi + 0x18)); ecx = esi; /* 0x360AB5C0: mov ecx, esi */ RECOMP_ICALL(0x360AB560u); /* 0x360AB5C2: call 0x360ab560 */ /* not lifted */ RECOMP_FLAGS_IN(); @@ -12670,7 +12678,7 @@ L_360AB6A1: RECOMP_FLAGS_IN(); _flag_a = (uint32_t)(eax); _flag_b = (uint32_t)(edi); _cf = (uint32_t)CMP_B(_flag_a, _flag_b); - eax = eax - edi; /* 0x360AB6C6: sub eax, edi */ + if (!health_included) eax = eax - edi; /* 0x360AB6C6: sub eax, edi */ _flag_k = FK_CMP; PUSH32(esp, eax); /* 0x360AB6C8: push eax */ PUSH32(esp, 0x1Bu); /* 0x360AB6C9: push 0x1b */ diff --git a/client/game/kkr.dll/lifted-0052.c b/client/game/kkr.dll/lifted-0052.c @@ -1,5 +1,6 @@ #define RECOMP_GENERATED_CODE #include "recomp_types.h" +#include "kkr.dll/weapon_health.h" #include <math.h> #include <stdio.h> #include <stdlib.h> @@ -6010,6 +6011,7 @@ L_360B0AC3: RECOMP_ICALL(0x3601D0B0u); /* 0x360B0ACA: call 0x3601d0b0 */ /* not lifted */ RECOMP_FLAGS_IN(); L_360B0ACF: + weapon_health_snapshot(MEM32(edi + 4), MEM32(edi + 8)); edx = MEM32(edi + 0x20); /* 0x360B0ACF: mov edx, dword ptr [edi + 0x20] */ eax = MEM32(esi + 0xE4); /* 0x360B0AD2: mov eax, dword ptr [esi + 0xe4] */ ecx = esi + 0xE4; /* 0x360B0AD8: lea ecx, [esi + 0xe4] */ diff --git a/client/game/kkr.dll/weapon_health.c b/client/game/kkr.dll/weapon_health.c @@ -0,0 +1,69 @@ +#include "recomp_types.h" +#include "kkr.dll/weapon_health.h" + +/* Keep animation results intact when an absolute HP update includes their damage. */ +static struct weapon_health { + uint32_t weapon; + uint64_t slots; + struct weapon_health *next; +} *pending; + +void weapon_health_forget(uint32_t weapon) +{ + for (struct weapon_health **entry = &pending; *entry; entry = &(*entry)->next) { + if ((*entry)->weapon != weapon) continue; + struct weapon_health *removed = *entry; + *entry = removed->next; + free(removed); + return; + } +} + +int weapon_health_take(uint32_t weapon, uint32_t slot) +{ + for (struct weapon_health *entry = pending; entry; entry = entry->next) { + if (entry->weapon != weapon) continue; + uint64_t bit = UINT64_C(1) << slot; + int included = (entry->slots & bit) != 0; + entry->slots &= ~bit; + if (!entry->slots) weapon_health_forget(weapon); + return included; + } + return 0; +} + +static void snapshot_weapons(uint32_t node, uint32_t nil, uint32_t type, uint32_t id) +{ + if (node == nil) return; + snapshot_weapons(MEM32(node), nil, type, id); + + /* KKR sub_3607A320's weapons use sub_360AB4C0's fifty-entry result ring. */ + uint32_t actor = MEM32(node + 20); + uint32_t holder = MEM32(node + 12) == 50000 ? MEM32(actor + 0x16c) : 0; + if (holder && MEM32(holder + 0x58) == type && MEM32(holder + 0x5c) == id) { + for (unsigned slot = 0; slot < 16; slot++) { + uint32_t weapon = MEM32(holder + 0x0c + slot * 4); + if (!weapon) continue; + uint64_t slots = 0; + for (uint32_t index = MEM32(weapon + 0x18); index != MEM32(weapon + 0x14); index = (index + 1) % 50) + slots |= UINT64_C(1) << index; + if (!slots) continue; + struct weapon_health *entry = pending; + while (entry && entry->weapon != weapon) entry = entry->next; + if (!entry) { + entry = malloc(sizeof(*entry)); + if (!entry) abort(); + *entry = (struct weapon_health){weapon, 0, pending}; + pending = entry; + } + entry->slots |= slots; + } + } + snapshot_weapons(MEM32(node + 8), nil, type, id); +} + +void weapon_health_snapshot(uint32_t type, uint32_t id) +{ + uint32_t actors = MEM32(0x3806c110); + if (actors) snapshot_weapons(MEM32(MEM32(actors + 4) + 4), MEM32(actors + 8), type, id); +} diff --git a/client/game/kkr.dll/weapon_health.h b/client/game/kkr.dll/weapon_health.h @@ -0,0 +1,10 @@ +#ifndef WEAPON_HEALTH_H +#define WEAPON_HEALTH_H + +#include <stdint.h> + +void weapon_health_snapshot(uint32_t type, uint32_t id); +int weapon_health_take(uint32_t weapon, uint32_t slot); +void weapon_health_forget(uint32_t weapon); + +#endif diff --git a/client/runtime/browser_testing.c b/client/runtime/browser_testing.c @@ -98,6 +98,24 @@ static void actor(FILE *output, uint32_t object, uint32_t type, uint32_t id, int if (i) fputc(',', output); fprintf(output, "%d", (int32_t)MEM32(stats + i * 4)); } + fputs("],\"weapons\":[", output); + unsigned weapons = 0; + if (combat) { + /* KKR sub_360AB5A0 consumes these real results at animation impact. */ + for (unsigned slot = 0; slot < 16; ++slot) { + uint32_t weapon = MEM32(combat + 0x0c + slot * 4); + if (!weapon) continue; + if (weapons++) fputc(',', output); + uint32_t read = MEM32(weapon + 0x18), write = MEM32(weapon + 0x14); + uint32_t results = MEM32(MEM32(weapon + 0x10) + 4); + fprintf(output, "{\"slot\":%u,\"read\":%u,\"write\":%u,\"pending\":[", slot, read, write); + for (uint32_t index = read; index != write; index = (index + 1) % 50) { + if (index != read) fputc(',', output); + fprintf(output, "[%d,%u]", (int32_t)MEM32(results + index * 8), MEM32(results + index * 8 + 4)); + } + fputs("]}", output); + } + } fputc(']', output); if (local) { /* kkr.dll/lifted-0026.c::sub_36052A20 / sub_36052790 enumerate action types. */ diff --git a/client/tests/browser_testing.c b/client/tests/browser_testing.c @@ -97,6 +97,28 @@ static void snapshots_include_reclaim_booths_without_mutation(void) assert(g_eax == 123 && g_esp == 456); } +static void snapshots_preserve_wrapped_weapon_results(void) +{ + MEM32(0x5000116c) = 0x50008100; + MEM32(0x50008124) = 0x50008200; + MEM32(0x50008210) = 0x50008300; + MEM32(0x50008304) = 0x50008400; + MEM32(0x50008214) = 1; + MEM32(0x50008218) = 49; + MEM32(0x50008400 + 49 * 8) = 7; + MEM32(0x50008404 + 49 * 8) = 4; + MEM32(0x50008400) = 13; + MEM32(0x50008404) = 5; + + browser_test_request(); + browser_test_frame(); + + assert(strstr(snapshot, "\"weapons\":[{\"slot\":6,\"read\":49,\"write\":1,\"pending\":[[7,4],[13,5]]}]")); + assert(MEM32(0x50008214) == 1 && MEM32(0x50008218) == 49); + assert(MEM32(0x50008400 + 49 * 8) == 7 && MEM32(0x50008404 + 49 * 8) == 4); + assert(g_eax == 123 && g_esp == 456); +} + static void completed_picks_record_the_query_pixel_and_result(void) { guest_map("test action view", 0x2b0e0000, 0x10000); @@ -170,6 +192,7 @@ int main(void) snapshots_observe_directory_clear_and_new_frames(); snapshots_observe_active_local_actions_without_mutation(); snapshots_include_reclaim_booths_without_mutation(); + snapshots_preserve_wrapped_weapon_results(); free(snapshot); puts("PASS: frame snapshots, native inventory, directory clearing and guest state preservation"); } diff --git a/client/tests/critical_result.c b/client/tests/critical_result.c @@ -12,6 +12,7 @@ void sub_360AB580(void); void sub_360AB5A0(void); void sub_36075DB0(void); void sub_3607BE50(void); +void sub_360B0A50(void); static unsigned reads, writes, feedbacks, generic_feedbacks, deaths, ammo_updates; static unsigned missing_attacker, missing_target, target_local; @@ -69,7 +70,7 @@ static void actor_setter(void) { assert(g_ecx == 0x500020e4); assert(MEM32(g_esp + 4) == 27); - assert(MEM32(g_esp + 8) <= MEM32(0x50002300)); + assert(MEM32(g_esp + 8) <= MEM32(0x50002300) || MEM32(g_esp + 8) == 205); writes++; MEM32(0x50002300) = MEM32(g_esp + 8); g_esp += 12; @@ -109,7 +110,7 @@ static void feedback(void) assert(g_ecx == 0x50000900); assert(MEM32(g_esp + 4) == (target_local ? 30 : 32)); assert(MEM32(g_esp + 8) == 0x50002000); - assert(MEM32(g_esp + 12) == 13 || MEM32(g_esp + 12) == 0); + assert(MEM32(g_esp + 12) == 13 || MEM32(g_esp + 12) == 7 || MEM32(g_esp + 12) == 0); assert(MEM32(g_esp + 16) == 0x50001000); assert(MEM32(g_esp + 20) == 0 && MEM32(g_esp + 24) == 90); assert(MEM32(g_esp + 28) == expected_result); @@ -351,13 +352,95 @@ static void zero_result_backlog(void) } } +static void absolute_health_keeps_real_weapon_results(void) +{ + const struct { unsigned index, late, snapshots, target, health; } cases[] = { + {0, 0, 1, 2, 205}, {49, 0, 2, 2, 205}, + {0, 1, 1, 2, 198}, {0, 0, 1, 3, 198}, {0, 0, 0, 2, 193}, + {49, 2, 1, 2, 198} + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + expected_result = 4; + death_reason = 0; + ammunition = 3; + target_local = 1; + missing_attacker = missing_target = 0; + setup(); + MEM32(0x3806c110) = 0x50009200; + MEM32(0x50009204) = MEM32(0x50009208) = 0x50009220; + MEM32(0x50009224) = 0x50009240; + MEM32(0x50009240) = MEM32(0x50009248) = 0x50009220; + MEM32(0x5000924c) = 50000; + MEM32(0x50009250) = 1; + MEM32(0x50009254) = 0x50001000; + MEM32(0x50002300) = 200; + MEM32(0x50000024) = 7; + MEM32(0x50003050) = 2; + MEM32(0x50003058) = 50000; + MEM32(0x5000305c) = cases[i].target; + MEM32(0x50005014) = MEM32(0x50005018) = cases[i].index; + if (cases[i].late != 1) sub_360AECB0(); + + // Deliver the same absolute HealthDamage update used by resource recovery. + MEM32(0x3616ff70) = 0x3606da90; + MEM32(0x50009004) = 50000; + MEM32(0x50009008) = 2; + MEM32(0x50009020) = 205; + MEM32(0x50009024) = 12; + uint8_t weapon[0x40], results[400]; + memcpy(weapon, (void *)ADDR(0x50005000), sizeof(weapon)); + memcpy(results, (void *)ADDR(0x50008100), sizeof(results)); + + for (unsigned snapshot = 0; snapshot < cases[i].snapshots; ++snapshot) { + g_esp = 0x5000ff00; + g_ecx = 0x50009000; + sub_360B0A50(); + assert(MEM32(0x50002300) == 205); + assert(memcmp(weapon, (void *)ADDR(0x50005000), sizeof(weapon)) == 0); + assert(memcmp(results, (void *)ADDR(0x50008100), sizeof(results)) == 0); + } + if (cases[i].late) { + g_esp = 0x5000ff00; + g_ecx = 0x50000000; + sub_360AECB0(); + } + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 0; + MEM32(g_esp + 8) = 6; + g_ecx = 0x50003000; + sub_3607A2E0(); + + assert(g_esp == 0x5000ff0c); + assert(MEM32(0x50002300) == cases[i].health); + unsigned hits = cases[i].late == 2 ? 2 : 1; + assert(reads == hits && writes == cases[i].snapshots + hits && feedbacks == hits && ammo_updates == hits); + assert(MEM32(0x50005014) == (cases[i].index + hits) % 50); + assert(MEM32(0x50005018) == MEM32(0x50005014)); + assert(MEM32(0x50003050) == 2 && MEM32(0x5000305c) == cases[i].target && deaths == 0); + + // A subsequent real hit must still debit HP normally after the snapshot. + g_esp = 0x5000ff00; + g_ecx = 0x50000000; + sub_360AECB0(); + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = 0; + MEM32(g_esp + 8) = 6; + g_ecx = 0x50003000; + sub_3607A2E0(); + assert(MEM32(0x50002300) == cases[i].health - 7); + assert(reads == hits + 1 && writes == cases[i].snapshots + hits + 1 && feedbacks == hits + 1 && ammo_updates == hits + 1); + } +} + int main(void) { assert(guest_map("critical result fixture", 0x50000000, 0x10000)); assert(guest_map("critical result imports", 0x36160000, 0x20000)); + assert(guest_map("actor directory", 0x38060000, 0x10000)); queued_results(); missing_attacker_results(); backlog_results(); zero_result_backlog(); - puts("native weapon results: impact, backlog drain, zero-result parity, feedback, death and ammo passed"); + absolute_health_keeps_real_weapon_results(); + puts("native weapon results: impact, backlog drain, absolute HP reconciliation, feedback, death and ammo passed"); } diff --git a/docs/first-aid.md b/docs/first-aid.md @@ -1,9 +1,10 @@ # First Aid research for 14.9.1 -The First Aid TODO remains open. A tested prototype handles the selected -item's charges, targeting, lock and healing feedback, but an absolute health -update can double-apply an incoming queued weapon hit in the native client. -The prototype is retained locally rather than enabled in the server. +Regular immediate-use health stims are enabled. The maintained client prevents +an absolute HealthDamage snapshot from double-applying already queued weapon +damage at impact. The startup kit remains unsupported because its authored +activation delay requires a separate contract; it is not consumed for only one +of its two effects. Original-server healing cadence remains unresolved. ## Item and skill evidence @@ -72,7 +73,38 @@ in `local/reports/combat-client-pass2-decompiles-9.json`, and executor/gate `ev_f28cc89d25d840908ea753e766d4e2d1a718ef5138b04f190e82062755593b1d` in `local/reports/combat-client-decompiles-19.json`. -## Prototype checks and remaining delivery gap +## Maintained client reconciliation + +`client/game/kkr.dll/weapon_health.c` records the pending ring slots for each +attacker targeting a HealthDamage recipient. The snapshot already includes +these received outcomes. At impact, `sub_360AB5A0` consumes the original result, +feedback and damage amount but omits its second HP debit. Later outcomes debit +HP normally. Append, construction and destruction clear obsolete slot records. +No result, animation state, native timer or ammunition value is synthesized or +rewritten. The server publishes a quiet absolute HP update for accepted health +stims during combat, after committing restoration, charge and user cooldown. + +The red native regression reproduced 205 dropping to198 after a queued7 hit. +The corrected regression covers repeated snapshots, another target, wraparound, +a later real hit and immediate mixed-backlog drain. The read-only browser +snapshot exposes real weapon queues without a separate memory probe. +`TestBrowserFirstAidQueuedHit` and `tools/client/test_first_aid.mjs` create a +controlled two-client scenario, right-click kit23314 while a real Leet result +is pending, require healed HP before impact on both clients, then require both +to retain authoritative HP after impact. They also check one charge, native lock +rejection, no extra weapon result and unchanged server attack deadlines. +Artifacts are retained under `local/first-aid-queued-hit/`; the final fixture +uses level10 and raw Body Development55. This is controlled verification, not +earned progression. The client correction does not establish historical server +publication timing or close the broader HP prediction/observer audit. + +Run the focused hardware-browser check with the normal desktop environment: + +```sh +AO_GAME_TEST=1 go test ./server -run '^TestBrowserFirstAidQueuedHit$' -count=1 -timeout=10m -v +``` + +## Earlier prototype checks and delivery research A native UI-consumer audit confirms that the discrepancy reaches both health displays. Local StatView100424d0 reads Health27 through the mode2 skill getter. diff --git a/docs/medical-consumables.md b/docs/medical-consumables.md @@ -3,10 +3,13 @@ The server decodes immediate resource kits from their catalog functions, requirements, quality, range and lock metadata. There are no template-ID branches for medical use. The full catalog admission test currently identifies -these ten definitions: +these thirteen definitions: | Template / authored QL | Item | Health | Nano | Lock | | --- | --- | ---: | ---: | --- | +| 23314 / 1 | Simple First-Aid Kit | 10..12 | 0 | User First Aid 123, 40s | +| 23316 / 200 | Simple First-Aid Kit | 1000 | 0 | User First Aid 123, 40s | +| 160276 / 400 | Ultra Advanced First-Aid Kit | 1400 | 0 | User First Aid 123, 40s | | 25812 / 1 | Treatment Laboratory | 30 | 0 | Patient Treatment 124, 15s | | 25811 / 200 | HQ Health Treatment Laboratory | 1500 | 0 | Patient Treatment 124, 15s | | 160277 / 400 | Superb Quality Health Treatment Laboratory | 5000 | 0 | Patient Treatment 124, 15s | @@ -46,7 +49,8 @@ and does not buff the player's Treatment or First Aid. Every effect is inspected before admission. Unknown functions, conditional or repeating effects, different recipients, unsupported lock skills and positive attack delays remain unsupported. The startup First-Aid Kit116629 must restore -both health and nano during combat; it is not admitted as a nano-only item or +both health and nano during combat and has ItemDelay294=2. Its delayed use is +not implemented; it is not admitted as a nano-only item or given a new combat prohibition. See [First Aid delivery](first-aid.md). Accepted use commits both resource values, one source charge and the proper diff --git a/server/browser_first_aid_test.go b/server/browser_first_aid_test.go @@ -0,0 +1,93 @@ +package main + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" + "time" +) + +func TestBrowserFirstAidQueuedHit(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for the controlled WASM First Aid regression") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/first-aid-queued-hit", time.Now().Format("20060102-150405")) + world := newTestServer(t) + var npc *character + for _, actor := range world.characters { + if actor.npc && actor.playfield == 950 && actor.monsterData == 17655 && actor.level == 1 && actor.combatProfile != nil && (npc == nil || actor.id < npc.id) { + npc = actor + } + } + if npc == nil { + t.Fatal("no level-one Leet for controlled reproduction") + } + players := []*character{} + for i := 0; i < 2; i++ { + player := world.newCharacter() + player.name, player.level, player.profession, player.appearance = fmt.Sprint("First Aid ", i), 10, 9, 0x315 + player.position, player.rotation = npc.position, [4]float32{0, 0, 0, 1} + player.position[2] -= float32(2 + i*3) + player.stats.Body.BodyDevelopment = 55 + player.stats.NanoAiding.FirstAid = 7 + player.health = 200 + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("first-aid-", i)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + players = append(players, player) + } + if granted, err := world.grantItem_locked(players[0], 23314); !granted || err != nil { + t.Fatal(granted, err) + } + players[0].inventory.Items[0].Count = 3 + if err := world.saveInventory_locked(players[0], players[0].inventory); err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"owner": players[0].id, "observer": players[1].id, "npc": npc.id, + "health": players[0].health, "maximumHealth": players[0].maximumHealth(), "inventory": players[0].inventory, + "fighting": npc.fighting, "nextAttack": npc.nextAttack, "rechargeUntil": npc.rechargeUntil, "lock": players[0].skillLocks[123]}) + }) + // Controlled setup, not earned progression. Advance one production attack on + // demand; no regeneration or later swings obscure the ordering. + mux.HandleFunc("POST /test-attack", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + world.mutex.Lock() + updates := make(map[*worldClient][][]byte) + world.startAttack_locked(npc, players[0], time.Now(), updates) + deadline := npc.nextAttack + world.mutex.Unlock() + world.sendCombatUpdates(updates) + world.updateMutex.Unlock() + world.advanceCombat(deadline) + w.WriteHeader(http.StatusNoContent) + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Minute) + defer cancel() + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_first_aid.mjs"), host.URL, output) + command.Dir = root + command.Stdout, command.Stderr = os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + if err != nil { + t.Fatal(err) + } +} diff --git a/server/first_aid_test.go b/server/first_aid_test.go @@ -0,0 +1,82 @@ +package main + +import ( + "encoding/binary" + "fmt" + "reflect" + "testing" + "time" +) + +func TestFirstAidHealthCommitsDuringCombat(t *testing.T) { + for _, other := range []bool{false, true} { + for _, count := range []uint16{1, 3} { + for _, clamp := range []bool{false, true} { + t.Run(fmt.Sprintf("other%t/count%d/clamp%t", other, count, clamp), func(t *testing.T) { + world, target, _ := newStartupLaboratoryWorld(t, other) + player, client := world.characters[1], world.clients[1] + player.stats.NanoAiding.FirstAid = 7 + player.inventory.Items[0].Template, player.inventory.Items[0].Count = 23314, count + player.fighting, target.fighting, target.sitting = 1000000, 1000000, false + if clamp { + target.health = target.maximumHealth() - 1 + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("UPDATE characters SET health=? WHERE id=?", target.health, target.id); err != nil { + t.Fatal(err) + } + conn := &consumableCommitConn{db: world.db, target: target.id} + client.conn = conn + started := time.Now() + + err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + restored := newTestInventoryServer(t) + + if err != nil || !conn.observed || conn.err != nil || conn.count != count-1 || + conn.health != target.health || conn.nano != 1 || !conn.firstAid.Valid || conn.patient.Valid || + restored.characters[target.id].health != target.health || target.nano != 1 || + count > 1 && !reflect.DeepEqual(restored.characters[1].inventory.Items, player.inventory.Items) || + !restored.characters[1].skillLocks[123].Equal(player.skillLocks[123]) { + t.Fatal("health, charge and user lock were not committed before success", err, conn.err) + } + if clamp && target.health != target.maximumHealth() || !clamp && (target.health < 11 || target.health > 13) { + t.Fatal("First Aid differs from the authored 10..12 HP or maximum clamp", target.health) + } + if player.skillLocks[123].Before(started.Add(40*time.Second)) || player.skillLocks[123].After(time.Now().Add(40*time.Second)) || + player.fighting != 1000000 || target.fighting != 1000000 || other && !target.skillLocks[123].IsZero() { + t.Fatal("First Aid changed combat or locked the patient") + } + if count == 1 && (len(player.inventory.Items) != 0 || len(restored.items) != 0) || count == 3 && player.inventory.Items[0].Count != 2 { + t.Fatal("First Aid did not consume exactly one charge") + } + healthPackets := 0 + for _, packet := range conn.packets { + if binary.BigEndian.Uint32(packet[16:20]) == 0x3710256c { + healthPackets++ + if binary.BigEndian.Uint32(packet[24:28]) != target.id || binary.BigEndian.Uint32(packet[29:33]) != target.health { + t.Fatal("combat health snapshot differs from the committed patient HP") + } + } + } + if healthPackets != 1 { + t.Fatal("First Aid suppressed or repeated the combat HP update", healthPackets) + } + + // A replay and a new request during the shared First Aid lock cannot debit again. + before, _ := readTestItemStore(world) + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) + world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 2)[20:]) + after, _ := readTestItemStore(world) + if string(before) != string(after) || target.health != conn.health { + t.Fatal("replay or locked First Aid use changed the committed outcome") + } + }) + } + } + } +} diff --git a/server/resource_kit.go b/server/resource_kit.go @@ -118,8 +118,7 @@ func decodeResourceKit(definition *gamedata.Item) (resourceKit, bool) { return kit, false } if kit.lockSkill == 123 && itemStat(definition, 371) == 0 { - // Combat HP delivery is unresolved; do not consume only a stim's nano half. - return kit, kit.health[1] == 0 + return kit, true } return kit, (kit.lockSkill == 124 || kit.lockSkill == 131) && itemStat(definition, 371) != 0 } @@ -216,7 +215,16 @@ func (server *server) useResourceKit_locked(client *worldClient, index int, body updates := make(map[*worldClient][][]byte) server.queueCombat_locked(updates, player, target, n3Packet(0x35505644, 50000, client.id, action)) if kit.health[1] != 0 { - server.queueQuietHealth_locked(updates, target) + 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)) + } else { + server.queueQuietHealth_locked(updates, target) + } } if item.Count == 1 { var removal []byte diff --git a/server/resource_kit_test.go b/server/resource_kit_test.go @@ -26,7 +26,7 @@ func TestResourceKitCatalogAdmission(t *testing.T) { } slices.Sort(admitted) - if !reflect.DeepEqual(admitted, []uint32{25811, 25812, 25820, 25821, 85366, 85367, 116628, 160277, 160278, 160295}) { + if !reflect.DeepEqual(admitted, []uint32{23314, 23316, 25811, 25812, 25820, 25821, 85366, 85367, 116628, 160276, 160277, 160278, 160295}) { t.Fatal("unexpected medical use contract in the full catalog", admitted) } } @@ -371,24 +371,20 @@ func TestStartupLaboratoryOutputFailurePreservesBothGainsAndPatientLock(t *testi } } -func TestUnimplementedFirstAidNeverConsumesOnlyPartOfItsEffect(t *testing.T) { - for _, template := range []uint32{23314, 116629} { - t.Run(fmt.Sprint(template), func(t *testing.T) { - world, target, conn := newStartupLaboratoryWorld(t, true) - player := world.characters[1] - player.inventory.Items[0].Template, player.inventory.Items[0].Count = template, 1 - if err := world.saveInventory_locked(player, player.inventory); err != nil { - t.Fatal(err) - } - before, _ := readTestItemStore(world) +func TestStartupFirstAidDelayNeverConsumesOnlyPartOfItsEffect(t *testing.T) { + world, target, conn := newStartupLaboratoryWorld(t, true) + player := world.characters[1] + player.inventory.Items[0].Template, player.inventory.Items[0].Count = 116629, 1 + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) - err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) - after, _ := readTestItemStore(world) + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + after, _ := readTestItemStore(world) - if err != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 1 || - !player.skillLocks[123].IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { - t.Fatal("unsupported First Aid partially restored a resource, consumed its last charge or started a lock", err) - } - }) + if err != nil || !bytes.Equal(before, after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 1 || + !player.skillLocks[123].IsZero() || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("unsupported First Aid partially restored a resource, consumed its last charge or started a lock", err) } } diff --git a/tools/client/test_first_aid.mjs b/tools/client/test_first_aid.mjs @@ -0,0 +1,88 @@ +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 server = async () => (await games[0].page.request.get(url + '/test-state')).json(); +const actor = (game, identity) => game.state.actors.find(actor => actor.type === 50000 && actor.id === identity); +const pending = (game, identity) => actor(game, identity)?.weapons.some(weapon => weapon.pending.length); +try { + for (let i = 0; i < 2; ++i) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'first-aid-' + i, url}]); + const page = await context.newPage(); + const game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + } + const [owner, observer] = games; + const initial = await server(); + await Promise.all(games.map(game => game.wait('both clients and the Leet', () => + actor(game, initial.owner) && actor(game, initial.observer) && actor(game, initial.npc)))); + await owner.key('F1'); + await owner.key('KeyI'); + await owner.save(output + '/ready'); + assert.equal(owner.local().inventory[0].templates[0], 23314); + assert.equal(owner.local().inventory[0].count, 3); + assert.equal(owner.local().stats[27], 200); + await owner.page.bringToFront(); + await owner.page.locator('#canvas').focus(); + const point = await owner.point(681, 65); + await owner.page.mouse.move(point.x, point.y); + + // The fixture advances one ordinary Leet swing; all item actions use native browser input. + assert((await owner.page.request.post(url + '/test-attack')).ok()); + await Promise.all(games.map(game => game.wait('real incoming result before impact', () => pending(game, initial.npc)))); + evidence.pending = {server: await server(), clients: games.map(game => ({ + health: actor(game, initial.owner).stats[27], leet: actor(game, initial.npc)}))}; + assert(evidence.pending.server.health < 200); + assert(evidence.pending.clients.every(client => client.health === 200)); + const sequence = owner.sequence; + await Promise.all([ + owner.click(681, 65, 'right'), + ...games.map(async game => { + await game.wait('absolute heal while the real hit is pending', () => + actor(game, initial.owner).stats[27] > 200 && pending(game, initial.npc)); + return {health: actor(game, initial.owner).stats[27], leet: actor(game, initial.npc)}; + }) + ]).then(([, ...clients]) => { evidence.healedBeforeImpact = clients; }); + await owner.wait('one First Aid charge', () => owner.local().inventory[0].count === 2); + const healed = await server(); + evidence.healed = healed; + assert(healed.health >= evidence.pending.server.health + 10 && healed.health <= evidence.pending.server.health + 12); + assert(evidence.healedBeforeImpact.every(client => client.health === healed.health)); + for (let i = 0; i < games.length; ++i) + assert.deepEqual(evidence.healedBeforeImpact[i].leet.weapons, evidence.pending.clients[i].leet.weapons); + assert.equal(healed.inventory.Items[0].Count, 2); + assert.notEqual(healed.lock, '0001-01-01T00:00:00Z'); + assert.equal(healed.fighting, initial.owner); + assert.equal(healed.nextAttack, evidence.pending.server.nextAttack); + assert.equal(healed.rechargeUntil, evidence.pending.server.rechargeUntil); + await Promise.all(games.map(game => game.wait('healed HP and drained real result', () => + actor(game, initial.owner).stats[27] === healed.health && !pending(game, initial.npc)))); + evidence.afterImpact = games.map(game => ({health: actor(game, initial.owner).stats[27], leet: actor(game, initial.npc)})); + for (let i = 0; i < games.length; ++i) { + assert.equal(evidence.afterImpact[i].leet.fighting, evidence.pending.clients[i].leet.fighting); + assert.equal(evidence.afterImpact[i].leet.combatTarget, evidence.pending.clients[i].leet.combatTarget); + } + const resultPackets = owner.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' && + ['46002f16', '5c654b28'].includes(event.opcode)); + assert.equal(resultPackets.length, 0, 'Healing invented another weapon result'); + await owner.click(681, 65, 'right'); + assert.equal((await server()).inventory.Items[0].Count, 2); + assert.equal(owner.local().inventory[0].count, 2); + await Promise.all(games.map((game, i) => game.save(output + '/verified-' + i))); + console.log('PASS: real pending hit, one First Aid charge and lock, both HP snapshots agree after impact; no extra weapon results or attack-clock changes'); +} 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, i) => game.save(output + '/final-' + i))); } + finally { await browser.close(); } +}