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.
Implementation phases · 0 to 8
Nine execution prompts, one per implementation phase (0–8). Each prompt is self-contained, evidence-based, and hands off to the next. Every section ends with a copyable hand-off prompt that can be pasted into a fresh agent session in the fork repository. Together they build the event-driven harness loop that defines the T3 Trades proof of concept.
Phase map
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.
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.
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.
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.
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.
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.
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.
PROMPT-07 · Phase 7 — Conversational modification. Authority patches, deterministic-control interpretation, ambiguity handling. Builds on Phase 5 primitives, not a second execution path.
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
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.
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
Constraints
upstream/main as a read-only remote-tracking ref; do not create or commit to a local mirror branchTasks
upstream, and add the writable product repository as originorigin/main as the product line; use short-lived feature/trading-* branches and reviewed sync/upstream-YYYY-MM-DD-<shortSHA> branches onlySteps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
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.
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
Inspect
Constraints
Tasks
Steps
apps/server/src/ws.ts)Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
Gives PROMPT-03 the read-only market/account ports, freshness thresholds, reconnect reconciliation behavior, and the ETH subscriptions that watches will evaluate.
Context
Inspect
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
Gives PROMPT-04 a proven event-driven resume loop, the wakeup payload contract, and the deterministic services that execution and signing will reuse.
Context
Inspect
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
Turn the resumed harness's typed entry requests into validated, signed, idempotent Hyperliquid orders with reconciled fills, positions, and cumulative-loss accounting.
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
Inspect
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
Guarantee confirmed exchange-native reduce-only protection for every filled size, and expose deterministic risk-control buttons that work while the harness is unavailable.
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
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
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
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
Gives PROMPT-08 the full conversational and deterministic control surface, the versioned authority path, and the conversation timeline that recovery and conformance will exercise.
Context
Inspect
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
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.
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.
Context
Inspect
Constraints
Tasks
Steps
Parallel tracks
Outputs
Acceptance
Tests
Docs
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
Provider, exchange, and authority boundaries that every phase respects, and the seams trading is allowed to extend.
Exchange-native protection, precision, partial-fill behavior, and reconciliation that Phases 2, 5, and 6 build on.
Recovery paths, agent_unavailable handling, and per-provider conformance that close out Phase 8.