Bucksley / app · bucksley.ai / Tests / BucksleyKitTests / BucksleyKitTests.swift
| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import BucksleyKit |
| 4 | |
| 5 | /// Recorded responses for the connector tests. |
| 6 | struct StubHTTP: HTTPClient { |
| 7 | let handler: @Sendable (URLRequest) -> (Int, String) |
| 8 | func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { |
| 9 | let (status, body) = handler(request) |
| 10 | return (Data(body.utf8), HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!) |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | func tempStore() throws -> WorkspaceStore { |
| 15 | if Keychain.memory == nil { Keychain.memory = [:] } // shared by parallel tests; never wipe it mid-run |
| 16 | return try WorkspaceStore(folder: FileManager.default.temporaryDirectory.appendingPathComponent("bucksley-tests-\(UUID().uuidString)")) |
| 17 | } |
| 18 | |
| 19 | func tx(_ id: String, _ day: String, _ amount: Decimal, _ text: String, account: String = "a1", pending: Bool = false, category: String? = nil) -> Transaction { |
| 20 | Transaction(id: id, accountID: account, day: day, amount: amount, description: text, bankCategory: category, pending: pending) |
| 21 | } |
| 22 | |
| 23 | @Suite struct Resolving { |
| 24 | @Test func userEditsWinOverRulesAndBankData() { |
| 25 | let t = tx("t1", "2026-11-02", -84.27, "TRADER JOE S #552 OAKLAND CA") |
| 26 | let rule = Rule(matchText: "trader joe", setCategoryID: "dining", rename: "TJ's") |
| 27 | var edit = TransactionEdit(transactionID: "t1"); edit.categoryID = "groceries"; edit.note = "Thanksgiving" |
| 28 | let plain = Ledger.resolve(t, rules: [], edit: nil) |
| 29 | #expect(plain.categoryID == "groceries") |
| 30 | #expect(plain.name == "Trader Joe S") |
| 31 | let ruled = Ledger.resolve(t, rules: [rule], edit: nil) |
| 32 | #expect(ruled.categoryID == "dining" && ruled.name == "TJ's" && ruled.ruleID == rule.id) |
| 33 | let edited = Ledger.resolve(t, rules: [rule], edit: edit) |
| 34 | #expect(edited.categoryID == "groceries" && edited.name == "TJ's" && edited.note == "Thanksgiving" && edited.edited) |
| 35 | } |
| 36 | |
| 37 | @Test func mccAndKeywordsPickCategories() { |
| 38 | #expect(Defaults.guessCategory(tx("x", "2026-11-01", -5.5, "LOCAL GROCER STORE", category: "mcc:5411")) == "groceries") |
| 39 | #expect(Defaults.guessCategory(tx("x", "2026-11-01", -17.99, "NETFLIX.COM")) == "subscriptions") |
| 40 | #expect(Defaults.guessCategory(tx("x", "2026-11-01", 3420, "ACME PAYROLL DIRECT DEP")) == "income") |
| 41 | #expect(Defaults.guessCategory(tx("x", "2026-11-01", -500, "CHASE CREDIT CARD PAYMENT")) == "transfer") |
| 42 | #expect(Defaults.cleanName("SQ *BLUE BOTTLE COFFEE 0423 OAKLAND CA") == "Blue Bottle Coffee") |
| 43 | } |
| 44 | |
| 45 | @Test func rulesRespectAmountAndAccount() { |
| 46 | let rule = Rule(matchText: "amazon", minAmount: 100, accountID: "a1", setCategoryID: "home") |
| 47 | #expect(rule.matches(tx("1", "2026-11-01", -150, "AMAZON MKTPLACE"))) |
| 48 | #expect(!rule.matches(tx("2", "2026-11-01", -50, "AMAZON MKTPLACE"))) |
| 49 | #expect(!rule.matches(tx("3", "2026-11-01", -150, "AMAZON MKTPLACE", account: "a2"))) |
| 50 | } |
| 51 | |
| 52 | @Test func splitsCountTowardEachCategory() throws { |
| 53 | let store = try tempStore() |
| 54 | try store.upsert([tx("t1", DayKey.today, -100, "COSTCO WHOLESALE")]) |
| 55 | try store.edit("t1") { $0.splits = [Split(amount: 70, categoryID: "groceries"), Split(amount: 30, categoryID: "home")] } |
| 56 | let ledger = try store.ledger() |
| 57 | #expect(ledger.spent("groceries", month: MonthKey.current) == 70) |
| 58 | #expect(ledger.spent("home", month: MonthKey.current) == 30) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | @Suite struct Store { |
| 63 | @Test func postedChargeReplacesItsPendingOne() throws { |
| 64 | let store = try tempStore() |
| 65 | try store.upsert([tx("p1", "2026-11-20", -42.10, "SHELL OIL 1234", pending: true)]) |
| 66 | let counts = try store.upsert([tx("posted-9", "2026-11-22", -42.10, "SHELL OIL 1234")]) |
| 67 | #expect(counts.updated == 1 && counts.added == 0) |
| 68 | #expect(try store.transactions().map(\.id) == ["posted-9"]) |
| 69 | } |
| 70 | |
| 71 | @Test func newerEditWinsFieldByField() throws { |
| 72 | let store = try tempStore() |
| 73 | try store.edit("t1", device: "Mac") { $0.note = "from the Mac"; $0.categoryID = "dining" } |
| 74 | var phone = TransactionEdit(transactionID: "t1", updatedAt: Date.now.addingTimeInterval(60), device: "iPhone") |
| 75 | phone.reviewed = true |
| 76 | #expect(try store.mergeEdits([phone]) == 1) |
| 77 | let merged = try store.edits()["t1"]! |
| 78 | #expect(merged.reviewed == true && merged.note == "from the Mac" && merged.categoryID == "dining" && merged.device == "iPhone") |
| 79 | var stale = TransactionEdit(transactionID: "t1", updatedAt: .distantPast, device: "iPhone"); stale.reviewed = false |
| 80 | #expect(try store.mergeEdits([stale]) == 0) |
| 81 | #expect(try store.edits()["t1"]!.reviewed == true) |
| 82 | } |
| 83 | |
| 84 | @Test func balancesBackfillFromTransactions() throws { |
| 85 | let store = try tempStore() |
| 86 | let today = "2026-11-25" |
| 87 | try store.upsert([tx("1", "2026-11-25", -100, "A"), tx("2", "2026-11-24", 500, "B"), tx("3", "2026-11-20", -50, "C")]) |
| 88 | let account = Account(id: "a1", connectionID: "c", name: "Checking", institution: "Bank", kind: .checking, balance: 1000) |
| 89 | try store.recordBalances([account], today: today) |
| 90 | let points = Dictionary(uniqueKeysWithValues: try store.balances().map { ($0.day, $0.balance) }) |
| 91 | #expect(points["2026-11-25"] == 1000) |
| 92 | #expect(points["2026-11-24"] == 1100) |
| 93 | #expect(points["2026-11-23"] == 600) |
| 94 | #expect(points["2026-11-19"] == 650) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | @Suite struct Budgets { |
| 99 | func ledger(budgets: [Budget], txs: [Transaction]) throws -> Ledger { |
| 100 | let store = try tempStore() |
| 101 | try store.upsert(txs) |
| 102 | try store.update { $0.budgets = budgets } |
| 103 | return try store.ledger() |
| 104 | } |
| 105 | |
| 106 | @Test func rolloverCarriesWhatWasLeft() throws { |
| 107 | let l = try ledger(budgets: [Budget(categoryID: "groceries", amount: 600, rollover: true, startMonth: "2026-09")], |
| 108 | txs: [tx("1", "2026-09-10", -500, "TRADER JOES"), tx("2", "2026-10-10", -650, "TRADER JOES"), tx("3", "2026-11-05", -300, "TRADER JOES")]) |
| 109 | let status = l.budgetStatus(month: "2026-11", today: "2026-11-15").first! |
| 110 | #expect(status.carried == 50) // +100 in Sep, −50 in Oct |
| 111 | #expect(status.available == 650 && status.spent == 300 && status.remaining == 350) |
| 112 | #expect(abs(Decimal(status.pace) - Decimal(0.5)) < Decimal(0.01)) |
| 113 | } |
| 114 | |
| 115 | @Test func paceFlagsOverspendingEarly() throws { |
| 116 | let l = try ledger(budgets: [Budget(categoryID: "dining", amount: 300)], txs: [tx("1", "2026-11-03", -240, "SWEETGREEN")]) |
| 117 | let status = l.budgetStatus(month: "2026-11", today: "2026-11-10").first! |
| 118 | #expect(status.aheadOfPace) |
| 119 | #expect(AskBucksley.suggestion(l, today: "2026-11-10")?.contains("Dining") == true) |
| 120 | } |
| 121 | |
| 122 | @Test func suggestionsComeFromPastMonths() throws { |
| 123 | var txs: [Transaction] = [] |
| 124 | for (i, m) in ["2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10"].enumerated() { |
| 125 | txs.append(tx("g\(i)", m + "-12", -Decimal(480 + i * 10), "WHOLE FOODS")) |
| 126 | } |
| 127 | let l = try ledger(budgets: [], txs: txs) |
| 128 | let s = l.budgetSuggestions(today: "2026-11-15") |
| 129 | #expect(s.first?.categoryID == "groceries") |
| 130 | #expect(s.first?.amount == 475) // last three months average $520, less 8%, to the nearest $25 |
| 131 | #expect(Ledger.friendly(312) == 325 && Ledger.friendly(87) == 90 && Ledger.friendly(12) == 15) |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | @Suite struct Recurring { |
| 136 | @Test func findsMonthlySubscriptions() throws { |
| 137 | let store = try tempStore() |
| 138 | try store.upsert(["2026-08-03", "2026-09-03", "2026-10-03", "2026-11-03"].enumerated().map { tx("n\($0)", $1, -17.99, "NETFLIX.COM") } |
| 139 | + [tx("x1", "2026-10-07", -12, "RANDOM CAFE"), tx("x2", "2026-11-19", -40, "RANDOM CAFE"), tx("x3", "2026-11-20", -9, "RANDOM CAFE")]) |
| 140 | let items = try store.ledger().recurring(today: "2026-11-20") |
| 141 | #expect(items.count == 1) |
| 142 | #expect(items.first?.cadence == .monthly && items.first?.nextDay == "2026-12-03" && items.first?.amount == Decimal(string: "17.99")) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | @Suite struct Connectors { |
| 147 | static let simplefinBody = """ |
| 148 | {"errors":[],"accounts":[{"org":{"domain":"beta-bridge.simplefin.org","name":"SimpleFIN Demo"},"id":"ACT-1","name":"SimpleFIN Checking","currency":"USD", |
| 149 | "balance":"24119.91","available-balance":"24119.91","balance-date":1795600000, |
| 150 | "transactions":[{"id":"T1","posted":1795500000,"amount":"-05.50","description":"Grocery store","payee":"Grocery store","memo":"LOCAL GROCER","transacted_at":1795500000,"mcc":"5411"}]}, |
| 151 | {"org":{"name":"Card Co"},"id":"ACT-2","name":"Rewards Card","currency":"USD","balance":"-1236.18","balance-date":1795600000,"transactions":[]}]} |
| 152 | """ |
| 153 | |
| 154 | @Test func simpleFINClaimAndPull() async throws { |
| 155 | let http = StubHTTP { request in |
| 156 | if request.httpMethod == "POST" { return (200, "https://user:pass@bridge.example/simplefin") } |
| 157 | #expect(request.value(forHTTPHeaderField: "Authorization") == "Basic " + Data("user:pass".utf8).base64EncodedString()) |
| 158 | #expect(request.url!.absoluteString.hasPrefix("https://bridge.example/simplefin/accounts?start-date=")) |
| 159 | return (200, Connectors.simplefinBody) |
| 160 | } |
| 161 | let token = Data("https://bridge.example/simplefin/claim/abc".utf8).base64EncodedString() |
| 162 | let access = try await SimpleFIN(http: http).claim(setupToken: token) |
| 163 | #expect(access == "https://user:pass@bridge.example/simplefin") |
| 164 | let now = Date(timeIntervalSince1970: 1795600000) |
| 165 | let pull = try await SimpleFIN(http: http).pull(accessURL: access, connectionID: "c1", since: now.addingTimeInterval(-86_400 * 30), now: now) |
| 166 | #expect(pull.accounts.count == 2) |
| 167 | #expect(pull.accounts.first { $0.name == "Rewards Card" }?.kind == .credit) |
| 168 | #expect(pull.transactions.first?.amount == Decimal(string: "-5.5")) |
| 169 | #expect(pull.transactions.first?.bankCategory == "mcc:5411") |
| 170 | } |
| 171 | |
| 172 | @Test func accountKindGuessReadsBankNames() { |
| 173 | #expect(AccountKind.guess(from: "Adv Plus Banking- 2623 (2623)") == .checking) |
| 174 | #expect(AccountKind.guess(from: "Advantage Savings- 5401 (5401)") == .savings) |
| 175 | #expect(AccountKind.guess(from: "Unlimited Cash Rewards Visa Signature- 0626 (0626)") == .credit) |
| 176 | #expect(AccountKind.guess(from: "Business Adv Unlimited Cash Rewards - 1342 (1342)") == .credit) |
| 177 | #expect(AccountKind.guess(from: "Merrill Edge Self-Directed CMA-Edge 1234") == .investment) |
| 178 | #expect(AccountKind.guess(from: "CMA-Edge- 5Z04 (5Z04)") == .investment) |
| 179 | #expect(AccountKind.guess(from: "Roth IRA - 7781") == .investment) |
| 180 | #expect(AccountKind.guess(from: "Company 401(k)") == .investment) |
| 181 | #expect(AccountKind.guess(from: "Total Checking 4401") == .checking) |
| 182 | } |
| 183 | |
| 184 | @Test func simpleFINVersion2ConnectionsAndErrors() async throws { |
| 185 | let body = """ |
| 186 | {"errlist":[{"code":"con.auth","msg":"Authentication failed for Merrill - the owner","conn_id":"CON-M"}], |
| 187 | "connections":[{"conn_id":"CON-B","name":"BofA - the owner","org_id":"bofa","org_name":"Bank of America","sfin_url":"x"}, |
| 188 | {"conn_id":"CON-M","name":"Merrill - the owner","org_id":"ml","org_name":"Merrill","sfin_url":"x"}, |
| 189 | {"conn_id":"CON-F","name":"Fidelity","org_id":"f","org_name":"Fidelity","sfin_url":"x"}], |
| 190 | "accounts":[{"id":"ACT-1","name":"Adv Plus Banking- 2623 (2623)","conn_id":"CON-B","currency":"USD","balance":"3067.98","available-balance":"2884.03","balance-date":1795600000,"transactions":[{"id":"T1","posted":1795500000,"amount":"-5","description":"Coffee"},{"bad":true}]}, |
| 191 | {"id":"ACT-2","name":"CMA-Edge","conn_id":"CON-M","currency":"USD","balance":1520.5,"balance-date":1795600000, |
| 192 | "holdings":[{"id":"H1","symbol":"VTI","description":"Vanguard Total Stock Market ETF","shares":"4.5","market_value":"1320.50","cost_basis":"1100"},{"id":"H2","description":"Cash","market_value":200}]}]} |
| 193 | """ |
| 194 | let http = StubHTTP { request in |
| 195 | #expect(request.url!.query!.contains("version=2")) |
| 196 | return (200, body) |
| 197 | } |
| 198 | let now = Date(timeIntervalSince1970: 1795600000) |
| 199 | let pull = try await SimpleFIN(http: http).pull(accessURL: "https://u:p@bridge.example/simplefin", connectionID: "c1", since: now.addingTimeInterval(-86_400 * 10), now: now) |
| 200 | #expect(pull.accounts.count == 2) |
| 201 | #expect(pull.accounts.first { $0.name.hasPrefix("Adv Plus") }?.institution == "Bank of America") |
| 202 | #expect(pull.accounts.first { $0.name.hasPrefix("Adv Plus") }?.kind == .checking) |
| 203 | #expect(pull.accounts.first { $0.name == "CMA-Edge" }?.balance == Decimal(string: "1520.5")) |
| 204 | #expect(pull.accounts.first { $0.name == "CMA-Edge" }?.kind == .investment) |
| 205 | let holdings = pull.accounts.first { $0.name == "CMA-Edge" }?.holdings ?? [] |
| 206 | #expect(holdings.count == 2 && holdings[0].symbol == "VTI" && holdings[0].gain == Decimal(string: "220.5")) |
| 207 | #expect(pull.transactions.count == 1) |
| 208 | #expect(pull.warnings.contains { $0.contains("Merrill needs you to sign in again") }) |
| 209 | #expect(pull.warnings.contains { $0.hasPrefix("Fidelity is connected in SimpleFIN Bridge but sent no accounts") }) |
| 210 | } |
| 211 | |
| 212 | @Test func syncKeepsAHandPickedKindButFixesOldGuesses() throws { |
| 213 | let store = try tempStore() |
| 214 | let connection = Connection(kind: .simplefin, name: "SimpleFIN Bridge") |
| 215 | var stale = Account(id: "a1", connectionID: connection.id, name: "Adv Plus Banking", institution: "BofA", kind: .other, balance: 10) |
| 216 | var picked = Account(id: "a2", connectionID: connection.id, name: "Joint", institution: "BofA", kind: .savings, balance: 10) |
| 217 | picked.kindChosen = true |
| 218 | try store.update { $0.accounts = [stale, picked]; $0.connections = [connection] } |
| 219 | stale.kind = .checking |
| 220 | var fresh = picked; fresh.kind = .other; fresh.kindChosen = nil |
| 221 | var pull = BankPull(); pull.accounts = [stale, fresh] |
| 222 | try BankSync(store: store).apply(pull, to: connection) |
| 223 | let accounts = try store.load().accounts |
| 224 | #expect(accounts.first { $0.id == "a1" }?.kind == .checking) |
| 225 | #expect(accounts.first { $0.id == "a2" }?.kind == .savings) |
| 226 | } |
| 227 | |
| 228 | @Test func plaidSyncNegatesAmountsAndPaginates() async throws { |
| 229 | nonisolated(unsafe) var pages = 0 |
| 230 | let http = StubHTTP { request in |
| 231 | let body = (try? JSONSerialization.jsonObject(with: request.httpBody!)) as? [String: Any] ?? [:] |
| 232 | #expect(body["client_id"] as? String == "cid" && body["secret"] as? String == "sec") |
| 233 | switch request.url!.path { |
| 234 | case "/accounts/balance/get": |
| 235 | return (200, #"{"item":{"institution_name":"First Platypus Bank"},"accounts":[{"account_id":"A","name":"Plaid Checking","mask":"0000","type":"depository","subtype":"checking","balances":{"current":110,"available":100,"iso_currency_code":"USD"}},{"account_id":"B","name":"Plaid Credit Card","type":"credit","subtype":"credit card","balances":{"current":410,"iso_currency_code":"USD"}}]}"#) |
| 236 | case "/transactions/sync": |
| 237 | pages += 1 |
| 238 | if pages == 1 { return (200, #"{"added":[{"transaction_id":"t1","account_id":"A","amount":6.33,"date":"2026-11-20","name":"Uber 072515 SF**POOL**","merchant_name":"Uber","pending":false,"personal_finance_category":{"primary":"TRANSPORTATION","detailed":"TRANSPORTATION_TAXIS_AND_RIDE_SHARES"}}],"modified":[],"removed":[],"next_cursor":"c1","has_more":true}"#) } |
| 239 | return (200, #"{"added":[{"transaction_id":"t2","account_id":"A","amount":-500,"date":"2026-11-21","name":"ACME PAYROLL","pending":false}],"modified":[],"removed":[{"transaction_id":"old","account_id":"A"}],"next_cursor":"c2","has_more":false}"#) |
| 240 | default: return (400, #"{"error_message":"unexpected"}"#) |
| 241 | } |
| 242 | } |
| 243 | let pull = try await Plaid(environment: .sandbox, clientID: "cid", secret: "sec", http: http).pull(accessToken: "access", connectionID: "p", institution: "Bank", cursor: nil) |
| 244 | #expect(pull.accounts.first { $0.name.hasPrefix("Plaid Credit") }?.balance == -410) |
| 245 | #expect(pull.accounts.first?.institution == "First Platypus Bank") |
| 246 | #expect(pull.transactions.map(\.amount) == [Decimal(string: "-6.33")!, 500]) |
| 247 | #expect(pull.removedTransactionIDs == ["p:A:old"] && pull.plaidCursor == "c2") |
| 248 | #expect(Defaults.guessCategory(pull.transactions[0]) == "transport") |
| 249 | } |
| 250 | |
| 251 | @Test func plaidErrorsAreReadable() async throws { |
| 252 | let http = StubHTTP { _ in (400, #"{"error_code":"ITEM_LOGIN_REQUIRED","error_message":"login required"}"#) } |
| 253 | await #expect(throws: BucksleyError.self) { |
| 254 | _ = try await Plaid(environment: .sandbox, clientID: "a", secret: "b", http: http).pull(accessToken: "x", connectionID: "p", institution: "Bank", cursor: nil) |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | @Test func copilotCSVKeepsCategoriesNotesAndTags() throws { |
| 259 | let csv = """ |
| 260 | date,name,amount,status,category,parent category,excluded,tags,type,account,account mask,note,recurring |
| 261 | 2026-11-02,Trader Joe's,84.27,posted,Groceries,Food,false,"family, weekly",regular,Sapphire Card,1234,"Turkey, stuffing", |
| 262 | 2026-11-03,Payroll,-3420.00,posted,Paycheck,,false,,income,Checking,9876,, |
| 263 | 2026-11-04,Netflix,17.99,posted,Subscriptions,,true,,regular,Sapphire Card,1234,,Netflix |
| 264 | """ |
| 265 | let store = try tempStore() |
| 266 | let result = try BankSync(store: store).importCSV(csv, fileName: "copilot.csv") |
| 267 | #expect(result.transactions == 3 && result.accounts == 2) |
| 268 | let ledger = try store.ledger() |
| 269 | let tj = ledger.entries.first { $0.transaction.description == "Trader Joe's" }! |
| 270 | #expect(tj.amount == Decimal(string: "-84.27") && tj.categoryID == "groceries" && tj.note == "Turkey, stuffing" && tj.tags == ["family", "weekly"] && tj.reviewed) |
| 271 | let pay = ledger.entries.first { $0.transaction.description == "Payroll" }! |
| 272 | #expect(pay.amount == 3420 && ledger.workspace.category(pay.categoryID)?.kind == .income) |
| 273 | #expect(ledger.entries.first { $0.transaction.description == "Netflix" }!.excluded) |
| 274 | #expect(CSVImport.rowsOf("a,\"b,\"\"c\"\"\"\n1,2").last == ["1", "2"]) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | @Suite struct Agents { |
| 279 | func rpc(_ server: MCPServer, _ method: String, _ params: [String: Any] = [:]) async -> [String: Any] { |
| 280 | await server.handle(["jsonrpc": "2.0", "id": 1, "method": method, "params": params]) ?? [:] |
| 281 | } |
| 282 | |
| 283 | @Test func readToolsWorkAndWritesAreGatedAndLogged() async throws { |
| 284 | let store = try tempStore() |
| 285 | try store.upsert([tx("t1", DayKey.today, -42, "SHELL OIL")]) |
| 286 | try store.update { $0.accounts = [Account(id: "a1", connectionID: "c", name: "Checking", institution: "Bank", kind: .checking, balance: 900)] } |
| 287 | let server = MCPServer(store: store, sync: { BankSync.Report() }) |
| 288 | let initialize = await rpc(server, "initialize", ["protocolVersion": "2025-06-18", "clientInfo": ["name": "Claude Code"]]) |
| 289 | #expect((initialize["result"] as? [String: Any])?["protocolVersion"] as? String == "2025-06-18") |
| 290 | let list = await rpc(server, "tools/list") |
| 291 | let tools = ((list["result"] as? [String: Any])?["tools"] as? [[String: Any]]) ?? [] |
| 292 | #expect(tools.count == MCPServer.tools.count) |
| 293 | #expect(tools.allSatisfy { ($0["annotations"] as? [String: Any])?["destructiveHint"] as? Bool == false }) |
| 294 | |
| 295 | let status = await rpc(server, "tools/call", ["name": "get_status", "arguments": [:]]) |
| 296 | #expect(((status["result"] as? [String: Any])?["structuredContent"] as? [String: Any])?["review_queue"] as? Int == 1) |
| 297 | |
| 298 | let blocked = await rpc(server, "tools/call", ["name": "mark_reviewed", "arguments": ["transaction_ids": ["t1"]]]) |
| 299 | #expect((blocked["result"] as? [String: Any])?["isError"] as? Bool == true) |
| 300 | |
| 301 | try store.update { $0.settings.agentsCanWrite = true } |
| 302 | _ = await rpc(server, "tools/call", ["name": "mark_reviewed", "arguments": ["transaction_ids": ["t1"]]]) |
| 303 | _ = await rpc(server, "tools/call", ["name": "set_budget", "arguments": ["category_id": "gas", "amount": 200]]) |
| 304 | let ledger = try store.ledger() |
| 305 | #expect(ledger.reviewQueue.isEmpty) |
| 306 | #expect(ledger.workspace.budgets.first?.amount == 200) |
| 307 | #expect(ledger.workspace.agentLog.count == 2 && ledger.workspace.agentLog.allSatisfy { $0.client == "Claude Code" }) |
| 308 | #expect(try store.edits()["t1"]?.device == "Claude Code") |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | @Suite struct Ask { |
| 313 | @Test func offlineAnswersUseTheNumbers() throws { |
| 314 | let store = try tempStore() |
| 315 | try store.upsert([tx("1", DayKey.today, -84.27, "TRADER JOES")]) |
| 316 | let answer = AskBucksley.offlineAnswer("How much on groceries?", ledger: try store.ledger()) |
| 317 | #expect(answer.contains("$84.27") && answer.contains("Groceries")) |
| 318 | #expect(AskBucksley.context(try store.ledger()).contains("Trader Joes")) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | @Suite struct Snapshots { |
| 323 | @Test func phoneAdoptsSnapshotWithoutLosingItsNewerEdits() throws { |
| 324 | let mac = try tempStore(), phone = try tempStore() |
| 325 | try mac.upsert([tx("t1", DayKey.today, -10, "A"), tx("t2", DayKey.today, -20, "B")]) |
| 326 | try mac.edit("t1", device: "Mac") { $0.note = "mac note" } |
| 327 | try phone.edit("t2", device: "iPhone") { $0.reviewed = true } |
| 328 | try phone.adopt(try CloudSync.snapshot(from: mac)) |
| 329 | let ledger = try phone.ledger() |
| 330 | #expect(ledger.entries.count == 2) |
| 331 | #expect(ledger.entries.first { $0.id == "t1" }?.note == "mac note") |
| 332 | #expect(ledger.entries.first { $0.id == "t2" }?.reviewed == true) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | @Suite struct StandardSettings { |
| 337 | func defaults() -> UserDefaults { |
| 338 | let name = "bucksley-tests-\(UUID().uuidString)" |
| 339 | return UserDefaults(suiteName: name)! |
| 340 | } |
| 341 | |
| 342 | @Test func cardWaitsForTheMilestone() { |
| 343 | let d = defaults() |
| 344 | for _ in 0..<4 { SupportPrompt.recordCoreAction(in: d) } |
| 345 | #expect(!SupportPrompt.claim(in: d)) |
| 346 | SupportPrompt.recordCoreAction(in: d) |
| 347 | #expect(SupportPrompt.claim(in: d)) |
| 348 | } |
| 349 | |
| 350 | @Test func cardReturnsWeeklyUntilEveryBoxIsClicked() { |
| 351 | let d = defaults() |
| 352 | for _ in 0..<5 { SupportPrompt.recordCoreAction(in: d) } |
| 353 | let start = Date(timeIntervalSince1970: 1_800_000_000) |
| 354 | #expect(SupportPrompt.claim(now: start, in: d)) |
| 355 | #expect(!SupportPrompt.claim(now: start.addingTimeInterval(6 * 86_400), in: d)) // 7-day wait |
| 356 | #expect(!SupportPrompt.record(.feedback, in: d)) // one click doesn't stop it |
| 357 | #expect(SupportPrompt.claim(now: start.addingTimeInterval(7 * 86_400 + 1), in: d)) |
| 358 | for action in [SupportPrompt.Action.share, .support] { SupportPrompt.record(action, in: d) } |
| 359 | #expect(SupportPrompt.record(.apps, in: d)) // all four now |
| 360 | #expect(!SupportPrompt.claim(now: start.addingTimeInterval(30 * 86_400), in: d)) |
| 361 | } |
| 362 | |
| 363 | @Test func dontShowAgainStopsTheCardForGood() { |
| 364 | let name = "bucksley-tests-\(UUID().uuidString)" |
| 365 | let d = UserDefaults(suiteName: name)! |
| 366 | for _ in 0..<5 { SupportPrompt.recordCoreAction(in: d) } |
| 367 | let start = Date(timeIntervalSince1970: 1_800_000_000) |
| 368 | #expect(SupportPrompt.claim(now: start, in: d)) |
| 369 | SupportPrompt.dismissForGood(in: d) |
| 370 | #expect(SupportPrompt.isDismissedForGood(in: d)) |
| 371 | #expect(!SupportPrompt.claim(now: start.addingTimeInterval(8 * 86_400), in: d)) |
| 372 | // A fresh read of the same store (as after a relaunch) still keeps it hidden. |
| 373 | let relaunched = UserDefaults(suiteName: name)! |
| 374 | #expect(!SupportPrompt.claim(now: start.addingTimeInterval(365 * 86_400), in: relaunched)) |
| 375 | } |
| 376 | |
| 377 | @Test func reviewIsRequestedOnceAfterFiveActions() { |
| 378 | let d = defaults() |
| 379 | #expect(!SupportPrompt.claimReview(in: d)) |
| 380 | for _ in 0..<5 { SupportPrompt.recordCoreAction(in: d) } |
| 381 | #expect(SupportPrompt.claimReview(in: d)) |
| 382 | #expect(!SupportPrompt.claimReview(in: d)) |
| 383 | } |
| 384 | |
| 385 | @Test func supportActionsCollectNoMoney() { |
| 386 | #expect(SupportPrompt.Action.allCases == [.feedback, .share, .support, .apps]) |
| 387 | #expect(SupportPrompt.clicked("tip,share") == [.share]) // old stored tip clicks are ignored |
| 388 | } |
| 389 | } |