Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Tests/AgentsFlowTests.swift10// Description : Rules of the trading-agent screens: the live forms start11// empty and stay incomplete until every limit is typed12// (expiry mandatory, nothing defaulted), the mandate13// expectation is built from what was TYPED, a mode's label14// and figures can never appear under another mode, every15// stop path runs without a passkey, and server states map to16// words without inventing any. Fixtures are answers of a17// throwaway stack (2026-11-18), trimmed.18// Module : Tests19// Repository : https://git.spboucher.ai/sp-wallet-ios20// Created : 2026-11-1821// Last Modified : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import Testing97import SPWalletCore98@testable import SPWallet99100private enum Fx {101 static let spot = #"""102 {"id":"83bb9cc0-7d9b-4d2c-b3e3-744629db0241","name":"Probe spot","mission":"probe","state":"PAPER_TRADING","mode":"PAPER","network":"base","networkName":"Base","universe":["ETH","BTC"],"cash":"USDC","interval":"1h",103 "risk":{"maxLossPct":10,"mandateDays":7,"maxDailyUsd":50,"maxOrderUsd":20,"slippageBps":50,"maxExposurePct":50,"maxOrdersPerDay":5},104 "holdings":[{"symbol":"USDC","asset":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913","assetSymbol":"USDC","name":"USD Coin","kind":"cash","issuer":null},{"symbol":"ETH","asset":"native","assetSymbol":"ETH","name":"Ether","kind":"native","issuer":null}],105 "vaultAddress":"0x1e5d93f21bdd042A66E90EdC8BDCd46D6fedd7e2","vaultIndex":1,"capitalUsdc":"100","strategyVersionId":"a93d30d5-2167-43ce-af81-f5fcc63d11d3","mandateId":null,"mandate":null,"family":"custom","template":null,"engine":"bar","configVersion":2,106 "vault":[],"mandateStatus":null,"paper":null,107 "versions":[{"id":"a93d30d5-2167-43ce-af81-f5fcc63d11d3","name":"ma_trend","version":"3","code_sha256":"a3134bf5c1b9c799c0ebed4a404533e0808bf1dec6de0d59db40b000f820d0ae","status":"approved","notes":"","metrics":{"test":{"sharpe":1.2}},"robustness":null,"benchmarks":null,"config":null}],108 "orders":[],"equity":[],"log":[]}109 """#110 static let network = #"""111 {"id":"base","name":"Base","family":"evm","chainRef":"eip155:8453","native":{"id":"native","symbol":"ETH","name":"Ether","decimals":18},112 "tokens":[{"id":"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913","symbol":"USDC","name":"USD Coin","decimals":6}],"explorerAddr":"https://basescan.org/address/","minConf":3}113 """#114 static func performance(_ mode: String) -> String {115 #"{"points":2,"totalReturn":{"value":0.05,"reason":null},"netPnlUsd":{"value":null,"reason":"fewer than two equity points"},"closedTrades":0,"orders":1,"warnings":[],"mode":"\#(mode)","label":"X","equityCurve":[{"ts":1795040220000,"equity":1000},{"ts":1795043820000,"equity":1050}]}"#116 }117 static func decode<T: Decodable>(_ s: String, as: T.Type = T.self) throws -> T { try APICoding.decoder().decode(T.self, from: Data(s.utf8)) }118 static func spotDetail() throws -> SpotAgentDetail {119 guard case .spot(let d) = try decode(spot, as: AgentDetail.self) else { throw APIError(status: 0, code: "fixture", message: "spot expected") }120 return d121 }122 static var completeForm: SpotLiveForm {123 SpotLiveForm(budget: "100", maxOrder: "20", maxDaily: "50", ordersPerDay: "5", lossPct: "10", days: "7", assets: ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "native"])124 }125}126127/** Records every request and answers from a script keyed by "METHOD path". */128private final class ScriptedTransport: HTTPTransport, @unchecked Sendable {129 private let lock = NSLock()130 private var answers: [String: String]131 private(set) var requests: [(method: String, path: String, body: String)] = []132 init(_ answers: [String: String]) { self.answers = answers }133 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {134 let method = request.httpMethod ?? "GET", path = request.url?.path ?? ""135 let body = request.httpBody.map { String(decoding: $0, as: UTF8.self) } ?? ""136 let answer: String? = lock.withLock { requests.append((method, path, body)); return answers["\(method) \(path)"] }137 guard let answer else { return (Data(#"{"error":"not_found","message":"unscripted"}"#.utf8), HTTPURLResponse(url: request.url!, statusCode: 404, httpVersion: nil, headerFields: nil)!) }138 return (Data(answer.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "application/json"])!)139 }140 var seen: [(method: String, path: String, body: String)] { lock.withLock { requests } }141}142143private func client(_ t: ScriptedTransport) -> APIClient {144 APIClient(configuration: APIConfiguration(origin: URL(string: "http://localhost:1")!, rpId: "localhost", userAgent: "tests"), tokens: InMemoryTokenStore(), transport: t)145}146147@Suite struct SpotLiveFormTests {148 @Test func theFormStartsEmptyAndNothingIsPreselected() throws {149 let a = try Fx.spotDetail().agent, f = SpotLiveForm()150 #expect(f.budget.isEmpty && f.maxOrder.isEmpty && f.maxDaily.isEmpty && f.ordersPerDay.isEmpty && f.lossPct.isEmpty && f.days.isEmpty && f.assets.isEmpty)151 #expect(f.missing == SpotLiveForm.Field.allCases)152 #expect(!f.isComplete(agent: a))153 // an empty field is missing, not wrong: no message invents a value154 #expect(SpotLiveForm.Field.allCases.allSatisfy { f.problem($0, agent: a) == nil })155 }156157 @Test func everyLimitMustBeTypedBeforeTheMandateCanBePrepared() throws {158 let a = try Fx.spotDetail().agent159 #expect(Fx.completeForm.isComplete(agent: a))160 // leaving out any single field keeps the form incomplete161 var f = Fx.completeForm; f.budget = ""; #expect(!f.isComplete(agent: a))162 f = Fx.completeForm; f.maxOrder = ""; #expect(!f.isComplete(agent: a))163 f = Fx.completeForm; f.maxDaily = ""; #expect(!f.isComplete(agent: a))164 f = Fx.completeForm; f.ordersPerDay = ""; #expect(!f.isComplete(agent: a))165 f = Fx.completeForm; f.lossPct = ""; #expect(!f.isComplete(agent: a))166 f = Fx.completeForm; f.assets = []; #expect(!f.isComplete(agent: a))167 f = Fx.completeForm; f.assets = ["native"]; #expect(!f.isComplete(agent: a) && f.problem(.assets, agent: a) != nil)168 }169170 @Test func theExpiryIsMandatory() throws {171 let a = try Fx.spotDetail().agent172 var f = Fx.completeForm173 f.days = ""; #expect(!f.isComplete(agent: a) && f.missing == [.days])174 f.days = "0"; #expect(!f.isComplete(agent: a) && f.problem(.days, agent: a) != nil)175 f.days = "365"; #expect(!f.isComplete(agent: a) && f.problem(.days, agent: a) != nil)176 f.days = "sans"; #expect(!f.isComplete(agent: a))177 f.days = "7"; #expect(f.isComplete(agent: a))178 }179180 @Test func aTypedLimitThatIsNotTheAgentsIsRefusedBeforeAnyRequest() throws {181 let a = try Fx.spotDetail().agent182 var f = Fx.completeForm183 f.maxOrder = "2000"; #expect(!f.isComplete(agent: a) && f.problem(.maxOrder, agent: a)?.contains("20 USD") == true)184 f = Fx.completeForm; f.maxDaily = "51"; #expect(!f.isComplete(agent: a))185 f = Fx.completeForm; f.ordersPerDay = "6"; #expect(!f.isComplete(agent: a))186 f = Fx.completeForm; f.lossPct = "50"; #expect(!f.isComplete(agent: a))187 f = Fx.completeForm; f.budget = "1000"; #expect(!f.isComplete(agent: a))188 // the same value written differently is the same value; a comma is a decimal separator189 f = Fx.completeForm; f.maxOrder = "20,0"; f.budget = "100.00"; #expect(f.isComplete(agent: a))190 f = Fx.completeForm; f.maxOrder = "-20"; #expect(f.problem(.maxOrder, agent: a) != nil)191 f = Fx.completeForm; f.maxOrder = "2e1"; #expect(f.problem(.maxOrder, agent: a) != nil)192 }193194 @Test func theExpectationIsBuiltFromWhatWasTyped() throws {195 let d = try Fx.spotDetail(), n = try Fx.decode(Fx.network, as: Network.self)196 let e = try Fx.completeForm.expectation(detail: d, network: n)197 #expect(e.maxOrderUsd.text == "20" && e.maxDailyUsd.text == "50" && e.maxOrdersPerDay == 5 && e.mandateDays == 7)198 #expect(e.vault == "0x1e5d93f21bdd042A66E90EdC8BDCd46D6fedd7e2" && e.vaultIndex == 1 && e.network == "base")199 #expect(e.strategySha256 == "a3134bf5c1b9c799c0ebed4a404533e0808bf1dec6de0d59db40b000f820d0ae")200 #expect(e.assets.map(\.symbol) == ["USDC", "ETH"] && e.assets.map(\.decimals) == [6, 18] && e.assets.filter(\.isCash).count == 1)201 // an incomplete form never yields an expectation202 var f = Fx.completeForm; f.days = ""203 #expect(throws: ApprovalError.self) { try f.expectation(detail: d, network: n) }204 // a mandate that says something else than what was typed is refused by the Core's comparison205 let wider: JSONValue = ["v": 1, "mandateId": "a6340bef-6425-431d-8e41-69989911736b", "keyId": "spw-6e2ac52b366efc7f", "vaultIndex": 1, "vault": "0x1e5d93f21bdd042A66E90EdC8BDCd46D6fedd7e2", "network": "base", "provider": "kyberswap",206 "assets": ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "native"], "maxOrder": ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913": "25000000", "native": "11345330000000000"],207 "maxDaily": ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913": "50000000", "native": "28363320000000000"], "maxOrdersPerDay": 5, "maxSlippageBps": 150, "createdAt": 1795040298, "expiresAt": 1795645098,208 "strategySha256": "a3134bf5c1b9c799c0ebed4a404533e0808bf1dec6de0d59db40b000f820d0ae", "label": "Probe spot"]209 let now = Date(timeIntervalSince1970: 1_795_040_300)210 #expect(throws: ApprovalError.inconsistent("per-order cap")) { try AgentsAPI.check(mandate: try AgentSpotMandate(served: wider), against: e, now: now) }211 }212213 @Test func thePerpFormNeedsAnAccountAValidityAndTheLeverage() throws {214 var f = PerpLiveForm()215 #expect(f.accountId == nil && f.days.isEmpty && f.maxLeverage.isEmpty && !f.canAskReadiness(maxDays: 30))216 f.accountId = "acct"; #expect(!f.canAskReadiness(maxDays: 30))217 f.days = "45"; #expect(!f.canAskReadiness(maxDays: 30) && f.daysProblem(maxDays: 30) != nil)218 f.days = "0"; #expect(!f.canAskReadiness(maxDays: 30))219 f.days = "14"; #expect(f.canAskReadiness(maxDays: 30) && f.typedDays == 14)220 }221}222223@Suite struct AgentModeLabellingTests {224 @Test func aBadgeAlwaysSaysItsModeInWords() {225 let research = AgentModeBadge.of(mode: .research, kind: .spot, liveNetwork: nil, tradesRealMoney: false)226 let paper = AgentModeBadge.of(mode: .paper, kind: .perp, liveNetwork: nil, tradesRealMoney: false)227 #expect(research.text == "SIMULATION" && paper.text == "PAPIER")228 for b in [research, paper] { #expect(!b.text.contains("RÉEL") && !b.text.localizedCaseInsensitiveContains("argent réel") && !b.realMoney) }229 let unknown = AgentModeBadge.of(mode: .unknown, kind: .spot, liveNetwork: nil, tradesRealMoney: true)230 #expect(!unknown.text.contains("RÉEL") && !unknown.text.contains("PAPIER") && !unknown.text.contains("SIMULATION") && !unknown.realMoney)231 }232233 @Test func realMoneyIsOnlySaidWhenTheCoreSaysSo() {234 let spot = AgentModeBadge.of(mode: .live, kind: .spot, liveNetwork: nil, tradesRealMoney: true)235 #expect(spot.text.contains("RÉEL") && spot.text.contains("argent réel") && spot.realMoney)236 let testnet = AgentModeBadge.of(mode: .live, kind: .perp, liveNetwork: "testnet", tradesRealMoney: false)237 #expect(testnet.text.contains("TESTNET") && !testnet.text.contains("argent réel") && !testnet.realMoney)238 let mainnet = AgentModeBadge.of(mode: .live, kind: .perp, liveNetwork: "mainnet", tradesRealMoney: true)239 #expect(mainnet.text.contains("MAINNET") && mainnet.text.contains("argent réel"))240 // a record that cannot tell (a summary without its network) never claims real money241 let untold = AgentModeBadge.of(mode: .live, kind: .perp, liveNetwork: nil, tradesRealMoney: nil)242 #expect(untold.text.contains("RÉEL") && !untold.text.contains("argent réel") && !untold.realMoney)243 // even "mainnet" without the Core's verdict does not say it244 #expect(!AgentModeBadge.of(mode: .live, kind: .perp, liveNetwork: "mainnet", tradesRealMoney: nil).text.contains("argent réel"))245 }246247 @Test func theBadgeOfAnAgentFollowsTheCore() throws {248 let a = try Fx.spotDetail().agent249 #expect(a.mode == .paper && !a.tradesRealMoney && AgentModeBadge.of(a).text == "PAPIER")250 // a live agent that the server reports STOPPED keeps its mode but is not shown as trading real money251 let live = try Fx.decode(Fx.spot.replacingOccurrences(of: #""mode":"PAPER""#, with: #""mode":"LIVE""#).replacingOccurrences(of: "PAPER_TRADING", with: "LIVE"), as: Agent.self)252 #expect(live.tradesRealMoney && AgentModeBadge.of(live).text.contains("argent réel"))253 let stopped = try Fx.decode(Fx.spot.replacingOccurrences(of: #""mode":"PAPER""#, with: #""mode":"LIVE""#).replacingOccurrences(of: "PAPER_TRADING", with: "STOPPED"), as: Agent.self)254 #expect(AgentModeBadge.of(stopped).text == "RÉEL · arrêté" && !AgentModeBadge.of(stopped).realMoney)255 }256257 @Test func aFigureOfOneModeIsRefusedUnderAnotherHeading() throws {258 let paper = try Fx.decode(Fx.performance("paper"), as: AgentPerformance.self)259 #expect(try ModeGuard.figure(paper.totalReturn, heading: .paper).value == 0.05)260 #expect(try ModeGuard.scoped(paper.equityCurve, heading: .paper).count == 2)261 for heading in [AgentMode.live, .research, .unknown] {262 do { _ = try ModeGuard.figure(paper.totalReturn, heading: heading); Issue.record("a paper figure passed under \(heading)") }263 catch let e as APIError { #expect(e.code == "mode_mismatch") }264 do { _ = try ModeGuard.scoped(paper.equityCurve, heading: heading); Issue.record("a paper curve passed under \(heading)") }265 catch let e as APIError { #expect(e.code == "mode_mismatch") }266 }267 // an unknown mode is never accepted, even under its own heading268 #expect(throws: APIError.self) { try ModeGuard.check(.unknown, heading: .unknown) }269 // the label that travels with a figure names its mode; a simulation says what it is worth270 #expect(ModeGuard.label(.research) == "simulation sur données historiques — ne garantit rien")271 #expect(ModeGuard.label(.paper).contains("papier") && ModeGuard.label(.live) == "réel" && !ModeGuard.label(.paper).contains("réel"))272 }273274 @Test @MainActor func aLiveAnswerToAPaperReadLeavesNothingOnScreen() async throws {275 // the server answers LIVE records to the paper read: the Core refuses (mode_mismatch), the workspace shows the error and no row276 let t = ScriptedTransport(["GET /api/v1/agents/a1/orders": #"{"mode":"live","orders":[]}"#, "GET /api/v1/agents/a1/performance": Fx.performance("live"),277 "GET /api/v1/agents/a1/journal": #"{"mode":"paper","entries":[{"id":"1","ts":1795040298301,"mode":"live","kind":"state","title":"x"}]}"#])278 let api = AgentsAPI(client(t)), records = ModeRecords(agentId: "a1", mode: .paper)279 for tab in [AgentRecordTab.orders, .performance, .journal] { await records.load(tab, api: api) }280 #expect(records.orders == nil && records.performance == nil && records.journal == nil)281 #expect([AgentRecordTab.orders, .performance, .journal].allSatisfy { (records.errors[$0] as? APIError)?.code == "mode_mismatch" })282 // the read asked for exactly its own mode283 #expect(t.seen.allSatisfy { $0.method == "GET" })284 // and a correct answer is kept285 let ok = ScriptedTransport(["GET /api/v1/agents/a1/performance": Fx.performance("paper")])286 let good = ModeRecords(agentId: "a1", mode: .paper)287 await good.load(.performance, api: AgentsAPI(client(ok)))288 #expect(good.performance?.mode == .paper && good.errors[.performance] == nil)289 }290}291292@Suite struct AgentStopTests {293 private static let summary = #"{"id":"a1","name":"A","mission":"","kind":"spot","family":"custom","template":null,"engine":"bar","state":"stopped","phase":"STOPPED","mode":"paper","venue":"spot","network":"base","universe":["ETH"],"interval":"1h","capitalUsd":"100","riskLimits":{},"configVersion":2,"strategy":null,"mandate":null,"pausedFrom":null,"live":{"capable":true,"code":null,"reason":null},"stopReason":null}"#294 private static let paused = summary.replacingOccurrences(of: #""state":"stopped","phase":"STOPPED""#, with: #""state":"paused","phase":"PAUSED""#)295 private static let kill = #"{"engaged":true,"reason":"engaged by the owner from the agents panel","at":1795040298301,"by":"owner","readOnly":false,"readOnlyReason":null,"release":{"route":"/risk","passkey":true}}"#296 private static let command = #"{"taken":"nothing","command":"pull","sessionId":null,"note":null,"result":null}"#297298 @Test func noStopActionEverNeedsAPasskey() {299 #expect(AgentStopAction.allCases.count == 7)300 #expect(AgentStopAction.allCases.allSatisfy { !$0.requiresPasskey })301 #expect(AgentStopAction.stop.isFinal && AgentStopAction.revokeMandate.isFinal && !AgentStopAction.pause.isFinal)302 // every confirmation says what will happen303 #expect(AgentStopAction.allCases.allSatisfy { !$0.title.isEmpty && $0.consequence(agent: nil).count > 30 })304 }305306 @Test func everyStopPathRunsWithoutAnAuthenticatorAndShowsTheServersAnswer() async throws {307 let a = try Fx.spotDetail().agent308 let t = ScriptedTransport(["POST /api/v1/agents/\(a.id)/pause": Self.paused, "POST /api/v1/agents/\(a.id)/stop": Self.summary, "POST /api/v1/agents/\(a.id)/revoke": Fx.spot.replacingOccurrences(of: "PAPER_TRADING", with: "STOPPED"),309 "POST /api/v1/agents/\(a.id)/perp/flatten": #"{"orders":[],"positionsLeft":0}"#, "POST /api/v1/mm/agents/\(a.id)/command": Self.command, "POST /api/v1/agents/kill-switch/engage": Self.kill])310 // the runner is built from the API alone: there is no parameter through which a passkey could be asked311 let runner = AgentStopRunner(api: AgentsAPI(client(t)))312 #expect(try await runner.run(.pause, agent: a) == AgentStateLabel.of("PAUSED").text)313 #expect(try await runner.run(.stop, agent: a) == AgentStateLabel.of("STOPPED").text)314 #expect(try await runner.run(.revokeMandate, agent: a) == AgentStateLabel.of("STOPPED").text)315 #expect(try await runner.run(.flattenPaper, agent: a).contains("0"))316 #expect(try await runner.run(.pullQuotes, agent: a).contains("pull"))317 #expect(try await runner.run(.flattenInventory, agent: a).contains("rien à faire"))318 #expect(try await runner.run(.engageKillSwitch, agent: a) == "Arrêt d’urgence engagé")319 let seen = t.seen320 #expect(seen.map(\.path) == ["/api/v1/agents/\(a.id)/pause", "/api/v1/agents/\(a.id)/stop", "/api/v1/agents/\(a.id)/revoke", "/api/v1/agents/\(a.id)/perp/flatten",321 "/api/v1/mm/agents/\(a.id)/command", "/api/v1/mm/agents/\(a.id)/command", "/api/v1/agents/kill-switch/engage"])322 // no assertion, no challenge request: nothing of a passkey ceremony travels on a stop323 #expect(seen.allSatisfy { $0.method == "POST" && !$0.body.contains("assertion") && !$0.path.contains("prepare") && !$0.path.contains("approve") })324 #expect(seen[4].body.contains(#""command":"pull""#) && seen[5].body.contains(#""command":"flatten""#))325 }326327 @Test func aKillSwitchTheServerDidNotConfirmIsNotReportedAsEngaged() async throws {328 let a = try Fx.spotDetail().agent329 let t = ScriptedTransport(["POST /api/v1/agents/kill-switch/engage": Self.kill.replacingOccurrences(of: #""engaged":true"#, with: #""engaged":false"#)])330 let said = try await AgentStopRunner(api: AgentsAPI(client(t))).run(.engageKillSwitch, agent: a)331 #expect(said.contains("PAS confirmé"))332 }333334 @Test func aRefusedStopSurfacesTheServersError() async throws {335 let a = try Fx.spotDetail().agent336 do { _ = try await AgentStopRunner(api: AgentsAPI(client(ScriptedTransport([:])))).run(.stop, agent: a); Issue.record("expected a refusal") }337 catch let e as APIError { #expect(e.status == 404 && e.code == "not_found") }338 }339}340341@Suite struct AgentStateMappingTests {342 @Test func serverStatesMapToWordsAndUnknownOnesStayVerbatim() {343 #expect(AgentStateLabel.of("PAPER_TRADING").text == "En marche" && AgentStateLabel.of("LIVE").tone == .ok)344 #expect(AgentStateLabel.of("PAUSED").text == "En pause" && AgentStateLabel.of("STOPPED").text == "Arrêté")345 #expect(AgentStateLabel.of("STOPPING").text.contains("clôture"))346 #expect(AgentStateLabel.of("SOMETHING_NEW").text == "SOMETHING_NEW" && AgentStateLabel.of("SOMETHING_NEW").tone == .neutral)347 #expect(AgentStateLabel.isRunning("PAPER_TRADING") && AgentStateLabel.isRunning("LIVE") && !AgentStateLabel.isRunning("STOPPING") && !AgentStateLabel.isRunning("CREATED"))348 #expect(AgentStateLabel.isPaused("PAUSED") && AgentStateLabel.isWindingDown("STOPPING"))349 // a created agent is not shown as running, and nothing maps to a success by default350 #expect(AgentStateLabel.of("CREATED").tone == .neutral && AgentStateLabel.of("").tone == .neutral)351 }352353 @Test func aVaultReturnIsOnlySettledWhenConfirmedAndArrived() {354 #expect(VaultReturnState.confirmed.tone == .ok && VaultReturnState.broadcast.tone == .info && VaultReturnState.failed.tone == .danger && VaultReturnState.notSent.tone == .warn)355 #expect(VaultReturnState.unknown.label == "État inconnu" && VaultReturnState.broadcast.label.contains("non confirmé"))356 #expect(AgentJobStatus.failed.tone == .danger && AgentJobStatus.queued.tone == .info && AgentJobStatus.unknown.tone == .neutral)357 }358359 @Test @MainActor func aVaultReturnKeepsItsIdempotencyKeyUntilItIsOver() {360 let v = VaultModel(agentId: "a1")361 let k = v.key(network: nil, asset: "native")362 #expect(k.range(of: "^[A-Za-z0-9_-]{8,64}$", options: .regularExpression) != nil)363 #expect(v.key(network: nil, asset: "native") == k, "a retry reuses the key")364 #expect(v.key(network: "arbitrum", asset: "native") != k && v.key(network: nil, asset: "0xabc") != k)365 v.release(network: nil, asset: "native")366 #expect(v.key(network: nil, asset: "native") != k, "a finished return frees the key for the next one")367 }368369 @Test func theOverviewSnapshotKeepsTheModeItWasSavedWith() throws {370 let s = try Fx.decode(#"{"id":"a1","name":"A","mission":"m","kind":"perp","family":"momentum","template":"momentum","engine":"bar","state":"active","phase":"PAPER_TRADING","mode":"paper","venue":"hyperliquid","network":"hyperliquid","universe":["BTC"],"interval":"1h","capitalUsd":"1000","riskLimits":{"maxLeverage":2},"configVersion":3,"strategy":{"name":"m","version":"2","sha256":"ab","path":null,"status":"approved","kind":"python"},"mandate":null,"pausedFrom":null,"live":{"capable":true,"code":null,"reason":null},"stopReason":null}"#, as: AgentSummary.self)371 let snap = AgentOverviewSnapshot(s)372 let back = try APICoding.decoder().decode(AgentOverviewSnapshot.self, from: try APICoding.encoder().encode(snap))373 #expect(back == snap && back.mode == .paper && back.phase == "PAPER_TRADING" && back.strategyVersion == "2")374 #expect(AgentsCacheKey.list.hasPrefix("agents-") && AgentsCacheKey.killSwitch.hasPrefix("agents-") && AgentsCacheKey.overview("a1").hasPrefix("agents-"))375 }376}377378@Suite struct AgentCreationFormTests {379 @Test func creationFormsStartEmptyAndNameWhatIsMissing() {380 #expect(SpotCreateForm().problem(maxSymbols: 12) != nil && SpotCreateForm().request(assets: [:], maxSymbols: 12) == nil)381 #expect(PerpCreateForm().problem(maxInstruments: 8, minCapital: "50") != nil && PerpCreateForm().request(maxInstruments: 8, minCapital: "50") == nil)382 let s = SpotCreateForm(), p = PerpCreateForm()383 #expect(s.capital.isEmpty && s.lossPct.isEmpty && s.maxOrder.isEmpty && s.maxDaily.isEmpty && s.ordersPerDay.isEmpty && s.mandateDays.isEmpty && s.network == nil && s.symbols.isEmpty)384 #expect(p.maxLeverage.isEmpty && p.capital.isEmpty && p.totalLossPct.isEmpty && p.instruments.isEmpty)385 }386387 @Test func aSpotRequestCarriesExactlyWhatWasTyped() throws {388 var f = SpotCreateForm(name: " Mon agent ", mission: "", network: "base", symbols: ["ETH", "BTC"], cash: "USDC", interval: "1h", capital: "100", exposurePct: "50", lossPct: "10", maxOrder: "20", maxDaily: "50", ordersPerDay: "5", mandateDays: "7", slippageBps: "50")389 #expect(f.problem(maxSymbols: 12) == nil)390 let r = try #require(f.request(assets: [:], maxSymbols: 12))391 #expect(r.name == "Mon agent" && r.universe == ["BTC", "ETH"] && r.capitalUsdc == "100" && r.risk.maxOrderUsd.text == "20" && r.risk.maxDailyUsd.text == "50" && r.risk.mandateDays == 7 && r.risk.maxLossPct == 10)392 f.mandateDays = ""; #expect(f.request(assets: [:], maxSymbols: 12) == nil)393 f.mandateDays = "91"; #expect(f.problem(maxSymbols: 12) != nil)394 f.mandateDays = "7"; f.maxDaily = "10"; #expect(f.problem(maxSymbols: 12) != nil, "a daily cap below the per-order cap is refused")395 f.maxDaily = "50"; f.lossPct = "0"; #expect(f.problem(maxSymbols: 12) != nil)396 }397398 @Test func aPerpRequestStaysInsideTheServersBounds() throws {399 var f = PerpCreateForm(name: "P", mission: "", instruments: ["BTC"], interval: "1h", capital: "1000", maxLeverage: "2", grossX: "1,5", positionX: "1", dailyLossPct: "3", totalLossPct: "10", slippageBps: "30", minTradePct: "2")400 let r = try #require(f.request(maxInstruments: 8, minCapital: "50"))401 #expect(r.kind == "perp" && r.risk.maxLeverage == 2 && r.risk.maxGrossExposureX == 1.5 && r.capitalUsdc == "1000")402 f.maxLeverage = "6"; #expect(f.problem(maxInstruments: 8, minCapital: "50") != nil)403 f.maxLeverage = "2"; f.capital = "10"; #expect(f.problem(maxInstruments: 8, minCapital: "50") != nil)404 f.capital = "1000"; f.dailyLossPct = "20"; #expect(f.problem(maxInstruments: 8, minCapital: "50") != nil, "the daily loss cannot exceed the total loss")405 }406407 @Test func templateValuesKeepTheTypeOfTheProposalAndAreNeverFilledForTheOwner() {408 #expect(TemplateCreateForm.value("500", like: .int(1)) == .int(500))409 #expect(TemplateCreateForm.value("2,5", like: .int(1)) == .double(2.5))410 #expect(TemplateCreateForm.value("250", like: .string("50")) == .string("250"))411 #expect(TemplateCreateForm.value("abc", like: .string("50")) == nil)412 #expect(TemplateCreateForm.value("spread_inventory", like: .string("as")) == .string("spread_inventory"))413 #expect(TemplateCreateForm.value("false", like: .bool(true)) == .bool(false) && TemplateCreateForm.value("maybe", like: .bool(true)) == nil)414 #expect(TemplateCreateForm.value("", like: .int(1)) == nil)415 let f = TemplateCreateForm()416 #expect(f.risk.isEmpty && f.config.isEmpty && f.capital.isEmpty && f.strategyPath == nil)417 }418}419