> For the complete documentation index, see [llms.txt](https://nytshift.gitbook.io/nytshift-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nytshift.gitbook.io/nytshift-docs/normative-design/architecture.md).

# Architecture

## Product boundary

NIGHTSHIFT is an AI-assisted terminal, not an unrestricted autonomous trading agent. The model produces a structured `TradeProposal`; the user or an explicitly authorized deterministic controller creates a separate `TradeIntent`; the AEGIS deterministic risk service is the sole policy authority; the execution boundary signs only a recently confirmed or policy-authorized, fee-disclosed intent. Future premium automation must use a revocable expiring policy and can never give the model a wallet key or direct signer access.

## Data plane

1. The browser market plane maintains one pooled public WebSocket per venue for active market, order-book, trade and candle subscriptions. Arcus and Hyperliquid order books replace state from complete frames; Lighter starts from a complete snapshot and applies changes only when `begin_nonce` exactly continues the prior `nonce`. Lighter gaps preserve the last accepted state, force resubscription and trigger strict REST repair. Arcus public `orders` and `userFills` subscriptions join that pool only for an exact inspected address and accept only address-echoing frames. Ref-counting, exact unsubscribe/replay, heartbeat, stale detection, byte/message/connection ceilings and bounded jitter are shared across consumers; REST seeds public market/account state, while a new venue account snapshot remains the only recovery from a detected Arcus order-sequence gap.
2. Normalized REST candles are the sole write authority for the local market-history checkpoint. Valid provider bars are keyed by venue, live-discovered symbol and interval; corrections replace the same timestamp, retention and LRU caps are deterministic, and only a closed-bar correction or bounded open-bar cadence causes an atomic write. A provider failure may read this store but cannot change the response's degraded provenance or bypass current market discovery. Schema migration never synthesizes a candle or newer observation time.
3. The web BFF pins Arcus/Hyperliquid REST reads to exact official endpoints, streams bodies through a byte ceiling, caps concurrency, owns cooldown/half-open circuit state and applies opaque per-account local budgets. `/api/market/health` returns aggregate reason codes and counters only. Hyperliquid `perpDexs`, `allPerpMetas` and `metaAndAssetCtxs` cross one shared bounded parser: actual DEX array indexes derive primary/HIP-3 L1 asset IDs, every active DEX receives its exact collateral-token authority, required precision/leverage/name/cardinality invariants fail closed, additive unknown fields raise aggregate schema drift, and the same drift blocks reconciliation/review before AEGIS evaluation.
4. A Next.js proxy gives every page request a fresh CSP nonce. Next framework scripts/styles receive the nonce automatically; scripts use `strict-dynamic`, external fonts are self-hosted, and the remaining inline exception is scoped to computed style attributes used by charts/depth visuals.
5. Browser watchlists are versioned local display preferences, capped and parsed through a strict venue-symbol grammar. Each venue owns an independent favorite set and filter mode; saved symbols are intersected with current live discovery or the canonical chain registry and never become data-plane authority.
6. Browser price alerts are versioned local rules, not a data source or execution path. Every rule is evaluated against its exact venue/symbol and a timestamped observation no more than 90 seconds old. Perpetual observations additionally require a currently live feed, exact venue identity, one unique symbol and `markState: available`; a retained held mark is never an alert observation. Trigger evidence is persisted once; evaluation exists only while the terminal is open, and Robinhood Chain evaluation is limited to the currently selected asset with verified Chainlink context.
7. Browser workspace layouts are exact, bounded presentation preferences for watchlist, trade/intelligence and portfolio visibility. Four built-in presets and up to eight named views never carry market/account data or authority; responsive breakpoints remain the final containment rule.
8. The command palette is a bounded projection of existing state, never a new data or execution authority. Perpetual instruments enter only from currently live venue overviews and format price only through the same per-market mark-authority projection used by the terminal; Robinhood Chain items come from the canonical identity registry and remain explicitly non-listing. Palette actions are limited to navigation, read-only inspection and presentation preferences. The command-deck coverage matrix uses the same separation: canonical Robinhood contracts establish identity, while exact underlying symbols may attach currently live Arcus/Lighter/Hyperliquid perpetual analytical context. Arcus `ONLINE` listings are preferred, degraded catalogs contribute no retained matches, venue schedules never infer a holiday-adjusted open state, and the terminal handoff writes display preferences only. Spot evidence is a separate projection: an ecosystem provider listing is not a router deployment, pool, quote, liquidity observation or execution capability. Until exact primary-source contracts and semantics are reviewed, every canonical spot asset remains visibly unverified with zero quote/execution authority.
9. Browser candle history is a bounded merge of validated venue REST pages and streamed updates, keyed by exact venue, symbol and interval. Incoming overlap replaces the same timestamp but a current REST page cannot discard earlier pagination or a newer stream-only bar. Request sequence/context guards reject stale responses; continuity is calendar-aware, and streamed gaps or recovery from a degraded socket request a throttled REST repair without hiding retained history.
10. The technical-chart renderer treats style/study configuration as a series-lifecycle boundary. Strict bounded local preferences choose the studies and periods; a current-bar revision or append updates existing series, while venue corrections, backfills, retained-window shifts and context changes replace complete data. Source-candle UTC O/H/L/C/V remains the inspection authority regardless of visual style. Before market state reaches any terminal consumer, one shared reference classifier treats the finite positive venue mark as authority and the oracle/index as corroboration: malformed or more-than-5%-divergent reference values are discarded numerically and exact quarantine state/reason is retained. Hyperliquid `allMids` is midpoint evidence only and never advances a mark; the bounded `allDexsAssetCtxs` parser maps primary and HIP-3 contexts by exact DEX and metadata index. A mark move above 25% advances only with a close same-frame oracle/index; otherwise the prior accepted mark/time are held across stream and REST recovery and the feed degrades until corroborated recovery. A second consumer projection returns no live price from that held state: chart risk, all PAPER venues, price alerts, order shortcuts, watchlists, palette results, market briefs and book mark labels cannot consume it, while an evidence surface may name only its explicitly retained `LAST ACCEPTED ... HELD` value. A separate chart-risk projection accepts market context only from a live catalog observation no older than 60 seconds and account context only from an exact venue/symbol inspection no older than 90 seconds; Lighter additionally requires the exact numeric market ID. Multiple matches are ambiguous, expired/degraded evidence removes every affected price line, and absent entry or liquidation values remain absent instead of being derived locally. Account capital is an equally strict projection: Hyperliquid selects only the exact primary or deployer DEX clearinghouse state; Arcus margin totals exist only when every returned position supplies margin; and Lighter totals exist only when every returned type-0 account supplies finite collateral, available balance and initial margin. Equity, available collateral, margin usage, utilization, capital buffer, position leverage/mode/notional and unrealized PnL remain venue-labeled, partial or unavailable; missing leverage or capital is never reconstructed. Exact-market performance is independent: Hyperliquid and Arcus sum closed PnL only from available bounded public fill windows and read cumulative funding only from one exact position, while Lighter reads realized PnL and funding paid only from one exact symbol/market-ID position. Windowed PnL is never labeled lifetime, incomplete normalized values never produce partial sums and duplicate exact positions remain ambiguous. A separate exact venue/symbol history projection deduplicates returned funding observations and reports only bounded descriptive statistics. Liquidation context is a dedicated additive contract: Lighter supplies only documented `liquidation`/`deleverage` public execution tags from the latest 100 rows, while Hyperliquid and Arcus remain explicitly not documented and ordinary trades are never heuristically reclassified. 10a. Retained REST chart history is atomically bound to exact venue/symbol/interval identity. A context change remounts the native renderer, hides its canvas and numeric axes, and accepts no history until an exact-identity response or stream frame arrives. Superseded response sequences and late stream callbacks cannot populate the new context.
11. `packages/venues` defines the read-only adapter contract for assets, network, prices, portfolio and simulation. The Robinhood Chain adapter validates chain ID 4663 and keeps mock/live sources structurally distinct.
12. Public-wallet activity keeps canonical ERC-20 logs and native ETH as separate evidence rails. The token rail scans only the immutable 27-contract registry. The native rail is available only through an Alchemy primary endpoint and accepts bounded `external` transfers with exact raw wei; it owns separate ranges/gaps and never promotes internal contract transfers to covered history. Schema migration adds typed provenance without inventing native coverage for legacy checkpoints.
13. Advisory `TradeProposal` analysis crosses a strict authenticated import boundary and enters a separate identity-only lifecycle store. Full evidence, assumptions, risk text, prompts and model output are never persisted there. Directional records can reserve one exact Hyperliquid review intent only; confirmation consumes the proposal before signer I/O. This binding is supplementary evidence and never replaces current venue/account reads or deterministic AEGIS policy.
14. The Robinhood Chain provider monitor continuously probes the configured HTTP topology, supervises verified `newHeads` WSS streams, evaluates evidence-backed alerts and atomically retains secret-free topology/open/resolved transitions across restarts. Managed archive qualification additionally requires a protected endpoint-bound capability document measured through both HTTPS historical-state and WSS-head probes. Its separate timer command cannot bootstrap or accept endpoint rotation, serializes through a recoverable exclusive lock, replaces evidence only after a complete re-verification and lets the runtime expire old evidence independently of refresh state. When explicitly configured, alert lifecycle events enter a schema-v2 durable outbox in the same write; leased workers deliver HMAC-signed, idempotent envelopes with bounded retry. Chain connectivity, provider topology/health/incidents and aggregate activity health cross the browser boundary only through a dedicated immutable-v1 public contract. Pre-serialization validation rejects endpoint URLs, credentials, local paths, wallet identifiers and inconsistent readiness claims; the official public RPC remains structurally diagnostic. Price, portfolio, address activity and canonical radar cross a separate immutable-v1 Robinhood Chain data contract. It binds usable prices to reviewed feed/sequencer/pause evidence, portfolio completeness to exact-decimal canonical holdings, activity cursors to archive/gap evidence and radar coverage to the reviewed 25/21 identity/feed split; failure telemetry is address-free. The same anonymous contract has an additive bridge-evidence read sourced only from a reviewed immutable registry. It freezes chain 4663/parent chain 1, one canonical route, five provider-owned partner route families, official L1/L2 contract identities, canonical timing and the separate withdrawal claim requirement. Every route retains `quoteCapability: none`, `executionCapability: none` and provider-live-quote-required fees; the browser clears stale evidence and an external handoff never becomes wallet or transaction authority.
15. Arcus execution alerting stays inside the isolated signer. Order failures and reconciliation transitions enter its bounded SQLite outbox transactionally, then a leased worker sends secret-free HMAC envelopes without environment proxies, redirects, or retained response bodies. Disabled/degraded/overflowed delivery blocks ordinary execution; emergency cancel-all remains independent.
16. The signer store has a distinct recovery and audit boundary. An application ID and ordered schema history bind its intent, reconciliation, audit, alert and Hyperliquid scope, bracket-leg, all-fill, lifecycle, fee-ledger, leverage-idempotency and venue-dead-man tables; exclusive migrations preserve rows and commit only after exact schema plus SQLite integrity checks. Signer and BFF health require schema v8 and WAL before either ordinary or emergency authority. Schema v5 protective-stop rows migrate explicitly to stop-loss identity; V4 take-profit scopes remain distinguishable without changing the immutable public lifecycle contract. Schema v7 retains account/network-bound schedule state, the exact pre-action CLOID set and domain-specific action claims; schema v8 binds rehearsal evidence to the exact account and deliberately clears legacy unbound rehearsal timestamps. Normalized execution-review verdicts are persisted before an approval token can leave the BFF. Hyperliquid status, all matching fills and builder revenue commit as one regression-protected observation; leverage and dead-man actions use separate exact-once claims and never share order submission. Authenticated reads select only Arcus-prefixed events and project a fixed detail-free shape under the exact signer/eligibility account scope. Backup, restore and signer runtime serialize through one owner-PID operation lock. Cold snapshots use SQLite point-in-time copying, an exact sensitive-data manifest, schema/integrity/fingerprint evidence and SHA-256; guarded restore preserves the replaced database plus WAL/SHM sidecars. These snapshots are never mixed into the public-store backup allowlist.
17. Hyperliquid mainnet entry authority additionally depends on a venue-native dead-man lease. The signer uses the official `scheduleCancel` action with a fixed 30-second deadline; the authenticated terminal supplies operator-presence heartbeats every ten seconds, and each heartbeat re-reads the primary plus every discovered perp DEX before extending the deadline. Pre-signing failures are proven not attempted. Any ambiguity after signing stops heartbeats and becomes post-deadline reconcile-only. Disarm requires independent zero-open-order proof, ACK never proves cancellation, and fresh testnet `scheduledCancel` rehearsal plus a live recent heartbeat are enforced independently in the BFF and signer.
18. Landing and terminal readiness are projections of that monitor snapshot, never inferences from a block height alone. Public diagnostic connectivity, production redundancy, divergence, archive state, WSS head state and stabilization remain distinct presentation states. The terminal's build-trust poller additionally runs `/api/health` through the strict release projection with a bounded request and response size; any transport, JSON or semantic failure clears the last identity rather than preserving a stale verified badge. Its top-bar, keyboard and command-palette entry all open the same accessible read-only dialog and cannot alter configuration or authority. The command-deck activation projection independently joins that strict health response to the current provider-topology contract. Privy is ready only with matching browser/server configuration and fresh app-bound production login/wallet/cookie/identity-token rehearsal evidence; native Advanced Charts requires both a license-attested v32 tree and fresh evidence bound to the exact release/tree after drawing, studies, resolutions, history, zoom, persistence, reconnect and responsive production rehearsal; production RHC data requires fresh stabilized redundant HTTP/archive/WSS proof; and live order authority stays locked while the disabled execution/mainnet invariants hold. A configuration value is never promoted to execution authority, and any malformed, contradictory, stale or missing join clears the activation surface.
19. The local backup boundary snapshots only the allowlisted activity, provider-observability, control-plane-observability, advisory-proposal lifecycle, agent-access, agent-automation, public market-history, opaque-account portfolio-reconciliation and private customer-preference stores. Versioned manifests bind logical paths, data classes, byte counts and SHA-256 digests; restore requires a stopped supervisor and preserves the replaced files for rollback. Customer-profile verification rejects raw provider identity, email, wallet and credential material.
20. Subscription acknowledgements, Info requests and injected EVM providers supply boot/reconnect snapshots.
21. Producers normalize external messages into versioned canonical events/read models.
22. Redis Streams carries ephemeral real-time events; Postgres/Timescale stores durable audit, order/fill and time-series state.
23. Every protected control-plane request begins with a fresh BFF-owned span UUID. Review also creates a durable execution-flow root that is HMAC-bound into the one-use confirmation ticket and retained with both Arcus and Hyperliquid signer audit. Later exact CLOID/client-ID operations can rejoin only through authenticated loopback audit lookup; browser-supplied lineage is ignored. A separate atomic schema-v3 store records only span/root UUIDs, fixed operation/outcome/timing fields, fixed-code rolling-SLO alert lifecycle and leased delivery state under bounded retention; exact schema-v1/v2 events migrate with their span as root. Its authenticated summary joins public-feed age and Robinhood Chain divergence; optional HTTPS delivery uses stable IDs, exact-body HMAC, redirect rejection and bounded retry. It never contains request/order/account/receiver data, and correlation never substitutes for signer audit or venue reconciliation. Hyperliquid mainnet, but not testnet, requires healthy delivery.
24. Canonical boundary schemas live in one versioned Zod registry and generate committed JSON Schema Draft 2020-12 plus OpenAPI 3.1.1 development/signer documents. Separately versioned anonymous public-market, public-account, public-RHC-readiness and public-RHC-data documents freeze normalized browser DTOs. Producers validate objects before serialization, attach exact contract headers and fail closed without returning/logging raw provider data, validation detail or account addresses. Existing named-v1 definitions and operation request/parameter/security/response boundaries are immutable; TypeScript/Python parity tests bind all nine signer request models, including the additive leverage-only and parent/TP/SL V4 requests. Capital-moving prices, sizes and notionals cross both signer boundaries as bounded non-exponent decimal strings, are checked by exact integer/`Decimal` arithmetic, and convert to a venue SDK number only at the final Hyperliquid library adapter.
25. `portfolio` reduces idempotent events into queryable materialized account state and regularly reconciles against its venue source.
26. Hyperliquid monetization uses only its native builder-code field. A live per-account `userFees` quote and `maxBuilderFee` approval check precede confirmation. The configured builder also must report at least 100 USDC perps account value and an explicit Standard-mode `userAbstraction` response of `disabled`; missing, default, unified, portfolio-margin or DEX-abstraction evidence fails closed. Every manual review and Agent Pro policy supplies a separate current-leg total-fee ceiling. Exact HIP-3 deployer scale and growth-mode evidence transforms the account rate; referral and aligned-quote discounts are deliberately not assumed, producing a conservative worst case. The exact builder address/rate, qualification observations and user ceiling are bound into the HMAC ticket, rechecked before submit, validated again against isolated signer configuration and sent through immutable fee-bound V2 or additive bracket V4. Hyperliquid does not carry the protocol ceiling in the order payload, so a later GTC fill is not guaranteed to remain below it; child fills and funding remain separate. Fees are fill-only, and Arcus/Lighter receive no invented surcharge.
27. Builder revenue is recognized only from Hyperliquid fill evidence. The signer persists parent and protective CLOID scope plus exact take-profit/stop-loss leg identity before submit, resolves each CLOID through `orderStatus`, pages unaggregated `userFillsByTime`, accepts only the matching order ID and positive exact `builderFee`, and records each venue trade ID once. Aggregate token totals cross the BFF; raw account-wide fills do not. The documented 10,000-fill venue retention and bounded pagination remain explicit coverage limits, so this ledger is not represented as an independent long-term exchange archive.
28. Agent Pro credential issuance is a separate commercial capability boundary. A compact Ed25519 license binds opaque license/customer IDs, activation/expiry, active-credential capacity and UTC-month proposal-attempt allowance; the supervised web process receives only the public key and signed license. Each policy-evaluated attempt updates fixed audit plus aggregate usage in one atomic schema-v2 checkpoint. Operator export contains only opaque IDs, month and reconciled counters. Missing entitlement locks issuance, invalid configuration makes health unsafe, rotation invalidates licensed credentials, and the issuer private key is excluded from web, config and backup scopes. This entitlement never grants execution authority and does not represent payment collection.
29. Agent Pro automation is additive and sender-constrained. Proposal-only signed v1 terms remain non-executable; v2 adds a monthly automation-attempt allowance. An operator-created maximum-24-hour testnet policy binds one active credential, exact account/market/side/entry/reduce-only/risk/frequency limits, an explicit current-leg total-fee ceiling and a client-held P-256 key. Each new valid DPoP request ID meters atomically with its durable policy outcome, repeats live fee evidence before signer claim, keeps exact replay free and status unmetered, and stops overage before signer I/O. Schema-v3 storage validates and revokes migrated v1/v2 policies so an old policy cannot silently inherit new fee authority. The credential never receives cancel, funding, wallet, direct-signer or mainnet authority.
30. Commercial reporting never turns configuration or usage into revenue. The isolated signer aggregates exact positive builder fees only from its deduplicated retained fill ledger, grouping by fee token and UTC month without returning account/order/trade identity. The operator BFF strictly validates that projection, joins only aggregate Agent Pro usage, marks premium activity unpriced without payment evidence, and reports payment collection unconfigured. Coverage remains `bounded-local`, native builder-reward claims are not reconciled, and the documented builder-wide archive remains un-ingested until its schema is reviewed.
31. Venue builder reward reporting is a separate read-only proof. The operator BFF joins official referral state only to strict spot-token identity, enforces token-zero root parity, retains exact decimal strings, removes builder/referrer/account identity and labels combined claim balances as not ledger-reconciled. The documented builder-fill archive is not ingested while its normative CSV schema remains unpublished, and the browser has no `claimRewards` signing or submission capability.
32. AEGIS treats reduce-only as a position invariant, not a trusted caller flag. Fresh signed position quantity determines the only valid closing side and maximum normalized quantity; a flat, adding or position-flipping request is rejected before entry-only breaker bypass applies. New entries also project every applicable reviewed correlation group before the broader gross cap. Dynamic policies are structurally validated, decisions retain the immutable-v1 reason set and the signed risk-decision ID continues into signer audit.
33. Portfolio reconciliation is a monotonic coverage-aware authority boundary. Complete remote order/position/account snapshots may replace local projections; unavailable sections retain the last accepted state and set degraded health. A disappeared non-terminal order becomes unknown until exact status/fill evidence proves finality. Fill and funding windows append idempotently under explicit bounded coverage, while stale, future or out-of-sequence snapshots cannot mutate capital state. The atomic schema-v1 checkpoint uses only opaque account digests and fixed divergence codes; aggregate integrity/health crosses the public process boundary, never order, fill, position or account identity.
34. Configured Hyperliquid account authority is server-owned and signer-scoped. One coordinator hashes the exact account/network scope, coalesces concurrent calls and normalizes every discovered perp DEX through timestamped clearinghouse/open-order reads plus exact missing-order status and bounded event-time fill/funding pagination. `allPerpMetas` binds each DEX to a collateral token; strict `spotMeta` identity and borrow/lend reserve oracles convert Standard, Unified and Portfolio Margin capital, positions and HIP-3 lifecycle values into the common USD model. Portfolio Margin debt reduces equity, while venue borrowing/cap headroom is never reconstructed locally. Every fresh review separately requires `activeAssetData` to match requested leverage and bound order quantity plus available collateral. Schema drift, missing DEX state, stale time, unresolved orders, unsafe holds/debt, missing token/oracle or active-capacity mismatch preserves prior capital and locks review, submit and policy-bound automation. The browser receives only fixed reason, generation, mode, balance-authority label, coverage and aggregate counts.
35. Hyperliquid leverage authority is deliberately separate from order authority. A mismatch yields no order ticket; a short-lived leverage review binds exact current/target leverage, current cross/isolated mode and venue maximum. A separate operator confirmation is revalidated immediately before one exact-once official-SDK action. `activeAssetData` is the completion authority, ambiguous outcomes are never retried, automation cannot invoke the action and success only offers a completely fresh order review.
36. Production paper trading is a browser-local projection of the already normalized public L2 plane, not a fixture API or execution service. PAPER accepts only a fresh, strictly sorted, two-sided, uncrossed Arcus/Hyperliquid/Lighter book and performs exact visible-depth consumption. Immediate market and crossing IOC remainder never become future fills. Its bounded schema-v2 ledger persists only user-defined paper capital, normalized simulated executions and reduced paper positions, replays the complete non-truncated tape, rejects unknown/tampered/oversized state, enforces one-times entry-notional against realized equity and makes reduce-only incapable of opening or flipping. One deterministic portfolio projection joins only exact local position, active-GTC and protection contexts, sorts the selected market first and navigates through the existing venue/symbol selection boundary. It exposes retained entry/realized evidence and account-wide entry notional, never stale away marks, away unrealized PnL or cross-venue capital. A separate maximum-32-KiB schema-v1 local GTC book retains no more than eight active and 32 total lifecycle rows. Placement must be non-crossing; standard limits reserve remaining limit notional, reduce-only limits reserve exact opposing position size, and later ledger drift rejects invalidated reservations. Only one oldest eligible order can consume one venue/symbol book observation, partials watermark that observation and require a newer book, and cancel is local/idempotent. Away GTC contexts continue through exact pooled Arcus/Hyperliquid streams plus bounded REST repair; Lighter remains REST-only without a retained numeric market index. The panel projects the same strict book into exact oldest-first away rows with per-context live/repair/syncing/degraded/protection-paused state; one local cancellation rewrites the complete book and never sends a venue cancel. This conservative rule prevents displayed-depth reuse but does not claim exchange queue simulation. A separate maximum-32-KiB schema-v2 protection book retains no more than eight unique venue/symbol plans, migrating only a strict legacy single plan. Every plan binds one exact current position and fresh venue mark. A reached stop/take-profit creates only a same-market reduce-only paper exit against book evidence observed at or after the trigger, retaining exact partial remainder and invalidating only the drifted plan. Selected and away contexts remain independently observable: Hyperliquid uses `activeAssetCtx` and explicitly rejects `allMids` as trigger authority, Arcus reuses its exact market/L2 streams, Lighter uses market stats with REST-only away depth, and REST catalog repair is pooled once per venue. Every matching GTC context pauses while protection is armed; unrelated contexts continue. The envelope, GTC and protection models are intentionally venue-neutral and never presented as margin, venue-native resting/TP/SL orders or execution guarantees. All protection stops when the tab closes. Fees, funding, leverage, cross/isolated margin, liquidation and queue priority remain unmodeled. APPROVAL continues to expose the reviewed no-send/human-confirmation path, while LIVE renders the server-owned mainnet readiness result and cannot alter execution configuration.
37. NS-416 supersedes item 33's entry-only away-portfolio display restriction without changing execution authority. A tab-scoped mark monitor derives only strict ledger contexts, reuses reviewed exact venue mark normalizers, caps per-asset Hyperliquid streams, pools Arcus/Lighter overview subscriptions and performs one REST catalog repair per represented venue. Each row can expose fresh exact mark and unrealized PnL, but stale, absent or context-mismatched evidence remains unavailable. Mark-to-market paper equity is exact-decimal realized balance plus unrealized PnL and is withheld unless every open position is fresh. It is never venue equity, margin, withdrawable collateral or a fill price; fees, funding and liquidation remain unmodeled.
38. NS-417 turns complete exact PAPER equity into a browser-local exposure gate without claiming venue risk authority. A maximum-8-KiB strict schema-v1 checkpoint binds one ledger identity and immutable user-entered UTC daily-loss/peak-drawdown basis points. It advances only after every nonzero position has a fresh exact mark observed no earlier than that position revision; closed realized-PnL records remain flat and need no mark. Loss ratios round upward. Daily breaches latch until a fresh checkpoint establishes the next UTC day; drawdown breaches latch until full ledger reset. Missing/corrupt policy, incomplete marks and breaches pause standard immediate placement plus standard selected/away GTC fills, while reduce-only orders, local protection and local cancellation remain available. This adds no signing, venue order, margin, liquidation, keeper or background guarantee.
39. NS-418 makes visible-depth entry slippage part of that same immutable ledger-bound PAPER policy. No default exists: the user chooses an integer 1–500 basis-point ceiling before standard exposure is available. For each standard immediate or GTC candidate, exact consumed notional is compared with the same quantity at the first executable book level; only adverse movement counts and any fractional basis point rounds upward. An immediate breach returns fixed policy evidence without a ledger mutation. A GTC breach leaves the exact order open for a newer observation and cannot prevent a later reduce-only candidate from exiting. Reduce-only immediate, GTC and protection paths deliberately bypass this entry-only cap while retaining their existing position constraints. The calculation does not model spread, fees, exchange queue, hidden liquidity, market impact beyond visible depth or venue slippage guarantees.
40. NS-419 independently gates observed entry spread so a one-level fill cannot report zero consumed-depth slippage while crossing an abnormally wide book. The user chooses a second immutable integer 1–500 basis-point ceiling. After strict two-sided normalization, PAPER computes `(best ask - best bid) / midpoint` through exact integer coefficients and rounds fractional basis points upward. Standard immediate and local GTC placement/fill paths fail or remain watching before ledger mutation when the ceiling is exceeded; later reduce-only candidates remain eligible. The retained checkpoint names exact authority, rounding and standard-entry-only scope. This is not an oracle, cross-venue fair-value check, fee model or venue execution promise.
41. NS-443 adds a customer-scoped PostgreSQL application ledger without collapsing trust domains. Privy-authenticated profiles and complete strict PAPER documents use the same opaque domain-separated customer digest, exact optimistic revisions and one active/archived session lifecycle. A separate minimum-32-byte service secret HMACs exact Privy-verified `venue + network + wallet` bindings; one digest has one customer owner, while raw addresses never enter storage. Normalized PAPER rows plus append-only position, PnL and risk projections remain rebuildable from retained evidence. Strict Hyperliquid signer lifecycle reconciliation may add testnet/live order, retained fill, token-fee, builder-fee and closed-PnL projections under immutable observation/replay rules; the matching configured-account portfolio generation adds coverage-labeled equity, available margin, exposure, position/mark/liquidation/leverage/margin/funding and funding events. Raw wallet/CLOID/order/trade/transaction/funding identities become keyed digests, bounded evidence never becomes converged and unavailable domains write no invented value. Guest PAPER stays browser-local. Signed execution intent, idempotency, audit and reconciliation authority stay in the isolated SQLite WAL signer store. The client writes locally first, serializes database updates, compacts mark-only snapshots and imports newer offline state only when every prior execution is byte-identical under the same ledger identity. Divergent state is retained for recovery rather than merged or discarded. PostgreSQL stores no raw Privy DID/email/token, wallet signature, key or signer path and grants no signing, submission, cancellation, retry, funding, withdrawal or mainnet authority.
42. NS-444 closes the managed Hyperliquid process gap without weakening capital gates. The signer supervisor accepts testnet or explicit mainnet, never Arcus, and projects only the selected network plus a matching mainnet flag into its loopback child. Mainnet requires an explicit canary notional and rejects anything above the compiled $12 first-canary ceiling before child launch. The offline doctor still derives and rejects owner/account key reuse without a network request; strict health binds child mode, dead-man network, account/builder fingerprints and schema-8 WAL safety; one shared store lock preserves testnet rehearsal evidence and excludes concurrent signers or maintenance. Runtime state/logs retain only fingerprints and process metadata. Starting the child performs no venue action and does not bypass database, identity, eligibility, builder, alerting, portfolio, dead-man, allowlist, leverage, confirmation or action-time authorization gates.
43. NS-445 makes campaign scope a signer authority instead of trusting only the web layer. The supervised child receives a canonical symbol allowlist plus maximum mainnet leverage; first-canary mainnet startup requires exact BTC-only and 1x values. The offline doctor and authenticated health expose only a SHA-256 scope digest, count and leverage cap. The BFF hashes its own canonical allowlist and locks readiness on any mismatch, while AEGIS takes the lower signer leverage ceiling. Opening orders and leverage changes outside signer policy fail before adapter or idempotency state; reduce-only exits and cancellation remain available so a policy reduction cannot trap risk. The strict read-only readiness report independently proves the leverage ceiling without printing symbols or making a venue request.
44. NS-446 separates campaign proof from campaign execution. A private exact-schema draft enumerates every required testnet lifecycle/recovery case or the mainnet canary closure, pre/post/final readiness, fresh per-mutation authorization, customer-database projection and final flat/zero-order/kill-switch/signer/backup state. Creation rejects incomplete, over-broad, unresolved or identity-bearing records, then binds the canonical redacted document to a SHA-256 digest; verification is offline and reports only fixed aggregate state. The digest must be retained independently and is not a signature. The tool has no network, signer, funding, cancellation, retry or venue authority.
45. NS-422 makes manual Hyperliquid slippage explicit instead of inheriting the platform default invisibly. A canonical whole-number 1-30 bps operator ceiling is required before provider I/O. The effective minimum of operator, platform and optional automation policy derives the normalized marketable entry limit and protective trigger-to-limit prices and remains the AEGIS midpoint deviation cap. The effective value is HMAC-bound into the short-lived ticket and rechecked with fresh book/account state before signer I/O. It is a price envelope, not venue acceptance, fill, depth, queue or protection finality; a triggered protective limit can rest after a gap. Normalized public L2 price and size remain paper-fill authority when a venue omits per-level queue cardinality and the adapter emits the nonnegative zero sentinel. The terminal renders that count unavailable rather than as zero real orders. Negative or fractional counts, unsorted sides, crossed books, stale time and missing two-sided depth still fail closed; accepting unavailable cardinality never creates queue position or priority evidence.
46. Hyperliquid take-profit authority is additive and user-bound. Opening reviews may include one optional profitable-side trigger; the control plane derives a conservative profitable-side limit and unique CLOID, then V4 submits parent, reduce-only TP and reduce-only SL in one official-SDK `normalTpsl` batch. Missing fields, reused CLOIDs, reduce-only parents, wrong-side triggers/limits or unexpected status cardinality fail closed. V2 parent-plus-SL and V3 testnet automation remain immutable; automation rejects rather than drops a take-profit bracket. Each child is fixed-size and limit-triggered, so gap/resting risk remains visible and no sibling-cancel or dynamic-resize behavior is claimed without separate venue proof.

Modal interaction is a browser authority boundary as well as an accessibility concern. One active dialog identity owns focus containment and Escape handling; changing from the command palette to another dialog transfers that ownership without restoring focus through the background. Order and cancellation mutations mark the dialog busy and cannot be hidden with Escape. When the final dialog closes, focus returns to the initiating connected element. Reduced-motion preference changes only presentation and scroll animation, never data, policy or execution state.

The injected-wallet boundary is read-only and browser-owned. EIP-6963 discovers multiple providers without trusting self-attested wallet labels as identity; a legacy EIP-1193 provider is only a fallback. NIGHTSHIFT requests accounts, observes account/chain/disconnect events, and can ask the wallet to switch or explicitly add the official chain-4663 metadata. It never calls signing, permission, approval or transaction methods, never stores a connected address in browser persistence, and continues to resolve holdings/activity through the server-owned Robinhood Chain provider plane.

Customer authentication is independent of both that public inspector and the local operator session. A configured Privy client permits only Google or EVM-wallet login, creates an embedded EVM wallet for `users-without-wallets`, constrains programmatic wallet switching to the reviewed Robinhood Chain definition, and lets an authenticated user link more wallets. The server verifies the provider access token against the exact app before a request becomes an authenticated customer session. Private profile reads and writes additionally require an identity token and cross-check its bounded authenticated-user object against the access-token DID; provider-linked wallets and currently connected browser wallets remain separate evidence sets. Strict presentation preferences persist under a domain-separated opaque customer digest with no raw DID, email or wallet, using atomic private writes, optimistic revisions and same-origin PATCH. Browser authentication or a profile record does not create a `TradeIntent`, operator cookie, entitlement, eligibility decision, signer capability, transfer or withdrawal authority. Missing, malformed, cross-app, expired or conflicting token evidence fails closed without a local fallback identity.

Customer Arcus withdrawal authority is a separate user-owned boundary. The dual-token private prepare route repeats exact withdraw-to-self documentation, chain-4663 proxy/implementation, account, collateral and compliance evidence without requesting a signature. Only an independently enabled runtime with fresh Privy production evidence, production RHC data, a private HMAC secret and a healthy opaque lifecycle store can persist and return a 120-second one-use ticket. The browser must match the exact connected provider wallet, switch it to chain 4663, obtain the exact typed confirmation phrase and call only `eth_signTypedData_v4`; it never receives or stores a key. The BFF recovers that signer, re-runs the complete preflight with the retained nonce, atomically claims the ticket before the fixed-origin POST and never retries. HTTP 202 is a pending acknowledgement. A separate exact-wallet reconciliation route accepts finality only from one matching retained withdrawal ID, amount, account and documented terminal transfer state. Raw customer identity, wallet address and signature never enter the durable checkpoint or public health; corruption makes health unsafe and the opaque lifecycle is covered by stopped-runtime backup/restore.

Privy configuration and production activation are separate evidence. The public app ID and server secret can initialize their respective SDK boundaries but cannot prove dashboard login methods, allowed origins, identity-token enablement, cookie DNS or an end-to-end browser flow. A private exact-schema rehearsal document binds a SHA-256 app-ID fingerprint to the fixed apex/`www` origins, cookie domain, chain 4663, embedded-wallet policy, all required dashboard/browser checks and a maximum 30-day expiry. Its digest prevents accidental mutation, private regular-file loading rejects symlinks and Unix group/world access, and health publishes only fixed state/reason/expiry. Command-deck and external activation projections require this evidence in addition to configured browser/server SDKs; expiry or app rotation clears readiness without affecting the independent execution lock.

Advanced Charts asset integrity and production activation are separate evidence. The self-hosted private v32 package verifier proves exact files, version, tree digest and entrypoint SRI but cannot prove the rendered left rail, real datafeed, studies, history ranges, zoom, persistence, reconnect repair or responsive containment. A second private exact-schema document binds those observed checks to the immutable release commit/artifact, licensed version/tree/count/bytes, fixed production origin, required resolutions/indicators and a maximum 30-day expiry. Health exposes only fixed state/reason/expiry. Release or asset rotation clears readiness, malformed evidence makes health unsafe, and the complete custom chart remains available. Advanced Charts persists layouts and study templates; drawings persist inside layouts, while separate chart/drawing-template UI remains unclaimed because current official documentation identifies it as Trading Platform-only.

## Control and execution plane

The browser-to-BFF authority boundary is separate from the signer credential. Public market/account reads remain anonymous. Arcus no-send preflight is also unprivileged but accepts only same-origin, byte-bounded JSON, keys its fan-out budget on an opaque account hash, re-reads every policy input from Arcus, and returns no token or promotable signed payload. Execution review, submit, cancel, reconciliation and audit routes require a valid short-lived operator session. A server-only secret is constant-time verified once, then replaced with an HMAC-authenticated HttpOnly/SameSite-Strict cookie scoped to `/api`. A separate CSRF value is returned to the same-origin client and held only in memory. Mutation bodies are byte bounded and rate budgets key on the random session ID, never `x-forwarded-for`.

```
AI proposal ─┐
User ticket ─┼─> TradeIntent -> schema -> freshness -> risk -> user confirmation
Market/account state ┘                                      |
                                                             v
                           execution-py -> Hyperliquid /exchange
                                        -> Arcus protected REST (Ed25519)
                                  |                  |
                                  └── audit <── order/fill reconciliation
```

The execution service owns venue signing and execution operations only; it does not own strategy or risk. Its Hyperliquid scope owns the official SDK, API-wallet key, `cloid`, short `expiresAfter` and order/cancel calls. Its independently disabled Arcus scope owns an operator-provided Ed25519 PEM, monotonic nanosecond clock, official typed canonical payloads, exact protected place/cancel calls, client-ID reconciliation and its own execution-alert outbox. Arcus place review binds one automatic cancel on reconciliation failure; the signer persists its exact scope before submission, claims it atomically at most once, and owns a durable incident latch that only terminal venue state can resolve. The signer database upgrades through an exclusive migration transaction and exposes only aggregate version/current/integrity/journal evidence; unsafe persistence removes all order and emergency authority. A network policy should admit internal requests only from the control plane and pin egress to the required official venue and reviewed operator-alert endpoints. The browser gets only redacted signer state, aggregate store/alert health and short-lived HMAC tickets from the BFF; it never receives either venue key, webhook URL, webhook secret, or database path. HTTP acknowledgements remain non-final and the Arcus public lifecycle reducer retains snapshot/update/gap-recovery authority. No scope may be enabled until its storage, alerting, venue limits, eligibility, rate state, funding, rehearsals, canary and final authorization gates are satisfied.

Hyperliquid manual entry review forces one complete configured-account reconciliation across every discovered perp DEX and rejects stale, partial, unsynchronized or account-mode-divergent evidence. That all-DEX snapshot is the authority for equity, positions and gross notional; selected-market `activeAssetData` remains a separate capacity constraint. Canonical operator market-position and portfolio-gross ceilings may only tighten the percentage-based AEGIS policy, are signed into the one-use ticket and are re-evaluated against a new generation before signer I/O. They gate only new exposure: reduce-only still requires the exact closing side and bounded remaining size but is not trapped by an existing notional breach.

`apps/api` is not that control plane and is not part of supervised production. It is an optional development-only Fastify process for deterministic AEGIS evaluation, proposal validation, and in-memory paper orders. Startup requires explicit enablement and a separate 32–4096 byte bearer capability, rejects every bind except `127.0.0.1`, caps request bodies and sockets, ignores forwarded-address authority, and labels every stateful response `executionCapability: "none"`. The production BFF remains in `apps/web`.

## State machine

`pending_risk → rejected | approved → submitted → open | partially_filled | filled | cancelled | unknown`

* `rejected` is terminal for the intent; create a new intent after any change.
* `unknown` means the request may have reached the exchange. Query by `cloid` before retrying.
* fill events are deduplicated before position/PnL effects.
* reconnect always performs snapshot-plus-stream reconciliation; visible L2 names REST fallback, WebSocket-live, gap and age explicitly.

## Deployment units

* `web`: loopback product and production BFF/control plane; no wallet key. Its public health projection reads the immutable release root directly and publishes exact commit/artifact provenance only from a stable regular-file pair whose directory matches the commit prefix. Ordinary source checkouts remain unversioned; deployed marker corruption makes health unsafe. The Nightshift command deck consumes only a strict subset of that response, clears stale proof on failure, and presents deployment identity, process execution locks, Robinhood Chain provider qualification and venue metadata as independent states. Supervised localhost startup validates preflight and build freshness before the child exists. An operator-requested restart stops the current child, re-runs preflight, rebuilds according to the validated `autoBuild` policy, launches only after success and verifies the disabled-execution health contract. Build failure leaves a fixed `build-failed` state with no child instead of serving either stale or partially replaced output; automatic crash recovery continues to restart the already accepted bundle without compiling moving source.
* `api`: dormant authenticated loopback development tool; paper/evaluation only and never a production dependency.
* `venues`: shared read-only interfaces and provider injection; no signer or submit method.
* `market-data`: outbound Hyperliquid WS/Info plus normalized Arcus public REST/WS; pooled by symbol/user limits.
* `risk`: pure library initially; independently deployable once multiple consumers exist.
* `execution-py`: private network, single nonce/timestamp owner per venue API wallet, restricted egress. Hyperliquid and Arcus scopes are independently disabled by default; Arcus loads an operator-owned Ed25519 PEM by file path only and pins egress to the official testnet/mainnet origins.
* `hl-signer-supervisor`: separate testnet-or-explicit-capped-mainnet loopback process owner for Hyperliquid. It accepts a dedicated API-wallet key by absolute file path only, rejects a master-wallet key, starts with no venue request through lazy SDK initialization, holds the shared signer-store lock and supervises an exact authenticated health contract including redacted symbol/leverage policy proof without granting execution authority.
* `postgres`, `redis`, telemetry collector\`: private data plane.

## Scaling rule

Scale market read paths and the API horizontally. Do not scale one signing key across concurrent execution replicas until nonce ownership and idempotency are transactional and exclusive. Prefer one agent wallet per execution process/subaccount.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://nytshift.gitbook.io/nytshift-docs/normative-design/architecture.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
