# PokeBridge Linux migration

This is a development build of the local memory/packet bridge. The Linux official
client initially downloaded revision 34693 on October 30, 2026, then updated
itself to revision 34702, 34863, 34868 and 34932. The current build targets the
hash-bound 34932 binary. Live party, position, bag, packet decoding, movement,
wild battle completion and return-to-training have been checked on this build.
Client memory profiles are bound to the binary's SHA-256
and the current process identity. Old Windows addresses are never reused.

Revision34932 has new hash-bound native layouts and remapped packet IDs. Its
independent encrypted bootstrap, six-party HP/PP, bag, overworld movement,
party reordering, repeated wild battles and normal GUI Start/Stop/Start have
been checked live. The earlier battle stall is fixed by reading the active
actor's actual Disable restriction, choosing another available move, and
clearing that transient restriction when the native state clears it. PP is not
fabricated and duplicate unacknowledged actions remain blocked. Native zero-ID
outcomes are retained as opaque turn events, not guessed damage or obedience
messages. A closed client decoder exits and cannot overwrite a newer live
session's status. These compatibility checks do not certify later story/HM
features or a complete unattended playthrough.

## Launch

Source checkout: run `./PokeBridge.sh` with Python 3.14 and PySide6 available.
Packaged build: extract the complete directory and run `PokeBridge`.
Choose **Import ROM folder**, select your own
extracted ROM directory, then choose **Open / reconnect client**. At least one
compatible Black or White ROM is required. Log into the official client.

The Automation tab defaults to **Wild battle cycle** and shows party HP, the
active member's current move PP, and the live packet session. Diagnostics
shows the transport, decoded packet count, and features verified for this client
revision. Unsupported modes remain disabled; an open window is not evidence of
a working automation mode. The separate legacy headless dashboard is not the
local bridge's game connection and is not required for this workflow.

Select **Badge progression · beta**, then click **Start automation**, to use the
train → gym attempt → confirmed badge / heal-and-train-retry coordinator.
It saves retry targets per character, selects a party member using known moves,
type coverage, HP/PP and a configured obedience-policy ceiling, and shows its
next gym and training target in Live activity. Only exact badge flags advance
the campaign. After a proven loss, the target rises by two levels, up to that
ceiling. Whole-party mode continues training weak members after a blackout even
when the configured target is already at the ceiling. A fully trained team that
still loses is flagged for team/strategy review, heals, and re-evaluates the
available team before retrying; it never raises the target above the ceiling.
Type/level policies use ROM baselines, not unseen server teams.
Badge training defaults to **Train every party member**. It rotates through
non-egg members below the target, but a prepared gym squad can attempt the next
badge without waiting for every unrelated low-level member. The live policy
requires up to three target-level, healthy attackers (or the entire smaller
party), prioritizes a known usable super-effective counter, and heals before
departure. Whole-party progress remains visible separately; it is not falsely
reported complete. A confirmed loss raises the squad's training target within
the cap before another retry. Remaining members resume training between stages.
The current trainee stays selected during training, and health/PP changes
trigger healing rather than silent exclusion.
Before moving toward training grass, the bot puts the selected weak trainee in
the first party slot using the client's party-order packet and waits for native
confirmation. A trainee with a usable damaging move and more than 35% HP fights
directly when it equals or exceeds the wild opponent's level. The old 60%-HP and
nominal type-disadvantage guards no longer force that trainee out. Trainees one
or two levels below the wild retain the more cautious health/type check.
Critical HP, exhausted attacks, or an observed same-opponent hit threatening a
knockout can still require a stronger finisher;
trainees are not switched back in repeatedly. Health and PP are checked again
each turn. Live
participation and level changes, not sent switch commands, establish progress.
The fallback in-battle entry path avoids unsafe level gaps and super-effective
matchups, and can select a safe alternate in automatic whole-party mode. A
surviving injured participant hands off before healing so the
finisher can complete the battle and preserve its EXP opportunity.
**Train selected gym core only** preserves the earlier single-project policy.
Confirmed route-trainer blackouts also raise the training target by two levels,
without counting as gym attempts or granting badges. They require observed
all-fainted party state followed by relocation to a known Center.

