commit 61347e4b4fdba935e86b3e82485af749caa9a8a1
parent b0ddc6be3086f993276911b2796733ef4d769056
Author: anon <anon@example.com>
Date: Tue, 3 Nov 2026 20:21:59 +0000
Enable original stationary surgery clinics
Diffstat:
19 files changed, 1590 insertions(+), 14 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1894,7 +1894,7 @@ introduction and starting-item gameplay remain open below.
Remove the numeric alias and require the full vending type. Failing handler
cases cover both known collisions; native information and vending clicks,
normal cancellation, page replay and cold inventory retention pass. Static
- information/clinic script execution remains in the world-item Use task.
+ information script execution remains in the world-item Use task.
See [typed shop identities](docs/shop-typed-identities.md).
- [ ] [P2] Recover complete historical shop stock, including the starter QETS
category's actual membership. Original descriptors identify
@@ -2188,6 +2188,9 @@ introduction and starting-item gameplay remain open below.
sight and completion target gates. Exercise interrupted zoning, additional
strain rules and historical NCU replacement admission policy. Current replacement uses the final
allocation after removal.
+ Stationary clinic delivery currently identifies the user as the passive
+ program's caster; recover the original item-induced caster identity together
+ with offline/death policy. See [stationary clinics](docs/stationary-clinics.md).
- [x] Apply one damage-over-time effect. Check: the expected number of ticks
occurs and stopping/removing the effect prevents further ticks.
Sixty complete ordinary single-Hit contracts share a template-driven tick
@@ -2473,11 +2476,20 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
player state. Both page reconnects, separate R/Pick Up, exact-book hand-in
and cold recovery conserve all 37 final owned items, with 803 credits and
unchanged XP/IP/vitals/supplies. Other world-item effects remain unsupported.
- Include original static information objects and Stationary Automated Surgery
- Clinic 43553, resolving their own placements and complete effect contracts;
- they are separate from numerically equal vending identities. See
- [typed shop identities](docs/shop-typed-identities.md).
+ Original static information objects and other complete effect contracts
+ remain. Resolve their own placements independently of numerically equal
+ vending identities; see [typed shop identities](docs/shop-typed-identities.md).
See [world-item Use](docs/mission-objectives.md#pickup-protocol).
+- [x] [P1] Use the original stationary surgery clinics. Authorize all 155 original
+ type-51005 placements, require 300 credits and no combat, and atomically commit
+ the fee, 1000-point health/nano restoration and five-minute program 157490.
+ Preserve its +100 Treatment, implant permission, refresh without stacking,
+ independent portable access and removal on zoning. Failed/ignored writes,
+ COMMIT failures, lost replies and expiry/zone retries preserve complete state.
+ Two short WASM phases verify failed Use/recovery, committed cash publication,
+ native implant wear, owner/observer views, page/cold recovery and controlled zoning
+ followed by a visible native removal refusal. See
+ [stationary clinics](docs/stationary-clinics.md).
- [x] Populate the fixed mission through shared admitted NPC profiles. Acceptance
commits five concrete level-1 Leets with the assignment and key; reconnect,
reentry and cold load retain those lives without re-reading a spawn recipe.
diff --git a/docs/implants.md b/docs/implants.md
@@ -234,8 +234,10 @@ applies trickle once.
Portable Surgery Clinic 43552, exact QL 1, type 51005, is supported for self-use
from ordinary inventory. Select yourself before using it. Other selected
-targets are rejected; friendly clinic use and stationary clinics remain future
-work. The item comes from `server/gamedata/items/items_002.yaml` and
+targets are rejected; friendly portable-clinic use remains future work.
+The 155 original stationary clinics now supply their separate paid, five-minute
+Treatment/access effect; see [stationary clinics](stationary-clinics.md).
+The portable item comes from `server/gamedata/items/items_002.yaml` and
[Auno's historical 14.2.1 record](https://auno.org/ao/db.php?id=43552&patch=14020100).
The clinic requires Treatment > 5 and a selected character. Its raw
diff --git a/docs/shop-typed-identities.md b/docs/shop-typed-identities.md
@@ -8,9 +8,9 @@ shop uses `51035:3221226422`. Both are reachable from the controlled fixture at
Vending Use now requires type 51035. The terminal dispatcher no longer forwards
type-51005 requests by numeric shop membership. Static information and clinic
-objects retain their independent terminal/world-item path. Their full script
-execution remains open; refusing an unsupported static Use does not establish
-the original script's server behavior.
+objects retain their independent terminal/world-item path. The recovered
+[stationary clinic contract](stationary-clinics.md) now executes through that
+path. Static information script execution remains open.
## Original placements
diff --git a/docs/stationary-clinics.md b/docs/stationary-clinics.md
@@ -0,0 +1,118 @@
+# Stationary surgery clinics
+
+Original Stationary Automated Surgery Clinic 43553 now uses its own typed
+placement and complete effect contract. Its world Use is independent of the
+vending object with the same numeric ID. The former generic terminal path
+rejected it, leaving both its healing and implant-access workflow unavailable.
+
+## Original contract
+
+The 14.9.1 resource has type 51005, QL1, Use bit8 and no Carry bit. Its action3
+criteria are Cash61 >299 AND stat410 ==0. The existing combat consumer supplies
+that zero/nonzero gate. No Treatment threshold, Treatment cooldown or selected
+character requirement is authored for this stationary item.
+
+| OnUse function | Authored effect |
+| --- | --- |
+| 53002 | CurrentNano214 +1000 |
+| 53002 | Health27 +1000 |
+| 53044 | Five-minute / leave-playfield surgery message |
+| 53057 | `Enabled!`, color2 |
+| 53030 | Graphics13600 with original color arguments |
+| 53002 | Cash61 -300 |
+| 53051 | Cast program157490 |
+
+The child, Stationary Surgery Clinic Effect 157490, has duration stat8=30000
+centiseconds. Its complete OnUse is Modify53045(Treatment124,+100) and
+RestrictAction53067(mask16,duration0). The permission lasts with the timed
+program; its description explicitly requires removal on zoning. Its flags
+0xD8002 exclude it from used NCU and ordinary cancellation in the existing
+native active-program consumer, despite its authored NCU stat54=999.
+Raw action136's Level >5000 criterion is retained. Ordinary player casting
+remains closed; this work admits the clinic's item-induced application, without
+generalizing that action gate.
+
+| Resource | Complete original payload SHA256 |
+| --- | --- |
+| 43553 | `e72d6f5caa15be8609c9cd95bb6ca58dca182b6ac12bfd283c7e804145a003be` |
+| 157490 | `f48913020b55dd5150bf9f36d2a6e330904f2244f62c3e49917740cd3cc03b03` |
+
+`tools/data/extract_clinics.py` extracts all 155 placements from original statels
+1000026 into `server/gamedata/clinics.yaml`. Every source row has type51005,
+template43553 and an empty placement script, so no per-placement effect override
+is omitted. The original index SHA256 is
+`46e5dc54af9358cc9bff05f4358e86af630e497bc677f361c133c88073b84d71`.
+Raw placements, source ordinals and hashes are retained in
+`local/stationary-clinic/placements.json`. Both complete template payloads are
+freshly reparsed and compared field for field in `source-audit.json`.
+
+## Commit and lifecycle
+
+An authenticated, living, ready user must be within five metres of the actual
+clinic in the same playfield. Independent equipment, trade, shop and bank state
+is preserved; these contexts add no new clinic requirement.
+The fee, capped restorations and installed/refreshed program commit in one
+SQLite transaction before success, resources or program delivery. Replayed Use
+sequences do not charge or extend access. A new affordable Use pays again and
+refreshes the same program, without stacking Treatment.
+
+The server sends the committed cash balance explicitly. The first native run
+received health1001, nano1002 and Features22 but retained cash700 after the
+database committed400; an absolute Cash61 update corrects that delivery gap.
+Program action177 supplies the child because the native CastNano executor is
+an original no-op; its retained evidence is described in
+[client effect handlers](combat-client-effect-handlers.md).
+
+Surgery access combines the portable clinic's independent deadline with the
+active stationary program. Expiring either source preserves the other. Program
+expiry removes Treatment and permission through the existing active-nano
+transaction and action65. A failed removal retains both modifier and permission
+until removal commits on retry. Features224
+publication preserves native base6 and any remaining surgery access.
+
+Cross-playfield replacement filters this program before committing the new
+character. Changed active-program membership now commits with edited character
+records, so a failed or ignored removal cannot publish the destination. Other
+active programs and same-playfield edits remain intact. No new timer/schema is
+introduced and ordinary inventory actions do not checkpoint unchanged programs.
+
+The child currently identifies the user as caster. The original server's exact
+item-induced caster identity, offline-time policy and death exceptions remain
+unverified. Remaining-time persistence follows the existing active-program
+policy; this implementation does not establish those historical policies.
+
+## Verification
+
+The public Use regression fails before implementation. Focused Go checks cover
+both restorations, exact fee boundaries, duplicate/refresh requests, admission,
+all placement bindings, cold state, ordinary-cast/cancel rejection, lost replies,
+expiry and overlap with portable access. Abort/ignored/rewrite/COMMIT faults
+cover fees, resources and program installation; expiry and zoning also exercise
+failed/ignored removal and retry while retaining an unrelated program.
+
+Two WASM clients use real original-clinic picking. The warm phase first receives
+an injected database failure, reconnects with unchanged700 cash / HP1 / nano2,
+then successfully pays300 and observes HP1001 / nano1002 / Features22. Native
+implant wear succeeds with raw Treatment0 and trickle9, while server Treatment
+is109. Page and fresh-server recovery retain the same implant and paid effect;
+cold native removal/rewear also succeeds.
+
+A controlled cross-playfield checkpoint then removes the effect. After the new
+world's ready acknowledgement, a visible native attempt to remove the retained
+implant reports that technical supervision is required. This isolates effect
+retirement; it does not test the original shop-door approach. The fixture's
+level, skills, funds and implant are controlled conditions, not earned progress.
+
+Accepted native evidence is under `local/stationary-clinic/20261103-120007/`:
+25.54 seconds warm and 18.55 seconds cold, with no client exceptions. Earlier
+fixture errors and the cash-publication baseline remain separately retained.
+All 11 accepted traces are complete. Independent SQLite checks retain one
+physical implant, the exact paid balances/resources and the expected program
+membership before/after zoning; integrity and foreign-key checks pass.
+
+The affected Go run passes 69 roots / 266 results. Final clinic checks pass
+10 roots / 44 results, including independent equipment/trade/shop/bank state.
+Focused race checks pass 11 roots / 45 results; finalized expiry and context
+cases pass another 1/3 and 1/5 respectively. These runs overlap in coverage.
+Vet, Node syntax and formatting checks pass. `local/stationary-clinic/verification.json`
+records the source hashes, complete artifact checks and remaining policy gaps.
diff --git a/server/browser_stationary_clinic_test.go b/server/browser_stationary_clinic_test.go
@@ -0,0 +1,144 @@
+package main
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "testing"
+ "time"
+)
+
+func TestBrowserStationaryClinic(t *testing.T) {
+ if os.Getenv("AO_GAME_TEST") != "1" {
+ t.Skip("set AO_GAME_TEST=1 for stationary surgery clinics")
+ }
+ _, source, _, _ := runtime.Caller(0)
+ root := filepath.Dir(filepath.Dir(source))
+ output := filepath.Join(root, "local/stationary-clinic", time.Now().Format("20060102-150405"))
+ t.Chdir(t.TempDir())
+ for _, phase := range []string{"warm", "cold"} {
+ t.Run(phase, func(t *testing.T) {
+ world := newServerForTest(t)
+ if phase == "warm" {
+ for index := 0; index < 2; index++ {
+ player := world.newCharacter()
+ player.appearance, player.profession = 0x115, 1
+ player.playfield, player.position = 1183, [3]float32{176.32516 + float32(index)*2, 5.75, 131.5}
+ player.rotation = [4]float32{0, 1, 0, 0}
+ player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("stationary-clinic-", index))))
+ player.stats = testCharacterStats()
+ if index == 0 {
+ player.level = 200
+ player.stats.Abilities = characterAbilitiesStats{40, 40, 40, 40, 40, 40}
+ player.stats.Abilities.Stamina, player.stats.Abilities.Psychic = 320, 320
+ player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 500, 500
+ player.stats.NanoAiding.Treatment = 0
+ player.health, player.nano = 1, 2
+ if player.trainingMaximum(152) < 500 || player.trainingMaximum(132) < 500 {
+ t.Fatal("clinic fixture exceeds native training caps")
+ }
+ }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ }
+ owner := world.characters[1]
+ inventory := owner.inventory
+ inventory.Credits = 700
+ if err := world.saveInventory_locked(owner, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(owner, 101173); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fault_clinic BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(ABORT, 'controlled clinic failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ owner := world.characters[1]
+ 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()
+ programs := []uint32{}
+ for _, effect := range owner.activeNanos {
+ programs = append(programs, effect.program)
+ }
+ treatment, _ := owner.effectiveStat(124)
+ json.NewEncoder(w).Encode(map[string]any{"phase": phase, "inventory": owner.inventory, "health": owner.health, "nano": owner.nano,
+ "programs": programs, "treatment": treatment, "permission": owner.canChangeImplants(time.Now()), "playfield": owner.playfield})
+ })
+ mux.HandleFunc("POST /test-clear-failure", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ defer world.mutex.Unlock()
+ if _, err := world.db.Exec("DROP TRIGGER fault_clinic"); err != nil {
+ t.Error(err)
+ w.WriteHeader(500)
+ }
+ })
+ mux.HandleFunc("POST /test-zone", func(w http.ResponseWriter, r *http.Request) {
+ world.mutex.Lock()
+ destination := owner.userData()
+ world.mutex.Unlock()
+ destination.Playfield, destination.Position = 1180, [3]float32{211.67, 6.16, 173.8}
+ if err := world.updateUser(destination); err != nil {
+ t.Error(err)
+ w.WriteHeader(500)
+ }
+ })
+ host := httptest.NewServer(mux)
+ t.Cleanup(host.Close)
+ closeTestBrowserStreams(t, world)
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ ticker := time.NewTicker(20 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case now := <-ticker.C:
+ world.advanceEquipment(now)
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ defer func() { cancel(); <-stopped }()
+
+ command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_stationary_clinic.mjs"), host.URL, filepath.Join(output, phase))
+ command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
+ err := command.Run()
+ closeTestSessions(t, world)
+ if _, saveErr := world.db.Exec("VACUUM INTO ?", filepath.Join(output, phase, "world.sqlite")); saveErr != nil {
+ t.Fatal(saveErr)
+ }
+ t.Logf("Browser artifacts: %s", output)
+
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := []ownedItem{{ID: 1, Type: 51022, Template: 101173, Quality: 1, Slot: 37, Count: 1}}
+ if !slices.Equal(owner.inventory.Items, expected) || owner.inventory.Credits != 400 || owner.health != 1001 || owner.nano != 1002 ||
+ len(world.characters[2].inventory.Items) != 0 || world.characters[2].inventory.Credits != 0 || world.nextItem != 1 {
+ t.Fatal("native clinic use lost resources, fee or implant ownership", owner.inventory, owner.health, owner.nano)
+ }
+ if owner.canChangeImplants(time.Now()) != (phase == "warm") || (phase == "warm" && len(owner.activeNanos) != 1) || (phase == "cold" && len(owner.activeNanos) != 0) {
+ t.Fatal("native clinic replay or zoning retained the wrong access")
+ }
+ })
+ if t.Failed() {
+ return
+ }
+ }
+}
diff --git a/server/control.go b/server/control.go
@@ -8,6 +8,7 @@ import (
"log"
"math"
"net/http"
+ "slices"
"strconv"
"strings"
"time"
@@ -329,6 +330,10 @@ func (server *server) prepareUser_locked(character, updated *character) {
updated.geometry = server.geometry
updated.skillLocks = character.skillLocks
updated.activeNanos = character.activeNanos
+ if updated.playfield != character.playfield {
+ // The stationary surgery effect explicitly ends when leaving its playfield.
+ updated.activeNanos = slices.DeleteFunc(slices.Clone(updated.activeNanos), func(effect activeNano) bool { return effect.program == 157490 })
+ }
updated.team = character.team
updated.buddies = character.buddies
updated.missions = character.missions
diff --git a/server/equipment.go b/server/equipment.go
@@ -104,7 +104,7 @@ func (character *character) canMoveEquipment(item ownedItem, destination uint32,
if destination < 64 && (!item.fitsEquipmentSlot(destination) || !character.canEquip(item)) {
return false
}
- if item.isImplant() && (!now.Before(character.implantChangesUntil) ||
+ if item.isImplant() && (!character.canChangeImplants(now) ||
item.Slot < 64 && !item.requirementsMet(7, character.meetsStatRequirement)) {
return false
}
diff --git a/server/gamedata/clinics.yaml b/server/gamedata/clinics.yaml
@@ -0,0 +1,466 @@
+# Generated from original 14.9.1 statels by extract_clinics.py.
+3221226188:
+ playfield: 716
+ position: [635.7000122070312, 40.0, 1665.0999755859375]
+3221226652:
+ playfield: 1180
+ position: [211.66964721679688, 5.410000324249268, 171.30001831054688]
+3221226653:
+ playfield: 1181
+ position: [180.85635375976562, 5.0, 161.90774536132812]
+3221226654:
+ playfield: 1182
+ position: [194.0, 8.101115226745605, 175.010498046875]
+3221226655:
+ playfield: 1183
+ position: [176.32516479492188, 5.000364303588867, 129.0]
+3221226656:
+ playfield: 1184
+ position: [206.27157592773438, 5.000329494476318, 106.18438720703125]
+3221226657:
+ playfield: 1185
+ position: [211.0, 5.000149726867676, 131.60000610351562]
+3221226658:
+ playfield: 1186
+ position: [183.6773681640625, 5.000950813293457, 125.45294189453125]
+3221226659:
+ playfield: 1187
+ position: [205.04010009765625, 5.0, 137.36627197265625]
+3221227477:
+ playfield: 2005
+ position: [201.08334350585938, 5.0, 170.44284057617188]
+3221227485:
+ playfield: 2013
+ position: [205.08334350585938, 5.0, 200.44284057617188]
+3221227495:
+ playfield: 2023
+ position: [221.08334350585938, 5.0, 212.44284057617188]
+3221227506:
+ playfield: 2034
+ position: [123.52458190917969, 5.000219821929932, 224.0]
+3221227515:
+ playfield: 2043
+ position: [207.7710418701172, 5.0, 208.0]
+3221227525:
+ playfield: 2053
+ position: [207.65396118164062, 5.0, 206.0]
+3221227536:
+ playfield: 2064
+ position: [188.704345703125, 5.0, 154.791259765625]
+3221227545:
+ playfield: 2073
+ position: [202.704345703125, 5.0, 196.791259765625]
+3221228472:
+ playfield: 3000
+ position: [102.95066833496094, 115.0, 130.01702880859375]
+3221228473:
+ playfield: 3001
+ position: [102.30000305175781, 115.0, 128.5]
+3221228474:
+ playfield: 3002
+ position: [102.30000305175781, 115.0, 128.5]
+3221228475:
+ playfield: 3003
+ position: [102.30000305175781, 115.0, 128.5]
+3221228476:
+ playfield: 3004
+ position: [102.30000305175781, 115.0, 128.5]
+3221228477:
+ playfield: 3005
+ position: [102.30000305175781, 115.0, 128.5]
+3221228478:
+ playfield: 3006
+ position: [102.30000305175781, 115.0, 128.5]
+3221228479:
+ playfield: 3007
+ position: [102.30000305175781, 115.0, 128.5]
+3221228480:
+ playfield: 3008
+ position: [102.30000305175781, 115.0, 128.5]
+3221228481:
+ playfield: 3009
+ position: [102.30000305175781, 115.0, 128.5]
+3221228482:
+ playfield: 3010
+ position: [102.30000305175781, 115.0, 128.5]
+3221228483:
+ playfield: 3011
+ position: [102.30000305175781, 115.0, 128.5]
+3221228484:
+ playfield: 3012
+ position: [102.30000305175781, 115.0, 128.5]
+3221228485:
+ playfield: 3013
+ position: [102.30000305175781, 115.0, 128.5]
+3221228486:
+ playfield: 3014
+ position: [102.30000305175781, 115.0, 128.5]
+3221228487:
+ playfield: 3015
+ position: [102.30000305175781, 115.0, 128.5]
+3221228488:
+ playfield: 3016
+ position: [102.30000305175781, 115.0, 128.5]
+3221228489:
+ playfield: 3017
+ position: [102.30000305175781, 115.0, 128.5]
+3221228490:
+ playfield: 3018
+ position: [102.30000305175781, 115.0, 128.5]
+3221228491:
+ playfield: 3019
+ position: [102.30000305175781, 115.0, 128.5]
+3221228492:
+ playfield: 3020
+ position: [102.30000305175781, 115.0, 128.5]
+3221228493:
+ playfield: 3021
+ position: [102.30000305175781, 115.0, 128.5]
+3221228494:
+ playfield: 3022
+ position: [102.30000305175781, 115.0, 128.5]
+3221228495:
+ playfield: 3023
+ position: [102.30000305175781, 115.0, 128.5]
+3221228496:
+ playfield: 3024
+ position: [102.30000305175781, 115.0, 128.5]
+3221228497:
+ playfield: 3025
+ position: [102.30000305175781, 115.0, 128.5]
+3221228498:
+ playfield: 3026
+ position: [102.30000305175781, 115.0, 128.5]
+3221228499:
+ playfield: 3027
+ position: [102.30000305175781, 115.0, 128.5]
+3221228500:
+ playfield: 3028
+ position: [102.30000305175781, 115.0, 128.5]
+3221228501:
+ playfield: 3029
+ position: [102.30000305175781, 115.0, 128.5]
+3221228502:
+ playfield: 3030
+ position: [102.30000305175781, 115.0, 128.5]
+3221228503:
+ playfield: 3031
+ position: [102.30000305175781, 115.0, 128.5]
+3221228504:
+ playfield: 3032
+ position: [102.30000305175781, 115.0, 128.5]
+3221228505:
+ playfield: 3033
+ position: [102.30000305175781, 115.0, 128.5]
+3221228506:
+ playfield: 3034
+ position: [102.30000305175781, 115.0, 128.5]
+3221228507:
+ playfield: 3035
+ position: [102.30000305175781, 115.0, 128.5]
+3221228508:
+ playfield: 3036
+ position: [102.30000305175781, 115.0, 128.5]
+3221228509:
+ playfield: 3037
+ position: [102.30000305175781, 115.0, 128.5]
+3221228510:
+ playfield: 3038
+ position: [102.30000305175781, 115.0, 128.5]
+3221228511:
+ playfield: 3039
+ position: [102.30000305175781, 115.0, 128.5]
+3221228512:
+ playfield: 3040
+ position: [102.30000305175781, 115.0, 128.5]
+3221228513:
+ playfield: 3041
+ position: [102.30000305175781, 115.0, 128.5]
+3221228514:
+ playfield: 3042
+ position: [102.30000305175781, 115.0, 128.5]
+3221228515:
+ playfield: 3043
+ position: [102.30000305175781, 115.0, 128.5]
+3221228516:
+ playfield: 3044
+ position: [102.30000305175781, 115.0, 128.5]
+3221228517:
+ playfield: 3045
+ position: [102.30000305175781, 115.0, 128.5]
+3221228518:
+ playfield: 3046
+ position: [102.30000305175781, 115.0, 128.5]
+3221228519:
+ playfield: 3047
+ position: [102.30000305175781, 115.0, 128.5]
+3221228520:
+ playfield: 3048
+ position: [102.30000305175781, 115.0, 128.5]
+3221228521:
+ playfield: 3049
+ position: [102.30000305175781, 115.0, 128.5]
+3221228522:
+ playfield: 3050
+ position: [102.30000305175781, 115.0, 128.5]
+3221228523:
+ playfield: 3051
+ position: [102.30000305175781, 115.0, 128.5]
+3221228524:
+ playfield: 3052
+ position: [102.30000305175781, 115.0, 128.5]
+3221228525:
+ playfield: 3053
+ position: [102.30000305175781, 115.0, 128.5]
+3221228526:
+ playfield: 3054
+ position: [102.30000305175781, 115.0, 128.5]
+3221228527:
+ playfield: 3055
+ position: [102.30000305175781, 115.0, 128.5]
+3221228528:
+ playfield: 3056
+ position: [102.30000305175781, 115.0, 128.5]
+3221228529:
+ playfield: 3057
+ position: [102.30000305175781, 115.0, 128.5]
+3221228530:
+ playfield: 3058
+ position: [102.30000305175781, 115.0, 128.5]
+3221228531:
+ playfield: 3059
+ position: [102.30000305175781, 115.0, 128.5]
+3221228572:
+ playfield: 3100
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228573:
+ playfield: 3101
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228574:
+ playfield: 3102
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228575:
+ playfield: 3103
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228576:
+ playfield: 3104
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228577:
+ playfield: 3105
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228578:
+ playfield: 3106
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228579:
+ playfield: 3107
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228580:
+ playfield: 3108
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228581:
+ playfield: 3109
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228582:
+ playfield: 3110
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228583:
+ playfield: 3111
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228584:
+ playfield: 3112
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228585:
+ playfield: 3113
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228586:
+ playfield: 3114
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228587:
+ playfield: 3115
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228588:
+ playfield: 3116
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228589:
+ playfield: 3117
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228592:
+ playfield: 3120
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228593:
+ playfield: 3121
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228594:
+ playfield: 3122
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228595:
+ playfield: 3123
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228596:
+ playfield: 3124
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228597:
+ playfield: 3125
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228598:
+ playfield: 3126
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228599:
+ playfield: 3127
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228600:
+ playfield: 3128
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228601:
+ playfield: 3129
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228602:
+ playfield: 3130
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228603:
+ playfield: 3131
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228604:
+ playfield: 3132
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228605:
+ playfield: 3133
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228606:
+ playfield: 3134
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228607:
+ playfield: 3135
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228608:
+ playfield: 3136
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228609:
+ playfield: 3137
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228610:
+ playfield: 3138
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228611:
+ playfield: 3139
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228612:
+ playfield: 3140
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228613:
+ playfield: 3141
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228614:
+ playfield: 3142
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228615:
+ playfield: 3143
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228616:
+ playfield: 3144
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228617:
+ playfield: 3145
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228618:
+ playfield: 3146
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228619:
+ playfield: 3147
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228620:
+ playfield: 3148
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221228621:
+ playfield: 3149
+ position: [45.56584548950195, 24.999652862548828, 107.864990234375]
+3221292188:
+ playfield: 1180
+ position: [241.60000610351562, 5.010000228881836, 179.0]
+3221292191:
+ playfield: 1183
+ position: [203.5, 5.009941577911377, 137.39999389648438]
+3221292194:
+ playfield: 1186
+ position: [209.5, 5.010000228881836, 111.0]
+3221422730:
+ playfield: 650
+ position: [736.4910888671875, 10.40000057220459, 1333.751708984375]
+3221488301:
+ playfield: 685
+ position: [2496.08837890625, 1.399999976158142, 1261.3726806640625]
+3221621748:
+ playfield: 3060
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621749:
+ playfield: 3061
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621750:
+ playfield: 3062
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621751:
+ playfield: 3063
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621752:
+ playfield: 3064
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621753:
+ playfield: 3065
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621754:
+ playfield: 3066
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621755:
+ playfield: 3067
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621756:
+ playfield: 3068
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621757:
+ playfield: 3069
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621758:
+ playfield: 3070
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621759:
+ playfield: 3071
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621768:
+ playfield: 3080
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621769:
+ playfield: 3081
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621770:
+ playfield: 3082
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621771:
+ playfield: 3083
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621772:
+ playfield: 3084
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621773:
+ playfield: 3085
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621774:
+ playfield: 3086
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621775:
+ playfield: 3087
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621776:
+ playfield: 3088
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221621777:
+ playfield: 3089
+ position: [108.3477783203125, 39.999237060546875, 71.21334838867188]
+3221684829:
+ playfield: 605
+ position: [2087.723388671875, 30.90819549560547, 2273.3203125]
+3221684894:
+ playfield: 670
+ position: [1046.8875732421875, 15.399759292602539, 4030.20068359375]
+3223388665:
+ playfield: 505
+ position: [1873.8016357421875, 25.0, 1285.4208984375]
diff --git a/server/gamedata/clinics_test.go b/server/gamedata/clinics_test.go
@@ -0,0 +1,19 @@
+package gamedata
+
+import "testing"
+
+func TestStationaryClinicsMatchOriginalPlacements(t *testing.T) {
+ clinic := ClinicTerminals[3221226655]
+
+ if len(ClinicTerminals) != 155 || clinic.Playfield != 1183 || clinic.Position != [3]float32{176.32516, 5.0003643, 129} {
+ t.Fatal("original stationary clinic placement changed")
+ }
+ for id, clinic := range ClinicTerminals {
+ if id&65535 != clinic.Playfield {
+ t.Fatal("clinic identity does not belong to its original playfield", id)
+ }
+ if _, known := Playfields[clinic.Playfield]; !known {
+ t.Fatal("clinic references an unknown playfield", id)
+ }
+ }
+}
diff --git a/server/gamedata/load.go b/server/gamedata/load.go
@@ -45,6 +45,10 @@ var (
Playfield uint32 `yaml:"playfield"`
Position [3]float32 `yaml:"position"`
}
+ ClinicTerminals map[uint32]struct {
+ Playfield uint32 `yaml:"playfield"`
+ Position [3]float32 `yaml:"position"`
+ }
InsuranceTerminals struct {
Scanners map[uint32]struct {
Template uint32 `yaml:"template"`
@@ -100,6 +104,7 @@ func init() {
loadYAML("playfields.yaml", &Playfields)
loadYAML("player_appearances.yaml", &PlayerAppearances)
loadYAML("banks.yaml", &BankTerminals)
+ loadYAML("clinics.yaml", &ClinicTerminals)
loadYAML("insurance.yaml", &InsuranceTerminals)
loadYAML("shops.yaml", &ShopMachines)
loadYAML("mission_booths.yaml", &MissionBooths)
diff --git a/server/implants.go b/server/implants.go
@@ -88,6 +88,19 @@ func skillLockPacket(owner, stat, seconds uint32) []byte {
return n3Packet(0x5e477770, 50000, owner, body)
}
+func (player *character) canChangeImplants(now time.Time) bool {
+ if now.Before(player.implantChangesUntil) {
+ return true
+ }
+ for _, effect := range player.activeNanos {
+ // Stationary permission stays with the installed program until removal commits.
+ if effect.program == 157490 {
+ return true
+ }
+ }
+ return false
+}
+
func (server *server) advanceItemEffects(now time.Time) {
server.updateMutex.Lock()
defer server.updateMutex.Unlock()
@@ -108,7 +121,11 @@ func (server *server) advanceItemEffects(now time.Time) {
player.implantChangesUntil = time.Time{}
body := binary.BigEndian.AppendUint32(nil, 224)
// Restore normal features, including the permission to cast programs.
- body = binary.BigEndian.AppendUint32(body, 6)
+ features := uint32(6)
+ if player.canChangeImplants(now) {
+ features |= 16
+ }
+ body = binary.BigEndian.AppendUint32(body, features)
updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, id, body))
}
}
diff --git a/server/insurance.go b/server/insurance.go
@@ -10,6 +10,9 @@ func (server *server) handleTerminalUse(client *worldClient, body []byte) error
if _, bank := gamedata.BankTerminals[binary.BigEndian.Uint32(body[44:48])]; bank && binary.BigEndian.Uint32(body[40:44]) == 51005 {
return server.handleBankUse(client, body)
}
+ if _, clinic := gamedata.ClinicTerminals[binary.BigEndian.Uint32(body[44:48])]; clinic && binary.BigEndian.Uint32(body[40:44]) == 51005 {
+ return server.handleStationaryClinicUse(client, body)
+ }
server.updateMutex.Lock()
defer server.updateMutex.Unlock()
server.mutex.Lock()
diff --git a/server/item_database.go b/server/item_database.go
@@ -201,6 +201,11 @@ func (server *server) persistItems_locked(store itemStore) error {
if err := updateRecord(tx, "characters", edited.id, characterColumns, record.fields()); err != nil {
return err
}
+ if !slices.Equal(edited.activeNanos, server.characters[edited.id].activeNanos) {
+ if err := writeActiveNanos(tx, edited, time.Now()); err != nil {
+ return err
+ }
+ }
}
if store.mission != nil {
if err := insertMission(tx, store.mission); err != nil {
diff --git a/server/nano_buffs.go b/server/nano_buffs.go
@@ -320,7 +320,7 @@ func (server *server) loadActiveNanos() error {
}
periodic := damageOverTimeNano(effect.program)
healing := healingOverTimeNano(effect.program)
- if !statBuffNano(effect.program) && !initiativeDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil {
+ if effect.program != 157490 && !statBuffNano(effect.program) && !initiativeDebuffNano(effect.program) && controlNano(effect.program) == nil && periodic == nil && healing == nil || effect.remaining < 0 || server.characters[id] == nil {
return fmt.Errorf("character %d has an unsupported active nano %d", id, effect.program)
}
if periodic != nil {
@@ -388,6 +388,15 @@ func (server *server) removeNano_locked(player *character, index int, now time.T
previous := *player
*player = candidate
server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{65, 0, 0, effect.caster, effect.program}))
+ if effect.program == 157490 {
+ features := uint32(6)
+ if player.canChangeImplants(now) {
+ features |= 16
+ }
+ body := binary.BigEndian.AppendUint32(nil, 224)
+ body = binary.BigEndian.AppendUint32(body, features)
+ server.queueCombat_locked(updates, player, player, n3Packet(0x2b333d6e, 50000, player.id, body))
+ }
if !player.npc {
server.finishResourceChange_locked(updates, player, previous, now)
}
diff --git a/server/stationary_clinic.go b/server/stationary_clinic.go
@@ -0,0 +1,112 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "time"
+)
+
+func (server *server) handleStationaryClinicUse(client *worldClient, body []byte) error {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ player := server.characters[client.id]
+ if len(body) != 48 || server.clients[client.id] != client || !client.target || !client.ready || client.loading || player.health == 0 ||
+ binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id ||
+ binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 ||
+ binary.BigEndian.Uint32(body[28:32]) != 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 ||
+ binary.BigEndian.Uint32(body[36:40]) != client.id || binary.BigEndian.Uint32(body[40:44]) != 51005 {
+ return nil
+ }
+ sequence := binary.BigEndian.Uint32(body[20:24])
+ if sequence <= client.useSequence {
+ return nil
+ }
+ client.useSequence = sequence
+ now := time.Now()
+ clinic, known := gamedata.ClinicTerminals[binary.BigEndian.Uint32(body[44:48])]
+ position := predictedPosition_locked(player, now)
+ x, y, z := position[0]-clinic.Position[0], position[1]-clinic.Position[1], position[2]-clinic.Position[2]
+ accepted := known && clinic.Playfield == player.playfield && x*x+y*y+z*z <= 25 &&
+ server.itemUseRequirementsMet_locked(player, player, ownedItem{Type: 51005, Template: 43553, Quality: 1, Count: 1})
+ if accepted {
+ // Commit the authored fee, restorations and complete timed effect together.
+ candidate := *player
+ candidate.inventory.Credits -= 300
+ candidate.health, candidate.nano = min(player.maximumHealth(), player.health+1000), min(player.maximumNano(), player.nano+1000)
+ candidate.activeNanos = slices.Clone(player.activeNanos)
+ effect := activeNano{program: 157490, caster: player.id, remaining: 5 * time.Minute, expiresAt: now.Add(5 * time.Minute)}
+ index := slices.IndexFunc(candidate.activeNanos, func(other activeNano) bool { return other.program == 157490 })
+ if index < 0 {
+ candidate.activeNanos = append(candidate.activeNanos, effect)
+ } else {
+ candidate.activeNanos[index] = effect
+ }
+ db, err := server.database()
+ if err != nil {
+ return err
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if err := updateRecord(tx, "players", player.id, "credits", []any{candidate.inventory.Credits}); err != nil {
+ return err
+ }
+ if err := updateRecord(tx, "characters", player.id, "health, nano", []any{candidate.health, candidate.nano}); err != nil {
+ return err
+ }
+ if err := writeActiveNanos(tx, &candidate, now); err != nil {
+ return err
+ }
+ var savedID uint32
+ if err := tx.QueryRow("SELECT id FROM characters JOIN players USING(id) WHERE id=? AND (credits, health, nano) IS (?, ?, ?)",
+ player.id, candidate.inventory.Credits, candidate.health, candidate.nano).Scan(&savedID); err != nil {
+ return fmt.Errorf("clinic outcome for player %d was not saved: %w", player.id, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ *player = candidate
+ player.savedVitals.Health, player.savedVitals.Nano = player.health, player.nano
+ }
+
+ // Complete native Use before publishing committed resources and the timed effect.
+ reply := slices.Clone(body[16:])
+ binary.BigEndian.PutUint32(reply, 2)
+ if accepted {
+ binary.BigEndian.PutUint32(reply, 1)
+ }
+ ackError := client.send(n3Packet(0x52526858, 50000, client.id, reply))
+ if !accepted {
+ return ackError
+ }
+ updates := make(map[*worldClient][][]byte)
+ server.queueCombat_locked(updates, player, player, characterActionPacket(player.id, [5]uint32{177, 53019, 157490, player.id, 30000}))
+ server.queueHealthSnapshot_locked(updates, player)
+ updates[client] = append(updates[client], nanoPointsPacket(player))
+ cash := binary.BigEndian.AppendUint32(nil, 61)
+ cash = binary.BigEndian.AppendUint32(cash, player.inventory.Credits)
+ updates[client] = append(updates[client], n3Packet(0x2b333d6e, 50000, client.id, cash))
+ text := "You have 5 minutes (or until you leave the playfield) to swap implants."
+ feedback := binary.BigEndian.AppendUint32(nil, uint32(len(text)))
+ feedback = append(feedback, text...)
+ feedback = append(feedback, 0, 0)
+ updates[client] = append(updates[client], n3Packet(0x5f4b442a, 50000, client.id, feedback))
+ sourcePackets := updates[client]
+ delete(updates, client)
+ server.sendCombatUpdates(updates)
+ if ackError != nil {
+ return ackError
+ }
+ for _, packet := range sourcePackets {
+ if err := client.send(packet); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/server/stationary_clinic_test.go b/server/stationary_clinic_test.go
@@ -0,0 +1,472 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "slices"
+ "testing"
+ "time"
+)
+
+func stationaryClinicUseRequest(sequence uint32) []byte {
+ request := shopUseRequest(sequence)
+ binary.BigEndian.PutUint32(request[40:44], 51005)
+ binary.BigEndian.PutUint32(request[44:48], 3221226655)
+ return request
+}
+
+func newStationaryClinicWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, output := newEquipmentWorld(t)
+ player := world.characters[1]
+ player.level, player.playfield = 200, 1183
+ player.position = [3]float32{176.32516, 5.00036, 129}
+ player.stats.Abilities = characterAbilitiesStats{40, 40, 40, 40, 40, 40}
+ player.stats.Abilities.Stamina, player.stats.Abilities.Psychic = 320, 320
+ player.stats.Body.BodyDevelopment, player.stats.Body.NanoPool = 500, 500
+ player.stats.NanoAiding.Treatment = 0
+ player.health, player.nano = 1, 2
+ if player.maximumHealth() < 1001 || player.maximumNano() < 1002 {
+ t.Fatal("fixture cannot distinguish the authored 1000-point restoration from a refill")
+ }
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.savePosition_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ inventory := player.inventory
+ inventory.Credits = 700
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(player, 101173); err != nil || !granted {
+ t.Fatal(granted, err)
+ }
+ output.packets = nil
+ return world, output
+}
+
+func TestStationaryClinicCommitsFeeResourcesAndSurgeryEffect(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ items := slices.Clone(player.inventory.Items)
+ started := time.Now()
+
+ err := world.handleTerminalUse(client, stationaryClinicUseRequest(1))
+
+ if err != nil || player.inventory.Credits != 400 || player.health != 1001 || player.nano != 1002 ||
+ player.nanoBonus(124) != 100 || len(player.activeNanos) != 1 || !slices.Equal(player.inventory.Items, items) {
+ t.Fatal("stationary clinic did not commit its complete fee, restoration and Treatment effect", err)
+ }
+ effect := player.activeNanos[0]
+ if effect.program != 157490 || effect.remainingAt(started) < 5*time.Minute || effect.remainingAt(time.Now()) > 5*time.Minute ||
+ len(output.packets) == 0 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 1 || player.usedNCU() != 0 ||
+ !player.canMoveEquipment(items[1], 37, time.Now()) {
+ t.Fatal("clinic delivery or five-minute implant permission differs")
+ }
+ cashUpdates := 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e && binary.BigEndian.Uint32(packet[29:33]) == 61 {
+ cashUpdates++
+ if binary.BigEndian.Uint32(packet[33:37]) != 400 {
+ t.Fatal("clinic published an uncommitted cash balance")
+ }
+ }
+ }
+ if cashUpdates != 1 {
+ t.Fatal("clinic did not publish its committed cash balance exactly once", cashUpdates)
+ }
+ cold := newTestInventoryServer(t).characters[1]
+ if cold.inventory.Credits != 400 || cold.health != 1001 || cold.nano != 1002 || cold.nanoBonus(124) != 100 ||
+ !slices.Equal(cold.inventory.Items, items) || !cold.canMoveEquipment(items[1], 37, time.Now()) {
+ t.Fatal("cold clinic outcome lost cash, resources, effects or an item")
+ }
+}
+
+func TestStationaryClinicRejectsUnavailableUseWithoutEffects(t *testing.T) {
+ for _, scenario := range []string{"cash 299", "range", "vertical range", "wrong zone", "unknown clinic", "wrong type", "foreign owner", "dead", "loading", "replaced", "replay", "own combat", "incoming combat"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ request := stationaryClinicUseRequest(1)
+ switch scenario {
+ case "cash 299":
+ inventory := player.inventory
+ inventory.Credits = 299
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ case "range":
+ player.position[0] += 5.01
+ case "vertical range":
+ player.position[1] += 5.01
+ case "wrong zone":
+ player.playfield = 1180
+ case "unknown clinic":
+ binary.BigEndian.PutUint32(request[44:48], 999)
+ case "wrong type":
+ binary.BigEndian.PutUint32(request[40:44], 51035)
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "dead":
+ player.health = 0
+ case "loading":
+ client.loading = true
+ case "replaced":
+ world.clients[1] = &worldClient{id: 1}
+ case "replay":
+ client.useSequence = 1
+ case "own combat":
+ player.fighting = 1000000
+ case "incoming combat":
+ world.fighting[1000000] = &character{id: 1000000, fighting: 1}
+ }
+ inventory := player.inventory
+ health, nano := player.health, player.nano
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ err = world.handleStationaryClinicUse(client, request)
+ after, readErr := readTestItemStore(world)
+
+ if err != nil || readErr != nil || !bytes.Equal(before, after) || !reflect.DeepEqual(player.inventory, inventory) ||
+ player.health != health || player.nano != nano || len(player.activeNanos) != 0 || player.canChangeImplants(time.Now()) {
+ t.Fatal("refused clinic use changed a fee, resource, item or permission", err, readErr)
+ }
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x52526858 || binary.BigEndian.Uint32(packet[29:33]) != 2 {
+ t.Fatal("refused clinic use published an effect")
+ }
+ }
+ })
+ }
+}
+
+func TestStationaryClinicRefreshChargesOnceAndDoesNotStack(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ inventory := player.inventory
+ inventory.Credits = 600
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ deadline := player.activeNanos[0].expiresAt
+ output.packets = nil
+
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+
+ if player.inventory.Credits != 300 || len(output.packets) != 0 || player.activeNanos[0].expiresAt != deadline {
+ t.Fatal("duplicate Use charged or extended the clinic effect")
+ }
+
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(3)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t).characters[1]
+
+ if player.inventory.Credits != 0 || len(player.activeNanos) != 1 || player.nanoBonus(124) != 100 ||
+ !player.activeNanos[0].expiresAt.After(deadline) || cold.inventory.Credits != 0 || cold.nanoBonus(124) != 100 {
+ t.Fatal("clinic refresh stacked, failed the exact 300-credit boundary or lost cold state")
+ }
+}
+
+func TestStationaryClinicFailureRollsBackThenRetries(t *testing.T) {
+ for _, failure := range []string{"fee", "ignored fee", "rewritten fee", "resources", "ignored resources", "rewritten resources", "program", "ignored program", "commit"} {
+ t.Run(failure, func(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ statement := "CREATE TRIGGER fault_clinic BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(ABORT, 'fee'); END"
+ switch failure {
+ case "ignored fee":
+ statement = "CREATE TRIGGER fault_clinic BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(IGNORE); END"
+ case "rewritten fee":
+ statement = "CREATE TRIGGER fault_clinic AFTER UPDATE OF credits ON players BEGIN UPDATE players SET credits=700 WHERE id=1; END"
+ case "resources":
+ statement = "CREATE TRIGGER fault_clinic BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(ABORT, 'resources'); END"
+ case "ignored resources":
+ statement = "CREATE TRIGGER fault_clinic BEFORE UPDATE OF health ON characters BEGIN SELECT RAISE(IGNORE); END"
+ case "rewritten resources":
+ statement = "CREATE TRIGGER fault_clinic AFTER UPDATE OF health ON characters BEGIN UPDATE characters SET health=1 WHERE id=1; END"
+ case "program":
+ statement = "CREATE TRIGGER fault_clinic BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(ABORT, 'program'); END"
+ case "ignored program":
+ statement = "CREATE TRIGGER fault_clinic BEFORE INSERT ON active_nanos BEGIN SELECT RAISE(IGNORE); END"
+ case "commit":
+ statement = "CREATE TABLE clinic_commit_failure (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fault_clinic AFTER INSERT ON active_nanos BEGIN INSERT INTO clinic_commit_failure VALUES(9999999); END"
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ failed := world.handleTerminalUse(client, stationaryClinicUseRequest(1))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if failed == nil || player.inventory.Credits != 700 || cold.inventory.Credits != 700 ||
+ player.health != 1 || player.nano != 2 || cold.health != 1 || cold.nano != 2 ||
+ len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || len(output.packets) != 0 {
+ t.Fatal("failed clinic outcome exposed a partial fee, resource, program or reply", failed)
+ }
+
+ if _, err := world.db.Exec("DROP TRIGGER fault_clinic"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(2)); err != nil {
+ t.Fatal(err)
+ }
+ cold = newTestInventoryServer(t).characters[1]
+
+ if player.inventory.Credits != 400 || cold.inventory.Credits != 400 || player.health != 1001 || cold.health != 1001 ||
+ player.nano != 1002 || cold.nano != 1002 || player.nanoBonus(124) != 100 || cold.nanoBonus(124) != 100 {
+ t.Fatal("clinic retry lost or repeated part of its outcome")
+ }
+ })
+ }
+}
+
+func TestStationaryClinicExpiryAndPortablePermissionAreIndependent(t *testing.T) {
+ for _, other := range []string{"none", "portable remains", "portable expires first"} {
+ t.Run(other, func(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ finish := player.activeNanos[0].expiresAt
+ if other == "portable remains" {
+ player.implantChangesUntil = finish.Add(time.Minute)
+ }
+ if other == "portable expires first" {
+ player.implantChangesUntil = finish.Add(-time.Minute)
+ }
+ output.packets = nil
+
+ if other == "portable expires first" {
+ world.advanceItemEffects(player.implantChangesUntil)
+ if !player.canChangeImplants(finish.Add(-time.Second)) {
+ t.Fatal("portable expiry removed stationary access")
+ }
+ }
+ world.advanceNanos(finish)
+ world.advanceNanos(finish.Add(time.Second))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || player.nanoBonus(124) != 0 || cold.nanoBonus(124) != 0 ||
+ player.canChangeImplants(finish) != (other == "portable remains") || player.inventory.Credits != 400 || cold.inventory.Credits != 400 {
+ t.Fatal("clinic expiry lost cash, retained Treatment or removed independent access")
+ }
+ removals := 0
+ for _, packet := range output.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 65 {
+ removals++
+ }
+ }
+ if removals != 1 {
+ t.Fatal("clinic expiry did not remove exactly one native effect", removals)
+ }
+ })
+ }
+}
+
+func TestStationaryClinicZoneRemovalCommitsWithDestination(t *testing.T) {
+ for _, failure := range []string{"none", "failed removal", "ignored removal"} {
+ t.Run(failure, func(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ player.activeNanos = append(player.activeNanos, activeNano{program: 27169, caster: 1, remaining: time.Minute, expiresAt: time.Now().Add(time.Minute)})
+ if err := world.saveActiveNanos_locked(player, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ destination := player.userData()
+ destination.Playfield = 1180
+ if failure != "none" {
+ operation := "ABORT, 'zone removal'"
+ if failure == "ignored removal" {
+ operation = "IGNORE"
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fault_clinic_zone BEFORE DELETE ON active_nanos WHEN OLD.program_id=157490 BEGIN SELECT RAISE(" + operation + "); END"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ output.packets = nil
+
+ err := world.updateUser(destination)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if failure != "none" {
+ if err == nil || player.playfield != 1183 || cold.playfield != 1183 || player.nanoBonus(124) != 100 ||
+ cold.nanoBonus(124) != 100 || world.clients[1] != client || len(output.packets) != 0 {
+ t.Fatal("failed zone removal published a destination or lost the clinic effect", err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fault_clinic_zone"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.updateUser(destination); err != nil {
+ t.Fatal(err)
+ }
+ cold = newTestInventoryServer(t).characters[1]
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ if player.playfield != 1180 || cold.playfield != 1180 || player.canChangeImplants(time.Now()) || cold.canChangeImplants(time.Now()) ||
+ player.nanoBonus(124) != 0 || cold.nanoBonus(124) != 0 || len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 ||
+ player.activeNanos[0].program != 27169 || cold.activeNanos[0].program != 27169 || player.inventory.Credits != 400 || cold.inventory.Credits != 400 {
+ t.Fatal("zone transition retained stationary access or removed an unrelated program")
+ }
+ })
+ }
+}
+
+func TestStationaryClinicLostReplyKeepsCommittedObserverOutcome(t *testing.T) {
+ world, _ := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ observer := &combatTestConn{}
+ world.characters[2] = &character{id: 2, playfield: 1183, health: 100}
+ world.clients[2] = &worldClient{id: 2, conn: observer, ready: true, target: true}
+ client.conn = &failingCombatConn{}
+
+ failed := world.handleTerminalUse(client, stationaryClinicUseRequest(1))
+ cold := newTestInventoryServer(t).characters[1]
+
+ if failed == nil || player.inventory.Credits != 400 || cold.inventory.Credits != 400 ||
+ player.nanoBonus(124) != 100 || cold.nanoBonus(124) != 100 || cold.health != 1001 || cold.nano != 1002 {
+ t.Fatal("lost clinic reply reversed or partially committed the outcome", failed)
+ }
+ programs := 0
+ for _, packet := range observer.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 177 {
+ programs++
+ }
+ }
+ if programs != 1 {
+ t.Fatal("failed owner reply suppressed the healthy observer's program", programs)
+ }
+}
+
+func TestStationaryClinicExpiryFailureRetainsEffectThenRetries(t *testing.T) {
+ for _, operation := range []string{"ABORT, 'expiry'", "IGNORE"} {
+ t.Run(operation, func(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ finish := player.activeNanos[0].expiresAt
+ if _, err := world.db.Exec("CREATE TRIGGER fault_clinic_expiry BEFORE DELETE ON active_nanos BEGIN SELECT RAISE(" + operation + "); END"); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ world.advanceNanos(finish)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if len(player.activeNanos) != 1 || len(cold.activeNanos) != 1 || len(output.packets) != 0 || player.inventory.Credits != 400 || cold.inventory.Credits != 400 ||
+ !player.canChangeImplants(finish) || !cold.canChangeImplants(finish) {
+ t.Fatal("failed expiry lost an effect or published removal")
+ }
+
+ if _, err := world.db.Exec("DROP TRIGGER fault_clinic_expiry"); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceNanos(finish.Add(time.Second))
+ cold = newTestInventoryServer(t).characters[1]
+
+ if len(player.activeNanos) != 0 || len(cold.activeNanos) != 0 || player.nanoBonus(124) != 0 || cold.nanoBonus(124) != 0 ||
+ player.canChangeImplants(finish.Add(time.Second)) || player.inventory.Credits != 400 || cold.inventory.Credits != 400 {
+ t.Fatal("expiry retry did not remove exactly the timed permission and modifier")
+ }
+ })
+ }
+}
+
+func TestStationaryClinicEffectRejectsOrdinaryCastingAndCancellation(t *testing.T) {
+ world, output := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ inventory := player.inventory
+ inventory.LearnedNanos = []uint32{157490}
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, 1, 53019, 157490})[20:]); err != nil {
+ t.Fatal(err)
+ }
+
+ if client.nanoCast != nil || len(player.activeNanos) != 0 || player.inventory.Credits != 700 || player.nano != 2 {
+ t.Fatal("ordinary casting bypassed the clinic contract")
+ }
+
+ if err := world.handleTerminalUse(client, stationaryClinicUseRequest(1)); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+ if err := world.handleNanoRemoval(client, characterActionPacket(1, [5]uint32{65, 0, 0, 53019, 157490})[20:]); err != nil {
+ t.Fatal(err)
+ }
+
+ if len(player.activeNanos) != 1 || player.nanoBonus(124) != 100 || !player.canChangeImplants(time.Now()) || len(output.packets) != 0 || player.inventory.Credits != 400 {
+ t.Fatal("ordinary removal cancelled the protected clinic effect")
+ }
+}
+
+func TestStationaryClinicPreservesIndependentActionState(t *testing.T) {
+ for _, action := range []string{"equipment", "trade", "shop", "bank"} {
+ t.Run(action, func(t *testing.T) {
+ world, _ := newStationaryClinicWorld(t)
+ player, client := world.characters[1], world.clients[1]
+ switch action {
+ case "equipment":
+ if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil || client.equipment == nil {
+ t.Fatal("admit independent equipment move", err)
+ }
+ case "trade":
+ client.trade = &playerTrade{}
+ case "shop":
+ client.shop = &shopTrade{}
+ case "bank":
+ client.bank = &bankSession{}
+ }
+ trade, shop, bank := client.trade, client.shop, client.bank
+ deadline := time.Time{}
+ if client.equipment != nil {
+ deadline = client.equipment.readyAt
+ }
+ items := slices.Clone(player.inventory.Items)
+
+ err := world.handleTerminalUse(client, stationaryClinicUseRequest(1))
+
+ if err != nil || player.inventory.Credits != 400 || player.nanoBonus(124) != 100 ||
+ !slices.Equal(player.inventory.Items, items) || client.trade != trade || client.shop != shop || client.bank != bank {
+ t.Fatal("clinic use disturbed an independent action or refused an unauthored context", err)
+ }
+ if action == "equipment" {
+ if client.equipment == nil || client.equipment.itemID != 1 || client.equipment.source != 64 ||
+ client.equipment.destination != 6 || client.equipment.readyAt != deadline {
+ t.Fatal("clinic changed the admitted move or deadline")
+ }
+ world.advanceEquipment(deadline)
+ items[0].Slot = 6
+ }
+ cold := newTestInventoryServer(t).characters[1]
+ if !slices.Equal(player.inventory.Items, items) || !slices.Equal(cold.inventory.Items, items) || cold.inventory.Credits != 400 || cold.nanoBonus(124) != 100 {
+ t.Fatal("clinic use or equipment completion lost a durable outcome")
+ }
+ })
+ }
+}
diff --git a/server/world.go b/server/world.go
@@ -253,7 +253,7 @@ func fullCharacterPacket(character *character) []byte {
[2]uint32{47, uint32(character.appearance >> 2 & 3)},
[2]uint32{360, uint32(scale)},
[2]uint32{214, character.nano}, [2]uint32{221, character.maximumNano() - uint32(character.inventory.equipmentBonus(221))})
- if time.Now().Before(character.implantChangesUntil) {
+ if character.canChangeImplants(time.Now()) {
// Surgery access supplements the native base Features value of 6.
stats = append(stats, [2]uint32{224, 6 | 16})
}
diff --git a/tools/client/test_stationary_clinic.mjs b/tools/client/test_stationary_clinic.mjs
@@ -0,0 +1,131 @@
+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']});
+const games = [], sockets = [], evidence = {};
+try {
+ for (const index of [0,1]) {
+ const context = await browser.newContext({viewport:{width:1024,height:768}});
+ await context.addCookies([{name:'ao_client',value:'stationary-clinic-'+index,url}]);
+ const page = await context.newPage(), game = await GameTest.attach(page);
+ page.on('websocket', socket => { if (socket.url().endsWith('/browser-world')) sockets[index] = socket; });
+ games.push(game);
+ await page.goto(url);
+ await game.ready();
+ await page.waitForFunction(() => touchRegion(500,400)?.world === true);
+ await game.snapshot();
+ }
+ const [owner, observer] = games;
+ const server = async () => (await owner.page.request.get(url+'/test-state')).json();
+ const inventoryClick = async () => {
+ await owner.wait('implant actions end', state => !owner.local(state).actions.includes(3) && !owner.local(state).actions.includes(6));
+ const cell = owner.state.grids.flatMap(grid=>grid.cells).find(cell=>cell.identity[0]===104 && cell.identity[1]===48 && !cell.dummy);
+ assert(cell,'retained implant is visible in ordinary inventory');
+ await owner.click((cell.bounds[0]+cell.bounds[2])/2,(cell.bounds[1]+cell.bounds[3])/2,'right');
+ };
+ const reload = async () => {
+ await owner.page.reload(); await owner.ready();
+ await owner.page.waitForFunction(() => touchRegion(500,400)?.world === true);
+ await owner.snapshot();
+ };
+ const wearPanel = async () => {
+ if (!owner.state.regions.some(([left,top,right,bottom])=>left===832 && top===0 && right===1024 && bottom===360))
+ await owner.page.keyboard.press('Control+1');
+ await owner.wait('native Wear panel is open',state=>state.regions.some(([left,top,right,bottom])=>
+ left===832 && top===0 && right===1024 && bottom===360));
+ await owner.click(993,53);
+ };
+ evidence.initial = await server();
+ if (evidence.initial.phase === 'warm') {
+ assert.equal(evidence.initial.treatment,9);
+ assert.equal(owner.local().stats[224]&16,0);
+ await owner.key('KeyI');
+ await wearPanel();
+ await inventoryClick();
+ assert.equal((await server()).inventory.Items[0].Slot,64);
+ await owner.save(output+'/before-access');
+ await owner.page.keyboard.press('Control+1');
+ if (!owner.state.camera.firstPerson) await owner.key('F8');
+
+ // A real Use fails before any native fee or healing acknowledgement.
+ const failed = owner.sequence;
+ const closed = sockets[0].waitForEvent('close', {timeout:15000});
+ await owner.click(...await owner.pick(51005,3221226655),'right');
+ await owner.wait('failed clinic request reaches the server', () => owner.events.some(event=>event.sequence>failed &&
+ event.direction==='framesent' && event.opcode==='52526858'));
+ await closed;
+ assert((await owner.page.request.post(url+'/test-clear-failure')).ok());
+ await reload();
+ evidence.failed = await server();
+ assert.equal(evidence.failed.inventory.Credits,700);
+ assert.equal(evidence.failed.health,1); assert.equal(evidence.failed.nano,2);
+ assert.deepEqual(evidence.failed.programs,[]);
+ await owner.save(output+'/failed-recovered');
+
+ const use = owner.sequence;
+ await owner.click(...await owner.pick(51005,3221226655),'right');
+ await owner.wait('stationary surgery effect arrives', () => owner.events.some(event=>event.sequence>use &&
+ event.direction==='framereceived' && event.opcode==='5e477770' && Buffer.from(event.hex,'hex').readUInt32BE(29)===177 &&
+ Buffer.from(event.hex,'hex').readUInt32BE(37)===157490));
+ await Promise.all(games.map(game=>game.wait('native clinic healing is visible', state=>state.actors.some(actor=>actor.id===1 && actor.type===50000 && actor.stats[27]===1001))));
+ await owner.wait('native clinic cash, nano and permission agree', state=>owner.local(state).stats[61]===400 &&
+ owner.local(state).stats[214]===1002 && (owner.local(state).stats[224]&16)!==0);
+ evidence.used = await server();
+ assert.equal(evidence.used.treatment,109); assert.deepEqual(evidence.used.programs,[157490]);
+ assert.equal(evidence.used.inventory.Credits,400);
+ await owner.save(output+'/used');
+ await observer.save(output+'/observer-used');
+ await owner.key('KeyI');
+ await wearPanel();
+ await inventoryClick();
+ await owner.wait('clinic-qualified native implant wear', state=>owner.local(state).inventory.some(item=>item.id===1 && item.slot===37));
+ await owner.save(output+'/worn');
+ await reload();
+ } else {
+ assert.deepEqual(evidence.initial.programs,[157490]);
+ assert.equal(evidence.initial.treatment,109);
+ assert.equal(evidence.initial.inventory.Credits,400);
+ await wearPanel();
+ await owner.click(927,148,'right');
+ await owner.wait('cold clinic access permits implant removal', state=>owner.local(state).inventory.some(item=>item.id===1 && item.slot===48));
+ await owner.key('KeyI');
+ await inventoryClick();
+ await owner.wait('cold clinic access permits implant rewear', state=>owner.local(state).inventory.some(item=>item.id===1 && item.slot===37));
+ await owner.save(output+'/cold-reworn');
+
+ // A controlled cross-playfield checkpoint isolates effect retirement from travel.
+ assert((await owner.page.request.post(url+'/test-zone')).ok());
+ await owner.wait('native transition enters the destination', state=>owner.local(state)?.playfield===1180);
+ await owner.ready();
+ await owner.page.waitForFunction(() => touchRegion(500,400)?.world === true);
+ await owner.snapshot();
+ evidence.zoned = await server();
+ assert.deepEqual(evidence.zoned.programs,[]); assert.equal(evidence.zoned.treatment,9);
+ assert.equal(evidence.zoned.permission,false);
+ assert.equal(owner.local().stats[224]&16,0);
+ await wearPanel();
+ const refused = owner.sequence;
+ await owner.click(927,148,'right');
+ assert.equal((await server()).inventory.Items[0].Slot,37);
+ assert(!owner.events.some(event=>event.sequence>refused && event.direction==='framesent' && event.opcode==='47537a24'));
+ await owner.save(output+'/zoned-refusal');
+ await reload();
+ }
+ evidence.final = await server();
+ assert.equal(evidence.final.inventory.Credits,400);
+ assert.deepEqual(owner.local().inventory.map(item=>[item.id,item.slot,item.quality]),[[1,37,1]]);
+ assert(games.every(game=>game.errors.length===0));
+ console.log('PASS: stationary clinic fee, healing, implant access and '+evidence.initial.phase+' recovery agree with native input and server state');
+} finally {
+ try {
+ await fs.mkdir(output,{recursive:true});
+ await fs.writeFile(output+'/verification.json',JSON.stringify(evidence,null,2)+'\n');
+ await Promise.all(games.map((game,index)=>game.save(output+'/final-'+index)));
+ } finally { await browser.close(); }
+}
diff --git a/tools/data/extract_clinics.py b/tools/data/extract_clinics.py
@@ -0,0 +1,56 @@
+import hashlib
+import json
+import pathlib
+import struct
+
+import ao_database
+
+
+def main():
+ client = pathlib.Path('anarchy-vanilla-14.9.1')
+ assert (client / 'version.id').read_text().strip() == '14.9.1'
+ database = ao_database.Database(client)
+ terminals = {}
+ records = []
+
+ # Original statels carry identity, transform, template and counted scripts.
+ for kind, playfield in sorted(database.records):
+ if kind != 1000026:
+ continue
+ payload = database.read(kind, playfield)
+ offset = 4
+ for ordinal in range(struct.unpack_from('<I', payload)[0]):
+ size = struct.unpack_from('<I', payload, offset)[0]
+ offset += 4
+ raw = payload[offset:offset + size]
+ offset += size
+ assert len(raw) == size
+ if size < 64 or struct.unpack_from('<I', raw, 56)[0] != 43553:
+ continue
+ identity_type, identity = struct.unpack_from('<II', raw)
+ assert identity_type == 51005 and identity not in terminals
+ assert struct.unpack_from('<I', raw, 60)[0] == size - 64
+ assert raw[64:] == struct.pack('>5I', 102, 103, 1009, 0, 0)
+ terminals[identity] = dict(playfield=playfield, position=list(struct.unpack_from('<3f', raw, 24)))
+ records.append(dict(playfield=playfield, ordinal=ordinal, identity=identity,
+ raw_hex=raw.hex(), sha256=hashlib.sha256(raw).hexdigest(),
+ resource_sha256=hashlib.sha256(payload).hexdigest()))
+ assert offset == len(payload)
+ database.close()
+
+ # Retain only the location needed to authorize an actual terminal use.
+ lines = ['# Generated from original 14.9.1 statels by extract_clinics.py.']
+ for identity, terminal in sorted(terminals.items()):
+ lines.extend([f'{identity}:', f' playfield: {terminal["playfield"]}',
+ f' position: {json.dumps(terminal["position"])}'])
+ output = pathlib.Path('server/gamedata/clinics.yaml')
+ output.write_text('\n'.join(lines) + '\n')
+ report = pathlib.Path('local/stationary-clinic/placements.json')
+ report.parent.mkdir(parents=True, exist_ok=True)
+ report.write_text(json.dumps(dict(index_sha256=hashlib.sha256(database.index).hexdigest(),
+ records=records), indent=2) + '\n')
+ print(f'{output}: {len(terminals)} terminals')
+
+
+if __name__ == '__main__':
+ main()