commit 6e4f4995773fa831e8d07dbecd9b8fb274ba755e
parent 54cbaad2c76103e0dca744c4b3a524ea22bfd6d7
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 12:39:45 +0000
Preserve selected stack endpoints during resynchronization
Diffstat:
6 files changed, 290 insertions(+), 1 deletion(-)
diff --git a/TODO.md b/TODO.md
@@ -3782,6 +3782,15 @@ and server restarts. Turn every reproduced bug into a focused regression test.
cases, native completion/retry, page replay and exact cold ownership pass;
this leaves the broader audit open. See
[pending equipment](docs/inventory.md#another-move-while-equipment-is-pending).
+- [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
+ endpoint pair in stack resynchronization. Both anchors of three medical
+ families at QL1/2/100/101/199/200 now preserve feedback, counts and ownership
+ without writes or a changed equipment deadline. The short WASM check refuses
+ QL2/101 splits, completes the weapon, uses the restored QL2 laboratory for
+ 37 health/one charge and retains all three IDs through page/cold recovery.
+ See [selected stack resynchronization](docs/inventory-stacks.md#selected-quality-stack-resynchronization).
- [x] [P0] Join same-quality stacks stored against opposite reviewed anchors.
Native QL2 laboratories exposed the same low/high pair and sent action 53,
but a raw stored-template comparison refused the join and hid its source.
diff --git a/docs/inventory-stacks.md b/docs/inventory-stacks.md
@@ -165,6 +165,33 @@ and `ev_78e48f17a73e495dccf184968e44268af825c92b3d9bd79d86ccd44c30c86806`.
Apparent ATR activation calls on these paths resolve to original `0x1010def0`,
a `RET 4` stub, and must not be filled in as a missing adapter method.
+### Selected-quality stack resynchronization
+
+The ordinary-stack rebuild resolves each instance's low/high pair before sending
+AddTemplate. Repeating its stored anchor instead changed the native contract of
+an intermediate-quality stack. A controlled refused QL2 laboratory split exposed
+25811/25811 after starting with 25812/25811; storage still retained the same QL
+and three charges. Rebuild now preserves the selected pair, including collapsed
+exact endpoints, without changing ownership or the admitted equipment move.
+
+`TestStackSplitRefusalPreservesSelectedEndpoints` checks both stored anchors of
+all three medical families at QL1/2/100/101/199/200 through the public inventory
+handler. Feedback retains the correct endpoints, QL and count with no durable
+writes; equipment completion and cold loading retain both original identities.
+The focused WASM check refuses real Ctrl-splits of QL2/101 laboratories while
+server equipment completion is held past the local animation. It preserves both
+endpoint pairs and all six charges, then completes the weapon and normally uses
+the restored QL2 laboratory for 37 health and one charge. Page/cold recovery
+retains the same instances. The controlled level, skills, health and supplies
+are test conditions, not earned progression. Evidence is retained under
+`local/selected-stack-resync/`.
+
+Related Go checks pass 37 roots and 293 results; focused race checks pass three
+roots and 59 results in 107.654 seconds. Vet and Node syntax checks pass. The
+native run completes in 20.89 seconds with four clean, complete traces.
+Independent split/rebuild/use checks and source hashes are in
+`local/selected-stack-resync/verification.json`.
+
Stacks inside the supported [backpack](backpacks.md) use page 107's packed
handle/slot positions. Their optimistic-split correction uses the native Chest
InventoryUpdate replacement instead of rebuilding ordinary inventory.
diff --git a/server/browser_selected_stack_resync_test.go b/server/browser_selected_stack_resync_test.go
@@ -0,0 +1,87 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserSelectedStackSplitRefusal(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for selected-quality split refusal")
+ }
+
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/selected-stack-resync", time.Now().Format("20060102-150405"))
+ world := newTestServer(t)
+ player := world.newCharacter()
+ player.stats = testCharacterStats()
+ player.level = 100
+ player.stats.Abilities = characterAbilitiesStats{80, 80, 80, 80, 80, 80}
+ player.stats.NanoAiding.Treatment = 100
+ player.health = 1
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("selected-stack-resync")))
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ for _, template := range []uint32{209283, 25811, 25812} {
+ if granted, err := world.grantItem_locked(player, template); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ }
+ player.inventory.Items[1].Quality, player.inventory.Items[2].Quality = 2, 101
+ player.inventory.Items[1].Count, player.inventory.Items[2].Count = 3, 3
+ if err := world.saveInventory_locked(player, 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}
+ }
+ json.NewEncoder(w).Encode(map[string]any{"inventory": player.inventory, "pending": pending, "health": player.health})
+ })
+ 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(), 3*time.Minute)
+ defer cancel()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_selected_stack_resync.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)
+ }
+ cold := newTestInventoryServer(t)
+ expected := []ownedItem{{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1},
+ {ID: 2, Type: 51005, Template: 25811, Quality: 2, Slot: 65, Count: 2},
+ {ID: 3, Type: 51005, Template: 25812, Quality: 101, Slot: 66, Count: 3}}
+ if !slices.Equal(cold.characters[1].inventory.Items, expected) || cold.characters[1].health != 38 || cold.nextItem != 3 {
+ t.Fatal("selected split refusal/use changed equipment, charges or health")
+ }
+}
diff --git a/server/stack_resync_quality_test.go b/server/stack_resync_quality_test.go
@@ -0,0 +1,77 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "testing"
+)
+
+func TestStackSplitRefusalPreservesSelectedEndpoints(t *testing.T) {
+ for _, family := range [][2]uint32{{25812, 25811}, {85366, 85367}, {25820, 25821}} {
+ for _, anchor := range family {
+ for _, quality := range []uint32{1, 2, 100, 101, 199, 200} {
+ t.Run(fmt.Sprintf("%d/QL%d", anchor, quality), func(t *testing.T) {
+ world, output := newEquipmentWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if granted, err := world.grantItem_locked(player, anchor); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ player.inventory.Items[1].Quality, player.inventory.Items[1].Count = quality, 3
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("weapon did not begin its admitted move", err)
+ }
+ pending := *client.equipment
+ before := slices.Clone(player.inventory.Items)
+ persisted, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ auditCheckpointWrites(t, world)
+ output.packets = nil
+
+ err = world.handleInventory(client, stackActionPacket(1, 52, 65, 1)[20:])
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(persisted, after) || !slices.Equal(player.inventory.Items, before) ||
+ *client.equipment != pending || world.nextItem != 2 {
+ t.Fatal("refused split changed ownership or the admitted weapon move", err, readErr)
+ }
+ if writes := checkpointWrites(t, world); len(writes) != 0 {
+ t.Fatal("refused split wrote durable state", writes)
+ }
+ low, high := family[0], family[1]
+ if quality == 1 {
+ high = low
+ } else if quality == 200 {
+ low = high
+ }
+ var additions int
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x052e2f0c {
+ continue
+ }
+ additions++
+ if binary.BigEndian.Uint32(packet[29:33]) != low || binary.BigEndian.Uint32(packet[33:37]) != high ||
+ binary.BigEndian.Uint32(packet[37:41]) != quality || binary.BigEndian.Uint32(packet[41:45]) != 3 {
+ t.Fatal("refused split lost its selected endpoint contract")
+ }
+ }
+ if additions != 1 {
+ t.Fatal("refused split did not restore exactly one stack")
+ }
+ world.advanceEquipment(pending.readyAt)
+ cold := newTestInventoryServer(t)
+ before[0].Slot = 6
+ if !slices.Equal(cold.characters[1].inventory.Items, before) || cold.nextItem != 2 {
+ t.Fatal("admitted completion or cold recovery lost the selected stack")
+ }
+ })
+ }
+ }
+ }
+}
diff --git a/server/stacks.go b/server/stacks.go
@@ -155,7 +155,8 @@ func (server *server) syncStacks_locked(client *worldClient) error {
continue
}
var body []byte
- for _, value := range []uint32{item.Template, item.Template, item.Quality, uint32(item.Count)} {
+ low, high := item.templateIDs()
+ for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} {
body = binary.BigEndian.AppendUint32(body, value)
}
if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); err != nil {
diff --git a/tools/client/test_selected_stack_resync.mjs b/tools/client/test_selected_stack_resync.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',
+ 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: 'selected-stack-resync', 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 click = async (slot, button = 'left') => {
+ const source = game.state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy);
+ assert(source, 'the exact source must be visible');
+ await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2, button);
+ };
+ await game.key('i');
+ await page.keyboard.press('Control+1');
+ await click(48);
+ await game.click(867, 206);
+ await game.wait('native weapon request', () => game.events.some(event =>
+ event.direction === 'framesent' && event.opcode === '47537a24'));
+ evidence.pending = await server();
+ assert(evidence.pending.pending);
+ await game.wait('local equipment animation ends', state =>
+ !game.local(state).actions.includes(3) && !game.local(state).actions.includes(6));
+
+ // Refuse real optimistic splits while the authoritative weapon move is held.
+ for (const slot of [49, 50]) {
+ const source = game.state.grids.flatMap(grid => grid.cells).find(cell =>
+ cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy);
+ const sequence = game.sequence;
+ await page.keyboard.down('Control');
+ try { await click(slot); } finally { await page.keyboard.up('Control'); }
+ await game.wait('native optimistic split request', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framesent' && event.opcode === '5e477770' && Buffer.from(event.hex, 'hex').readUInt32BE(29) === 52));
+ await game.wait('authoritative three-charge source restored', state => game.local(state).inventory.some(item =>
+ item.slot === slot && item.count === 3) && game.local(state).inventory.length === 3);
+ await game.save(output + '/refused-' + slot);
+ for (const item of game.local().inventory.filter(item => item.slot === 49 || item.slot === 50))
+ assert.deepEqual(item.templates, [25812, 25811], 'refused split must preserve selected endpoints');
+ assert.deepEqual(await server(), evidence.pending);
+ if (game.state.dragged[0] !== 0) {
+ // Place the selected source in a different empty visual cell.
+ const grid = game.state.grids.find(grid => grid.cells.some(cell => cell.identity[0] === 104));
+ const destination = grid.cells.find(cell => cell.identity[0] === 0 && cell.index !== source.index);
+ await game.click((destination.bounds[0] + destination.bounds[2]) / 2, (destination.bounds[1] + destination.bounds[3]) / 2);
+ await game.wait('picked source placed and restored', state => state.dragged[0] === 0 &&
+ state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104 && cell.identity[1] === slot && !cell.dummy)));
+ }
+ assert.deepEqual(await server(), evidence.pending);
+ }
+ assert((await page.request.post(url + '/test-complete')).ok());
+ await game.wait('original weapon completes', state => game.local(state).inventory.some(item => item.id === 1 && item.slot === 6));
+
+ // The restored QL2 source must pass its native requirement and heal once.
+ await game.key('F1');
+ await game.key('KeyX');
+ await game.wait('seated laboratory user', state => game.local(state).stats[430] === 2);
+ await click(49, 'right');
+ await game.wait('selected QL2 laboratory heals', state => game.local(state).stats[27] === 38 &&
+ game.local(state).inventory.some(item => item.slot === 49 && item.count === 2));
+ evidence.used = await server();
+ assert.equal(evidence.used.health, 38);
+ await game.save(output + '/used');
+ await page.reload();
+ await game.ready();
+ assert.deepEqual(game.local().inventory.map(item => [item.id, item.slot, item.quality, item.count]).sort((a, b) => a[0] - b[0]),
+ [[1, 6, 1, 1], [2, 49, 2, 2], [3, 50, 101, 3]]);
+ assert.deepEqual(game.errors, []);
+ console.log('PASS: refused selected-quality splits preserve endpoints, equipment and charges, then permit native healing and page/cold recovery');
+} 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(); }
+}