The **Mt. Moon fossil** setting chooses Helix or Dome for badge mode. This narrow
story handler validates the scientist, coordinate battle trigger, fossil scripts
and exact dialogue references against the user's cartridge. It retains live NPC
collisions and requires the receipt message, closed UI and native fossil-object
removal before reporting that the gate cleared. Its end-to-end live fossil
exchange is still awaiting confirmation; unknown choices pause explicitly.

This is **not yet a complete unattended Kanto playthrough**. Cerulean routing,
a prepared-squad Misty retry, the resulting Cascade Badge flag, Bill's Cell
Separator scene, the S.S. Ticket receipt, the S.S. Anne rival battle, and the
captain's HM01 Cut receipt were observed live on revision34868.
Unhandled story choices,
later gym puzzles and unknown live obstacles remain explicit prerequisites.
The campaign falls back to supported training routes while their handlers are
unavailable; it does not claim to have cleared those gates. Automatic
PC transfers are not implemented. Counter-catching and automatic move replacement
are implemented but still need a complete post-update live confirmation.
**Auto · learn better attacks** compares exact offered IDs, power, accuracy,
same-type bonuses and gym weaknesses, replacing redundant status moves first
while preserving HMs, False Swipe and useful catching status moves. It changes
only the learning window's separate selection buffer, then uses the official
confirmation flow; it never edits the creature's learned moves directly.
The selected learning policy is respected: **Keep current moves** continues
without replacing moves, while **Pause** requests a choice in the client.

The area-objective planner now lists the ticket, HM, key-item and puzzle
dependencies before later gyms. Bill's S.S. Ticket and the captain's Cut reward
scripts are checked against the user's FireRed cartridge. Dedicated handlers
validate native NPC identities, exact dialogue references and receipt closure;
arrival at an NPC alone does not prove ownership. Bill's handler runs the Cell
Separator, follows his observed position after the scene, and collects the
ticket. Its receipt ledger is private and bound to the character and cartridge.
The captain route crosses the Underground Path to Vermilion and the S.S. Anne,
including direction-checked stair warps. It requires that verified ticket ledger,
uses live NPC collision checks, and can route back to a reciprocal Center from
the Underground, ship or captain room. A live rival battle, ship-to-Vermilion
healing trip, captain exchange and HM01 receipt/closed UI were confirmed. The
native bag also gained the HM item during that exchange. Receipt ledgers survive
backend restarts without repeating completed quests. Ticket-bound fallback
training can leave the captain room while later field-HM support is incomplete.
Cartridge item IDs
and flags are never reused as verified MMO item IDs. Automatic HM teaching and
field use are still unavailable, and missing handlers remain explicit. Training
can continue while those later story actions are incomplete.

Gym-counter planning compares usable party moves with the configured gym type
and searches verified wild encounter history for potential type counters. Type
alone does not prove the captured Pokémon has a suitable attack. Trainer
Pokémon are never recorded as wild spawn locations. Observations persist
privately by client revision. Counter routing uses observed grass coordinates
inside the supported story corridor and avoids live NPCs. Automatic
counter-catching requires a verified live wild target, item quantities and a
weakened opponent. On-demand Route24/25 cartridge encounter hints can supply an
Oddish search destination, but are not recorded as observed server spawns.
Catch weakening targets red HP (20% or less). It compares all living members'
available attacks and PP without a fixed species or move preference, switches
to a lower-damage member, and uses confirmed same-opponent hit damage to update
its estimates. When no attack meets the pessimistic critical-hit bound, it uses
the lowest estimated damage instead of stopping. This deliberately accepts KO
risk; estimates are not guarantees. A catch KO or empty ball stock does not stop
training. With no balls, even a shiny is battled normally, per the owner's policy.
Routine single-opponent battles are finished before Center recovery; fleeing is
off by default. Horde attacks use native actor side/position target bytes, not
party slots. Single-target moves focus one living opponent at a time; a known
shiny is preserved until the others are defeated, then the red-HP catch policy
takes over. Unknown layouts still cannot authorize guessed target bytes.
The collection option records verified own-party species privately per character,
across client revisions, and attempts unrecorded wild species even with a full
party. A six-member party no longer suppresses collection or gym-counter catch
decisions. This record is explicitly incomplete: it is not a complete PC/Pokédex
index. Sending a ball never marks a species owned without an authoritative own
observation, so boxed-only species can still be attempted again.
On revision34932, the separate native Pokémon summary window is recognized by
its creature identity, widget type and bound close callback. Automation closes
only that exact window using its real close button, confirms it disappeared,
then waits for fresh movement input. No summary is opened to check ownership;
unknown menus, evolution and move-learning prompts are not cancelled by this
handler.
Recoverable action failures keep the campaign active while refreshing native
state. A switch interrupted by the outgoing member fainting is handed to the
verified replacement selector. Rejected voluntary switch targets are avoided
for that encounter without being excluded from later forced replacements.
Movement and healing failures retry with bounded backoff and fresh observations;
temporary NPC obstructions trigger route replanning. Delayed badge confirmation
keeps waiting for exact badge flags rather than inventing a win. Unknown actors,
unsupported story gates and disconnected sessions still cannot authorize guessed
inputs. The operator's Stop button always cancels recovery.
Finding a missing next-gym counter takes priority over leveling unrelated party
members. After a route-trainer loss, acquisition resumes when a target-level
escort has recovered HP and damaging PP; it does not wait for the whole party.
The escort leads on the counter route. A caught member with a known usable
super-effective attack is trained first, then whole-party training resumes.
Revision34863/34868/34932 Kanto bag quantities now come from the real stack/definition
model, not regional story flags. Unsupported bags remain unknown rather than
being reported as empty. No capture or HM acquisition
is claimed merely because its planner selected an objective.
The GUI's normal Start/Stop buttons are exercised by the opt-in live
`python3 scripts/smoke-local-gui.py --mode badges --leave-running` check.
Add `--background` to verify movement while the control GUI retains foreground
focus. Launcher choices are saved privately and restored without auto-starting.

