# Arena trade admission and terminal journal

Implementation for coordinated rollout; **disabled unless
`STARQUEST_ARENA_TRADING_DIR` is configured**. Deployment of this source code is not
activation of Arena orders. Existing challenge admission, player linking, replay,
result publication and gameplay remain independent. Funding is out of scope.

Machine-readable contract: [arena-trading.openapi.json](arena-trading.openapi.json).

## Authority and endpoints

These are internal POST operations under `/api/arena/connect/trading/` on
`https://starquest.live`. They use the existing Arena connector service signature
and durable PostgreSQL transport nonces from `arena-connect-protocol.ts`. They are
not browser session operations, public partner reads or delegated agent APIs.
Only the existing first-party Arena service should possess that connector key.
Never distribute it to partners or browsers. Unknown fields reject. Successful
responses are JSON with `Cache-Control: no-store`; the private journal contains
pseudonymous account keys and must not be exposed through the public Arena relay.

| Suffix | Required JSON | Result |
| --- | --- | --- |
| `journal` | `stream_id`, `after` | Ordered events, cursor, more, healthy, stream identity |
| `admit` | `stream_id`, `match_id`, `owner`, `request_id`, `order_digest`, `outcome` | Durable accepted or rejected source decision |
| `acknowledge` | `sequence`, `event_hash`, `decision`, `receipt_hash` | Durable engine-decision acknowledgment |
| `barrier` | `match_id` | Immutable terminal record and count of unacknowledged admissions |

Bootstrap journal discovery with `{"stream_id":null,"after":0}`. Persist the
returned stream identity; subsequent reads must supply it. `after` is an exclusive
nonnegative integer sequence, not a timestamp. Pages contain at most 100 events;
follow `cursor` while `more` is true. An ahead-of-head cursor or different stream
returns 409. A changed identity is a recovery condition, never permission to reset
an existing consumer or recreate its markets automatically. This release does not
prune journal records or establish a production throughput/retention SLA.

Admission binds an immutable 32-character lowercase match ID, Arena's existing
64-character lowercase private owner key, lowercase UUID v4 request ID, 64-character
lowercase SHA256 digest of the exact order intent, and outcome 0–3. `stream_id` must
match this journal. The digest is opaque to the game; the Arena adapter must
verify that its original durable intent, account, market/source association and
outcome match the receipt before executing. Do not hash a command that includes a
not-yet-known admission sequence. Use a versioned canonical intent representation
independent of the source ticket; its engine-side schema must be agreed and tested
before activation. This source API does not check price, balance or inventory.

Transport retries use a fresh timestamp/nonce/signature. Business retries retain
**all original terms and request_id**, including after timeouts and game completion.
The same request returns the original positive or negative decision after restart.
Changed terms under an existing account/request ID return409. A 503 means the
operation is unconfirmed; it does not mean no durable write occurred. Invalid
service signatures/nonces return 401, malformed input 400, missing events 404.

## Ordering and the five-second execution deadline

The game process records an admission synchronously, with a full source snapshot,
current 60 Hz tick and UTC millisecond observation. It commits SQLite before sending
the response. Ticks cannot interleave with that synchronous operation. The ticket
has `accepted_tick`, `accepted_at`, `execute_before`, `event_sequence`, `event_hash`
and `snapshot`. `execute_before` is accepted_at + 5000 ms. It is the latest permitted
engine decision time for a new execution, not a reservation or a guaranteed fill.
Source and engine clocks must be synchronized and acceptance latency measured.

`state` events describe material eligibility/lifecycle changes. `admission` events
follow the actual source state that accepted the intent. A `terminal` event is
appended only after all previously accepted admissions in this journal. There
are no heartbeat events; unchanged scores/movement are in the existing live feed,
not repeated into the admission journal. Each accepted ticket contains a fresh
snapshot. A reader observation timestamp does not refresh a ticket or authorize
an order.

