Phase map

Phase 0 to Phase 8 at a glance

  1. PROMPT-00 · Phase 0 — Fork and integration baseline. Pin the upstream base, brand the fork, own release and update endpoints. Accept: the fork builds with no trading code and can ingest one upstream batch.

  2. PROMPT-01 · Phase 1 — Trading domain and workspace. Done as built: domain contracts, mission lifecycle, POC authority defaults, versioned strategy publishing, the two §14.3 tools over MCP, and the read-only workspace shell. Composer, timeline, and provider-derived binding move to Phase 3. Accept: one ETH momentum mission renders mandate and strategy; a second is rejected.

  3. PROMPT-02 · Phase 2 — Read-only Hyperliquid integration. Market resolution, precision, candles, BBO, account, orders, positions, WebSockets — plus the testnet lab: recorded fixtures, an opt-in live smoke suite, and a dev mission-bind for hands-on iteration. Accept: live ETH testnet reads through the tools; master-address queries only.

  4. PROMPT-03 · Phase 3 — Watches and harness wake-up. The central architecture proof. Accept: a final candle fires once and T3 resumes the same provider with a fresh snapshot.

  5. PROMPT-04 · Phase 4 — Execution and reconciliation. Preview, nonce, deterministic cloid, IOC/GTC, fills, positions, loss-budget — signed by an owner-approved interim testnet API wallet. Accept: Hyperliquid accepts the order and retry cannot duplicate it.

  6. PROMPT-05 · Phase 5 — Protection, deterministic controls, position management. Mandatory stop, partial-fill fallback, all deterministic buttons, bounded emergency close. Accept: protection confirmed for actual canonical size.

  7. PROMPT-06 · Phase 6 — Privy onboarding and signer swap. Master wallet, execution wallet, one-time t3-trades-poc API-wallet approval; retires the interim signer. Accept: ordinary testnet signing works without another prompt.

  8. PROMPT-07 · Phase 7 — Conversational modification. Authority patches, deterministic-control interpretation, ambiguity handling. Builds on Phase 5 primitives, not a second execution path.

  9. PROMPT-08 · Phase 8 — Recovery and per-provider conformance. Startup and reconnect recovery, agent_unavailable, and independent Codex/Claude/OpenCode conformance. No provider failover.

Phase 0 · Platform

PROMPT-00 · Fork and integration baseline

Purpose

Stand up the long-lived T3 Trades fork against a pinned upstream baseline before any trading code is written, so later phases add product-owned modules against a controlled divergence boundary.

Handoff

Gives PROMPT-01 a clean building fork, the pinned upstream SHA, the integration map of seams, the validated sync runbook, and the product-owned package layout conventions.

Context

Inspect

  • Upstream LICENSE, README, CONTRIBUTING, package.json, and pnpm-workspace.yaml
  • Upstream server update and version-negotiation code paths
  • Upstream desktop application identity and release workflow files
  • Upstream provider, orchestration, and contracts package layouts
  • Existing CI and signing configuration

Constraints

  • Preserve the upstream MIT license and copyright notice verbatim
  • Treat upstream/main as a read-only remote-tracking ref; do not create or commit to a local mirror branch
  • Do not reverse the upstream/origin remote meanings across machines
  • Do not leave forked clients pointing at upstream update or release endpoints
  • Keep divergence additive: new product-owned packages over broad upstream rewrites
  • Do not combine branding rewrites with architecture changes

Tasks

  • Clone the upstream direct history, rename the cloned remote to fetch-only upstream, and add the writable product repository as origin
  • Protect origin/main as the product line; use short-lived feature/trading-* branches and reviewed sync/upstream-YYYY-MM-DD-<shortSHA> branches only
  • Pin each accepted upstream commit with a new immutable accepted-baseline tag and record it in docs/upstream/BASELINE.md
  • Apply fork branding: product name, app IDs, executable names, artifact names, signing identities, and update feeds
  • Replace release, auto-update, and server-replacement endpoints with fork-controlled infrastructure
  • Write docs/upstream/PATCH_LEDGER.md seeded with the seams already touched
  • Produce an integration map of current T3 services and the narrow seams trading will extend
  • Expose both productVersion and t3UpstreamCommit from the build

Steps

  1. Clone and configure remotes using the Git strategy repository model
  2. Create the product and short-lived branches from the Git strategy branch map
  3. Pin the upstream base, create the accepted-baseline tag, and write BASELINE.md using the Git strategy setup runbook
  4. Apply branding and release/update independence after completing the Git strategy setup runbook
  5. Record the package-manager and exact build commands from the pinned commit
  6. Walk one sync batch through SYNC_RUNBOOK.md to validate the procedure
  7. Run upstream build, typecheck, lint, and tests on the fork baseline

Parallel tracks

  • Remotes, branches, and baseline pinning
  • Branding, identifiers, and release/update endpoints
  • Patch ledger and integration map authoring
  • Sync runbook dry-run

Outputs

  • Initialized fork repository with correct remotes and branches
  • docs/upstream/BASELINE.md with pinned commit, tag, fork version, and date
  • docs/upstream/PATCH_LEDGER.md seeded with branding seams
  • docs/upstream/SYNC_RUNBOOK.md validated by one batch
  • Build artifact exposing productVersion and t3UpstreamCommit

Acceptance

  • The fork builds without any trading code present
  • Client and server emit fork-controlled version metadata
  • One upstream batch is ingestible through the sync runbook
  • No updater, release feed, or replacement URL points at upstream T3

Tests

  • Upstream build, typecheck, lint, and unit tests pass on main
  • Version metadata asserts the fork name and upstream SHA
  • Grep asserts no upstream update/release hostname remains in code
  • Sync runbook reproduces a clean merge commit on a throwaway sync branch

Docs

  • docs/upstream/BASELINE.md
  • docs/upstream/PATCH_LEDGER.md
  • docs/upstream/SYNC_RUNBOOK.md
  • Integration map of T3 services and trading seams
Blockers. The fork repository, signing identity, or update infrastructure is not provisioned; or the pinned upstream commit fails its own build or tests and cannot be adopted.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 0 of T3 Trades: fork and integration baseline.
Read this whole prompt before acting, then work strictly in step order.

REPOSITORY FACTS
- Product fork (writable "origin"): github.com/0xgeorgemathew/t3code
- Upstream (fetch-only "upstream"): github.com/pingdotgg/t3code
- Specification evidence pin: 55dd01612efc51e19de479da5a0e348cbe2521e3
- Baseline candidate: v0.0.31 = a8e05cbb92633a1351529f2bc402071f615e5051
  (release commit on upstream main, 2026-07-29, 28 commits ahead of the
  evidence pin, which is its direct ancestor). The OWNER must confirm the
  approved baseline before you tag anything.
- Toolchain at both commits: pnpm@11.10.0, node ^24.13.1, task runner
  vite-plus ("vp"). There is NO turbo. Root scripts: pnpm typecheck,
  pnpm lint, pnpm test, pnpm fmt:check.

READ FIRST (the specification; do not skip)
- https://market-bender.mathew.workers.dev/git-strategy.html — the whole
  page. Its four runbooks are literal shell scripts with placeholders you
  will fill and execute.
- https://market-bender.mathew.workers.dev/architecture.html — section 6.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. Clone + remotes. Clone the fork; add upstream fetch-only and disable
   pushes (git remote set-url --push upstream DISABLED). Done when:
   `git remote -v` shows origin=fork (fetch+push), upstream=pingdotgg
   (fetch only, push DISABLED), and NO local branch named "upstream".
2. Build at the candidate baseline. corepack enable; pnpm install
   --frozen-lockfile; run all four gates unmodified. Done when: all pass.
   If any fail, STOP — the candidate is not adoptable; report verbatim.
3. Baseline pin. With the owner-approved SHA, execute the git-strategy
   setup runbook exactly: annotated tag upstream-base/YYYY-MM-DD-shortSHA,
   docs/upstream/BASELINE.md (approved SHA, tag, fork version, date, and
   the evidence pin recorded separately), reviewed via PR. Done when: the
   PR contains only BASELINE.md and the tag is published per the
   tag-publication runbook.
4. Branding sweep. Rename product name, app IDs, executable names,
   artifact names, and update feeds. Do NOT mix in any architecture
   change. Done when: a fresh build shows the fork identity everywhere a
   user can see it.
5. Endpoint independence. Grep the tree for upstream auto-update,
   release-feed, and server-replacement hostnames; point each at
   fork-controlled infrastructure or disable it. Done when: a grep for
   the upstream hostnames returns no executable reference, and a CI
   check enforces that grep permanently.
6. Version metadata. Expose productVersion and t3UpstreamCommit from both
   server and client builds. Done when: a running build serves both and a
   test asserts them.
7. Ledger + sync runbook. Seed docs/upstream/PATCH_LEDGER.md with every
   file steps 4-6 touched. Write docs/upstream/SYNC_RUNBOOK.md from the
   git-strategy batch-sync runbook and validate it by walking ONE real
   upstream batch on a throwaway sync branch. Done when: the throwaway
   merge builds, gates pass, and the branch is deleted.