## Client updates

The GUI detects a changed executable automatically and runs one repair assessment
per new hash. Known hash-bound profiles are loaded without hardcoding new wire
IDs into the bot. Profile-file changes invalidate the GUI's compatibility cache.
The relay can load a hash-checked bootstrap mapping for a new supported revision
without retaining an old validator until the next relay restart.

Before launching a supported client, the launcher preserves its binary and layout
under `runtime/compatibility/`. Unknown updates are compared with the latest saved
baseline, including source-specific bag layouts, typed classes, roots and input
probes. Ambiguous matches remain disabled; the full proposal and missing checks
are written to `runtime/data/compatibility-report.json`. This is automatic
detection and repair preparation, **not guaranteed self-repair of arbitrary client
changes**. Unknown packet registries and live state still need validation before
a new profile can be enabled. MFA is always completed through the official client.

Ordinary message dialogue now continues automatically in all local automation
modes, including NPC, trainer, gym and map-script speech. It checks the exact
topmost native message and observes the outgoing response before proceeding.
Confirm is held for a bounded 100 ms inside the client so it is sampled across
game ticks. A C SDL reader overlays only that temporary Confirm state in a
private snapshot; it does not alter SDL's real key array or the desktop's keys.
Releases are retried with a deadline if the event queue rejects one.
Movement waits for dialogue completion and resumes without requiring focus.
Yes/no and multi-option choices remain with their dedicated handlers (such as
healing and the selected fossil); trade/release/purchase choices are not guessed.

The native hook must be loaded when the client starts. PokeBridge reads memory
through Linux `process_vm_readv` and a revision-bound in-process reader.
Movement requests are consumed by the client's own directional action path;
battle commands use the encrypted packet bridge. Neither uses screenshots,
image matching, mouse coordinates, X11 input, Wayland
input injection, or another application's keyboard focus. Automation activates
only the client's internal event gate, using its verified private window ID;
it does not raise the game window or ask the desktop to change foreground focus.
Guarded NPC dialogue confirmations also remain inside that client. Movement
itself does not fall back to keyboard input. Unfocused operation is live-tested;
minimized, locked-desktop and suspended operation are not certified.

When the client is opened by this build, PokeBridge also starts the loopback
packet relay before launching it. The native hook redirects only TCP game
connections on port 7777 to that relay, sends the original numeric destination
in a local-only `PB1` prelude, and the relay strips that prelude before forwarding
the game bytes unchanged. Login/service traffic on other ports is not redirected.
Encrypted chunks are captured locally; the relay also reports framed packet
lengths and hashes. A bounded external process-memory helper recovers the current native session's
directional AES keys into a private pipe, verifies them against the captured
bootstrap, and immediately clears its temporary key buffers. Keys are never
written to a capture or status file. The decoder handles continuous CTR state,
the negotiated checksum, and inbound compression. Launching an already-open client
does not retrofit its existing socket; it must be restarted through PokeBridge
for redirect mode to be active.

