> 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/implementation-ledger/ns-443-durable-customer-trading-ledger.md).

# NS-443 · Durable customer trading ledger

## Outcome

NIGHTSHIFT adds a customer-scoped PostgreSQL application ledger for authenticated profile preferences, PAPER sessions, verified venue-account bindings, orders, fills, position/PnL projections, risk decisions, protection plans, funding placeholders, reconciliation runs and audit history. The isolated signer SQLite database remains the only authority for signed execution claims and venue reconciliation; credentials and signing material never enter the customer database.

Guest PAPER remains a bounded browser-only simulation. After Privy verification, one strict customer-paper API binds the same opaque domain-separated customer digest used by the profile boundary. The browser imports a complete local paper account only when the customer has no active database session. Later writes use exact optimistic revisions. Reset archives the server session and retains trade history instead of deleting it.

## Data model

* `customer_identities` stores only the opaque customer digest and lifecycle timestamps.
* `customer_profiles` stores strict preferences and optimistic revision.
* `customer_trading_sessions` owns one active PAPER session per customer and retains reset/archived sessions.
* `customer_paper_snapshots` stores the current strict full account document and SHA-256.
* `customer_trade_orders` and `customer_trade_fills` retain queryable lifecycle/fill history with exact decimal text.
* `customer_order_reconciliation_observations` retains immutable signer-contract observations, coverage and payload digests without raw provider identities.
* `customer_position_snapshots` and `customer_pnl_snapshots` are rebuildable, append-only projections by session revision.
* Risk, protection, funding, reconciliation and audit tables retain fixed-scope operational evidence.
* Composite customer/session foreign keys prevent cross-customer child rows. Current-position and current-PnL views are projections, never independent truth.

Fees, funding and liquidation remain `not-modeled` for current browser PAPER. Their nullable columns and event tables do not manufacture values. Migration `003_verified_execution_projection.sql` permits testnet/live order, retained fill, token fee, builder-fee and closed-PnL projections only after a Privy-verified account binding and strict signer reconciliation. The configured-account portfolio generation then adds coverage-labeled account equity/margin/exposure, positions, unrealized PnL, liquidation/leverage/margin fields and funding events. Account/positions require complete coverage; unavailable funding writes nothing and bounded funding remains bounded.

## Synchronization and recovery

* The complete browser document reuses the existing strict ledger, risk-envelope, GTC and protection parsers and stays capped at 160 KiB.
* Local storage is written before any network mutation. Database writes serialize, use expected revision and compact high-frequency mark-only changes to at most one pending snapshot per 30 seconds. Reset flushes the latest pending mark snapshot before archiving the session.
* Orders, fills, GTC/protection lifecycle changes bypass that mark debounce.
* The server independently enforces the original PAPER risk policy and an exact ordered suffix for retained executions; browser state cannot rewrite prior fills or loosen locked limits.
* On reconnect, a newer local document may extend the database only when every retained server execution is byte-identical and the ledger identity is unchanged.
* A different or divergent local session is retained in a bounded four-document recovery slot. It is never silently merged or discarded.
* A database failure pauses remote synchronization without stopping local PAPER exits or granting execution authority.

## Operations

`infra/postgres/001_init.sql` remains the legacy control-plane baseline. `002_customer_trading_ledger.sql` adds the customer schema. `003_verified_execution_projection.sql` adds keyed account ownership, live/testnet sessions, immutable reconciliation observations and exact fee/closed-PnL projections. `pnpm db:migrate` applies ordered migrations under a PostgreSQL advisory lock and records the exact SHA-256; changed, unknown or missing history fails verification. Compose does not preload SQL outside that registry. `pnpm db:status` and `pnpm db:verify` are read/verification operations.

When Privy server identity is configured, `/api/health` is unsafe unless the customer database is configured and queryable. An unsigned/read-only deployment may remain explicitly `unconfigured`.

## Boundaries

* No Privy DID, email, bearer/identity token, wallet signature, private key, mnemonic or signer database path is stored.
* A verified wallet remains provider-owned evidence; only a keyed, domain-separated account digest may bind reconciled account rows. One venue/network/digest has one customer owner.
* Raw wallet addresses, CLOIDs, provider order/trade IDs and transaction hashes are not stored. Exact replay is idempotent; conflicting or regressing evidence fails closed.
* PostgreSQL does not sign, submit, cancel, retry, fund, withdraw, enable mainnet or change execution configuration.
* PAPER remains live-book simulation with no venue order, fees, funding, leverage, liquidation or queue guarantee.

## Verification

* Strict document, authenticated route, revision-conflict, reset/archive, client-response, offline-extension and divergent-recovery tests.
* Profile and health regression tests.
* PostgreSQL 17 migration/status/verify rehearsal against a fresh database.
* Full contracts, typecheck, test, build, smoke and handoff gates before promotion.


---

# 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/implementation-ledger/ns-443-durable-customer-trading-ledger.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.