The engine/adapter must process source events in order, persist its consumer cursor
with its ledger decision, exclude repeated execution and record **durable negative
order decisions** as well as successful receipts. It must reject expired tickets,
wrong digests/accounts/matches/outcomes, changed streams, gaps and conflicting
retries. Poll snapshots are not substitute admissions. The current prediction
engine does not yet implement this ordered consumer; its order route remains off.

Acknowledge each admitted event only after the corresponding engine result is
committed and recoverable. `decision` is `executed` or `rejected`; `receipt_hash`
is the hash of that durable engine receipt in either case. The source records the
acknowledgment as an operated-service assertion; it does not independently verify
the engine database. An exact retry succeeds, conflicting acknowledgment 409.
Never acknowledge a timeout as rejection without a permanent engine stop.

A barrier is `settlement_ready` only when terminal, source-healthy, and every
accepted admission for that match is acknowledged. Expired tickets do **not**
automatically drain it: an execution could have committed before a lost response.
The consumer must verify matching stream, match, terminal sequence/hash and exact
source winner/evidence, then perform existing exactly-once settlement. Final game
presentation, career rewards and ordinary result publication do not wait for
Arena; only the practice exchange settlement uses this barrier.

## Outcome rules and restart behavior

Joining and outcome eligibility are different. `join_closed` reflects destroyed,
zero-hull or collapsing stations. A time-limit game can still be won on accumulated
points by a house with a destroyed station. Consequently `eliminated` stays false
before terminal evidence, and terminal losers are marked only when a winner exists.
Do not copy the older live-feed station flag into exchange outcome elimination.
This implementation leaves Star Quest scoring rules unchanged.

Admission pauses in a decisive state with at most one joinable house, even before
final publication. This does not declare that house the winner. Ended matches
reject new admissions. Once captured, the terminal snapshot never changes during
the 12-second visual finale. Terminal draw uses winner=null; the exchange's neutral
void policy is separate from legacy pooled-pick refunds.

On startup, any journal match that was not terminal receives a recovery barrier
with winner=null. It cannot resume trading under that same match ID, even if the
gameplay checkpoint resumes. Existing tickets and pending acknowledgments survive.
An engine decision that already committed must be recovered and acknowledged;
unexecuted requests receive permanent negative receipts. Explicit shutdown,
vanished rooms and tick rewind likewise close admission. Journal/clock faults fail
closed for trading without stopping the game simulation. This is a conservative
practice-market interruption policy, not a claim of deterministic game recovery.

## Persistence and rollout

The optional directory contains `trading.sqlite` (0600) and SQLite WAL/SHM files.
Back up the complete database consistently with its WAL and preserve its stream ID.
The journal is single-game-process storage; concurrent replicas are not supported.
Material state, admission, terminal events and acknowledgment receipts have no
automatic expiry in this release. Measure growth, disk latency and backup/restore
before enabling the adapter. This journal does not store full game-state frames.

Events carry a SHA256 hash over the event **without** its `hash` field, using the
existing `canonical()` encoding in `server/arena.ts`: recursively sorted object
keys, preserved array order, compact JSON and UTF-8. `previous_hash` links the prior
global event, with 64 zeros at genesis. These hashes and authenticated HTTPS are
operated-service integrity, not public-chain anchoring or independent signatures.

Rollout sequence:

1. Review and deploy this additive code with the environment variable absent.
2. Agree the intent/negative-decision contract with the Arena prediction adapter.
3. Provision a private directory and enable this source observer. Check signed
   journal reads, clock skew, four-room tick latency and disk failure behavior.
4. Exercise delayed/lost admission responses, execution-before-lost-ack,
   terminal races, crash/restart, changed streams, and a destroyed house winning
   on points against the actual durable engine and source before enabling orders.
5. Keep order execution, practice liquidity provisioning and new transfers closed
   until coordinated acceptance. Funding/Stripe/real value remain paused.

Local tests cover SQLite persistence, exact retries, rejection permanence, hash
chains, pagination, stream mismatch, terminal drain, finale immutability, clock
rewind, write faults and signed HTTP boundaries. They are not SFO production
acceptance or proof that the still-missing engine consumer has been deployed.