The relay can also be tested independently with
`runtime/node/node scripts/run-local-packet-bridge.js --listen-port PORT
--upstream-host HOST --upstream-port PORT`. `--dynamic-upstream` is reserved for
the native redirect path. Both modes bind to loopback only.

## Verified and pending

- Official native Linux client launches and loads Black, FireRed, Emerald,
  Platinum and SoulSilver from the owner's files.
- The hook captures encrypted game socket traffic, including vectored I/O.
- A compiled Linux native-hook smoke test proves `connect()` redirection and
  `sendmsg()`/`recvmsg()` traffic traverse the loopback relay unchanged; the
  relay strips its local destination prelude and taps both packet directions.
- Ghidra 12.1.4 analysis and read-only runtime inspection identified the actual
  revision 34702 native cipher objects and phase-specific packet registry.
  Live key recovery, authenticated bootstrap validation, and gameplay decryption
  have been exercised against the running official client.
- Current entity spawn, compact movement, full position, removal, and character
  selection schemas are translated explicitly. Unknown current opcodes are not
  passed to legacy handlers. The GUI obtains the character's map and position
  from exact server records or the validated native player root, with the source
  labeled. Coordinate-like memory candidates are never treated as player state.
- The relay can insert encrypted client commands while re-encrypting subsequent
  official-client frames to keep the two CTR streams synchronized. Integration
  tests cover late attachment, insertion, cancellation, incorrect keys, and
  continued real-client traffic. A live test traversed from Pewter to Route2
  grass across the map boundary and completed repeated wild battle cycles.
  These are baseline results, not certification of every feature.
- GUI commands use a private local session socket. Decoder, client, and relay
  disconnects invalidate readiness; unconfirmed steps do not become map walls
  or learned routes.
- Read-only process memory access works on this Linux installation.
- The local bridge adopts character identity from the official client's actual
  character selection; no account or character ID is embedded in the launcher.
- The GUI has a bounded, read-only memory-candidate inspector for the observed
  coordinate marker. Its results include cached map/entity records and are not
  treated as the player until a stable authoritative root is verified.
- The shared battle, routing, catching, type, PP, party and Kanto policy tests
  run on Linux using recorded fixtures. They do not certify revision 34702.
- Current battle snapshots expose actual active-party identity, HP, move slots,
  current PP, and native wild/trainer classification. The tactical policy has
  tests for PP exhaustion, type matchups, party selection, red-HP weakening,
  empirical damage estimates and the owner's accepted catch-KO policy.
  Species/move metadata currently comes from the user's FireRed ROM
  and is explicitly marked as a baseline, not verified PokeMMO balance data.
- Voluntary trainer switches require a stable level/type/coverage advantage rather
  than HP changes alone, and are bounded per opponent. Fainting and exhausted
  usable moves can still require an additional replacement.
- Native five-member wild hordes expose exact actor target coordinates. The
  controller fights instead of fleeing, avoids spread moves while preserving a
  shiny, and catches only after the other living opponents are defeated.
- Center routes use reciprocal ROM map/door links and replan after observed
  transitions, including step-off exit arrows. Live tests have verified nurse
  interaction, restored party HP/PP, cleared local dialogue windows, the return
  trip to Route2 grass, and another wild encounter. The already-healthy nurse
  branch is supported without requiring a restoration message it never sends.
- Badge routes retain fresh native NPC obstacles across packet updates. Training
  and Center recovery use the same cave, ladder and ledge-aware route planner;
  cartridge tests include the return from Mt. Moon to its nearby Center.
- Ordinary hunting/training patrols, Center recovery and return-to-grass routes
  also avoid fresh native NPC positions. The Route6 trainer pair at13,32/13,33
  has a regression case; live recovery detoured to Vermilion and healed instead
  of repeatedly walking west into that pair.
- Prepared-squad readiness routed a party with an under-target member to Misty
  instead of waiting for all six members. The live trainer battle was won and
  the exact Kanto badge mask advanced from1 to3. The packet/native battle-start
  classification race found in that run has separate regression coverage; this
  is not proof of later HM, ticket or gym-puzzle automation.
