┌──────────────────────────────────────────────────────────────────────────────┐
│ 46 4F 52 47 45 2E 4F 53 :: KASPA-NATIVE QUANT / AI CONTROL PLANE │
│ │
│ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗ ██████╗ ███████╗ │
│ ██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝ ██╔═══██╗██╔════╝ │
│ █████╗ ██║ ██║██████╔╝██║ ███╗█████╗ ██║ ██║███████╗ │
│ ██╔══╝ ██║ ██║██╔══██╗██║ ██║██╔══╝ ██║ ██║╚════██║ │
│ ██║ ╚██████╔╝██║ ██║╚██████╔╝███████╗ ╚██████╔╝███████║ │
│ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝ │
│ │
│ [SIGNING: NON-CUSTODIAL] [NETWORK: MAINNET-FIRST] [TRUTH: RECEIPT-AWARE] │
│ [MODE: QUANT CORE + REAL AI OVERLAY] [RUNTIME: OPERATOR-GRADE] │
└──────────────────────────────────────────────────────────────────────────────┘
FORGE-OS is a Kaspa-native quant trading control plane with wallet-native signing, real AI overlay, deterministic quant guardrails, and production-oriented runtime controls.
It is built for operators who want:
- Kaspa-first execution (UTXO-aware, non-custodial signing)
- Real AI decisioning bounded by quant math and hard risk controls
- Multi-agent allocation with shared portfolio risk budgets
- Transparent queueing, receipts, attribution, and alerting
- A path from browser prototype to backend-scaled orchestration
Quick Jump (Operator Index)
- Quick Start
- Browser Extension (MV3)
- Mainnet / Testnet Runtime Switching
- Kaspa Network Coverage
- Swap + KRC Token Metadata
- Local Node Mode (kaspad)
- Wallet Support (Current)
- Transaction Lifecycle + Receipts
- Scaling Modules (Backend Starters)
- Operator Recipes (Copy/Paste)
- Testing & Validation
- GitHub DIY Ops Hacks
- Troubleshooting By Symptom
- Production Readiness Checklist
| Plane | What It Does | Why It Matters |
|---|---|---|
| Decision | Deterministic quant core -> real AI overlay -> guarded fusion | Keeps the AI useful, but bounded by math + risk rules |
| Execution | Wallet-native signing, queueing, lifecycle state machine, treasury routing | No seed storage, explicit approval paths, auditable tx flow |
| Truth / Audit | Receipts, provenance badges, consistency checks, audit signatures | Operators can tell what is estimated vs confirmed vs verified |
| Extension | Managed vault popup, UTXO sync, dry-run checks, in-extension signing | Keeps signing local and enforces fail-closed pre-sign policies |
| Scale | AI proxy, scheduler, shared cache, callback consumer, metrics | Browser stays control plane while backend handles orchestration |
flowchart LR
A[Kaspa Data Feed] --> B[Quant Core]
B --> C[AI Overlay]
C --> D[Guarded Fusion]
D --> E[Execution Queue]
E --> F[Wallet Sign/Broadcast]
F --> G[Receipt Poll + Backend Receipt Import]
G --> H[PnL Attribution + Alerts + Audit]
H --> B
Most “AI trading dashboards” stop at UI. FORGE-OS implements the actual runtime stack:
- Wallet-native authorization (site adapters + managed extension vault) with no insecure key handling
- Quant core first (regime, volatility, Kelly/risk caps, EV sizing)
- AI overlay second (bounded by quant envelope; can run every cycle)
- Execution lifecycle tracking (submitted -> broadcasted -> pending confirm -> confirmed/failed/timeout)
- Treasury fee routing with on-chain payout support
- Multi-agent portfolio allocator with shared capital/risk constraints
- Production-scale starters: AI proxy + scheduler/shared market cache
WalletGate (Kasware / Kaspium / Demo)
-> Wizard (agent config + strategy template)
-> Dashboard (operator control plane)
-> Kaspa Feed (price / blockdag / balance / utxos)
-> Quant Engine Client (Web Worker preferred)
-> Deterministic Quant Core (regime, vol, Kelly, EV, risk)
-> Real AI Overlay (always/adaptive, bounded by quant core)
-> Guarded Fusion (risk envelope + execution constraints)
-> Execution Queue (signing lifecycle + receipt lifecycle)
-> Treasury Payout (on-chain fee transfer, queue fallback)
-> Alerts (Telegram / Discord / email-webhook)
-> PnL Attribution (estimated + receipt-aware hybrid telemetry)
Browser Extension (MV3)
-> Vault (AES-256-GCM + Argon2id, legacy PBKDF2 read/migrate, auto-lock, optional session persistence)
-> Popup (Wallet / Swap / Agents / Security)
-> UTXO Sync (standard vs covenant classification)
-> Dry-Run Validator (5 hard checks, fail-closed)
-> Signer + Broadcaster (managed wallet path)
-> Site Bridge (forge-os domains only, popup approval for connect/sign)
Scale Path (Server)
-> AI Proxy (queueing, rate limits, retries, /health, /metrics)
-> Scheduler + Shared Market Cache (multi-agent cycle dispatch, /metrics)
- Wallet-gated access (
Kasware,Kaspium,Demo) - Mainnet-first boot with runtime network switching (
?network=mainnet|testnet-10|testnet-11|testnet-12) - Kaspa network resolver supports aliases (
testnet,tn10,tn11,tn12) - Agent setup wizard with strategy templates:
- DCA accumulator
- Trend
- Mean reversion
- Volatility breakout
- Quant + AI decision engine with bounded fusion
- Web Worker quant/AI execution path (with controlled fallback)
- Accumulate-only execution discipline support
- Multi-agent portfolio view with shared risk budget + capital allocator
- Action queue with manual sign / autonomous gating flows
- Receipt polling and lifecycle reconciliation for broadcast txs
- PnL attribution panel (signal quality / slippage / fees / timing / missed fills)
- Alerts panel (Telegram / Discord / email-webhook)
- Treasury panel + on-chain treasury payout flow
- Wallet panel (balance, UTXO view, withdraw tools)
- Managed vault with AES-256-GCM encryption + Argon2id KDF (legacy PBKDF2 vaults auto-migrate), auto-lock alarm, and optional popup-reopen session persistence
- Popup app tabs:
wallet,swap,agents,security - Live feed health states (
LIVE FEED,PARTIAL FEED,FEED OFFLINE) with active RPC endpoint visibility - Portfolio privacy toggle (
HIDE/SHOW) persisted in extension storage - Network cycling in popup (
MAINNET,TN10,TN11,TN12) with network-aware address normalization - UTXO pipeline classifies
standardvscovenant; default coin selection only spendsstandardUTXOs - Dry-run hard gates before signing: UTXO availability, fee sufficiency, value conservation, address validity, and network-prefix match
- Site provider bridge (
window.forgeos) routes connect/sign requests through popup approval flow
- Typecheck + lint + unit tests + perf tests + build + smoke validation
- Playwright E2E suite (wallet gate, queue sign/reject, treasury second tx, network switch, controls)
- GitHub Pages deploy + domain validation tooling
- AI proxy and scheduler backend starters with
/healthand Prometheus/metrics
- Node.js 18+
- npm 9+
- Chromium browser (for extension loading)
- Optional: Kasware extension
- Optional: Kaspium mobile wallet
- Optional: Firefox (alternate extension build target)
npm installnpm run devnpm run cinpm run test:e2eBoot Sequence (Recommended Dev Flow)
npm install
npm run ci
npm run devThen in a separate terminal:
npm run test:e2enpm run build
npm run preview# Chromium package
npm run build:ext
# Firefox package
npm run build:ext:firefox
# Dev watch build for localhost extension testing
npm run dev:extLoad unpacked from dist-extension/extension in your browser's extension developer mode.
The extension can use a locally managed kaspad process as its primary RPC backend.
- Toggle from extension
Securitytab:KASPA RPC ENDPOINT -> LOCAL NODE MODE - Backend selection order:
- local node RPC (when enabled + healthy + synced + matching network profile)
- configured remote RPC pool fallback (
official/igra/kasplex/custom)
- Supported local profiles:
mainnet,testnet-10,testnet-11,testnet-12 - Signing boundary is unchanged (non-custodial signer remains inside existing extension vault flow)
- Data storage defaults to managed OS-native app-data paths; custom dir override is optional
Start local node control service:
cp .env.local-node.example .env.local-node
set -a; source .env.local-node; set +a
npm run local-node:startOptional control endpoints:
GET /metrics(JSON) orGET /metrics?format=prometheusGET /events(SSE lifecycle/status stream)
Real runtime check (start/status/stop + RPC health):
npm run local-node:doctorFull operator and troubleshooting guide:
LOCAL_NODE.md
Local Confidence Pass (Fast)
npm run ci
npm run test:e2eUse this before changing runtime logic, wallet flows, or queue/receipt handling.
Receipt Truth / Attribution Debug Pass
npm run dev
# optional in separate shells (backend truth path)
node server/callback-consumer/index.mjs
node server/scheduler/index.mjsThen in UI verify:
- queue truth labels (
BROADCASTED,CHAIN CONFIRMED,BACKEND CONFIRMED) - receipt provenance badges (
CHAIN,BACKEND,ESTIMATED) - PnL mode (
estimated,hybrid,realized) and confirmation floor
Redis Scheduler + Load Smoke (Multi-Instance)
TEST_REDIS_URL=redis://127.0.0.1:6379 npm run test:scheduler:redis
LOAD_PIPELINE_SCHEDULER_REDIS_URL=redis://127.0.0.1:6379 \
LOAD_PIPELINE_CALLBACK_REDIS_URL=redis://127.0.0.1:6379 \
LOAD_PIPELINE_SCHEDULER_INSTANCES=2 \
npm run load:pipelineThis validates failover/idempotency safety paths, not just UI behavior.
Create .env from .env.example.
VITE_KAS_API_MAINNETVITE_KAS_API_TESTNETVITE_KAS_API_FALLBACKS_MAINNETVITE_KAS_API_FALLBACKS_TESTNETVITE_KAS_EXPLORER_MAINNETVITE_KAS_EXPLORER_TESTNETVITE_KAS_WS_URL_MAINNETVITE_KAS_WS_URL_TESTNETVITE_KAS_NETWORK(mainnet default in.env.example)VITE_KAS_ENFORCE_WALLET_NETWORKVITE_KASPIUM_DEEP_LINK_SCHEMEVITE_KASPA_MAINNET_API_ENDPOINTSVITE_KASPA_TN10_API_ENDPOINTSVITE_KASPA_TN11_API_ENDPOINTSVITE_KASPA_TN12_API_ENDPOINTSVITE_KASPA_IGRA_MAINNET_API_ENDPOINTS,VITE_KASPA_IGRA_TN10_API_ENDPOINTS,VITE_KASPA_IGRA_TN11_API_ENDPOINTS,VITE_KASPA_IGRA_TN12_API_ENDPOINTSVITE_KASPA_KASPLEX_MAINNET_API_ENDPOINTS,VITE_KASPA_KASPLEX_TN10_API_ENDPOINTS,VITE_KASPA_KASPLEX_TN11_API_ENDPOINTS,VITE_KASPA_KASPLEX_TN12_API_ENDPOINTSVITE_KASPA_KASPLEX_API_ENDPOINTS(generic metadata pool fallback)
Provider preset behavior:
official,igra, andkasplexnow ship with built-in working L1 endpoint maps per network profile.- Environment values override those defaults per profile (
MAINNET,TN10,TN11,TN12). - Extension
Securitytab can still override pool order/entries at runtime. - Saving custom/override endpoints requests host permission for that endpoint origin (required by MV3 before fetch is allowed).
VITE_ACCUMULATE_ONLYVITE_LIVE_EXECUTION_DEFAULTVITE_FEE_RATEVITE_TREASURY_SPLITVITE_TREASURY_ADDRESS_MAINNETVITE_TREASURY_ADDRESS_TESTNETVITE_ACCUMULATION_ADDRESS_MAINNETVITE_ACCUMULATION_ADDRESS_TESTNETVITE_TREASURY_FEE_ONCHAIN_ENABLED
VITE_SWAP_ENABLEDVITE_SWAP_ROUTE_SOURCE(blocked|kaspa_native|evm_0x)VITE_SWAP_DEX_ENDPOINTVITE_SWAP_KASPA_NATIVE_QUOTE_PATHVITE_SWAP_KASPA_NATIVE_EXECUTE_PATHVITE_SWAP_KASPA_NATIVE_STATUS_PATHVITE_SWAP_KASPA_NATIVE_TIMEOUT_MSVITE_SWAP_MAX_SLIPPAGE_BPSVITE_SWAP_DEFAULT_SLIPPAGE_BPSVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINTSVITE_SWAP_KRC_TOKEN_METADATA_CACHE_TTL_MSVITE_SWAP_KRC_TOKEN_METADATA_CACHE_MAX_ENTRIESVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_SUCCESS_REWARDVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_FAILURE_PENALTYVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_TIMEOUT_PENALTYVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_MISS_PENALTYVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_LATENCY_PENALTY_PER_100MSVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_DECAY_TAU_MSVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_BACKOFF_BASE_MSVITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_BACKOFF_MAX_MSVITE_SWAP_EVM_CHAIN_IDSVITE_SWAP_REQUIRE_EXTERNAL_EVM_SIGNERVITE_SWAP_ZEROX_QUOTE_ENDPOINTVITE_SWAP_ZEROX_API_KEYVITE_SWAP_ZEROX_EXPECTED_SETTLER_TOVITE_SWAP_ZEROX_EXPECTED_ALLOWANCE_SPENDERVITE_SWAP_SETTLEMENT_CONFIRMATIONSVITE_SWAP_SETTLEMENT_POLL_MSVITE_SWAP_SETTLEMENT_TIMEOUT_MSVITE_FORGEOS_STRICT_EXTENSION_AUTH_CONNECT(true= require extension popup auth bridge;false= allow managed-wallet fallback when extension transport is unavailable)
VITE_AI_API_URLVITE_AI_MODELVITE_ANTHROPIC_API_KEY(frontend direct-call only; backend proxy preferred)VITE_AI_FALLBACK_ENABLEDVITE_AI_OVERLAY_MODE(alwaysdefault)VITE_AI_OVERLAY_MIN_INTERVAL_MSVITE_AI_OVERLAY_CACHE_TTL_MSVITE_AI_SOFT_TIMEOUT_MSVITE_AI_MAX_ATTEMPTSVITE_QUANT_WORKER_ENABLEDVITE_QUANT_WORKER_SOFT_TIMEOUT_MSVITE_DECISION_AUDIT_SIGNER_URL(optional server-side cryptographic audit signer endpoint,/v1/audit-sign)VITE_DECISION_AUDIT_SIGNER_TOKEN(optional)VITE_DECISION_AUDIT_SIGNER_TIMEOUT_MSVITE_DECISION_AUDIT_SIGNER_REQUIREDVITE_DECISION_AUDIT_SIGNER_PUBLIC_KEY_URL,VITE_DECISION_AUDIT_SIGNER_PINNED_FINGERPRINTS,VITE_DECISION_AUDIT_SIGNER_REQUIRE_PINNED(UI-side signature verification + key pinning)
VITE_EXECUTION_RECEIPT_IMPORT_ENABLEDVITE_EXECUTION_RECEIPT_API_URLVITE_EXECUTION_RECEIPT_API_TOKENVITE_EXECUTION_RECEIPT_API_TIMEOUT_MSVITE_PNL_REALIZED_MIN_CONFIRMATIONSVITE_PNL_REALIZED_CONFIRMATION_POLICY_JSON(tiered realized confirmation policy by action/risk/amount)
VITE_FREE_CYCLES_PER_DAYVITE_BILLING_UPGRADE_URLVITE_BILLING_CONTACTVITE_AUTO_CYCLE_SECONDS
FORGE-OS is mainnet-first.
Runtime network selection precedence:
?network=query param- runtime override (
localStorage, guarded) VITE_KAS_NETWORK- fallback
mainnet
Examples:
https://forge-os.xyz/?network=mainnethttps://forge-os.xyz/?network=testnet(alias for testnet profile)https://forge-os.xyz/?network=testnet-10https://forge-os.xyz/?network=testnet-11https://forge-os.xyz/?network=testnet-12
Address validation, explorer links, treasury routing, and accumulation vault routing all follow the active profile.
| Surface | Coverage | Notes |
|---|---|---|
| forge-os.xyz app | Mainnet + testnet profile | Query/env network resolver supports testnet-10, testnet-11, testnet-12 aliases |
| Extension popup | mainnet, testnet-10, testnet-11, testnet-12 |
Network badge cycles profiles; feed, swap, send, and dry-run logic follow active profile |
| Address safety | kaspa: + kaspatest: |
Prefix checks are enforced in send + dry-run validation |
The extension is a separate runtime surface under extension/*:
- Non-custodial managed wallet vault + signer path (no phrase export to site scripts)
- Popup-only approval flow for
FORGEOS_CONNECTandFORGEOS_SIGN - Content-script bridge forwards sanitized wallet metadata only (
address,network) - Built for Chromium and Firefox targets from the same codebase
- Compatibility boundary is explicit: extension provider interop is limited to
forge-osdomains configured in manifest/build config
- Swap routing defaults to live Kaspa-native mode (
VITE_SWAP_ENABLED=true,VITE_SWAP_ROUTE_SOURCE=kaspa_native) and can be overridden toblockedfor maintenance windows. kaspa_nativeroute supports custom token outputs by pasted address (krc20/krc721).- Token metadata resolver is env-driven and network-scoped:
VITE_SWAP_KRC_TOKEN_METADATA_ENDPOINTSVITE_KASPA_KASPLEX_*_API_ENDPOINTS(+ genericVITE_KASPA_KASPLEX_API_ENDPOINTS)
- Resolver now uses:
- in-memory TTL + LRU cache (
VITE_SWAP_KRC_TOKEN_METADATA_CACHE_TTL_MS,VITE_SWAP_KRC_TOKEN_METADATA_CACHE_MAX_ENTRIES) - endpoint health scoring (latency/error weighted with decay + temporary backoff) via
VITE_SWAP_KRC_TOKEN_METADATA_ENDPOINT_*knobs
- in-memory TTL + LRU cache (
- UI metadata preview remains fail-open (fallback icon/label), while quote/execution paths remain fail-closed.
- EVM
0xroute stays signer-isolated via external sidecar requirements.
- UTXOs are classified as
standardorcovenantduring sync. - Standard send/swap coin selection only uses
standardinputs. - Dry-run blocks covenant spends with
COVENANT_INPUT_UNSUPPORTEDunless a covenant-aware module is added. - This keeps default wallet behavior policy-safe while leaving room for future covenant spend modules.
This matrix covers wallet adapters used by the forge-os.xyz web control plane. The extension runtime uses a managed non-custodial vault/signing path documented above.
| Wallet | Connect | Send | Multi-Output | Network Checks | Signing Custody |
|---|---|---|---|---|---|
| Kasware | Extension | sendKaspa |
No (single-recipient path) | Yes | Wallet-side |
| Kaspium | Deep-link/manual | Deep-link + txid handoff |
No | Yes | Wallet-side |
| Kastle | Extension | sendKaspa / signAndBroadcastTx |
Conditional (raw tx path) | Yes | Wallet-side |
| Ghost Wallet | Provider bridge | transact |
Yes (outputs array) | Yes | Wallet-side |
| Tangem | Bridge/manual | External sign+broadcast | Bridge-dependent | Address/profile validation in app | Device-side |
| OneKey | Bridge/manual | External sign+broadcast | Bridge-dependent | Address/profile validation in app | Device-side |
| Demo | Local | Simulated | Simulated | N/A | N/A |
- Extension connect (
requestAccounts,getNetwork) - Network/profile enforcement (configurable)
- Send path (
sendKaspa) - Stronger timeout/error normalization in adapter
- Native multi-output send: no (single-recipient send path)
- Future path: PSKT/raw tx signing route may enable combined treasury output
- Mainnet-first connect behavior (testnet still optional)
- Deep-link transfer generation
- Manual
txidhandoff for receipt tracking - Address-prefix validation (
kaspa:/kaspatest:) - Native multi-output send: no (current deep-link flow is single-recipient + manual
txid)
- Injected
window.kastleprovider support in WalletGate and runtime adapter - Connect/account/network checks with mainnet/testnet profile enforcement
- Send path (
sendKaspa) wired into Forge-OS queue/signing lifecycle - Wallet selector uses the real Kastle logo in UI
- Native multi-output send: conditional via
signAndBroadcastTx(networkId, txJson)when theVITE_KASTLE_RAW_TX_ENABLEDraw-tx path is enabled and a txJson bridge/manual txJson input is available
- Custom
kaspa:*provider event bridge support in WalletGate and runtime adapter - Connect/account/network checks with profile enforcement
transactsend path wired into Forge-OS queue/signing lifecycle- Wallet selector uses the real Ghost Wallet logo in UI
- Native multi-output send: yes (
transactaccepts an outputs array; Forge-OS combines treasury fee output when eligible)
- Manual bridge connect (address pairing) in WalletGate
- External sign/broadcast flow with txid handoff back into Forge-OS
- Preserves hardware custody model (no private key handling in Forge-OS)
- Native multi-output send: bridge/manual dependent
- Manual bridge connect (address pairing) in WalletGate
- External sign/broadcast flow with txid handoff back into Forge-OS
- Preserves hardware custody model (no private key handling in Forge-OS)
- Native multi-output send: bridge/manual dependent
- Local tx/txid simulation for UI and testing workflows
Mainnet treasury is pinned in code and validated at startup.
Pinned mainnet treasury address:
kaspa:qpv7fcvdlz6th4hqjtm9qkkms2dw0raem963x3hm8glu3kjgj7922vy69hv85
Notes:
- Treasury micro-fee payout is sent as a separate tx for wallets without native multi-output support.
- Ghost Wallet can combine action + treasury outputs into a single transaction when the tx shape is eligible.
- Kastle can also use a combined treasury multi-output path when the feature-flagged raw-tx route is enabled and a raw txJson source is available.
- If treasury payout fails or is rejected, it is queued as a
TREASURY_FEEaction. - Spendable balance calculations reserve treasury payout + network fee to avoid overspend.
Queue items now track both:
pendingsigningsignedrejectedfailed
submittedbroadcastedpending_confirmconfirmedfailedtimeout
FORGE-OS polls Kaspa transaction endpoints with backoff and persists receipt telemetry, including:
submitted_tsbroadcast_tsconfirm_tsconfirm_ts_source(chainwhen receipt block timestamp is available)confirmationsfailure_reasonreceipt_fee_kas/receipt_fee_sompi(when exposed by API payload)- price snapshot telemetry at broadcast/confirm when available
This feeds receipt-aware attribution (estimated / hybrid / realized) and improves operator trust in execution state.
Forge-OS also enforces a truth degradation policy:
- if backend-vs-chain receipt mismatch rate exceeds policy thresholds,
realizedattribution is downgraded tohybrid - optional policy can block autonomous auto-approve until receipt consistency recovers
flowchart LR
A[SIMULATED] --> B[BROADCASTED]
B --> C[BACKEND CONFIRMED]
B --> D[CHAIN CONFIRMED]
C --> E[Receipt Consistency Check]
D --> E
E --> F[Realized PnL (confirmation floor policy)]
| Signal | Meaning |
|---|---|
| Truth Label | Execution state (SIMULATED, BROADCASTED, BACKEND CONFIRMED, CHAIN CONFIRMED, ESTIMATED) |
| Receipt Provenance | Where confirmation telemetry came from (CHAIN, BACKEND, ESTIMATED) |
| Consistency Badge | Whether backend and chain telemetry agree within configured tolerances |
| Audit Verification Badge | Browser-side crypto signature verification + signer key pin status |
FORGE-OS uses a quant-first, AI-bounded model:
- Deterministic quant core computes regime, volatility, risk score, EV, Kelly cap, SL/TP, and sizing
- Real AI overlay refines decisions using quant context
- Guarded fusion enforces risk limits and can block unsafe AI actions
- Calibration guardrails can automatically:
- reduce
ACCUMULATEsizing when calibration quality degrades - disable auto-approve when calibration health falls below policy
- reduce
Production guidance:
- Prefer backend proxy (
VITE_AI_API_URL) for AI calls - Keep API keys server-side
- Use
VITE_AI_OVERLAY_MODE=alwaysfor max AI involvement - Use
VITE_AI_FALLBACK_ENABLED=falseif you require strict AI availability (no silent quant fallback)
Run:
npm run ai:proxyProvides:
- queueing
- per-user rate limiting
- transient retry/backoff
- concurrency caps
GET /healthGET /metrics(Prometheus)
Prometheus metrics include:
- queue depth / in-flight / saturation state
- HTTP response counters
- upstream success / error / retry counters
- proxy latency histogram
- upstream latency histogram
Run:
npm run scheduler:startProvides:
- multi-agent registry (in-memory by default, Redis-backed persistence optional)
- server-side cycle scheduler queue with concurrency caps (Redis-authoritative execution queue when enabled)
- shared market snapshot cache (price/blockdag/balance) with TTL + in-flight dedupe
- optional token/service-token/JWT/JWKS auth with scopes + per-user quotas
- optional Redis-backed agent persistence + due schedule (degraded startup if Redis unavailable)
- optional Redis-authoritative due schedule + Redis execution queue + leader lock fencing + per-agent/task leases for multi-instance safety
- callback idempotency keys + fence-token propagation to downstream consumers (
X-ForgeOS-*headers and payload metadata) GET /healthGET /metrics(Prometheus)POST /v1/agents/registerGET /v1/market-snapshot?address=...POST /v1/scheduler/tick
This is the bridge toward moving orchestration out of the browser.
flowchart TB
UI[FORGE-OS Browser Control Plane]
UI --> AP[AI Proxy]
UI --> SCH[Scheduler]
SCH --> KC[Shared Market Cache]
SCH --> CB[Callback Consumer]
SCH --> TXB[Tx Builder]
AP --> AI[AI Provider]
TXB --> KRPC[Kaspa API / UTXO Endpoints]
CB --> REC[Execution Receipts Store]
SCH --> MET[Prometheus Metrics]
CB --> MET
AP --> MET
Run:
npm run tx-builder:startProvides:
- backend tx-builder endpoint for automatic
KastlesignAndBroadcastTx(..., txJson)flows - local
kaspa-wasmbuilder mode (TX_BUILDER_LOCAL_WASM_ENABLED=true) for true automatic Kastle multi-output txJson generation from UTXOs - command-hook mode (
TX_BUILDER_COMMAND) for local Kaspa tx-builder integration - bundled command executable
server/tx-builder/commands/kastle-http-bridge-command.mjsfor realTX_BUILDER_COMMANDdeployments that proxy a dedicated builder - upstream proxy mode (
TX_BUILDER_UPSTREAM_URL) GET /healthGET /metrics
Frontend integration:
VITE_KASTLE_TX_BUILDER_URLVITE_KASTLE_TX_BUILDER_TOKEN(optional)VITE_EXECUTION_RECEIPT_API_URL/VITE_EXECUTION_RECEIPT_API_TOKEN(optional backend receipt import for UI PnL / receipt reconciliation)
Run:
npm run callback-consumer:startProvides:
- downstream scheduler callback receiver with idempotency enforcement
- leader fence-token enforcement (
X-ForgeOS-Leader-Fence-Token) - exact execution receipt ingestion endpoints for backend attribution pipelines
- Redis Lua-backed atomic fence/idempotency checks when Redis is enabled
- receipt consistency telemetry counters in
/metrics(checks, mismatches, mismatch type breakdown) for frontend-reported backend-vs-chain consistency checks GET /healthGET /metricsGET /v1/eventsPOST /v1/scheduler/cycleGET/POST /v1/execution-receipts
Run:
npm run audit-signer:startProvides:
- server-side cryptographic signatures for frontend decision audit records
- local-key mode (Ed25519 PEM) and HSM/KMS-ready command mode (
AUDIT_SIGNER_COMMAND) - optional append-only hash-chained JSONL audit export (
AUDIT_SIGNER_APPEND_LOG_PATH) for external verification / replay - UI can verify signer signatures client-side and enforce pinned signer fingerprints when configured
GET /healthGET /metricsGET /v1/public-key(local-key mode)GET /v1/audit-logPOST /v1/audit-sign
Offline verification:
npm run audit-log:verify -- --file ./forgeos-audit.jsonl --strict-signatures- Import
ops/grafana/forgeos-operator-overview.jsoninto Grafana. - Add Prometheus recording/alert rules:
ops/prometheus/forgeos-recording-rules.ymlops/prometheus/forgeos-alert-rules.yml
- Includes backend truth/control/execution panels for:
- receipt consistency checks/mismatches + mismatch types (callback-consumer)
- scheduler queue/saturation and callback duplicate/stale-fence signals
- tx-builder local policy efficiency (selected inputs / fee / fallback usage)
Hidden Ops Notes (GitHub-friendly collapsible)
- The browser app is the operator control plane; it is not intended to be an HFT execution engine.
- For real scale, pair
server/ai-proxyandserver/schedulerwith Redis/Postgres plus distributed scheduler locking. - Ghost Wallet supports a treasury-combined multi-output path. Kastle has a feature-flagged raw-tx combined path (
signAndBroadcastTx) when a txJson source is provided. Other wallets use the separate treasury payout tx fallback. - Exact realized attribution still improves significantly once fill/confirmation receipts are ingested from a backend execution service.
npm run lint
npm run typecheck
npm run test:run
npm run test:perf
npm run load:pipeline
npm run build
npm run ci
npm run test:e2e| Goal | Command | Notes |
|---|---|---|
| Fast local correctness | npm run ci |
Includes domain verify, lint, typecheck, tests, build, fallback sync/verify, smoke |
| UI flow validation | npm run test:e2e |
Playwright flows for wallet gate / queue / treasury / controls |
| Redis scheduler semantics | npm run test:scheduler:redis |
Runs Redis-backed scheduler integration specs when TEST_REDIS_URL is set |
| Pipeline performance smoke | npm run load:pipeline |
Supports threshold assertions and multi-scheduler mode |
| Tx-builder policy benchmark | npm run bench:tx-policy |
Bench coin-selection + fee policy behavior across synthetic UTXO shapes |
| Audit export verification | npm run audit-log:verify -- --file ./forgeos-audit.jsonl --strict-signatures |
Offline hash-chain + signature verification |
Current flows include:
- demo wallet gate
- mocked Kasware wallet gate
- queue reject/sign flow
- treasury second-tx queue/sign flow
- network switching reset + URL update
- pause / resume / kill-switch controls
CI Notes (Why E2E Is Separate)
npm run cifocuses on fast correctness gates (lint/typecheck/unit/build/smoke/domain).- Playwright E2E runs in a dedicated GitHub Actions job for clearer failures and artifact uploads.
- The Playwright config uses strict port binding and CI-specific server reuse behavior for stability.
GitHub UI Power Moves (Maintainers / Reviewers)
| Goal | GitHub Trick | Why It Helps |
|---|---|---|
| Stable code references | Press y on a file page | Converts to a permalink tied to a commit |
| Link exact code lines | Append #Lx (for example #L120) |
Makes review comments and docs precise |
| Quick repo editor | Press . on repo page | Opens GitHub web editor instantly |
| Fast search | Use code search qualifiers (path:src, lang:ts) |
Speeds hotspot audits and refactors |
| Compare releases | /compare/<sha1>...<sha2> |
Clean change review before deploy |
| Blame regressions | “Blame” + line permalink | Tracks when a behavior changed |
Deployment Cleanup / Artifact Triage (GitHub Actions)
- Keep
CI,Deploy Pages, and (if enabled) load jobs visible in Actions favorites. - Use workflow run artifacts for:
- Playwright failure screenshots/videos
- load harness metrics output
- build/fallback verification traces
- When triaging a deploy issue:
- open
CI - confirm
buildandsmoke - open
Deploy Pages - run
npm run domain:check - verify live
manifest.jsonpoints to the latestassets/index-*.js
- open
| Symptom | First Check | Command / Action |
|---|---|---|
| Wallet connects but send flow fails | Wallet network/address prefix mismatch | Verify kaspa: vs kaspatest: and topbar network selector |
Queue stays BROADCASTED too long |
Receipt path health | Check callback-consumer /health and /metrics, then chain receipt polling |
PnL stays hybrid not realized |
Confirmation floor / receipt consistency | Check PnL header confirmation floor + queue provenance badges |
| Auto-approve stops firing | Calibration or truth guardrail degradation | Review Intelligence + runtime notices banners |
| Scheduler duplicate callback concerns | Fence/idempotency counters | Check callback-consumer metrics + Redis scheduler tests |
| Pages deploy looks old | Artifact / manifest drift | npm run domain:check and inspect live manifest.json |
- Workflow:
.github/workflows/deploy-pages.yml - Pages source should be GitHub Actions (not branch mode)
- Custom domain:
forge-os.xyz
npm run verify:domain
npm run domain:check
npm run domain:watch- Configure network-scoped mainnet/testnet Kaspa endpoints (
*_MAINNET,*_TESTNET). - Set
VITE_KAS_ENFORCE_WALLET_NETWORK=truefor stricter wallet/profile matching. - Verify treasury and accumulation addresses per network.
- Use backend AI proxy; do not expose production AI secrets in browser.
- Run
npm run ciandnpm run test:e2e. - Ensure GitHub Actions
CIandDeploy Pagesare green. - Validate real wallet flows on production:
- Kasware connect/sign/send
- Kaspium deep-link +
txidconfirmation - treasury fee payout destination and queue fallback behavior
Operator Launch Sequence (1-minute sanity path)
npm run cinpm run test:e2e- Start backend modules you need (
ai-proxy,scheduler,callback-consumer,tx-builder) - Confirm
/health+/metricson each enabled backend service - Connect a real wallet on mainnet (
forge-os.xyz) - Execute one small transaction and verify:
- queue truth label updates
- receipt provenance badge
- treasury route destination
- attribution reflects confirmation state
src/ForgeOS.tsx— root shell + topbar + network switch + multi-agent session statesrc/components/WalletGate.tsx— wallet connect gate (Kasware/Kaspium/demo)src/components/wizard/*— agent setup + strategy templates + deploy flowsrc/components/dashboard/*— runtime UI panelssrc/components/dashboard/hooks/*— dashboard runtime hooks (feed, lifecycle, queue, treasury, alerts, allocator)src/quant/*— quant math, quant core, AI fusion engine, worker clientsrc/wallet/WalletAdapter.ts— wallet transport mechanics and safety checkssrc/tx/queueTx.ts— tx validation/build/broadcast helperssrc/runtime/*— lifecycle, errors, persistence, alerts, quotas, portfolio statesrc/api/kaspaApi.ts— Kaspa REST integration + receipt lookupsextension/popup/Popup.tsx— extension app shell (wallet/swap/agents/security + live feed states)extension/vault/vault.ts— encrypted vault/session management for managed wallet modeextension/tx/*— tx builder/dry-run/signer/broadcast pipeline (managed wallet path)extension/swap/*— swap gating, route adapters, KRC metadata resolver, settlement trackingextension/content/*— page provider + site bridge for connect/sign relayserver/ai-proxy/*— AI proxy starter + metricsserver/scheduler/*— scheduler/shared cache starter + metricsserver/callback-consumer/*— reference downstream callback receiver + receipt ingestion startertests/*— unit, perf, and E2E suites
- No seed phrase or private key storage in app/backend logic
- Wallet-side signing only (Kasware / Kaspium)
- Kaspa prefix validation enforced (
kaspa:/kaspatest:) - Extension vault keeps signing session in-memory and supports auto-lock/session-expiry controls
- Covenant UTXOs are not spent by default standard flows
- Quant guardrails constrain AI decisions before execution
- Explicit lifecycle states and error taxonomy for queue/receipt handling
Threat Model Snapshot
- Do not move seed/private key handling into frontend or backend services.
- Treat all AI outputs as untrusted until validated by quant/risk envelopes.
- Keep network profile, address prefix, and treasury routing checks explicit and testable.
- Prefer backend AI proxy for secrets, observability, and rate limiting.
README.dev.md— developer architecture and implementation notesdocs/kaspa/links.md— curated Kaspa resource indexdocs/ai/kaspa-elite-engineer-mode.md— AI engineering briefdocs/ops/custom-domain.md— custom domain ops runbookAGENTS.md— repo operating rules for agents/contributors
This repo is designed as a Kaspa-first operator platform and a production-minded foundation for wallet-native quant automation.
If you are extending wallets/integrations, keep the repo standards intact:
- UTXO-first thinking
- non-custodial signing boundaries
- no insecure key handling
- network-aware address validation