commit a40219495e8843bdeb7691b706d7e665cfcc779e
parent 06fb2e1b901ff57be40048bff290d7a8d5c684b4
Author: anon <anon@example.com>
Date: Wed, 4 Nov 2026 18:26:49 +0000
Clear stale worn sources after container deposit refusals
Diffstat:
8 files changed, 456 insertions(+), 31 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -4433,6 +4433,16 @@ and server restarts. Turn every reproduced bug into a focused regression test.
again, removes/deposits normally and retains all three IDs and exact armor
effects through page/cold recovery. Direct transfer acceptance remains P1;
see [worn deposit refusals](docs/backpacks.md#direct-worn-deposit-refusals).
+- [x] [P0] Clear empty stale worn sources after direct container deposits.
+ A controlled committed transfer leaves the old vest and its eight AC effects
+ visible; a real chest-to-backpack drag previously received no correction.
+ Shared cancellation/unwear/clearing now affects only the empty row, without
+ writes or a changed unrelated equip deadline. Handler checks cover five wear
+ families, bag/bank routes, repeats and protected pending slots. A 26-second
+ WASM check completes the original axe, recovers/re-wears the same bagged vest
+ and retains all three IDs/effects through page and cold ownership loading.
+ The broader disappearance audit remains open; see
+ [stale worn deposits](docs/backpacks.md#empty-stale-worn-deposits).
- [x] [P0] Preserve selected-quality stack contracts after a refused split.
Reproduction: a real QL2 Ctrl-split during a controlled pending equip rebuilt
its native endpoints as 25811/25811 instead of 25812/25811. Resolve the shared
diff --git a/docs/backpacks.md b/docs/backpacks.md
@@ -404,7 +404,7 @@ It uses controlled gear and explicitly advances admitted equipment deadlines;
this is not earned-progression or original-server acceptance-policy evidence.
Public-handler checks cover weapon, HUD, deck, armor and implant pages, both
-bag/bank routes, repeats, invalid/empty rows, protected pending slots, unrelated
+bag/bank routes, repeats, invalid rows, protected pending slots, unrelated
equipment completion, unchanged sessions and zero refusal writes. The real
WASM baseline fails in 22.10 seconds; the complete corrected scenario passes
in 27.03. Captures, the rejected first candidate and independent checks are
@@ -414,6 +414,41 @@ restoration fix.
The related Go run passes 15 roots/87 results normally and under race detection;
vet and driver syntax pass. Seven complete native traces have no errors/drops.
+### Empty stale worn deposits
+
+An earlier committed transfer can leave a worn icon and its effects visible
+after the physical item has already moved. A real chest102:21-to-backpack request
+previously got no correction because the worn row was empty on the server.
+The focused native baseline retains all eight stale vest AC bonuses and the
+unchanged unrelated pending axe move; it fails after 25.12 seconds.
+
+Both ordinary removal and container routes now use the same stale-wear
+correction: cancel the actual source, undo its cached published wear contract
+once, clear only the empty row, and refresh the owner's derived resources.
+An empty weapon hand keeps its existing weapon-unbind sequence. No ownership
+writes or observer broadcasts occur. Pending source/destination slots remain
+protected, and the unsupported empty left-hand path stays unchanged. Available
+bank destinations use the same correction after their existing gate. Empty-row
+correction also requires the destination to be the owner's bank or an owned
+portable bag with a known session handle; forged/unknown targets retain their
+existing rejection behavior.
+
+The accepted 25.70-second WASM checkpoint commits the vest into its bag without
+refreshing the old native view. The actual stale deposit clears the vest and
+all eight bonuses while preserving the axe's original pending identity/deadline.
+Completion, page replay, direct bag wear of that same vest and another page
+replay retain all three IDs and exactly-once armor effects. Cold Go loading
+confirms their final properties and allocator. This is controlled stale-view
+evidence, not an original-server transfer-policy claim.
+
+Handler checks cover weapon, HUD, deck, armor and implant sources through bag
+and bank routes during idle, wear and removal, repeated correction, unchanged
+sessions, zero writes and cold ownership after unrelated completion. Captures
+and independent checks are retained under `local/stale-worn-deposit/`.
+The final related suite passes 36 roots/398 results in163.919 seconds; race
+checks pass 16 roots/205 results in143.605 seconds. Maintained-package vet and
+driver syntax pass, and all three accepted native captures have no errors/drops.
+
## Verification
`server/backpacks_test.go` exercises the actual world connection for opening and
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -227,10 +227,25 @@ func (server *server) moveContainerItem_locked(client *worldClient, body []byte)
} else if sourcePage == 101 && sourceSlot > 0 && sourceSlot < 16 ||
sourcePage == 102 && sourceSlot >= 16 && sourceSlot < 32 || sourcePage == 103 && sourceSlot >= 33 && sourceSlot <= 45 {
// Direct worn deposits are unsupported; restore their validated native source.
- if !slices.ContainsFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot }) ||
- client.equipment != nil && (sourceSlot == client.equipment.source || sourceSlot == client.equipment.destination) {
+ if client.equipment != nil && (sourceSlot == client.equipment.source || sourceSlot == client.equipment.destination) {
return nil
}
+ if !slices.ContainsFunc(items, func(item ownedItem) bool { return item.Slot == sourceSlot }) {
+ if sourceSlot == 8 {
+ return nil
+ }
+ targetType, targetID := binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32])
+ validTarget := targetType == 57005 && targetID == client.id
+ if targetType == 51017 && slices.ContainsFunc(items, func(item ownedItem) bool { return item.ID == targetID && item.isPortableContainer() }) {
+ for _, handle := range client.backpacks {
+ validTarget = validTarget || handle.id == targetID
+ }
+ }
+ if !validTarget {
+ return nil
+ }
+ return server.clearStaleWorn_locked(client, sourcePage, sourceSlot)
+ }
return client.send(characterActionPacket(client.id, [5]uint32{146, sourcePage, sourceSlot}))
} else if sourcePage != 104 || sourceSlot < 64 || sourceSlot >= 94 {
return nil
diff --git a/server/browser_stale_worn_deposit_test.go b/server/browser_stale_worn_deposit_test.go
@@ -0,0 +1,107 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserStaleWornContainerDeposit(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for a stale worn container deposit")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/stale-worn-deposit", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.level = 2
+ player.stats.Abilities.Sense, player.stats.Abilities.Agility = 8, 8
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("stale-worn-deposit")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ inventory := playerInventory{LastID: 3, Items: []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ {ID: 2, Type: 51022, Template: 85481, Quality: 1, Slot: 21, Count: 1},
+ {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1}}}
+ if err := world.saveInventory_locked(player, 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()
+ var pending any
+ if client := world.clients[1]; client != nil && client.equipment != nil {
+ pending = map[string]any{"itemID": client.equipment.itemID, "source": client.equipment.source,
+ "destination": client.equipment.destination, "readyAt": client.equipment.readyAt}
+ }
+ var armor [8]int32
+ for index := range armor {
+ armor[index] = player.equipmentBonus(90 + uint32(index))
+ }
+ json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending, "armor": armor})
+ })
+ // Commit the vest to its actual bag without refreshing the old worn view.
+ mux.HandleFunc("POST /test-stale-view", func(w http.ResponseWriter, r *http.Request) {
+ world.updateMutex.Lock()
+ defer world.updateMutex.Unlock()
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ inventory := player.inventory
+ inventory.Items = []ownedItem{inventory.Items[0], inventory.Items[2]}
+ vest := player.inventory.Items[1]
+ vest.Slot = 0
+ inventory.Containers = map[uint32][]ownedItem{3: {vest}}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Error(err)
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ })
+ mux.HandleFunc("POST /test-complete", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ finish := world.clients[1].equipment.readyAt
+ world.mutex.Unlock()
+ world.advanceEquipment(finish)
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_stale_worn_deposit.mjs"), host.URL, output)
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := playerInventory{LastID: 3, Items: []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1},
+ {ID: 3, Type: 51017, Template: 99228, Quality: 1, Slot: 65, Count: 1},
+ {ID: 2, Type: 51022, Template: 85481, Quality: 1, Slot: 21, Count: 1}}}
+ if !reflect.DeepEqual(player.inventory, expected) {
+ t.Fatal("stale worn deposit changed an owned instance")
+ }
+ slices.SortFunc(expected.Items, func(a, b ownedItem) int { return int(a.ID) - int(b.ID) })
+ cold := newTestInventoryServer(t)
+ if !reflect.DeepEqual(cold.characters[1].inventory, expected) || world.nextItem != 3 || cold.nextItem != 3 {
+ t.Fatal("stale worn deposit lost or duplicated durable ownership")
+ }
+}
diff --git a/server/inventory.go b/server/inventory.go
@@ -378,13 +378,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error {
binary.BigEndian.Uint32(body[24:28]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == client.id &&
(destination == 111 || destination >= 64 && destination < 94) {
// Clear an empty hand without destroying its detached physical weapon.
- for _, packet := range [][]byte{characterActionPacket(client.id, [5]uint32{146, 101, 6}),
- weaponUnequipPacket(client.id), characterActionPacket(client.id, [5]uint32{112, 101, 6})} {
- if err := client.send(packet); err != nil {
- return err
- }
- }
- return server.sendEquipmentResources_locked(client)
+ return server.clearStaleWorn_locked(client, sourceType, sourceSlot)
}
if index < 0 && (client.equipment == nil || sourceSlot != client.equipment.source && sourceSlot != client.equipment.destination) &&
key == 0x47537a24 &&
@@ -393,24 +387,7 @@ func (server *server) handleInventory(client *worldClient, body []byte) error {
binary.BigEndian.Uint32(body[24:28]) == 50000 && binary.BigEndian.Uint32(body[28:32]) == client.id &&
(destination == 111 || destination >= 64 && destination < 94) {
// Clear the stale worn row without deleting its detached physical instance.
- if err := client.send(characterActionPacket(client.id, [5]uint32{146, sourceType, sourceSlot})); err != nil {
- return err
- }
- removal := client.wornRemoval[sourceSlot]
- if removal != nil {
- if err := client.send(removal); err != nil {
- return err
- }
- client.wornRemoval[sourceSlot] = nil
- }
- if err := client.send(characterActionPacket(client.id, [5]uint32{112, sourceType, sourceSlot})); err != nil {
- return err
- }
- if removal == nil {
- return nil
- }
-
- return server.sendEquipmentResources_locked(client)
+ return server.clearStaleWorn_locked(client, sourceType, sourceSlot)
}
if index < 0 || (sourceSlot >= 64 && sourceType != 104) ||
(sourceSlot > 0 && sourceSlot < 16 && sourceType != 101) ||
@@ -512,6 +489,29 @@ func (client *worldClient) sendItemDeletion(body []byte, deleted []ownedItem) er
return nil
}
+func (server *server) clearStaleWorn_locked(client *worldClient, page, slot uint32) error {
+ if err := client.send(characterActionPacket(client.id, [5]uint32{146, page, slot})); err != nil {
+ return err
+ }
+ removal := client.wornRemoval[slot]
+ if slot == 6 {
+ removal = weaponUnequipPacket(client.id)
+ }
+ if removal != nil {
+ if err := client.send(removal); err != nil {
+ return err
+ }
+ client.wornRemoval[slot] = nil
+ }
+ if err := client.send(characterActionPacket(client.id, [5]uint32{112, page, slot})); err != nil {
+ return err
+ }
+ if removal == nil {
+ return nil
+ }
+ return server.sendEquipmentResources_locked(client)
+}
+
func (server *server) sendEquipmentResources_locked(client *worldClient) error {
character := server.characters[client.id]
// Inverse effects do not refresh the owner's cached derived foundations.
diff --git a/server/stale_worn_deposit_test.go b/server/stale_worn_deposit_test.go
@@ -0,0 +1,156 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "maps"
+ "reflect"
+ "slices"
+ "testing"
+)
+
+func TestStaleWornContainerDepositClearsOnlyItsEmptySource(t *testing.T) {
+ for _, worn := range [][3]uint32{{101, 6, 209283}, {101, 3, 161699}, {101, 9, 36779}, {102, 21, 85481}, {103, 37, 101173}} {
+ for _, destination := range []uint32{51017, 57005} {
+ for _, phase := range []string{"idle", "wear", "removal"} {
+ t.Run(fmt.Sprintf("page%d/slot%d/destination%d/%s", worn[0], worn[1], destination, phase), func(t *testing.T) {
+ world, output := newBackpackWearWorld(t, worn[2], 0)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleInventory(client, backpackMoveRequest(107, 65536, 50000, 1, worn[1])[20:]); err != nil || client.equipment == nil {
+ t.Fatal("fixture wear did not begin", err)
+ }
+ world.advanceEquipment(client.equipment.readyAt)
+ removal := slices.Clone(client.wornRemoval[worn[1]])
+ if worn[1] == 6 {
+ removal = weaponUnequipPacket(1)
+ }
+ if removal == nil {
+ t.Fatal("fixture has no published inverse")
+ }
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ index := slices.IndexFunc(inventory.Items, func(item ownedItem) bool { return item.Slot == worn[1] })
+ item := inventory.Items[index]
+ item.Slot = 0
+ inventory.Bank = []ownedItem{item}
+ inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ player.playfield, player.position = 705, [3]float32{985, 20.2001, 580}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTerminalUse(client, bankUseRequest(2)[20:]); err != nil || client.bank == nil {
+ t.Fatal("fixture bank did not open", err)
+ }
+ pendingSource, pendingDestination := uint32(64), uint32(6)
+ if worn[1] == 6 {
+ if granted, err := world.grantItem_locked(player, 85481); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ pendingSource = player.inventory.Items[len(player.inventory.Items)-1].Slot
+ pendingDestination = 21
+ }
+ var pending equipmentMove
+ if phase != "idle" {
+ if err := world.handleInventory(client, inventoryMovePacket(1, pendingSource, pendingDestination)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("unrelated equipment did not begin", err)
+ }
+ if phase == "removal" {
+ world.advanceEquipment(client.equipment.readyAt)
+ if err := world.handleInventory(client, itemMovePacket(1, pendingDestination, pendingSource)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("unrelated removal did not begin", err)
+ }
+ }
+ pending = *client.equipment
+ }
+ inventory, handles, bank := player.inventory, maps.Clone(client.backpacks), *client.bank
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ output.packets = nil
+ target := uint32(2)
+ if destination == 57005 {
+ target = 1
+ }
+
+ for range 2 {
+ if err := world.handleInventory(client, backpackMoveRequest(worn[0], worn[1], destination, target, 111)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ after, err := readTestItemStore(world)
+
+ expected := [][]byte{targetPacket(characterActionPacket(1, [5]uint32{146, worn[0], worn[1]})),
+ targetPacket(removal), targetPacket(characterActionPacket(1, [5]uint32{112, worn[0], worn[1]}))}
+ count := 10
+ if worn[1] == 6 {
+ count = 16
+ }
+ if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || len(output.packets) != count ||
+ !reflect.DeepEqual(player.inventory, inventory) || !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, inventory) ||
+ !reflect.DeepEqual(client.backpacks, handles) || *client.bank != bank ||
+ (phase != "idle") != (client.equipment != nil) || client.equipment != nil && *client.equipment != pending ||
+ client.wornRemoval[worn[1]] != nil || !reflect.DeepEqual(output.packets[:3], expected) {
+ t.Fatal("stale worn deposit omitted correction or changed ownership, writes, sessions or pending equipment", err, len(output.packets))
+ }
+ repeatedClear := 9
+ if worn[1] == 6 {
+ repeatedClear = 10
+ }
+ if !bytes.Equal(output.packets[8], expected[0]) || !bytes.Equal(output.packets[repeatedClear], expected[2]) {
+ t.Fatal("repeated correction changed its source or repeated an inverse")
+ }
+ if phase != "idle" {
+ world.advanceEquipment(pending.readyAt)
+ expected := inventory
+ expected.Items = slices.Clone(inventory.Items)
+ index := slices.IndexFunc(expected.Items, func(item ownedItem) bool { return item.ID == pending.itemID })
+ expected.Items[index].Slot = pending.destination
+ if client.equipment != nil || !reflect.DeepEqual(player.inventory, expected) ||
+ !reflect.DeepEqual(newTestInventoryServer(t).characters[1].inventory, expected) {
+ t.Fatal("stale worn correction changed the unrelated completion")
+ }
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestStaleWornContainerDepositPreservesInvalidTargets(t *testing.T) {
+ for _, scenario := range []string{"forged bag", "unknown bag", "foreign bank"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newStaleArmorMoveWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if granted, err := world.grantItem_locked(player, 99228); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ targetType, targetID := uint32(51017), uint32(3)
+ if scenario == "forged bag" {
+ targetID = 999
+ } else if scenario == "foreign bank" {
+ targetType, targetID = 57005, 2
+ client.bank = &bankSession{playfield: player.playfield, position: player.position}
+ }
+ removal := slices.Clone(client.wornRemoval[18])
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ output.packets = nil
+
+ err = world.handleInventory(client, backpackMoveRequest(102, 18, targetType, targetID, 111)[20:])
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || len(output.packets) != 0 ||
+ len(checkpointWrites(t, world)) != 0 || !bytes.Equal(removal, client.wornRemoval[18]) {
+ t.Fatal("invalid container target changed a stale source, its inverse or ownership", err, readErr)
+ }
+ })
+ }
+}
diff --git a/server/worn_container_deposit_test.go b/server/worn_container_deposit_test.go
@@ -99,7 +99,7 @@ func TestWornContainerDepositRestoresOwnedSource(t *testing.T) {
func TestWornContainerDepositPreservesInvalidAndPendingSources(t *testing.T) {
for _, destination := range []uint32{51017, 57005} {
- for _, scenario := range []string{"wrong page", "empty worn row", "pending source", "pending destination"} {
+ for _, scenario := range []string{"wrong page", "unsupported empty hand", "pending source", "pending destination", "empty pending destination"} {
t.Run(fmt.Sprintf("%d/%s", destination, scenario), func(t *testing.T) {
world, output := newBankWorld(t)
player, client := world.characters[1], world.clients[1]
@@ -119,8 +119,8 @@ func TestWornContainerDepositPreservesInvalidAndPendingSources(t *testing.T) {
switch scenario {
case "wrong page":
page = 102
- case "empty worn row":
- source = 15
+ case "unsupported empty hand":
+ source = 8
case "pending source":
if err := world.handleInventory(client, itemMovePacket(1, 6, 69)[20:]); err != nil || client.equipment == nil {
t.Fatal("fixture removal did not begin", err)
@@ -132,6 +132,14 @@ func TestWornContainerDepositPreservesInvalidAndPendingSources(t *testing.T) {
if err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]); err != nil || client.equipment == nil {
t.Fatal("fixture replacement did not begin", err)
}
+ case "empty pending destination":
+ inventory.Items[5].Slot = 69
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, inventoryMovePacket(1, 69, 6)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("fixture empty-hand wear did not begin", err)
+ }
}
var pending equipmentMove
if client.equipment != nil {
diff --git a/tools/client/test_stale_worn_deposit.mjs b/tools/client/test_stale_worn_deposit.mjs
@@ -0,0 +1,94 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import {createRequire} from 'node:module';
+import {GameTest} from './game_test.mjs';
+
+const {chromium} = createRequire(import.meta.url)('playwright');
+const [url, output] = process.argv.slice(2);
+const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [
+ '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage',
+ '--disable-background-timer-throttling', '--disable-renderer-backgrounding']});
+let game;
+const evidence = {};
+try {
+ const context = await browser.newContext({viewport: {width: 1024, height: 768}});
+ await context.addCookies([{name: 'ao_client', value: 'stale-worn-deposit', url}]);
+ const page = await context.newPage();
+ game = await GameTest.attach(page);
+ await page.goto(url);
+ await game.ready();
+ const server = async () => (await page.request.get(url + '/test-state')).json();
+ const cell = (state, page, slot) => state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy);
+ const click = async (cell, button = 'left') => {
+ assert(cell);
+ await game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2, button);
+ };
+ const armor = [5, 5, 1, 1, 5, 5, 1, 5];
+ assert.deepEqual(game.local().effectiveArmor, armor);
+ await game.key('i');
+ await click(cell(game.state, 104, 49), 'right');
+ await game.wait('empty bag open', state => state.grids.some(grid => grid.totalCells === 21));
+ await page.keyboard.press('Control+1');
+ assert((await page.request.post(url + '/test-stale-view')).ok());
+ await click(cell(game.state, 104, 48));
+ await game.click(867, 206);
+ await game.wait('real axe equip request', () => game.events.some(event => event.direction === 'framesent' && event.opcode === '47537a24'));
+ evidence.pending = await server();
+ assert.equal(evidence.pending.pending.itemID, 1);
+ assert.deepEqual(evidence.pending.armor, [0, 0, 0, 0, 0, 0, 0, 0]);
+ await game.wait('local equip animation ended', state => !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6));
+ await game.click(953, 53);
+ const sequence = game.sequence;
+ await game.click(927, 148);
+ await game.wait('actual stale vest pickup', state => state.dragged[0] === 102 && state.dragged[1] === 21);
+ await click(game.state.grids.find(grid => grid.totalCells === 21).cells.find(cell => cell.identity[0] === 0));
+ await game.wait('real stale worn deposit', () => game.events.some(event => event.sequence > sequence && event.direction === 'framesent' &&
+ event.opcode === '47537a24' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 102 && Buffer.from(event.hex, 'hex').readUInt32BE(37) === 51017));
+ evidence.refused = await server();
+ assert.deepEqual(evidence.refused, evidence.pending);
+ await game.save(output + '/requested');
+ await game.wait('stale vest row and all eight effects cleared', state => !game.local(state).inventory.some(item => item.slot === 21) &&
+ game.local(state).effectiveArmor.every(value => value === 0));
+ const replies = game.events.filter(event => event.sequence > sequence && event.direction === 'framereceived' &&
+ ['5e477770', '35505644'].includes(event.opcode)).map(event => [event.opcode,
+ ...Array.from({length: event.opcode === '35505644' ? 9 : 5}, (_, index) => Buffer.from(event.hex, 'hex').readUInt32BE(29 + index * 4))]);
+ assert.deepEqual(replies, [['5e477770', 146, 102, 21, 0, 0], ['35505644', 85481, 85481, 1, 1, 7, 102, 21, 0, 0],
+ ['5e477770', 112, 102, 21, 0, 0]]);
+ await game.save(output + '/corrected');
+ assert((await page.request.post(url + '/test-complete')).ok());
+ await game.wait('original pending axe completes', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6));
+ evidence.completed = await server();
+ assert.equal(evidence.completed.pending, null);
+
+ // Replay reveals the vest's actual bag placement; wear that same physical item.
+ await page.reload();
+ await game.ready();
+ if (!cell(game.state, 104, 49)) await game.key('i');
+ await click(cell(game.state, 104, 49), 'right');
+ await game.wait('exact vest restored in its bag', state => cell(state, 107, 65536));
+ await page.keyboard.press('Control+1');
+ await game.click(953, 53);
+ const retry = game.sequence;
+ await click(cell(game.state, 107, 65536));
+ await game.click(927, 148);
+ await game.wait('real recovered vest wear', () => game.events.some(event => event.sequence > retry && event.direction === 'framesent' && event.opcode === '47537a24'));
+ assert((await page.request.post(url + '/test-complete')).ok());
+ await game.wait('retained vest effects applied exactly once', state => game.local(state).inventory.some(item => item.id === 2 && item.slot === 21) &&
+ game.local(state).effectiveArmor.every((value, index) => value === armor[index]));
+ evidence.final = await server();
+ await page.reload();
+ await game.ready();
+ assert.deepEqual(await server(), evidence.final);
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot]), [[1, 6], [2, 21], [3, 49]]);
+ assert.deepEqual(game.local().effectiveArmor, armor);
+ assert.deepEqual(game.errors, []);
+ assert.equal(game.dropped, 0);
+ console.log('PASS: stale worn deposit clears exact source/effects, preserves pending equip, and recovers all three identities');
+} finally {
+ try {
+ await fs.mkdir(output, {recursive: true});
+ await fs.writeFile(output + '/verification.json', JSON.stringify(evidence, null, 2) + '\n');
+ if (game) await game.save(output + '/final');
+ } finally { await browser.close(); }
+}