aorecomp

Anarchy Online classic in the browser

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


commit c4c8e93c01cf8e1430ed46298e5e22cb425f6966
parent 33633e67765e38f702d20e1f3f074b0b91490203
Author: anon <anon@example.com>
Date:   Mon,  2 Nov 2026 17:37:34 +0000

Enable the complete startup First Aid kit contract

Diffstat:
MTODO.md | 23++++++++++++-----------
Mdocs/first-aid.md | 46+++++++++++++++++++++++++++++++++++++++-------
Mdocs/medical-consumables.md | 13+++++++------
Mserver/browser_first_aid_test.go | 144+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mserver/first_aid_test.go | 188++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------
Mserver/resource_kit.go | 3++-
Mserver/resource_kit_test.go | 8+++++---
Mtools/client/test_first_aid.mjs | 13+++++++++----
8 files changed, 273 insertions(+), 165 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -1374,8 +1374,8 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train Hardware WASM checks verify QL2 use of all three families, QL100/101 laboratory requirements/restoration, cooldown rejection, final-charge removal and cold 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). + acquisition. QL201..399 and complete medical stock remain open. See + [medical qualities](docs/medical-quality.md). - [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. The focused reproduction queued real damage before an absolute heal, then @@ -1387,15 +1387,16 @@ replay/failure tests and WASM checks are recorded in [IP training](docs/ip-train 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. +- [x] Execute the issued startup First-Aid kit's complete use contract. + Kit116629 restores both health and nano by5..7 during combat, consumes one + charge, and locks the user's FirstAid123 for40 seconds. The shipped native + use-action queue handles ItemDelay294=2 as20ms; admission no longer rejects + it. Go checks cover self/friend use, strict skill equality, clamping, last + charge, shared lock/replay, failure rollback/retry and cold persistence of + both effects. A short controlled two-client WASM check uses the actual kit + with a real8-damage result pending: HP192->197, nano1->6, charges3->2, with + both clients retaining197 through impact and native lock rejection. No + leveling or supply farming is needed. See [First Aid](docs/first-aid.md). - [ ] [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/docs/first-aid.md b/docs/first-aid.md @@ -1,10 +1,10 @@ # First Aid research for 14.9.1 -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. +Regular health stims and the startup health/nano kit are enabled. The maintained +client prevents an absolute HealthDamage snapshot from double-applying already +queued weapon damage at impact. The startup kit uses the shipped client's own +20ms item-use action and restores both resources together. Original-server +healing publication cadence remains unresolved. ## Item and skill evidence @@ -89,8 +89,8 @@ 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 +controlled two-client scenario, right-click kit23314 or116629 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 @@ -104,6 +104,38 @@ Run the focused hardware-browser check with the normal desktop environment: AO_GAME_TEST=1 go test ./server -run '^TestBrowserFirstAidQueuedHit$' -count=1 -timeout=10m -v ``` +## Startup delay and dual restoration + +The complete original record116629 has ItemDelay294=2, Health27 and Nano214 +endpoints5..7, user FirstAid123 lock40s and strict FirstAid>5. The full-catalog +admission test finds exactly one additional supported definition when the +nonzero-ItemDelay rejection is removed: this startup kit. Other unknown or +partial effect contracts remain rejected. + +Original KKR1004d780 reads ItemDelay294 and RechargeDelay210 and constructs an +item-use action of type4 through10052630/10052550. The counter stores the integer +centisecond amount and exposes seconds with a0.01 multiplier. Native100527c0 +advances the action and sets completion bit0x20;1004d880 waits for that bit before +executing the local use-completion callback. Thus value2 represents a20ms native +action. These client observations leave original server publication cadence +unresolved. Shipped-binary SHA-256 remains +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +REA evidence IDs are `ev_c4b58f1606fdd6b1cc3fc8d61c4a44ca9f48697ffa8c964fd7364dc4d778e4a9`, +`ev_e6916067edd620682135cb54f936ed6c60e177c4cb0a0d98d1bc5e503c6e9a87` +and `local/startup-first-aid/completion.json`; complete inline records are +retained in that directory. + +The controlled startup WASM run in +`local/first-aid-queued-hit/20261102-093202-116629/` records a real8-damage result +pending on both clients. Use heals authoritative192->197 and nano1->6, debits +charges3->2 and sets the user's40s lock. Both clients observe197 with the unchanged +result still pending and retain197 when it drains. The native damage text still +reports8; attack deadlines and combat targets remain unchanged. Native repeat +use is blocked and both trace error lists are empty. The case completes in21.41s. +Go tests additionally cover self/friend use, strict skill equality, maxima, +last-charge removal, exact charge/lock/resource persistence before success, and +rollback/retry when any of the four significant writes fails. + ## Earlier prototype checks and delivery research A native UI-consumer audit confirms that the discrepancy reaches both health diff --git a/docs/medical-consumables.md b/docs/medical-consumables.md @@ -3,12 +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 thirteen definitions: +these fourteen 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 | +| 116629 / 1 | Startup First-Aid Kit | 5..7 | 5..7 | 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 | @@ -47,11 +48,11 @@ from stat371. Activate10 AddSkill53028 initializes item skill-list metadata 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 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). +repeating effects, different recipients and unsupported lock skills remain +unsupported. The startup First-Aid Kit116629 restores both health and nano during +combat. Its ItemDelay294=2 uses the existing native20ms item-use action; this +field is not a reason to reject the complete contract. See +[First Aid delivery](first-aid.md#startup-delay-and-dual-restoration). Accepted use commits both resource values, one source charge and the proper actor's cooldown in the same SQLite transaction before success. Current values diff --git a/server/browser_first_aid_test.go b/server/browser_first_aid_test.go @@ -19,75 +19,79 @@ 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) + for _, template := range []uint32{23314, 116629} { + t.Run(fmt.Sprint(template), func(t *testing.T) { + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/first-aid-queued-hit", time.Now().Format("20060102-150405")+fmt.Sprint("-", template)) + 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, player.nano = 200, 1 + 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], template); !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, "nano": players[0].nano, "template": template, "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 @@ -8,75 +8,137 @@ import ( "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() +func TestFirstAidCommitsDuringCombat(t *testing.T) { + for _, kit := range []struct{ template, low, high uint32 }{{23314, 10, 12}, {116629, 5, 7}} { + for _, other := range []bool{false, true} { + for _, count := range []uint16{1, 3} { + for _, clamp := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/other%t/count%d/clamp%t", kit.template, 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 = kit.template, count + player.fighting, target.fighting, target.sitting = 1000000, 1000000, false + if clamp { + target.health = target.maximumHealth() - 1 + if kit.template == 116629 { + target.nano = target.maximumNano() - 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=?, nano=? WHERE id=?", target.health, target.nano, 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) + 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 err != nil || !conn.observed || conn.err != nil || conn.count != count-1 || + conn.health != target.health || conn.nano != target.nano || !conn.firstAid.Valid || conn.patient.Valid || + restored.characters[target.id].health != target.health || restored.characters[target.id].nano != target.nano || + 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 < 1+kit.low || target.health > 1+kit.high) { + t.Fatal("First Aid differs from its authored health endpoints or maximum clamp", target.health) + } + if kit.template == 116629 { + if clamp && target.nano != target.maximumNano() || !clamp && (target.nano < 6 || target.nano > 8) { + t.Fatal("startup First Aid lost its nano effect or maximum clamp", target.nano) } + } else if target.nano != 1 { + t.Fatal("health-only First Aid changed nano") + } + 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) } - } - 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") - } - }) + // 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 || target.nano != conn.nano { + t.Fatal("replay or locked First Aid use changed the committed outcome") + } + }) + } } } } } + +func TestStartupFirstAidRollsBackBothResourcesAndRetries(t *testing.T) { + for _, phase := range []string{"charge", "lock", "health", "nano"} { + t.Run(phase, func(t *testing.T) { + world, target, conn := newStartupLaboratoryWorld(t, true) + player := world.characters[1] + player.stats.NanoAiding.FirstAid = 7 + player.inventory.Items[0].Template, player.inventory.Items[0].Count = 116629, 3 + player.fighting, target.fighting, target.sitting = 1000000, 1000000, false + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + statement := "CREATE TRIGGER reject_stim BEFORE UPDATE ON items BEGIN SELECT RAISE(FAIL, 'charge'); END" + switch phase { + case "lock": + statement = "CREATE TRIGGER reject_stim BEFORE INSERT ON skill_locks BEGIN SELECT RAISE(FAIL, 'lock'); END" + case "health": + statement = "CREATE TRIGGER reject_stim BEFORE UPDATE OF health ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'health'); END" + case "nano": + statement = "CREATE TRIGGER reject_stim BEFORE UPDATE OF nano ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(FAIL, 'nano'); END" + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + before, _ := readTestItemStore(world) + + failed := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]) + after, _ := readTestItemStore(world) + var savedHealth, savedNano uint32 + if err := world.db.QueryRow("SELECT health,nano FROM characters WHERE id=2").Scan(&savedHealth, &savedNano); err != nil { + t.Fatal(err) + } + if failed == nil || string(before) != string(after) || target.health != 1 || target.nano != 1 || player.inventory.Items[0].Count != 3 || + savedHealth != 1 || savedNano != 1 || len(player.skillLocks) != 0 || len(target.skillLocks) != 0 || len(conn.packets) != 0 { + t.Fatal("failed startup First Aid left a partial restoration, charge, lock or success", failed) + } + if _, err := world.db.Exec("DROP TRIGGER reject_stim"); err != nil { + t.Fatal(err) + } + err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 2)[20:]) + cold := newTestInventoryServer(t) + + if err != nil || target.health < 6 || target.health > 8 || target.nano < 6 || target.nano > 8 || player.inventory.Items[0].Count != 2 || + cold.characters[2].health != target.health || cold.characters[2].nano != target.nano || + cold.characters[1].inventory.Items[0].Count != 2 || cold.characters[1].skillLocks[123].IsZero() || !cold.characters[2].skillLocks[123].IsZero() { + t.Fatal("startup First Aid retry did not commit both resources, one charge and the user lock", err) + } + }) + } +} diff --git a/server/resource_kit.go b/server/resource_kit.go @@ -45,8 +45,9 @@ func (item ownedItem) resourceKit() (resourceKit, bool) { func decodeResourceKit(definition *gamedata.Item) (resourceKit, bool) { kit := resourceKit{} + // KKR sub_3604D780 schedules ItemDelay in the native item-use action. if definition.HeaderWords[0] != 51005 || itemStat(definition, 76) != 0 || - itemStat(definition, 30)&40 != 40 || itemStat(definition, 212) == 0 || itemStat(definition, 294) != 0 { + itemStat(definition, 30)&40 != 40 || itemStat(definition, 212) == 0 { return kit, false } 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{23314, 23316, 25811, 25812, 25820, 25821, 85366, 85367, 116628, 160276, 160277, 160278, 160295}) { + if !reflect.DeepEqual(admitted, []uint32{23314, 23316, 25811, 25812, 25820, 25821, 85366, 85367, 116628, 116629, 160276, 160277, 160278, 160295}) { t.Fatal("unexpected medical use contract in the full catalog", admitted) } } @@ -371,10 +371,12 @@ func TestStartupLaboratoryOutputFailurePreservesBothGainsAndPatientLock(t *testi } } -func TestStartupFirstAidDelayNeverConsumesOnlyPartOfItsEffect(t *testing.T) { +func TestStartupFirstAidSkillEqualityPreservesBothEffects(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 + player.stats.Abilities = characterAbilitiesStats{1, 1, 1, 1, 1, 1} + player.stats.NanoAiding.FirstAid = 5 if err := world.saveInventory_locked(player, player.inventory); err != nil { t.Fatal(err) } @@ -385,6 +387,6 @@ func TestStartupFirstAidDelayNeverConsumesOnlyPartOfItsEffect(t *testing.T) { 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) + t.Fatal("First Aid at strict skill equality changed either resource, its last charge or lock", err) } } diff --git a/tools/client/test_first_aid.mjs b/tools/client/test_first_aid.mjs @@ -29,7 +29,7 @@ try { 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].templates[0], initial.template); assert.equal(owner.local().inventory[0].count, 3); assert.equal(owner.local().stats[27], 200); await owner.page.bringToFront(); @@ -49,14 +49,19 @@ try { 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)); + 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); + const [low, high] = initial.template === 116629 ? [5, 7] : [10, 12]; + assert(healed.health >= evidence.pending.server.health + low && healed.health <= evidence.pending.server.health + high); + if (initial.template === 116629) { + assert(healed.nano >= initial.nano + 5 && healed.nano <= initial.nano + 7); + await owner.wait('startup kit restored native nano', () => owner.local().stats[214] === healed.nano); + } else assert.equal(healed.nano, initial.nano); 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); @@ -79,7 +84,7 @@ try { 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'); + console.log('PASS:', initial.template, 'real pending hit, complete resource effects, one 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));