8. Integration map. Write docs/upstream/INTEGRATION_MAP.md listing, with
   verified paths at your baseline: provider/Services/ProviderService.ts
   + provider/Layers/ProviderService.ts, ProviderSessionDirectory,
   orchestration/{Services,Layers}/OrchestrationEngine.ts, decider.ts,
   projector.ts, Layers/ProjectionPipeline.ts, persistence/Migrations.ts
   (static import list; highest upstream migration is 034),
   mcp/McpHttpServer.ts + McpSessionRegistry.ts + McpInvocationContext.ts,
   the WS push path apps/server/src/ws.ts, and @t3tools/shared
   DrainableWorker + KeyedCoalescingWorker. Also read the overhauled
   AGENTS.md (changed in #4782) and record its rules for agents in the
   map. Done when: every listed path is verified to exist at the baseline.

ACCEPTANCE (verify each before reporting done)
- Fork builds with zero trading code; all gates green.
- Client and server emit fork name + upstream SHA.
- One upstream batch ingested through SYNC_RUNBOOK.md.
- No updater, release feed, or replacement URL points at upstream.
- BASELINE.md, PATCH_LEDGER.md, SYNC_RUNBOOK.md, INTEGRATION_MAP.md exist.

STOP AND ASK (owner decisions — never decide these yourself)
- The approved baseline SHA (candidate: v0.0.31 / a8e05cb).
- Branch-protection, reviewer, and signing policy.
- The fork's conformance command name (a placeholder script is fine).
- Real update/release infrastructure endpoints.

Phase 1 · Domain

PROMPT-01 · Trading domain and workspace

Purpose

Add the trading domain contracts, mission lifecycle, authority defaults, immutable harness binding, strategy publishing, and the read-only trading workspace shell so a harness can own an ETH momentum mission conceptually, with no exchange execution yet.

Handoff

Gives PROMPT-02 the running mission runtime, the published strategy surface with version-bound watch supersession, and the workspace shell that will display live market state. The watch registration tool contract ships with the watch runtime in PROMPT-03.

Done as built, 2026-07-30. Delivered on feature/trading-01-domain: contracts, migrations 035/036, TradingMissionService with the §11.1 table, POC defaults, binding immutability, versioned strategy publishing with watch supersession, the two §14.3 tools over the shared MCP boundary, orchestration commands/events/read model, and the read-only workspace shell. Deferred with new homes: execution/order/position contracts → PROMPT-04; watch registration tool contract → PROMPT-03; mission composer, timeline, thread-derived provider binding, and first-turn start → PROMPT-03; authority patch API → PROMPT-07. Until PROMPT-03 the fork pins a placeholder binding (provider: "claude").

Context

  • PROMPT-00 fork baseline and integration map
  • Domain §10 core domain model and Runtime §11 state machines
  • Tools §14 agent tool surface (mission and strategy tools)
  • Interface reference: the UI concepts prototype (workspace, status, mandate, timeline, controls)

Inspect

  • ProviderService session-start and resume seams
  • Existing T3 RPC, push-channel, and projection registration points
  • Existing persistence and optimistic-versioning conventions
  • Mission, authority, strategy, and harness-binding contracts from §10

Constraints

  • No exchange execution in this phase
  • ProviderService remains the only provider runtime; do not spawn provider CLIs
  • Only one active autonomous mission may exist at a time
  • Provider binding is immutable for an active mission
  • Do not put exchange credentials into provider prompts

Tasks

  • Author packages/trading-contracts: account, authority, mission (with harness binding and runs), strategy (momentum), market primitive, watch, events, and tools — execution, order, and position contracts are authored with the execution phase (PROMPT-04)
  • Implement TradingMissionService with mission creation, status transitions per §11.1, and the one-active-mission invariant
  • Apply POC authority and risk-policy defaults from §10.4
  • Persist the immutable harness binding per §10.2 at mission creation, bound to the creating thread (thread-derived provider selection lands in PROMPT-03)
  • Implement trading_publish_momentum_strategy with expected-version optimistic locking and watch supersession
  • Build the read-only trading workspace shell — mission status, mandate, strategy panel, and watch list from live projections; the composer and timeline of the Mission workspace prototype land in PROMPT-03
  • Register trading RPC and push projections through the existing seams

Steps

  1. Define and freeze the domain contracts in trading-contracts
  2. Implement mission and authority persistence with optimistic versions
  3. Add mission creation as an orchestration command that binds the mission to its creating thread
  4. Expose the mission and strategy publishing tools via the shared MCP/tool surface
  5. Compose the workspace React surfaces inside the existing T3 client
  6. Project mission and strategy state through the server's ordered WS push path (apps/server/src/ws.ts)

Parallel tracks

  • Domain contracts
  • Mission and authority services
  • Workspace UI surfaces
  • Projection and read-model rendering

Outputs

  • packages/trading-contracts domain types
  • TradingMissionService with one-mission invariant
  • Active-mandate, strategy, and watch read-model UI (workspace shell)
  • Strategy publishing tool with version control
  • Trading mission projection with ordered updates

Acceptance

  • One ETH momentum mission is created with a $1,000 mandate through the trading.mission.create orchestration command, bound to an existing thread
  • The bound thread's harness holds the §14.3 tools over the shared MCP boundary
  • The harness publishes a valid MomentumStrategyState
  • The UI renders the mandate and published strategy
  • Only one active mission exists; a second is rejected

Tests

  • Mission transition table unit tests per §11.1
  • Authority defaults unit tests (patch validation lands with the authority-patch API in PROMPT-07)
  • Provider-binding immutability contract test
  • Strategy publishing with stale version is rejected
  • Workspace presentation parity checks — status labels and watch descriptions (keyboard checks land with the composer in PROMPT-03)

Docs

  • packages/trading-contracts source
  • PATCH_LEDGER.md PROMPT-01/01B seam records
  • Mission read model (OrchestrationTradingMission) in packages/contracts/src/trading.ts
  • Handoff summary for PROMPT-02
Blockers. Verified cleared at the evidence pin 55dd016: ProviderService startSession and sendTurn are callable from server-side code (the ProviderCommandReactor already does both), and projection/push registration points exist (ProjectionPipeline projector list, ws.ts). This phase blocks only if the approved product baseline has regressed those seams.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

STATUS: completed as built on feature/trading-01-domain (2026-07-30).
Kept for the record; the lists above are the ratified as-built scope.

You are implementing Phase 1 of T3 Trades: trading domain and workspace.
Phase 0 is complete (fork, baseline tag, docs/upstream/*). No market
data, no exchange calls, no signing in this phase.
Branch: feature/trading-01-domain.

REPOSITORY FACTS
- Baseline: the SHA in docs/upstream/BASELINE.md. All seam facts below
  were verified at evidence pin 55dd016 AND at v0.0.31 (a8e05cb);
  re-check each once at YOUR baseline before relying on it.
- Gates: pnpm typecheck && pnpm lint && pnpm test.

READ FIRST
- https://market-bender.mathew.workers.dev/domain.html — every type.
  Copy contracts EXACTLY; do not rename fields. POC decisions already
  made: marginModes ["isolated"] only; allowDirectionReversal false.
- https://market-bender.mathew.workers.dev/runtime.html — section 11.1
  (mission statuses and blockedReason values).
- https://market-bender.mathew.workers.dev/tools.html — section 14.3.
- https://market-bender.mathew.workers.dev/architecture.html — section
  6.3 forbidden list. Violating any item there fails the phase.
- https://market-bender.mathew.workers.dev/prototype-workspace.html —
  variation A ("Thread") is the layout intent for the workspace shell.

VERIFIED UPSTREAM SEAMS (paths at the baseline)
- Contracts pattern: packages/contracts/src/orchestration.ts uses a
  three-tier command split (Client / DispatchableClient / Internal).
  Mirror that split for trading commands in packages/trading-contracts.
- New-event recipe, in this order: (1) schema in trading-contracts;
  (2) server re-exports in a NEW apps/server/src/trading/Schemas.ts;
  (3) decider case; (4) projector case; (5) ProjectionPipeline case plus
  a name in ORCHESTRATION_PROJECTOR_NAMES; (6) optional reactor
  registered in server.ts ReactorLayerLive. Items 3-6 are upstream
  edits — ledger each one.
- Migrations are STATIC imports in apps/server/src/persistence/
  Migrations.ts. Highest upstream migration is 034; trading tables start
  at 035. Each new migration needs BOTH the import line and the
  migrationEntries tuple.
- New packages: the pnpm-workspace packages/* glob auto-includes them.
  Mirror packages/shared's source-first per-subpath exports (raw .ts)
  and use catalog: for dependencies shared with upstream.
- MCP tools are process-global with per-invocation capability gating:
  widen McpCapability ("preview" -> add "trading") in
  apps/server/src/mcp/McpInvocationContext.ts; add
  apps/server/src/mcp/toolkits/trading/{tools,handlers}.ts copying the
  preview toolkit shape; register a TradingToolkitRegistration layer in
  McpHttpServer.ts; grant the capability in McpSessionRegistry.issue.
- UI push goes through apps/server/src/ws.ts. Upstream docs say
  "ServerPushBus"; no symbol by that name exists in code.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. Create packages/trading-contracts with one schema file per domain
   area: account, authority, mission, strategy (momentum), market
   primitive, watch, events, tools. Execution, order, and position
   contracts are authored in PROMPT-04 with the execution service. Copy
   each type from domain.html verbatim, field names included. Done
   when: the package typechecks and every type is importable via
   subpath exports.
2. Migration 035 (and 036 if needed): create trading_accounts,
   trading_missions, trading_authority_versions,
   momentum_strategy_versions, trading_watches, trading_harness_runs,
   trading_event_inbox (recovery.html section 18 lists all thirteen;
   execution/order/fill/reservation tables wait for PROMPT-04, execution).
   Optimistic-version columns on missions, authority, strategy, watches.
   Done when: migrating a fresh database succeeds and running it twice
   is a no-op.
3. TradingMissionService in apps/server/src/trading/: createMission,
   status transitions per runtime.html 11.1, one-active-mission
   invariant. Done when: unit tests cover every legal transition, reject
   every illegal one, and reject a second active mission.
4. pocAuthorityDefaults(allocatedCapitalUsd) exactly as on domain.html,
   typed : TradingAuthority. Done when: a test asserts the $1,000
   example yields 3x leverage, $3,000 notional, $100 cumulative,
   $20 per-position, isolated-only, reversal-off.
5. Provider binding: persist TradingHarnessBinding (provider,
   providerInstanceId, threadId) at mission creation; reject any change
   while the mission is active. Sessions stay owned by ProviderService;
   trading code never starts one directly (wake-ups land in PROMPT-03).
   Done when: a contract test proves immutability and greps prove
   trading code never spawns provider CLIs.
6. trading_publish_momentum_strategy: expected-version optimistic
   locking; on accept, increment version and mark prior-version watches
   superseded. Done when: a stale-version publish is rejected in a test.
7. Workspace shell in apps/web: mission status, mandate card, strategy
   panel, and watch list — driven by real projections only (the
   composer and timeline land in PROMPT-03). Done when: a created
   mission renders mandate and published strategy from live
   projections.
8. Wire trading RPC + projections through the existing seams (ws.ts
   channel, ProjectionPipeline). Done when: UI updates arrive ordered
   through the existing push path — no new websocket, no polling.

ACCEPTANCE
- One ETH momentum mission with a $1,000 mandate, bound to an existing
  thread; the bound harness publishes a valid MomentumStrategyState
  over the shared MCP tools; UI renders mandate + strategy; second
  active mission rejected; stale publish rejected; migration
  round-trip green.

STOP AND ASK
- Any deviation from the published contracts on domain.html.
- Any upstream edit beyond the seams named above.

Phase 2 · Exchange

PROMPT-02 · Read-only Hyperliquid integration

Purpose

Give the trading mission a read-only, reconciled view of live ETH testnet market and account truth through a single shared Hyperliquid adapter — and stand up the testnet lab (recorded fixtures, an opt-in live smoke suite, a dev mission bind) so the owner can iterate against the real exchange from day one.

Handoff

Gives PROMPT-03 the read-only market/account ports, freshness thresholds, reconnect reconciliation behavior, and the ETH subscriptions that watches will evaluate.

Context

  • PROMPT-01 mission runtime and workspace
  • Runtime §13 market data and Hyperliquid §15.2–15.3 gateway and precision
  • Hyperliquid documented info endpoint, WebSocket subscriptions, and candle intervals
  • Phase 2 acceptance gates: the Acceptance list below

Inspect

  • The documented info-endpoint and WebSocket wire shapes (no runtime SDK — direct HTTP/WS; community SDKs are dev-time cross-checks only)
  • Documented candle intervals and recent-candle availability
  • Account-query requirements: master address versus API-wallet address
  • Existing market-data freshness conventions in the workspace

Constraints

  • No signing in this phase; read-only only
  • Never query account state with the execution-wallet address
  • Never hard-code the ETH asset index
  • Direct 1m/3m/5m/15m/1h subscriptions; do not synthesize intervals locally
  • One tool response is bounded to 500 bars
  • All exchange shapes stay behind the HyperliquidGateway interface

Tasks

  • Implement HyperliquidInfoClient and HyperliquidWebSocketClient with bounded reconnect and resubscribe
  • Implement HyperliquidMarketResolver with cached symbol, asset index, szDecimals, max leverage, and availability
  • Implement HyperliquidPrecision: normalize size and price, remove trailing zeroes, verify exchange minimum notional
  • Implement market snapshot, candle history (1m/3m/5m/15m/1h direct), and BBO reads
  • Implement account state, open orders, and position reads using the master address
  • Reconcile canonical state through the Info API after reconnect; de-duplicate replayed records
  • Expose market and account tools: trading_resolve_market, trading_get_market_snapshot, trading_get_market_history, trading_get_order_book, trading_get_account_state, trading_get_position, trading_get_open_orders
  • Attach freshness metadata to tool results
  • Record fixtures from live testnet responses and replay them in unit tests
  • Add an env-gated live-testnet smoke suite covering each read path
  • Add a dev-only mission-create/bind affordance so the owner can bind a thread and exercise the tools interactively

Steps

  1. Create thin info and WebSocket transports directly on the documented API
  2. Build the market resolver and precision cache with freshness
  3. Subscribe to ETH 1m/3m/5m/15m/1h candles, BBO, asset context, and account channels
  4. Map exchange shapes to domain records behind the gateway interface
  5. Add reconnect snapshot refresh and dedupe
  6. Wire read-only tools into the shared MCP surface
  7. Stand up the testnet lab: fixture recorder, env-gated live smoke suite, dev mission bind

Parallel tracks

  • Market resolver and precision
  • Market streams and history
  • Account streams and reconciliation
  • Read-only tool wiring

Outputs

  • packages/hyperliquid read-only adapter
  • Cached ETH market metadata and precision normalizer
  • Live candle and BBO subscriptions with freshness
  • Account, order, and position reads against the master address
  • Read-only market and account tools
  • Testnet lab: recorded fixtures, opt-in live smoke suite, dev mission bind

Acceptance

  • The harness reads live ETH testnet market and account state through T3 tools
  • Account state is queried with the master-wallet address
  • The execution-wallet address is never used as account identity
  • Reconnect restores subscriptions and refreshes canonical state
  • Direct 1m, 3m, 5m, 15m, and 1h candle subscriptions are verified
  • The owner binds a thread with the dev affordance and watches the harness read live testnet data through the tools

Tests

  • Precision normalization unit tests (szDecimals, price, trailing zeroes, min notional)
  • Candle finalization tests for 1m/3m/5m/15m/1h
  • Reconnect resubscribe and canonical-state refresh tests
  • Account-query negative test asserting the API-wallet address is never used
  • Hyperliquid testnet smoke for each direct candle interval

Docs

  • packages/hyperliquid adapter source
  • Market metadata and freshness guarantees
  • Error taxonomy for read paths
  • Handoff summary for PROMPT-03
Blockers. Hyperliquid documented behavior cannot be reproduced for a required read operation on testnet; or account state cannot be read without exposing material the harness must never see.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 2 of T3 Trades: read-only Hyperliquid
integration. Phases 0-1 are complete. NOTHING here signs or mutates
exchange state. Branch: feature/trading-02-market-data.

BEFORE ANY CODE — STOP AND ASK IF UNDECIDED
- DECIDED 2026-07-30: no runtime SDK. Call the documented API directly
  behind HyperliquidGateway. Testnet endpoints: POST
  https://api.hyperliquid-testnet.xyz/info and the /ws WebSocket on the
  same host, per the official API docs. Community SDKs (e.g.
  @nktkas/hyperliquid) may be consulted as dev-time references, never
  imported at runtime.
- The funded testnet MASTER address for account reads (public address
  only in server config — reads need no key; the Info API is
  unauthenticated).
- Interval proof: record one fixture per interval (1m/3m/5m/15m/1h)
  showing testnet serves it directly via candle snapshot AND WebSocket
  subscription. If ANY interval is missing, STOP — the no-local-
  synthesis rule on runtime.html needs owner revision first.

READ FIRST
- https://market-bender.mathew.workers.dev/runtime.html section 13 —
  copy the freshness constants into named config: BBO stale after 2s;
  asset context 5s; account state 5s during execution; closed candles
  valid only after final close time, processed once; 500 bars max per
  response.
- https://market-bender.mathew.workers.dev/hyperliquid.html sections
  15.2-15.3 — implement the HyperliquidGateway interface as written.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. packages/hyperliquid: HyperliquidInfoClient (HTTP info API) and
   HyperliquidWebSocketClient (subscribe; bounded exponential backoff
   reconnect; resubscribe on reconnect). Done when: a kill-and-reconnect
   test restores every subscription without duplicate events.
2. HyperliquidMarketResolver: resolve and cache canonical symbol, asset
   index, szDecimals, max exchange leverage, availability — from live
   metadata. NEVER hard-code the ETH asset index; add a lint/grep test
   that fails on a literal index. Done when: resolver responses carry
   freshness stamps and the grep gate is in place.
3. HyperliquidPrecision: normalize size to szDecimals, normalize price,
   strip trailing zeroes, verify exchange minimum notional, return the
   normalized values. Done when: table-driven tests cover rounding
   edges, trailing zeroes, and min-notional rejection.
4. Market reads (snapshot: mark/mid/oracle/funding/open interest/day
   volume/BBO; candle history: direct intervals only, 500-bar cap;
   order book) and account reads (account state, open orders,
   positions) — MASTER-wallet address only. Done when: a negative test
   proves the execution-wallet address is never used for identity.
5. Reconnect reconciliation: after a WS reconnect, refresh canonical
   state via the Info API and de-duplicate replayed records. Done when:
   an out-of-order/replay fixture converges to canonical state.
6. Freshness metadata (source timestamp + age) on every read result.
   Done when: a stale-BBO fixture is flagged stale at exactly 2s.
7. Wire the seven read-only tools into the Phase 1 trading MCP toolkit:
   trading_resolve_market, trading_get_market_snapshot,
   trading_get_market_history, trading_get_order_book,
   trading_get_account_state, trading_get_position,
   trading_get_open_orders. Done when: a bound harness calls each tool
   and receives typed, freshness-stamped results.
8. Workspace: live price + sparkline and account essentials in the
   mission header (see the prototype's essentials strip), fed by
   projections, not direct fetches. Done when: the UI shows live
   testnet data.
9. Testnet lab: (a) fixture recorder — capture real info/WS responses
   into replayable unit-test fixtures; (b) env-gated live smoke suite
   (skipped unless the testnet env vars are set) covering every read
   path; (c) dev-only mission-create/bind command so the owner can
   bind the current thread to a mission and call the tools by hand.
   Done when: the owner chats with a bound harness and sees live
   testnet reads round-trip.

ACCEPTANCE
- Live ETH testnet market and account state readable through T3 tools;
  reconnect restores subscriptions and canonical state; every interval
  verified direct with a recorded fixture; the execution wallet never
  appears as account identity; every exchange shape stays behind the
  HyperliquidGateway interface; the dev bind lets the owner exercise
  every tool interactively.

Phase 3 · Architecture proof

PROMPT-03 · Watches and harness wake-up

Purpose

Prove the central architecture: the T3 server stays active after a harness turn ends, evaluates persisted watches, and resumes the same provider session with a fresh mission snapshot when a typed event fires.

Handoff

Gives PROMPT-04 a proven event-driven resume loop, the wakeup payload contract, and the deterministic services that execution and signing will reuse.

Central architecture proof. This phase verifies T3's existing same-provider resume path. It does not require provider switching or a new provider runtime, and a watch firing does not itself authorize a position.

Context

Inspect

  • ProviderService resume and session-availability APIs
  • Existing T3 queue workers and runtime receipt bus
  • Candle finalization and price-cross behavior from PROMPT-02 subscriptions
  • Existing optimistic-versioning patterns for watches

Constraints

  • Use T3's existing same-provider resume path; no provider switching or new provider runtime
  • Only one run may own the mission decision lease at a time
  • Watches are simple, deterministic, typed, and bound to a strategy version
  • A watch firing does not itself authorize a position
  • Do not generate new discretionary intent between turns

Tasks

  • Implement MarketWatchRegistry with persisted watches bound to strategy version per §12.1
  • Implement WatchEvaluator: candle-close and price-cross predicates, and scheduled reassessment
  • Implement TradingEventInbox with deduplication keys and TradingEventCoalescer
  • Implement TradingTurnCoordinator with the one-run-at-a-time decision lease per §12.3
  • Wire trading-to-ProviderService resume for the selected provider through existing APIs
  • Assemble the TradingHarnessWakeup payload with fresh market, account, strategy, authority, and pending events per §12.2
  • Author the §14.4 watch tool contracts and register the tools: trading_register_watch, trading_schedule_reassessment, trading_list_watches, trading_cancel_watch
  • Derive the harness binding from the bound thread's provider session at mission creation, replacing the Phase 1 placeholder binding, and start the first run (cause mission_created)
  • Build the mission composer and trading timeline in the workspace (deferred from Phase 1)

Steps

  1. Persist watches and supersede obsolete watches on strategy version change
  2. Build the candle-close and price-cross evaluators against the PROMPT-02 subscriptions
  3. Build the event inbox with coalescing and a single decision lease
  4. Connect the coordinator to ProviderService resume
  5. Deliver a fresh authoritative snapshot on each wake-up
  6. Verify duplicate or superseded events do not start a second run

Parallel tracks

  • Watch registry and evaluators
  • Event inbox and coalescer
  • Turn coordinator and lease
  • Provider resume wiring

Outputs

  • Persisted watch registry and evaluators
  • Event inbox with coalescing
  • TradingTurnCoordinator with single-lease enforcement
  • Provider resume wiring and wakeup payload assembly
  • Watch and schedule tools
  • Mission composer, trading timeline, and thread-derived provider binding

Acceptance

  • The harness registers a watch and its turn ends
  • T3 remains active and monitoring after the turn ends
  • A final candle triggers exactly once
  • T3 resumes the same provider session through ProviderService
  • Fresh market and account snapshots are delivered to the resumed turn
  • Duplicate or concurrent runs are prevented by the lease

Tests

  • Candle finalization fires a watch exactly once for 1m/3m/5m/15m/1h
  • Price-cross transition and watch supersession unit tests
  • Event coalescing and deduplication tests
  • Decision-lease concurrency test: a second run is queued or rejected
  • Same-session resumption contract test against ProviderService
  • Workspace keyboard and projection parity checks for the composer and timeline (deferred from Phase 1)

Docs

  • packages/trading-core watch and coordinator source
  • Wakeup payload schema
  • Same-provider resume wiring notes
  • Handoff summary for PROMPT-04
Blockers. Verified cleared at the evidence pin 55dd016: ProviderService.startSession automatically applies the persisted resumeCursor from ProviderSessionDirectory, and server-side dispatch of thread.turn.start into the orchestration engine is an established non-WebSocket pattern. This phase blocks only if the approved product baseline has regressed those seams.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 3 of T3 Trades: watches and harness wake-up.
This is the central architecture proof. Phases 0-2 are complete.
No execution, no signing. Branch: feature/trading-03-watches.

READ FIRST
- https://market-bender.mathew.workers.dev/runtime.html — sections 11.2,
  11.3, and 12.1-12.5. Copy TradingHarnessRun, MarketWatch, and
  TradingHarnessWakeup exactly (wakeup cause includes mission_created).
  Section 12.4 is the end-to-end walkthrough your final test must
  reproduce.
- https://market-bender.mathew.workers.dev/recovery.html — section 18.1
  (MissionInboxEvent; statuses pending / included_in_run / consumed).

VERIFIED UPSTREAM SEAMS (at 55dd016 and v0.0.31; re-check at your baseline)
- Same-provider resume is AUTOMATIC upstream: ProviderService.startSession
  (apps/server/src/provider/Layers/ProviderService.ts — search
  "effectiveResumeCursor", ~line 563 at v0.0.31) applies the persisted
  resumeCursor from ProviderSessionDirectory when the instance matches;
  recoverSessionForThread rebuilds a dead session from the binding.
- The wake mechanism you MUST use: dispatch a complete
  ThreadTurnStartCommand ("thread.turn.start") into
  OrchestrationEngineService.dispatch from server-side code. Precedents:
  serverRuntimeStartup.ts (dispatches project.create / thread.create at
  startup) and every reactor. Do NOT call ProviderService directly for
  wake-ups — the engine and ProviderCommandReactor own ensure-session
  and sendTurn.
- Reuse from @t3tools/shared: DrainableWorker (reactor work queues) and
  KeyedCoalescingWorker (one pending evaluation per key).
- Periodic timer template: apps/server/src/provider/Layers/
  ProviderSessionReaper.ts (Effect.forkScoped + Schedule.spaced +
  defect-safe sweep). Model scheduled reassessment on it.
- Timing bound: a queued turn start unadopted for 2 minutes is treated
  as failed (QUEUED_TURN_START_GRACE_MS in decider.ts). Keep wake
  latency well below it and assert adoption in a test.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. MarketWatchRegistry: persist all five watch types from 12.1
   (price_cross, candle_close, order_update, position_update,
   scheduled_reassessment), each bound to a strategyVersion; publishing
   a new version supersedes the previous version's watches. Done when:
   the supersession test passes.
2. WatchEvaluator over the Phase 2 subscriptions: candle_close fires
   only on a final close and exactly once per (watch, candle);
   price_cross evaluates against fresh BBO/mark only. Done when:
   replaying the same closed candle twice fires exactly once.
3. TradingEventInbox + coalescer: persist events with deduplicationKey;
   coalesce pending events per mission with KeyedCoalescingWorker. Done
   when: duplicate keys collapse and no event is lost (property test).
4. TradingTurnCoordinator: one decision lease per mission; run the seven
   pre-run checks from 12.3 in their listed order; result union is
   started | queued_behind_active_run | blocked{reason}. Done when: a
   concurrency test proves a second simultaneous request queues or
   rejects — never a second live run.
5. Wake path: the coordinator assembles TradingHarnessWakeup per 12.2
   (fresh market + account snapshots, active strategy, authority,
   pendingEvents, instruction; cause includes mission_created) and
   dispatches thread.turn.start carrying it. Done when: an end-to-end
   test resumes the SAME provider session (assert providerSessionId is
   unchanged) with fresh snapshots.
6. Watch tools into the trading MCP toolkit: trading_register_watch,
   trading_schedule_reassessment, trading_list_watches,
   trading_cancel_watch. Done when: the full 12.4 walkthrough passes —
   harness registers a watch, its turn ends, T3 stays active, the final
   candle fires once, the same session resumes.
7. Phase 1 deferrals: derive the harness binding from the bound
   thread's provider session at mission creation (replace the
   placeholder provider: "claude" in TradingMissionReactor); start the
   first run with cause mission_created; build the mission composer
   and timeline in the workspace with keyboard and projection parity
   checks. Done when: a mission created from the composer runs its
   first turn on the thread's actual provider.

ACCEPTANCE
- Final candle fires exactly once; T3 remains active after turn end;
  the same provider session resumes through ProviderService; duplicate
  or superseded events never start a second run; the lease concurrency
  test is green.

STOP AND ASK
- If server-side dispatch does NOT resume the session at your baseline
  (it does at v0.0.31): stop and report the failing call and error
  verbatim — a minimal upstream seam patch needs owner approval first.

Phase 4 · Execution

PROMPT-04 · Execution and reconciliation

Purpose

Turn the resumed harness's typed entry requests into validated, signed, idempotent Hyperliquid orders with reconciled fills, positions, and cumulative-loss accounting.

Handoff

Gives PROMPT-05 the validated signing path, deterministic cloid, reconciled fill and position reads, and the reservation ledger that protection and position management will resize.

Context

  • The interim testnet signer decision: an owner-approved Hyperliquid API wallet key in server config (Privy replaces it in PROMPT-06)
  • PROMPT-02 Hyperliquid adapter and precision
  • Hyperliquid §15.3–15.6 precision, market-like orders, cloid, and nonce
  • Risk §16 authority and risk (reservations and loss budget)

Inspect

  • HyperliquidExchangeClient submit and per-order status behavior
  • The official reference SDK's signing vectors — msgpack field order, trailing-zero normalization, lowercase addresses, the phantom-agent action hash
  • Master-address account-query path for fills and positions
  • Hyperliquid userFees response and fallback taker-fee reserve
  • Existing reconciliation triggers from §18.2

Constraints

  • No position increase without a valid stop defined and risk reserved before signing
  • Market-like behavior is marketable IOC limit derived from fresh best bid/ask, never stale mark
  • Persist the execution record before submission; retries reuse the same cloid and idempotency key
  • All signed actions pass through one serialized nonce lane
  • Local state never outranks Hyperliquid; reconcile after every submission and fill
  • No assumption that a submitted order filled
  • The interim signer is testnet-only with throwaway funds; mainnet requires the Privy wallet model from PROMPT-06

Tasks

  • Author the execution, order, and position contracts in trading-contracts (deferred from Phase 1)
  • Configure the interim testnet signer: an owner-approved Hyperliquid API wallet whose key lives in server config only — never client, harness, prompt, or logs
  • Implement trading_preview_order with precision normalization, authority checks, BBO freshness, and stop requirement
  • Implement HyperliquidNonceCoordinator: monotonic nonces, fast-forward, no duplicates, persisted recovery hint, serialized signing
  • Implement HyperliquidCloid deterministic 16-byte cloid from mission, strategy version, execution sequence, and action type
  • Implement HyperliquidOrderMapper for IOC and GTC orders and cancellation
  • Implement HyperliquidReconciler for fills, position state, and open orders via the master address
  • Wire Hyperliquid userFees lookup with the 5-bps fallback reserve
  • Implement risk reservations and cumulative-loss accounting per §16.2, including paid-fee versus unpaid-fee distinction
  • Enforce loss-budget exhaustion per §16.4: cancel increasing orders, block exposure, preserve protection, set blocked/cumulative_loss_limit
  • Implement reduce-only close through T3 orchestration

Steps

  1. Build the nonce coordinator and deterministic cloid first
  2. Add preview with full validation and reservation before signing
  3. Persist the execution record, then sign and submit through the serialized lane
  4. Inspect per-order statuses; query canonical fills and positions via the master address
  5. Compute realized loss, open risk, pending risk, and remaining budget; enforce exhaustion
  6. Reconcile after rejection, cancellation, partial fill, fee update, reduction, and close

Parallel tracks

  • Nonce and cloid
  • Preview and precision validation
  • Order mapping and submission
  • Reconciliation and loss-budget accounting

Outputs

  • HyperliquidExecutionService with nonce coordination and deterministic cloid
  • Preview and validation path
  • Fill and position reconciliation against canonical state
  • Risk reservation and cumulative-loss accounting
  • Loss-budget exhaustion enforcement

Acceptance

  • A resumed harness requests an entry and T3 validates and signs it
  • Hyperliquid accepts the order
  • Fill and position state return through T3 orchestration
  • A retry cannot duplicate the order
  • Loss-budget exhaustion blocks further exposure while preserving protection

Tests

  • Nonce monotonicity and no-duplicate unit tests
  • cloid determinism and collision tests
  • Precision normalization and min-notional tests
  • Cumulative-loss equation property tests per §16.2
  • Loss-budget exhaustion behavior test per §16.4
  • Idempotent retry test: same cloid does not create a second order

Docs

  • packages/hyperliquid execution source
  • Nonce and cloid design notes
  • Risk reservation and loss-budget accounting spec
  • Handoff summary for PROMPT-05
Blockers. Hyperliquid signing cannot be made idempotent via cloid; or canonical fill/position reconciliation cannot converge after disconnect.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 4 of T3 Trades: execution and reconciliation.
Phases 0-3 are complete. Branch: feature/trading-04-execution.
This is the only code path that spends testnet capital — follow the
stated order of operations EXACTLY; never reorder for convenience.

BEFORE ANY CODE — STOP AND ASK IF UNDECIDED
- The interim testnet signer: the owner supplies a Hyperliquid API
  wallet approved (via the Hyperliquid testnet UI) under the master
  account, plus its private key for SERVER CONFIG ONLY. Testnet-only,
  throwaway funds; Privy replaces it in PROMPT-06.
- Signing is hand-rolled per the decided no-runtime-SDK direction:
  msgpack action hash + EIP-712, verified byte-for-byte against the
  official hyperliquid-python-sdk's vectors BEFORE the first live
  submission. If the vectors cannot be reproduced, STOP — the owner
  chooses between debugging further and pinning a community signing
  module as a runtime exception.
- The cloid algorithm: derive16Bytes(missionId, strategyVersion,
  executionSequence, actionType) needs a concrete hash. Propose
  truncated SHA-256 and get owner sign-off.
- The allowed-slippage value (bps) for marketable IOC pricing.
- The bounded reconciliation window duration (seconds).

READ FIRST
- https://market-bender.mathew.workers.dev/hyperliquid.html sections
  15.3-15.6 (precision, IOC pricing, cloid, nonce lane) and 17.2 (the
  ten-step entry order of operations).
- https://market-bender.mathew.workers.dev/risk.html — all of section
  16: the seven concepts, the six equations (copy them into property
  tests), the 17-item increase checklist (implement as an ordered
  validator), and 16.4 exhaustion behavior.
- https://market-bender.mathew.workers.dev/recovery.html section 18.2 —
  the eight reconciliation triggers.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
0. Author the execution, order, and position contracts in
   trading-contracts (deferred from Phase 1) and load the interim
   signer from server config. Done when: the contracts typecheck with
   subpath exports and a unit test proves the key is readable from
   config and absent from every client bundle and log line.
1. HyperliquidNonceCoordinator: ONE serialized signing lane per
   execution wallet; nonces monotonic, fast-forwarded to current Unix
   ms, never duplicated; persist the last-issued nonce as a recovery
   hint. Done when: a concurrent-submission test shows strictly
   increasing nonces with no duplicates.
2. Deterministic cloid per the approved algorithm. Done when: identical
   inputs give identical cloids and a collision test over the input
   space passes.
3. trading_preview_order: run the FULL 17-item checklist from risk.html
   16.3 in its listed order — including precision normalization, BBO
   freshness (2s), mandatory stop info, isolated-margin-only — and
   RESERVE risk before any signing. Done when: every checklist item has
   a rejection test with a specific, inspectable reason string.
4. Order mapping: marketable IOC (buy = fresh best ask + slippage;
   sell = fresh best bid - slippage; never derived from stale mark) and
   resting GTC; cancellation. Done when: IOC price derivation is tested
   against fixture BBOs including a stale-BBO rejection.
5. Submission, in this exact order: persist execution record -> sign in
   the nonce lane -> submit -> inspect EVERY per-order status in the
   response -> query canonical state via the master address ->
   reconcile. Retries reuse the same cloid + idempotency key. Done
   when: a forced-retry test yields exactly one order on testnet.
6. HyperliquidReconciler: fills, position, open orders; wire all eight
   triggers from 18.2. Done when: a disconnect/reconnect test converges
   local state to canonical.
7. Loss accounting per 16.2 as pure functions with property tests:
   realized result, realized loss used, open position risk, pending
   entry risk, budget used, remaining. Paid vs unpaid fees never
   double-counted; positive PnL never enlarges the budget; userFees
   lookup with the 5 bps/side fallback when unreadable or stale.
8. Exhaustion per 16.4: cancel increasing orders; block entries,
   scale-ins, reversals, re-entry; preserve protection; set
   blocked/cumulative_loss_limit; notify. Enforce the guard: harness
   trading_resume_mission is REJECTED while blocked (user-only resume).
   Done when: the exhaustion test shows exposure blocked with the stop
   still live.
9. Reduce-only close through T3 orchestration. Done when: close
   submits a reduce-only IOC and reconciles to flat.

ACCEPTANCE
- Testnet accepts a validated, signed entry; fills and positions return
  through T3; a retry cannot duplicate (same cloid); exhaustion blocks
  exposure while preserving protection; all six equations hold under
  property tests.

Phase 5 · Protection

PROMPT-05 · Protection, deterministic controls, and position management

Purpose

Guarantee confirmed exchange-native reduce-only protection for every filled size, and expose deterministic risk-control buttons that work while the harness is unavailable.

Handoff

Gives PROMPT-06 a complete protected execution loop whose signer it can swap, and PROMPT-07 the deterministic control primitives, the protection reconciliation path, and the conversation surface that interpretation will wrap.

Context

Inspect

  • Hyperliquid normalTpsl and positionTpsl grouping and per-order status behavior
  • Parent-linked TP/SL partial-fill and manual-cancellation behavior
  • Insufficient-margin cancellation special case
  • The PROMPT-04 reservation and reconciliation services

Constraints

  • No acknowledged position increase may remain without confirmed reduce-only protection beyond the bounded reconciliation window
  • Never treat a grouped TP/SL response or a group's presence as proof every order is live
  • Never cancel a partially filled parent before independent protection is confirmed for the filled size
  • Every deterministic button must function while the harness is unavailable
  • Emergency close is a deterministic safety action, not a strategy decision

Tasks

  • Require a mandatory stop input on every position-increasing request
  • Validate the normalTpsl request path on testnet and inspect every per-order status
  • Implement partial-fill protection fallback: place or replace reduce-only stop for the actual canonical size
  • Implement the position-level or explicitly sized reduce-only stop path (positionTpsl or sized trigger)
  • Implement protection reconciliation and replacement after scale-in per §17.4
  • Implement deterministic Pause and Cancel entries buttons (trading_control_pause, trading_control_cancel_entries)
  • Implement deterministic 25/50/75/100% reduction buttons (trading_control_reduce_position)
  • Implement deterministic Close, Revoke, and Close-and-revoke buttons (trading_control_close_position, trading_control_revoke, trading_control_close_and_revoke)
  • Support scale-in, partial reduction, full close, and direction reversal through the same authority and execution path
  • Implement bounded emergency close: cancel increasing orders, reduce-only marketable IOC, at most three attempts, reconcile partial fills

Steps

  1. Validate normalTpsl and positionTpsl shapes on testnet before relying on them
  2. Add the mandatory stop gate to position-increasing validation
  3. Build partial-fill protection reconciliation that reads canonical size before placing protection
  4. Wire the deterministic control buttons to TradingControlService using the same execution path
  5. Implement protection replacement that confirms new protection before dropping the last valid stop where overlap is safe
  6. Implement the bounded emergency-close procedure and its terminal blocked state

Parallel tracks

  • Protection placement and reconciliation
  • Partial-fill and cancellation edge handling
  • Deterministic control buttons
  • Emergency close procedure

Outputs

  • Mandatory stop gate and validated normalTpsl path
  • Partial-fill protection fallback and replacement
  • Deterministic Pause, Cancel entries, Reduce, Close, Revoke, and Close-and-revoke controls
  • Scale-in, reduction, full close, and reversal flows
  • Bounded emergency close with at-most-three attempts

Acceptance

  • A full fill receives confirmed exchange-native protection
  • A partial fill receives protection for the actual canonical size
  • Manual cancellation of a partially filled parent does not remove the position's only stop
  • Per-order failures in a grouped request are detected
  • Every deterministic risk-control button works while the harness is unavailable
  • Emergency close reconciles partial fills and performs at most three bounded attempts

Tests

  • Full-fill IOC with linked TP/SL testnet evidence
  • Partial-fill protection fallback testnet evidence
  • Resting parent partial fill and manual cancellation testnet evidence
  • Insufficient-margin cancellation reconciliation testnet evidence
  • Per-order rejection inside a multi-order action testnet evidence
  • Stop replacement after scale-in testnet evidence
  • Deterministic buttons function with harness marked unavailable
  • Emergency close with partial IOC fill within three attempts

Docs

  • Protection placement and reconciliation source
  • Deterministic control button matrix
  • Emergency close runbook
  • Required testnet evidence catalogue from §17.6
Blockers. Hyperliquid grouped TP/SL cannot be confirmed as live through canonical state; or a deterministic button cannot be served without a harness turn.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 5 of T3 Trades: protection, deterministic
controls, and position management. Phases 0-4 are complete.
Branch: feature/trading-05-protection. This phase carries the safety
invariant — never weaken it to make a test pass.

THE INVARIANT (memorize before coding)
No acknowledged position increase may remain without confirmed
exchange-native reduce-only protection beyond the bounded reconciliation
window (fixed in Phase 4). Grouped TP/SL (normalTpsl) is an
optimization, never the safety mechanism. Never treat a batch as
atomic; inspect every per-order status.

READ FIRST
- https://market-bender.mathew.workers.dev/hyperliquid.html — ALL of
  section 17: 17.2 IOC path, 17.3 resting/partial fills, 17.4 scale-in,
  17.5 emergency close, 17.6 the 11 required testnet evidence cases.
  Your final deliverable is that matrix, filled in with real testnet
  evidence.
- https://market-bender.mathew.workers.dev/tools.html section 14.7 —
  the seven deterministic user-control RPCs.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. Mandatory stop gate: any position-increasing request without valid
   stop information is rejected at preview AND at submission. Done
   when: both rejection tests pass.
2. Validate normalTpsl grouping on testnet: submit a grouped
   entry+stop, inspect every per-order status, query canonical state,
   then reconcile protection against the ACTUAL canonical position size
   — the ten steps of 17.2 in order. Done when: the full-fill evidence
   case is recorded.
3. Partial-fill fallback per 17.3: protect the filled slice with an
   independent reduce-only stop BEFORE canceling a partially filled
   parent; reconcile again after cancellation. Done when: the
   partial-fill and manual-cancellation evidence cases are recorded.
4. Scale-in replacement per 17.4: after an increase, confirm protection
   for the new total size before dropping the previous stop where
   overlap is safe; never assume a fixed-size trigger resized itself.
   Done when: the scale-in evidence case is recorded.
5. TradingControlService + the seven RPCs wired to workspace buttons:
   trading_control_pause, trading_control_resume,
   trading_control_cancel_entries, trading_control_reduce_position
   (25/50/75/100%), trading_control_close_position,
   trading_control_revoke, trading_control_close_and_revoke. None may
   require a harness turn. Done when: every button is verified with the
   provider process stopped.
6. Emergency close per 17.5, deterministic and in order: set blocked;
   cancel non-reduce-only orders; read fresh position + BBO; submit
   reduce-only marketable IOC; reconcile; at most THREE bounded
   attempts; on failure preserve protection, stay blocked, notify with
   the exact remaining size and reason. Done when: a partial-IOC-fill
   simulation completes within three attempts and the failure path is
   also tested.
7. Position management through the same authority/execution path:
   scale-in, partial reduction, full close; direction reversal ONLY
   when the user's authority grants it (POC default off). Done when:
   reversal without authority is rejected.

ACCEPTANCE
- The 17.6 evidence matrix complete: all 11 cases on testnet, including
  WebSocket loss and a T3 restart inside the protection window; every
  deterministic button verified harness-down; per-order failures inside
  grouped requests detected and handled.

Phase 6 · Onboarding

PROMPT-06 · Privy onboarding and signer swap

Purpose

Establish authentication, a user-owned master wallet, and a one-time-approved Privy-managed execution wallet registered as a named Hyperliquid API wallet, so ordinary testnet signing works thereafter without per-order prompts. Replaces the interim configured signer from PROMPT-04 behind the unchanged execution boundary.

Handoff

Gives PROMPT-07 and PROMPT-08 the production-shaped wallet model: the approved execution wallet handle, the signing allowlist, and the TradingAccount lifecycle — signing behind the same nonce lane and execution boundary built in PROMPT-04 and PROMPT-05.

Context

Inspect

  • Privy authentication and wallet-provisioning APIs
  • Hyperliquid approveAgent and API-wallet registration flow
  • Existing T3 authenticated server boundary and session verification
  • Wallet lifecycle states from §10.1

Constraints

  • No raw private key may reach the harness, client, or provider prompt
  • Account state is queried with the master-wallet address, never the execution wallet
  • The execution wallet signs ordinary exchange actions only; administrative actions are excluded
  • Approval is one-time; no per-order user prompt for ordinary trading
  • ERC-4337 is not required for the testnet path

Tasks

  • Implement PrivyUserService and PrivyMasterWalletService for login and the user-owned master wallet
  • Implement PrivyExecutionWalletService for the server-controlled execution wallet
  • Implement HyperliquidAgentApproval with agent name t3-trades-poc and idempotent approveAgent
  • Verify approval against Hyperliquid canonical state before marking the wallet approved
  • Persist TradingAccount with master and execution wallet records and lifecycle status per §10.1
  • Build the wallet status UI showing onboarding, awaiting approval, approved, and error states
  • Exclude administrative actions (API-wallet replacement, withdrawals, transfers, builder-fee approval, arbitrary signing, wallet export) from the autonomous tool surface
  • Swap the execution signer from the interim configured key to the Privy execution wallet with no changes to the execution boundary, then revoke the interim agent on Hyperliquid and remove its key from config

Steps

  1. Define wallet lifecycle states per §10.1
  2. Implement the authenticated server boundary and Privy login
  3. Provision the master wallet and the separate execution wallet
  4. Submit the one-time approveAgent action and verify registration on testnet
  5. Apply the signing allowlist and policy isolation
  6. Render wallet status in the workspace

Parallel tracks

  • Auth and master wallet
  • Execution wallet provisioning
  • Agent approval and verification
  • Wallet status UI

Outputs

  • packages/privy-hyperliquid wallet services
  • One-time-approved execution wallet registered as t3-trades-poc
  • TradingAccount persistence with lifecycle states
  • Wallet status UI
  • Signing allowlist and policy isolation

Acceptance

  • The user completes the one-time approval
  • T3 verifies the wallet is registered on Hyperliquid
  • No raw private key reaches the harness or client
  • Ordinary testnet signing works without another user prompt
  • The interim signer is revoked on Hyperliquid and gone from config once the Privy wallet signs

Tests

  • Master-to-execution wallet separation contract test
  • Approval verification asserts canonical Hyperliquid registration
  • Negative authorization test: administrative actions are rejected
  • Secret-bundle scan: no key material in harness, client, or logs
  • Testnet approval and ordinary sign smoke

Docs

  • packages/privy-hyperliquid source
  • Wallet lifecycle and approval runbook
  • Signing allowlist matrix
  • Handoff summary for PROMPT-07
Blockers. Master-wallet ownership or recovery cannot be proven; or Privy or Hyperliquid approveAgent cannot satisfy idempotent one-time approval on testnet.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 6 of T3 Trades: Privy onboarding and the
signer swap. Phases 0-5 are complete. Branch: feature/trading-06-privy.

BEFORE ANY CODE — STOP AND ASK IF UNDECIDED
- Privy app credentials (app id + secret) for the fork.
- The Hyperliquid agent name (spec suggests t3-trades-poc; confirm
  before registering anything).

READ FIRST
- https://market-bender.mathew.workers.dev/hyperliquid.html section
  15.1 — the wallet model. Non-negotiable rules: account identity is
  the MASTER wallet; the execution wallet holds no capital, is never
  exported, and is REPLACED (never reused) after revocation.
- https://market-bender.mathew.workers.dev/domain.html section 10.1 —
  TradingAccount and wallet lifecycle states.
- Privy docs: the Hyperliquid agents-and-subaccounts recipe, policies
  and offline actions, access tokens.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. packages/privy-hyperliquid: PrivyUserService (login + token
   verification) and PrivyMasterWalletService (user-owned master
   wallet). Done when: login round-trips and the master address is
   persisted on TradingAccount.
2. PrivyExecutionWalletService: a server-controlled execution wallet,
   distinct from the master. Done when: a contract test proves the two
   are different addresses and the execution wallet never appears in an
   account-identity call.
3. HyperliquidAgentApproval: one-time approveAgent under the confirmed
   name; VERIFY the registration against canonical Hyperliquid state
   before marking approved; re-runs are no-ops. Done when: a double-run
   test performs exactly one approval.
4. TradingAccount lifecycle per 10.1: creating -> awaiting_approval ->
   approved, plus revoked and error. Done when: transition tests cover
   every state and revocation marks the wallet for replacement.
5. Signing allowlist: the execution wallet signs ordinary exchange
   actions ONLY. Hard-exclude, by name: API-wallet replacement,
   withdrawals, transfers, builder-fee approval, arbitrary tx/message
   signing, wallet export. Done when: a negative test rejects each
   excluded action.
6. Wallet status UI: onboarding / awaiting approval / approved / error.
   Done when: each state renders; approved shows agent name + master
   address and never any key material.
7. Secret gate: a CI test/grep proving no private key material reaches
   harness prompts, client bundles, or logs. Done when: the gate runs
   in CI and passes.
8. Signer swap: point TradingExecutionService at the Privy execution
   wallet with zero changes to preview, nonce, cloid, or
   reconciliation; then revoke the interim agent on Hyperliquid and
   delete its key from config. Done when: an execution smoke passes on
   the Privy signer and the interim agent no longer appears in the
   master account's approved agents.

ACCEPTANCE
- One-time approval verified against canonical Hyperliquid state;
  ordinary testnet signing works with no further user prompt; every
  administrative action is rejected by name; the secret gate is clean;
  the interim signer is revoked and removed.

Phase 7 · Conversation

PROMPT-07 · Conversational modification

Purpose

Let the user steer the mission and positions through natural language by interpreting unambiguous risk-reducing instructions onto the existing TradingControlService primitives and routing ambiguous exposure changes through the bound harness.

Handoff

Gives PROMPT-08 the full conversational and deterministic control surface, the versioned authority path, and the conversation timeline that recovery and conformance will exercise.

Not a second execution path. The deterministic buttons already exist from Phase 5. Phase 7 adds interpretation and conversation around those primitives; ambiguous exposure changes are clarified before any change.

Context

  • PROMPT-05 deterministic control primitives and protection path
  • Conversational control model (ask freely; deterministic controls act instantly): the UI concepts prototype
  • Tools §14.7 deterministic user-control API
  • The authority and strategy versioning from PROMPT-01

Inspect

  • TradingControlService and authority-patch surfaces from prior phases
  • Strategy publishing and version invalidation
  • Existing conversation and user-message routing in the mission runtime
  • Pause, resume, and revoke deterministic paths

Constraints

  • Phase 7 adds interpretation and conversation around Phase 5 primitives; it does not create a separate execution path
  • Material ambiguity must be clarified before any exposure change
  • Risk-reducing deterministic controls must not depend on a harness turn
  • Authority patches are enforced immediately and versioned
  • Do not interpret ambiguous exposure-changing instructions autonomously

Tasks

  • Implement MissionModificationService for authority patches with immediate enforcement and version bump (deferred from Phase 1: the first authorityVersion advance lands here, with its patch-validation tests)
  • Map unambiguous risk-reducing instructions (for example reduce half, move stop to break-even, cancel entries) onto TradingControlService
  • Route strategy instructions and ambiguous exposure changes through the bound harness turn
  • Implement clarification handling before exposure changes: ask, do not guess
  • Implement conversational pause, resume, and revoke over the deterministic primitives
  • Surface interpreted intent and the resulting deterministic action in the timeline

Steps

  1. Define the authority-patch and strategy-instruction contracts
  2. Classify incoming messages into deterministic-control, harness-routed, or needs-clarification
  3. Execute unambiguous risk-reducing instructions directly through TradingControlService
  4. Queue ambiguous or strategy-level instructions as a harness run with the user message in the wakeup
  5. Record the interpretation and the action taken in the timeline

Parallel tracks

  • Authority patches
  • Deterministic-control interpretation
  • Harness-routed strategy instructions
  • Clarification flow and timeline rendering

Outputs

  • MissionModificationService with versioned authority patches
  • Deterministic-control interpretation layer
  • Clarification handling for ambiguous exposure changes
  • Conversational pause, resume, and revoke
  • Timeline entries linking interpretation to action

Acceptance

  • Authority patches are enforced immediately and reflected in the next run
  • Unambiguous risk-reducing instructions map onto deterministic controls without a harness turn
  • Ambiguous exposure-changing messages trigger clarification before any change
  • Conversational pause, resume, and revoke reuse the deterministic primitives
  • Strategy instructions are routed through the bound harness

Tests

  • Authority-patch immediate-enforcement contract tests
  • Deterministic-control mapping table tests for the Guide-prototype examples (reduce half, move stop to break-even, cancel entries)
  • Ambiguity clarification test: exposure change is blocked until resolved
  • Conversational pause/resume/revoke parity with the deterministic buttons
  • Conversation-to-timeline correlation tests

Docs

  • MissionModificationService source
  • Interpretation and clarification rules
  • Conversation-to-control mapping catalogue
  • Handoff summary for PROMPT-08
Blockers. An instruction class cannot be classified as risk-reducing without ambiguity; or authority patches cannot be enforced atomically with strategy version invalidation.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 7 of T3 Trades: conversational modification.
Phases 0-6 are complete. Branch: feature/trading-07-conversation.

HARD RULE — NOT A SECOND EXECUTION PATH
The deterministic controls already exist (Phase 6). This phase adds
interpretation AROUND them. Nothing here may sign, submit, or touch the
exchange except through TradingControlService or a normal harness turn.
If you find yourself writing exchange calls, stop — you are off-spec.

READ FIRST
- https://market-bender.mathew.workers.dev/prototype-workspace.html —
  the target interaction model: free-form messages go to the agent; the
  four deterministic controls act instantly without it.
- https://market-bender.mathew.workers.dev/tools.html sections
  14.6-14.7 — including the blocked-mission resume guard.
- https://market-bender.mathew.workers.dev/domain.html — authority and
  strategy versioning.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. MissionModificationService: versioned authority patches (for
   example, lowering maximumPlannedRiskPerPositionUsd), enforced
   immediately, with the version bump atomic with strategy-version
   invalidation. Done when: a patch applied mid-mission governs the
   very next validation.
2. Message classifier with EXACTLY three routes, built as a reviewed
   mapping table (not ad-hoc conditionals):
   (a) deterministic-control — unambiguous risk-reducing phrases:
       "reduce half" -> trading_control_reduce_position 50;
       "cancel entries" -> trading_control_cancel_entries;
       "pause" -> trading_control_pause;
       "close it" -> trading_control_close_position.
       Execute directly; no harness turn.
   (b) harness-routed — strategy opinions and exposure changes
       ("take profit at 3,900", "trade the 15m instead"): queue a
       harness run with the user message in the wakeup payload.
   (c) needs-clarification — materially ambiguous ("do something about
       this position"): ask one specific question; block any exposure
       change until answered.
   Done when: table-driven tests cover all three routes including edge
   phrasings, and unmatched input defaults to route (b) or (c), never (a).
3. Interpretation echo: before executing route (a), record "Interpreted
   as: <action>" in the timeline together with the action taken. Done
   when: every deterministic execution has a linked interpretation
   entry.
4. Conversational pause / resume / revoke over the Phase 5 primitives,
   enforcing the blocked-mission rule (a cumulative_loss_limit block is
   resumable only by explicit user action). Done when: parity tests
   show identical outcomes for buttons and phrases.
5. Timeline correlation: interpretation, action, and harness routing
   all visible in order. Done when: the conversation-to-action
   correlation test passes.

ACCEPTANCE
- Authority patches apply immediately and version correctly; ambiguous
  exposure changes are blocked until clarified; deterministic mappings
  run without a harness turn; conversational and button controls are
  parity-tested.

Phase 8 · Recovery

PROMPT-08 · Recovery and per-provider conformance

Purpose

Make mission state recoverable across T3 restarts and reconnections, handle agent-unavailable states without provider substitution, and verify Codex, Claude, and OpenCode independently against the same T3 trading contracts before each is enabled.

Handoff

Hands off a recoverable, conformance-gated T3 Trades POC: the event-driven harness loop, deterministic execution and protection, conversational control, and per-provider evidence satisfying the nine POC acceptance outcomes.

No provider failover. This phase does not add provider swapping, failover, or cross-provider mission transfer. It verifies each provider independently against the same T3 trading contracts.

Context

Inspect

  • Persistence records from §18 and their migration path
  • Provider session start, resume, and availability behavior per provider
  • Reconciliation triggers from §18.2
  • The fork sync runbook and patch ledger from PROMPT-00

Constraints

  • No provider failover, swapping, or cross-provider mission transfer
  • A provider is exposed in the trading selector only after it passes conformance independently
  • A T3 restart may restore continuity; a provider failure moves the mission to agent_unavailable
  • Do not switch providers automatically on recovery
  • The Git strategy upstream-sync acceptance gates must hold

Tasks

  • Implement startup recovery per §18.3: restore account, mission, binding, strategy, authority, watches; reconnect; reconcile; resume timers; queue one run if material events occurred; resume the original provider
  • Implement reconnection recovery that restores subscriptions and canonical state before resuming
  • Implement the agent_unavailable state: preserve protection, continue monitoring, block new discretionary entry, allow retry, pause, close, or revoke
  • Run Codex conformance before enabling Codex: tool discovery, strategy publishing, watch registration, turn-end-while-active, same-session resumption, mission and version preservation, rejected execution handling, partial-fill reconciliation, pause and revoke behavior, no raw wallet request
  • Run Claude conformance before enabling Claude using the same matrix
  • Run OpenCode conformance before enabling OpenCode using the same matrix
  • Build the upstream sync regression suite per §21.5 and the Git strategy acceptance gates

Steps

  1. Implement and drill startup and reconnection recovery
  2. Define and verify the agent_unavailable transition and its allowed exits
  3. Run each provider through the §21.4 conformance matrix one at a time
  4. Gate each provider in the selector until its matrix passes
  5. Assemble the upstream sync regression suite and run it against one sync batch
  6. Confirm no provider substitution occurs in any recovery path

Parallel tracks

  • Startup and reconnection recovery
  • Agent-unavailable state
  • Per-provider conformance (Codex, Claude, OpenCode)
  • Upstream sync regression suite

Outputs

  • Startup and reconnection recovery paths
  • Agent_unavailable state and allowed user exits
  • Conformance evidence for each enabled provider
  • Upstream sync regression suite
  • Provider gating in the trading selector

Acceptance

  • Restart restores mission, watches, risk reservations, and provider binding
  • Reconnection restores subscriptions and canonical state
  • Provider failure moves the mission to agent_unavailable without substituting providers
  • Each provider is enabled only after passing the conformance matrix independently
  • One upstream sync integrates without rewriting trading modules and passes the regression suite

Tests

  • Restart recovery integration test asserting full state restoration
  • Reconnection reconciliation test after WebSocket loss
  • Agent_unavailable transition and no-substitution test
  • Codex, Claude, and OpenCode conformance matrices per §21.4
  • Upstream sync regression suite per §21.5
  • Git strategy acceptance-gate checklist for one sync batch

Docs

  • TradingRecovery source
  • Per-provider conformance reports
  • Upstream sync regression suite
  • Final POC acceptance evidence map against the nine acceptance outcomes
Blockers. A provider cannot resume the same session or preserve mission and version context; or restart cannot restore watch and reservation state deterministically.

Hand-off prompt

Copy into a fresh agent session working in the fork repository. It is self-contained; the linked pages are the full specification.

You are implementing Phase 8 of T3 Trades: recovery and per-provider
conformance. Phases 0-7 are complete. This phase closes out the POC.
Branch: feature/trading-08-recovery.

HARD RULE — NO PROVIDER FAILOVER
No provider swapping, failover, or cross-provider mission transfer,
anywhere, including every recovery path. A provider failure moves the
mission to agent_unavailable; the user chooses retry, pause, close, or
revoke.

PROVIDER FACTS (verified at v0.0.31)
- Upstream driver kinds: "codex", "claudeAgent", "opencode" (plus
  "cursor" and "grok", out of POC scope). Threads carry
  providerInstanceId; never infer the binding from the driver kind.

READ FIRST
- https://market-bender.mathew.workers.dev/recovery.html — section 18.3
  (the ten-step restart recovery; implement IN ORDER), 18.2, 21.4 (the
  conformance matrix; copy the ten checks verbatim), 21.5.
- https://market-bender.mathew.workers.dev/index.html#acceptance — the
  nine outcomes your final evidence map must cover.
- https://market-bender.mathew.workers.dev/git-strategy.html#exit —
  the sync acceptance gates.

WORKING RULES (apply to every step)
1. After EVERY numbered step run: pnpm typecheck && pnpm lint && pnpm test.
   Fix failures before starting the next step. Never batch fixes.
2. One commit per step; message style "feat(trading): <what changed>".
3. Never edit an upstream file unless this prompt names it as a seam. Every
   upstream edit gets a dated entry in docs/upstream/PATCH_LEDGER.md in the
   same commit.
4. If a file, symbol, or command named here does not exist at your baseline,
   STOP and report exactly what is missing. Do not improvise a substitute.
5. Finish with a report: what shipped, evidence for each acceptance item,
   anything deferred, and every upstream file you touched.

STEPS
1. Startup recovery in exactly the 18.3 order: account -> mission ->
   binding + resume cursor -> strategy/authority/watches -> reconnect
   streams -> query canonical exchange state -> reconcile -> resume
   timers -> queue ONE run if material events occurred offline ->
   resume the ORIGINAL provider. Done when: an integration test kills
   and restarts the server mid-mission and asserts full restoration,
   including risk reservations.
2. Reconnection recovery: subscriptions and canonical state restored
   before any resume. Done when: a WebSocket-loss test reconciles
   cleanly.
3. agent_unavailable: protection preserved; monitoring and
   deterministic controls stay live; discretionary entries blocked;
   retry / pause / close / revoke offered. Done when: a provider-kill
   test lands in agent_unavailable with every control still working.
4. Conformance harness: a runnable command (the Phase 0 conformance
   command) that executes the ten 21.4 checks against ONE provider:
   tool discovery, strategy publishing, watch registration,
   turn-end-while-active, same-session resumption, mission and version
   preservation, rejected execution handling, partial-fill
   reconciliation, pause and revoke behavior, no raw wallet request.
   Done when: it emits a pass/fail report artifact per provider run.
5. Run the matrix for codex, then claudeAgent, then opencode — one at a
   time. Gate each provider in the trading selector until ITS matrix
   passes. Done when: selector state reflects per-provider results and
   all three POC providers have reports.
6. Upstream sync regression suite per 21.5; run it against one real
   sync batch via SYNC_RUNBOOK.md and check the git-strategy acceptance
   gates. Done when: the batch integrates without rewriting trading
   modules.
7. Final evidence map: one document mapping each of the nine acceptance
   outcomes to its concrete test or evidence artifact. Done when: no
   outcome is unmapped.

ACCEPTANCE
- Restart and reconnection recovery proven; no provider substitution in
  any path; conformance reports for all three POC providers; the sync
  regression suite green on a real batch; the nine-outcome evidence map
  complete.

Related

Boundaries

Architecture

Provider, exchange, and authority boundaries that every phase respects, and the seams trading is allowed to extend.

Protection

Hyperliquid

Exchange-native protection, precision, partial-fill behavior, and reconciliation that Phases 2, 5, and 6 build on.

Testing

Recovery

Recovery paths, agent_unavailable handling, and per-provider conformance that close out Phase 8.