- Fainted-member replacement uses the current server's S169 party-selector
  request rather than waiting for another ordinary S216 attack turn. A live
  fainted Rattata was replaced with Charmeleon and the battle completed.
  The readiness wait accounts for queued faint and opponent-entry animations;
  it still requires the actual native replacement selector, never a blind key.
- A native memory-identified move-learning window is handled without visual
  recognition. Automatic attack replacement, keep-current and manual-choice
  policies are available. Keep-current was confirmed live on34863; automatic
  replacement is covered by model/selection tests and still needs a live offer.
- The previous native inventory model was identified as regional progression
  flags, not the bag. Revision34868 ball quantities now use the verified native
  bag stack/definition model, and a live weakened-target ball throw was observed.
  Full-party/PC capture outcomes are not certified. Unsupported item layouts
  remain unknown rather than appearing empty. The own-party reader exposes exact native maximum HP and
  IVs. Hidden opponent IVs are not claimed available.
- Kanto badges come from the eight exact native regional flags, not level caps
  or guessed contiguous counts. The current character's Boulder badge was
  verified. The badge retry coordinator is available as a GUI beta; full
  gym/story traversal is not complete.
- A client GC crash was traced to native hook return trampolines and corrected
  with true instruction probes. Sustained live battle, movement and healing
  tests have run without that crash. Shiny identity is read from actual native
  appearance flags. Current supported profiles expose the verified bag and
  item-command path; complete shiny/horde catching and PC outcomes remain
  uncertified. Unknown stock is not zero.

The private session command socket is listed in `runtime/data/packet-session.json`.
A separate read-only loopback diagnostics API exposes `/health`, `/status`, and
`/events?after=ID`. The GUI opens that API directly. Action attempts and failures
are recorded in `runtime/data/packet-actions.jsonl`; keys, passwords and packet
payloads are not recorded there. Status includes completed-battle and failure
counts, so a sent command is distinguishable from an observed outcome.
Session failures are retained as `lastSessionError` even after the current
connection becomes healthy. Capture activity order, rather than descriptor-map
insertion order, selects the newest observed session after socket reuse.

Unknown state stays unknown. There is no hard-coded overworld or badge cap.
Generic keys cannot cancel an unclassified evolution or dialogue.

## Optional local health watchdog

On Linux with a systemd user session, run
`python3 scripts/install-health-watchdog.py --install --enable` to check the
existing local session every 40 minutes. The computer must be awake and the user
session running. Inspect the schedule with
`systemctl --user list-timers pokebridge-health.timer`, or disable it with
`systemctl --user disable --now pokebridge-health.timer`.

Healthy checks and deliberate Stop actions are quiet. A known recoverable stop
can be resumed only with a ready, verified overworld session and an atomic check
that the operator has not changed their command. Unsupported updates, login/MFA,
unknown dialogue, shiny protection, learning choices, unresolved routes and
repeated failures require attention; they are not bypassed. The watchdog uses
desktop notifications for meaningful failures or recoveries and records its last
result privately in `runtime/data/health-watchdog.json`. It does not launch or
log into the game, run an AI coding session, or rewrite code automatically.

## Platform plan

Windows, Linux, macOS and Android share policy decisions and a versioned adapter
contract. Linux has the new launcher/native transport in this checkout. Windows
has the legacy launcher and agents, which still require updated native bindings.
macOS and Android adapters and release packages are not implemented or tested.
Full feature parity is not complete on the updated client.

Data is stored under `runtime/data` by default. ROM links and official game
configuration are under `runtime/client`. Neither is committed to GitHub or
included in the redistributable development archive.

## Build

Run `bash linux/build-native.sh` with a C compiler. The C library uses libc,
pthread and libdl; no Java or .NET runtime is required for the native adapter.
Install PySide6, Frida, and PyInstaller in a build virtualenv, provide
`runtime/node/node`, then run `bash linux/build-release.sh`.
The output is a self-contained Qt/Node Linux directory and tarball, with official
client assets but no ROMs, credentials, captures, or calibrated addresses.
The Linux binaries currently target the build machine's glibc and x86-64 ABI;
compatibility with older distributions remains unverified.
