aorecomp

Anarchy Online classic in the browser

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


commit 6fe77a31fabc543e842ad5743173f7ea67bf2f3d
parent 8c5379c9a1829a0ad7095602f0671403a609d796
Author: anon <anon@example.com>
Date:   Thu,  5 Nov 2026 00:59:09 +0000

Correct backpack split refusals when cancelling player trades

Diffstat:
MAGENTS.md | 19+++++++++++++++++--
MTODO.md | 40++++++++++++++++++++++++++++++++++++++--
Mdocs/backpacks.md | 24++++++++++++++++++++++++
Mserver/browser_depleted_backpack_split_test.go | 17++++++++++++++++-
Mserver/inventory.go | 9+++++++++
Mserver/player_trading_lifecycle_test.go | 45+++++++++++++++++++++++++++++++++++++++++++++
Mtools/client/test_depleted_backpack_split.mjs | 29++++++++++++++++++++++++++++-
7 files changed, 177 insertions(+), 6 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -17,8 +17,23 @@ 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. +- Before choosing work, name the existing open TODO, the observed failure or + missing behavior, and the specific remaining acceptance criterion this change + will complete. State its completion check before starting. +- Prefer implementing missing behavior and fixing reproduced failures. Add + regression coverage when it protects that change or completes a clearly + identified coverage requirement. +- After the focused regression and appropriate required checks pass, commit and + move to the next actionable TODO. Broaden verification only when a new failure, + material risk or explicit acceptance criterion requires it. +- Report behavior changes, verification, research and TODO closures separately. + More tests or retained screenshots do not themselves establish that a feature + advanced. +- Do not expand an item's completion criteria while working on it. Record newly + discovered work separately with a justified priority. +- Research must answer a named implementation question. Stop when the evidence + budget is exhausted; record the exact missing evidence and the condition that + would justify reopening the search. - Prefer the smallest reproducible scenario. Use controlled fixtures and existing checkpoints to reach the relevant state; clearly distinguish these from earned-progression evidence. diff --git a/TODO.md b/TODO.md @@ -15,8 +15,9 @@ related work; they are not batches that must be finished together. If one change naturally completes several milestones, verify and check off all of them rather than artificially limiting the implementation. -A verified first example does not complete its subsystem. Expand the coverage -milestones below as research identifies more 14.9.1 behavior and content; keep +A verified first example does not complete its subsystem. Record newly identified +14.9.1 behavior and content gaps separately, with a justified priority; do not +expand an existing milestone's completion check while working on it. Keep unsupported cases and unverified rules explicit until they have their own checks. ## Priorities and next playable milestone @@ -42,6 +43,29 @@ movement edge case before shipping a useful, tested slice. Historical accuracy remains the target: label provisional rules and reject unsupported item contracts as a whole rather than silently granting partial effects. +### Remaining P0 queue + +This indexes the seven open P0 milestones below; it does not replace their scope +or evidence. Implementation, necessary verification, historical evidence and +completion decisions are separate gaps. Passing a component does not close its +umbrella. Do not extend these checks during a change; record new work separately. + +| Existing P0 | Remaining gap / work type | Completion check | +| --- | --- | --- | +| Further levels and early enemy families | Historical evidence and scope decision: higher NPC growth/damage scaling is unmeasured; "further" levels/families has no finite remaining set. Player level10 and admitted Leet1..10 already have evidence. | Name the remaining target levels/families, recover their profiles without extrapolation, then verify the stated training, upgrades, recovery and mission outcomes. See [mission levels](docs/mission-levels.md). | +| Suitable loot qualities | Historical evidence: family membership/chance, level-relative QL distributions and fixed-QL exceptions remain provisional. Interval selection and durable transfers already work. | Implement the recovered selection rules and satisfy the existing boundary, empty/full, failure/retry, repeated-pickup and restart checks. See [loot qualities](docs/loot-quality-ranges.md). | +| Eligible mission tokens/XP | Historical evidence before implementation: qualifying kills/denominator, chance threshold/formula, faction exceptions and completion-XP arithmetic are missing. Token Use rules do not establish acquisition. | Recover those rules, then award token/XP atomically with completion; full inventory and failed-commit/retry must neither lose nor duplicate rewards. See [token evidence](docs/mission-encounters.md#completion-token-evidence). | +| Mission levels, encounters and rewards | Historical evidence before implementation: original difficulty mapping, encounter variation and reward-QL exceptions are unresolved; the later table remains explicitly provisional. | Implement independently evidenced selection rules and verify low/high levels, easy/hard settings, supported/refused ranges and usable exactly-once rewards through replay. See [mission levels](docs/mission-levels.md#evidence-and-provisional-policy). | +| Disappearing equipment | Necessary acceptance audit after the reproduced trade/backpack split refusal below is fixed. Other known failures have completed subitems; the umbrella still needs its stated path checks accounted for. | Map the accumulated creation/assignment, wear/remove, refusal and reconnect/restart evidence to the original criterion before closing the umbrella. Record any concrete remaining failure separately. See [backpacks](docs/backpacks.md). | +| Corpse loot, credits and expiry | Historical evidence plus necessary verification: original generic slope placement/ground anchor is unknown; broader streaming/picking remains separate from the passing transfer, rights and expiry checks. | Recover the placement rule and verify visible, pickable sloped remains and the existing partial-loot/reentry/restart accounting checks. Preserve the already verified ownership/credit invariants. See [corpse pose](docs/corpse-pose.md). | +| Repeatable two-client supported loop | Necessary verification/integration: the maintained fresh loop lacks connected creature-equipment acquisition and actual death/reclaim; separate earned continuations and controlled recovery fixtures exist. | Maintain those remaining phases with the same earned lineage, observer and exact item/cash accounting, using existing earned checkpoints to reach conditions. Separate controlled setup from earned evidence; extra cold-only fixtures or another leveling run do not complete the missing phases. See [starter progression](docs/starter-progression.md). | + +For evidence-blocked rows, reopen research only for a new dated primary source, +original-server capture or other evidence capable of resolving the named rule. +Later calculators, repeated broad searches and more play under provisional +balance do not resolve historical arithmetic. For the first row, the finite +remaining content/level target also needs an explicit completion decision. + The existing server already supports fighting, respawn, fixed corpse items and credits, provisional solo kill XP, leveling/IP, equipment, resurrection/reclaim, shop sales and a limited purchase subset. Completing the repeatable @@ -4556,6 +4580,18 @@ and server restarts. Turn every reproduced bug into a focused regression test. checks pass 44 roots/124 results, focused race checks pass 5/19, and ten native traces are clean. See [session and destination refusals](docs/backpacks.md#session-and-destination-policy-refusals) and `local/backpack-refusals/verification-summary.json`. +- [x] [P0] Correct an optimistic backpack split refused by player-trade + cancellation. P0 because normal Ctrl-click during a trade leaves a phantom + bag item and a stale source. Reproduction: open a three-charge laboratory in + a carried bag, receive a nearby trade request, then Ctrl-split the laboratory. + Check: cancel the trade, remove the clone, normally reopen the usable original + three-charge source, and preserve both owners' items without allocation. + This is a separate reproduced refusal under the existing disappearing-equipment + audit; it does not expand that umbrella's completion criteria. Known-source + window closure now passes the 21.26-second native check; normal reopening + restores all three charges. Both boundary/repeated public-handler refusals + preserve storage and allocation without writes. The umbrella remains open. See + [trade split refusal](docs/backpacks.md#split-refusal-during-player-trade). - [x] [P0] Correct an ordinary split after its old stack source is replaced by an individual item. Reproduction: retain the native laboratory row after a controlled bank exchange puts a loaded pistol in that slot, then Ctrl-click; diff --git a/docs/backpacks.md b/docs/backpacks.md @@ -445,6 +445,30 @@ in 87.677 seconds. Focused race checks pass five roots / nine results; the independent audit checks the baseline, exact close, one-charge reopening and four clean native traces. +### Split refusal during player trade + +An open backpack's ordinary three-charge laboratory can be Ctrl-split while a +nearby player trade is active. Cancelling the trade previously replayed ordinary +inventory stacks, leaving the optimistic backpack clone visible. The focused +WASM baseline times out on that exact source-window correction; no earlier +inventory mutation is needed. Evidence: +`local/depleted-backpack-split/20261104-165521/`. + +Trade cancellation now closes the known source backpack session/window for a +valid child position. It does not split the source or change either player's +ownership. Normal Use can reopen the complete original stack. This repairs the +current server's refusal protocol; it does not claim historical trade/split +policy evidence. + +The extended `TestBrowserDepletedBackpackSplit` passes in 21.26 seconds, including +normal reopening of all three charges before its existing depletion/recovery +phase, page replay and database ownership checks. The new +`TestPlayerTradeBackpackSplitClosesWithoutChangingOwnership` covers both child +boundaries and repeated requests: exact owner-window closure, peer cancellation, +unchanged item storage/counter and zero checkpoint writes. The existing accepted +bag split/join/delete and conflicting-trade-action regressions pass. Fixed native +evidence: `local/depleted-backpack-split/20261104-165641/`. + ## Stale withdrawal sources A known carried bag can have an empty slot behind a stale native window. The diff --git a/server/browser_depleted_backpack_split_test.go b/server/browser_depleted_backpack_split_test.go @@ -29,6 +29,11 @@ func TestBrowserDepletedBackpackSplit(t *testing.T) { if err := world.saveUser_locked(player); err != nil { t.Fatal(err) } + peer := world.newCharacter() + if err := world.saveUser_locked(peer); err != nil { + t.Fatal(err) + } + world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}} inventory := playerInventory{LastID: 2, Items: []ownedItem{ {ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, Containers: map[uint32][]ownedItem{1: { @@ -41,7 +46,14 @@ func TestBrowserDepletedBackpackSplit(t *testing.T) { 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{"inventory": player.inventory, "open": world.clients[1].backpacks[1].open}) + json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "peerInventory": peer.inventory, + "open": world.clients[1].backpacks[1].open, "trade": world.clients[1].trade != nil}) + }) + mux.HandleFunc("POST /test-trade", func(w http.ResponseWriter, r *http.Request) { + if err := world.handleTrade(world.clients[2], shopTradePacket([2]uint32{50000, 2}, 0, [2]uint32{50000, 1}, [2]uint32{})[20:]); err != nil { + t.Error(err) + w.WriteHeader(http.StatusInternalServerError) + } }) // Commit earlier consumption without refreshing the native three-charge row. mux.HandleFunc("POST /test-deplete-source", func(w http.ResponseWriter, r *http.Request) { @@ -84,4 +96,7 @@ func TestBrowserDepletedBackpackSplit(t *testing.T) { if world.nextItem != 2 || cold.nextItem != 2 { t.Fatal("refused depleted split allocated an identity") } + if len(peer.inventory.Items) != 0 || len(cold.characters[2].inventory.Items) != 0 { + t.Fatal("refused split transferred an item to the trade peer") + } } diff --git a/server/inventory.go b/server/inventory.go @@ -230,6 +230,15 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { return err } if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 { + position := binary.BigEndian.Uint32(body[24:28]) + if binary.BigEndian.Uint32(body[20:24]) == 107 && position&65535 < 21 { + handle := client.backpacks[position>>16] + if handle.id != 0 { + // Ordinary stack replay cannot remove an optimistic bag clone. + client.backpacks[position>>16] = backpackHandle{handle.id, false} + return client.send(backpackClosePacket(client.id, handle.id)) + } + } return server.syncStacks_locked(client) } if key == 0x47537a24 || key == 0x3a243f41 { diff --git a/server/player_trading_lifecycle_test.go b/server/player_trading_lifecycle_test.go @@ -77,6 +77,51 @@ func TestPlayerTradeConflictingInventoryActionCancelsWithoutActingOnRestoredSlot } } +func TestPlayerTradeBackpackSplitClosesWithoutChangingOwnership(t *testing.T) { + for name, slot := range map[string]uint32{"first": 0, "last": 20} { + t.Run(name, func(t *testing.T) { + world, conns := newPlayerTradeWorld(t) + player, client := world.characters[1], world.clients[1] + inventory := playerInventory{LastID: 5, Items: []ownedItem{ + {ID: 4, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1}}, + Containers: map[uint32][]ownedItem{4: { + {ID: 5, Type: 51005, Template: 25812, Quality: 2, Slot: slot, Count: 3}}}} + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { + t.Fatal(err) + } + playerTradeRequest(t, world, 2, 0, [2]uint32{50000, 1}, [2]uint32{}) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + conns[0].packets, conns[1].packets = nil, nil + request := characterActionPacket(1, [5]uint32{52, 107, 65536 + slot, 0, 1})[20:] + + for range 2 { + if err := world.handleInventory(client, request); err != nil { + t.Fatal(err) + } + } + after, err := readTestItemStore(world) + + cancel := targetPacket(shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})) + peerCancel := bytes.Clone(cancel) + binary.BigEndian.PutUint32(peerCancel[12:16], 2) + close := targetPacket(backpackClosePacket(1, 4)) + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || world.nextItem != 5 || + client.trade != nil || world.clients[2].trade != nil || client.backpacks[1] != (backpackHandle{4, false}) || + !reflect.DeepEqual(conns[0].packets, [][]byte{cancel, close, close}) || + !reflect.DeepEqual(conns[1].packets, [][]byte{peerCancel}) { + t.Fatal("trade split changed ownership, wrote storage or failed exact source closure", err) + } + }) + } +} + func TestPlayerTradeMovementAndControlEditCancelTheDraft(t *testing.T) { for _, scenario := range []string{"movement", "edit"} { t.Run(scenario, func(t *testing.T) { diff --git a/tools/client/test_depleted_backpack_split.mjs b/tools/client/test_depleted_backpack_split.mjs @@ -28,6 +28,33 @@ try { await game.click(681, 45, 'right'); await game.wait('original three-charge source opens', () => cell(0)); evidence.initial = await server(); + + // An ordinary three-charge split must restore its bag source when trade aborts. + const tradeSequence = game.sequence; + assert((await page.request.post(url + '/test-trade')).ok()); + await game.wait('native trade opens beside the bag', () => game.events.some(event => event.sequence > tradeSequence && + event.direction === 'framereceived' && event.opcode === '36284f6e' && Buffer.from(event.hex, 'hex').readUInt32BE(33) === 0)); + evidence.trading = await server(); + assert.equal(evidence.trading.trade, true); + const splitSequence = game.sequence; + await page.keyboard.down('Control'); + try { await click(cell(0)); } finally { await page.keyboard.up('Control'); } + await game.wait('real backpack split during trade', () => game.events.some(event => event.sequence > splitSequence && + event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52)); + evidence.tradeRequested = await server(); + await game.save(output + '/trade-requested'); + await game.wait('cancelled trade closes its split source window', () => !cell(0) && !cell(1)); + evidence.tradeRefused = await server(); + assert.deepEqual(evidence.tradeRefused, {...evidence.trading, trade: false, open: false}); + if (game.state.dragged[0] !== 0) { + await game.click(735, 45); + await game.wait('closed split source cannot be placed', snapshot => snapshot.dragged[0] === 0); + } + await game.click(681, 45, 'right'); + await game.wait('normal Use restores the complete three-charge source', () => cell(0) && !cell(1)); + assert.deepEqual((await server()).inventory, evidence.initial.inventory); + await game.save(output + '/trade-recovered'); + assert((await page.request.post(url + '/test-deplete-source')).ok()); evidence.depleted = await server(); assert.equal(evidence.depleted.open, true); @@ -65,7 +92,7 @@ try { [1, 48, [99228, 99228], 1, 1], [2, 49, [25812, 25811], 2, 1]]); assert.deepEqual((await server()).inventory, evidence.recovered.inventory); assert.deepEqual(game.errors, []); - console.log('PASS: stale equal-count split removes its phantom without allocation and recovers the exact remaining charge through normal withdrawal and page/cold loading'); + console.log('PASS: trade and stale-count refusals remove their bag clones without allocation; normal reopening preserves all three charges and later withdrawal retains the exact remaining charge'); } finally { try { await fs.mkdir(output, {recursive: true});