SPB Git

Repository Public License

LogicTests.swift 24.9 KB 386 lines swift

1// ORIX OS Automation2// File: Packages/ORIXFeatureRuns/Tests/ORIXFeatureRunsTests/LogicTests.swift3// Description: Unit tests of the pure logic: trigger sentences, cron builder, agenda across daylight-saving changes, schedule drafts, console buffer and assembler, export formats, metric aggregation.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXAppUI9@testable import ORIXFeatureRuns10import Testing1112private let en = Locale(identifier: "en_US")1314@Suite("Unit · trigger descriptions")15struct TriggerDescriptionTests {16    @Test(arguments: [17        ("* * * * *", "Every minute"),18        ("*/5 * * * *", "Every 5 minutes"),19        ("0 * * * *", "Every hour, on the hour"),20        ("30 * * * *", "Every hour at minute 30"),21        ("@hourly", "Every hour, on the hour"),22        ("15 */2 * * *", "Every 2 hours at minute 15"),23        ("0 9 * * *", "Every day at 09:00"),24        ("@daily", "Every day at 00:00"),25        ("30 7,18 * * *", "Every day at 07:30 and 18:30"),26        ("0 9 * * MON", "Every Monday at 09:00"),27        ("0 9 * * 1", "Every Monday at 09:00"),28        ("0 9 * * 1-5", "Every weekday at 09:00"),29        ("0 9 * * MON-FRI", "Every weekday at 09:00"),30        ("0 8 * * 1,3,5", "Every Monday, Wednesday, and Friday at 08:00"),31        ("0 10 * * 6,0", "Every Sunday and Saturday at 10:00"),32        ("0 10 * * 7", "Every Sunday at 10:00"),33        ("@weekly", "Every Sunday at 00:00"),34        ("0 6 1 * *", "On day 1 of every month at 06:00"),35        ("0 6 1,15 * *", "On days 1 and 15 of every month at 06:00"),36        ("@monthly", "On day 1 of every month at 00:00"),37        ("0 0 1 1 *", "Every year on January 1 at 00:00"),38        ("0 12 25 DEC *", "Every year on December 25 at 12:00"),39        ("0 9 * 1,7 *", "Every day in January and July at 09:00"),40        ("0 9-17 * * 1-5", "Every weekday, every hour from 09:00 to 17:00"),41        ("*/15 9-17 * * *", "Every 15 minutes from 09:00 to 17:59"),42        ("0 9 13 * 5", "On day 13 of the month or every Friday at 09:00"),43        ("*/10 * * * 1-5", "Every weekday, every 10 minutes"),44    ])45    func cronShapes(expression: String, expected: String) {46        #expect(TriggerDescriber.describeCron(expression, locale: en) == expected)47    }4849    @Test func invalidCronIsRefusedNotGuessed() {50        #expect(TriggerDescriber.describeCron("61 * * * *", locale: en) == nil)51        #expect(TriggerDescriber.describeCron("not cron", locale: en) == nil)52        #expect(TriggerDescriber.describe(.cron(expression: "bad", timezone: nil), locale: en).contains("Invalid schedule"))53    }5455    @Test func fullSentencesCarryZoneAndPath() {56        #expect(TriggerDescriber.describe(.cron(expression: "0 9 * * MON", timezone: "America/Toronto"), locale: en) == "Every Monday at 09:00 (America/Toronto)")57        #expect(TriggerDescriber.describe(.cron(expression: "0 9 * * *", timezone: nil), locale: en) == "Every day at 09:00 (this Mac's time zone)")58        let folder = NSHomeDirectory() + "/Documents/Research"59        #expect(TriggerDescriber.describe(.fileChange(path: folder, recursive: true, glob: nil, debounceSeconds: 2), locale: en) == "When files change in ~/Documents/Research")60        #expect(TriggerDescriber.describe(.fileChange(path: folder, recursive: true, glob: "*.pdf", debounceSeconds: 2), locale: en) == "When files matching *.pdf change in ~/Documents/Research")61        #expect(TriggerDescriber.describe(.fileChange(path: folder, recursive: false, glob: nil, debounceSeconds: 2), locale: en).hasSuffix("(top level only)"))62        #expect(TriggerDescriber.describe(.login) == "When you log in")63        #expect(TriggerDescriber.describe(.powerConnected) == "When the power adapter is connected")64        #expect(TriggerDescriber.describe(.networkAvailable) == "When the network becomes available")65        #expect(TriggerDescriber.describe(.appLaunch(bundleID: "example.not.installed")) == "When example.not.installed opens")66    }6768    @Test func intervalsUseTheLargestWholeUnit() {69        #expect(TriggerDescriber.describeInterval(45) == "Every 45 seconds")70        #expect(TriggerDescriber.describeInterval(60) == "Every minute")71        #expect(TriggerDescriber.describeInterval(1800) == "Every 30 minutes")72        #expect(TriggerDescriber.describeInterval(7200) == "Every 2 hours")73        #expect(TriggerDescriber.describeInterval(172_800) == "Every 2 days")74        #expect(TriggerDescriber.describeInterval(90) == "Every 90 seconds")75    }7677    @Test func policiesInPlainWords() {78        #expect(TriggerDescriber.describe(MissedRunPolicy.runAll(max: 3)) == "Catch up, at most 3 missed runs")79        #expect(TriggerDescriber.describe(ConcurrencyPolicy.parallel(max: 2)) == "Up to 2 at the same time")80    }8182    @Test func presetsRoundTripThroughCron() throws {83        let presets: [CronPreset] = [.everyMinutes(1), .everyMinutes(15), .hourly(minute: 20), .daily(hour: 9, minute: 5), .weekdays(hour: 8, minute: 0),84                                     .weekly(days: [1, 3], hour: 18, minute: 30), .monthly(day: 15, hour: 6, minute: 0)]85        for p in presets {86            _ = try CronExpression(p.expression)87            #expect(CronPreset.match(p.expression) == p, "\(p.expression)")88        }89        #expect(CronPreset.match("0 9 * * MON") == .weekly(days: [1], hour: 9, minute: 0))90        #expect(CronPreset.match("0 9 1 1 *") == nil)91        #expect(CronPreset.match("*/5 9-17 * * *") == nil)92    }93}9495@Suite("Unit · agenda and schedule drafts")96struct AgendaTests {97    let toronto = TimeZone(identifier: "America/Toronto")!9899    func date(_ y: Int, _ m: Int, _ d: Int, _ h: Int, _ min: Int = 0, zone: TimeZone) -> Date {100        var c = Calendar(identifier: .gregorian); c.timeZone = zone101        return c.date(from: DateComponents(year: y, month: m, day: d, hour: h, minute: min))!102    }103104    @Test func dailyJobKeepsItsWallClockAcrossFallBack() {105        // America/Toronto leaves daylight time on 2026-11-01: 09:00 local is 13:00 UTC before and 14:00 UTC after.106        var cal = Calendar(identifier: .gregorian); cal.timeZone = toronto107        let s = Schedule(id: "a", workflowID: "w", name: "Morning", trigger: .cron(expression: "0 9 * * *", timezone: "America/Toronto"))108        let (days, truncated) = AgendaBuilder.build(schedules: [s], from: date(2026, 10, 30, 12, zone: toronto), days: 7, calendar: cal)109        #expect(truncated.isEmpty)110        #expect(days.count == 7)111        #expect(days[0].items.isEmpty)   // 09:00 on the 30th already passed at noon112        let fires = days.flatMap(\.items).flatMap(\.times)113        #expect(fires.count == 6)114        for f in fires { #expect(AgendaBuilder.clock(f, in: toronto) == "09:00") }115        let gaps = zip(fires, fires.dropFirst()).map { $1.timeIntervalSince($0) / 3600 }116        #expect(gaps == [25, 24, 24, 24, 24])   // one 25-hour day: the clocks went back117    }118119    @Test func springForwardFiresOnceAfterTheGap() {120        var cal = Calendar(identifier: .gregorian); cal.timeZone = toronto121        // 02:30 does not exist on 2026-03-08 in Toronto.122        let s = Schedule(id: "a", workflowID: "w", name: "Night", trigger: .cron(expression: "30 2 * * *", timezone: "America/Toronto"))123        let (days, _) = AgendaBuilder.build(schedules: [s], from: date(2026, 3, 7, 0, zone: toronto), days: 3, calendar: cal)124        #expect(days.map { $0.items.first?.total ?? 0 } == [1, 1, 1])125        #expect(days.map { $0.items.first.map { AgendaBuilder.clock($0.times[0], in: toronto) } ?? "" } == ["02:30", "03:00", "02:30"])126    }127128    @Test func scheduleInAnotherZoneLandsOnTheLocalDayAndShowsBothClocks() {129        var cal = Calendar(identifier: .gregorian); cal.timeZone = toronto130        // 07:30 in Paris is 01:30 in Toronto the same day; 02:00 in Paris is 20:00 the day before.131        let paris = Schedule(id: "p", workflowID: "w", name: "Paris", trigger: .cron(expression: "30 7 * * *", timezone: "Europe/Paris"))132        let early = Schedule(id: "e", workflowID: "w", name: "Early", trigger: .cron(expression: "0 2 * * *", timezone: "Europe/Paris"))133        let (days, _) = AgendaBuilder.build(schedules: [paris, early], from: date(2026, 11, 21, 12, zone: toronto), days: 2, calendar: cal)134        #expect(days[0].items.map(\.name) == ["Early"])135        #expect(AgendaBuilder.clock(days[0].items[0].times[0], in: toronto) == "20:00")136        #expect(days[1].items.map(\.name) == ["Paris", "Early"])137        let item = days[1].items[0]138        #expect(AgendaBuilder.foreignZone(item, local: toronto)?.identifier == "Europe/Paris")139        let same = AgendaItem(scheduleID: "x", name: "x", timezone: "America/Toronto", times: item.times, total: 1, last: item.last)140        #expect(AgendaBuilder.foreignZone(same, local: toronto) == nil)141    }142143    @Test func frequentAndDisabledSchedulesAreBounded() {144        var cal = Calendar(identifier: .gregorian); cal.timeZone = toronto145        let now = date(2026, 6, 1, 0, zone: toronto)146        let minute = Schedule(id: "m", workflowID: "w", name: "Minute", trigger: .cron(expression: "* * * * *", timezone: "America/Toronto"))147        let off = Schedule(id: "o", workflowID: "w", name: "Off", trigger: .cron(expression: "0 9 * * *", timezone: nil), enabled: false)148        let paused = Schedule(id: "p", workflowID: "w", name: "Paused", trigger: .cron(expression: "0 9 * * *", timezone: nil), paused: true)149        let event = Schedule(id: "l", workflowID: "w", name: "Login", trigger: .login)150        let interval = Schedule(id: "i", workflowID: "w", name: "Interval", trigger: .interval(seconds: 6 * 3600), createdAt: now)151        let once = Schedule(id: "1", workflowID: "w", name: "Once", trigger: .once(at: now.addingTimeInterval(30 * 3600)))152        let (days, truncated) = AgendaBuilder.build(schedules: [minute, off, paused, event, interval, once], from: now, days: 7, calendar: cal)153        #expect(truncated == ["Minute"])154        #expect(Set(days.flatMap(\.items).map(\.name)) == ["Minute", "Interval", "Once"])155        let first = days[0].items.first { $0.name == "Minute" }!156        #expect(first.times.count == AgendaBuilder.shownPerDay)157        #expect(first.total == 1439)158        #expect(days[0].items.first { $0.name == "Interval" }?.total == 3)   // 06:00, 12:00, 18:00 (midnight belongs to the next day)159        #expect(days[1].items.contains { $0.name == "Once" })160    }161162    @Test func draftRoundTripsEveryTriggerKind() {163        let triggers: [TriggerSpec] = [164            .cron(expression: "0 9 * * 1", timezone: "America/Toronto"), .cron(expression: "*/7 3-5 * * *", timezone: nil),165            .once(at: Date(timeIntervalSince1970: 2_000_000_000)), .interval(seconds: 5400), .interval(seconds: 7200),166            .fileChange(path: "/tmp/x", recursive: false, glob: "*.csv", debounceSeconds: 4), .login, .appLaunch(bundleID: "com.apple.Safari"),167            .powerConnected, .networkAvailable,168        ]169        for t in triggers {170            let s = Schedule(id: "s", workflowID: "w", name: "n", trigger: t, enabled: true, missedRunPolicy: .runAll(max: 4), concurrency: .parallel(max: 3),171                             maxRetries: 2, retryBackoffSeconds: 45)172            let back = ScheduleDraft(schedule: s).makeSchedule(existing: s)173            #expect(back == s, "\(t)")174        }175        #expect(ScheduleDraft(schedule: Schedule(workflowID: "w", name: "n", trigger: .cron(expression: "*/7 3-5 * * *", timezone: nil))).useRawCron)176        #expect(!ScheduleDraft(schedule: Schedule(workflowID: "w", name: "n", trigger: .cron(expression: "0 9 * * 1", timezone: nil))).useRawCron)177    }178179    @Test func draftValidationAndCronPreview() throws {180        var d = ScheduleDraft()181        #expect(d.problems().contains("Choose a workflow."))182        d.workflowID = "w"183        #expect(d.problems().isEmpty)184        d.timezone = "America/Toronto"; d.useRawCron = true; d.rawCron = "0 9 * * MON"185        let now = date(2026, 11, 21, 12, zone: toronto)186        let dates = try d.cronPreview(now: now).get()187        #expect(dates.count == 5)188        #expect(dates[0] == date(2026, 11, 23, 9, zone: toronto))189        #expect(dates[4] == date(2026, 12, 21, 9, zone: toronto))190        d.rawCron = "0 25 * * *"191        guard case .failure(let e) = d.cronPreview(now: now) else { Issue.record("an out-of-range hour must be refused"); return }192        #expect(e.description.contains("hour"))193        #expect(!d.problems(now: now).isEmpty)194        d.rawCron = "0 0 30 2 *"195        guard case .failure = d.cronPreview(now: now) else { Issue.record("a date that never exists must be reported"); return }196        d.rawCron = "0 9 * * *"; d.timezone = "Mars/Olympus"197        guard case .failure = d.cronPreview(now: now) else { Issue.record("an unknown zone must be refused"); return }198        var w = ScheduleDraft(); w.workflowID = "w"; w.shape = .weekly; w.weekdays = []199        #expect(w.problems().contains("Choose at least one day of the week."))200        var o = ScheduleDraft(); o.workflowID = "w"; o.kind = .once; o.onceAt = now.addingTimeInterval(-60)201        #expect(!o.problems(now: now).isEmpty)202        var f = ScheduleDraft(); f.workflowID = "w"; f.kind = .fileChange203        #expect(f.problems() == ["Choose the folder to watch."])204    }205}206207@Suite("Unit · console buffer")208struct ConsoleBufferTests {209    @Test func keepsTheNewestLinesAndCountsTheRest() {210        var b = ConsoleBuffer(capacity: 100)211        for i in 0..<250 { b.append("line \(i)", level: i % 2 == 0 ? .stdout : .stderr) }212        #expect(b.lines.count == 100)213        #expect(b.dropped == 150)214        #expect(b.lines.first?.text == "line 150")215        #expect(b.lines.last?.text == "line 249")216        #expect(Set(b.lines.map(\.id)).count == 100)217        b.clear()218        #expect(b.lines.isEmpty && b.dropped == 0)219        b.append("after", level: .info)220        #expect(b.lines[0].id == 250)   // ids never repeat, even after clearing221    }222223    @Test func splitsMultilineTextAndCutsOverlongLines() {224        var b = ConsoleBuffer()225        b.append("a\nb\r\nc", level: .stdout)226        #expect(b.lines.map(\.text) == ["a", "b", "c"])227        b.append("", level: .stdout)228        #expect(b.lines.count == 3)229        b.append(String(repeating: "x", count: 10_000), level: .stdout)230        #expect(b.lines.last!.text.hasSuffix("[line cut]"))231        #expect(b.lines.last!.text.count < 4100)232    }233234    @Test func olderEventsAreInsertedInTimeOrder() {235        var b = ConsoleBuffer()236        let t = Date(timeIntervalSince1970: 1000)237        b.append("live 1", level: .stdout, time: t.addingTimeInterval(1))238        b.append("live 2", level: .stdout, time: t.addingTimeInterval(3))239        b.append("recorded", level: .approval, time: t.addingTimeInterval(2))240        b.append("same instant", level: .info, time: t.addingTimeInterval(3))241        #expect(b.lines.map(\.text) == ["live 1", "recorded", "live 2", "same instant"])242    }243244    @Test func searchIsCaseInsensitiveAndRespectsLevels() {245        var b = ConsoleBuffer()246        b.append("Error: file not found", level: .stderr)247        b.append("no problem here", level: .stdout)248        b.append("an ERROR again, résumé", level: .stdout)249        #expect(b.search("error").count == 2)250        #expect(b.search("error", levels: [.stdout]).count == 1)251        #expect(b.search("resume").count == 1)252        #expect(b.search("   ").isEmpty)253        #expect(b.search("RÉSUMÉ").count == 1 && b.search("found").count == 1 && b.search("foundx").isEmpty && b.search("d").count == 1)254        let m = ConsoleBuffer.Matcher("ab")!255        #expect(m.matches("xxAB") && m.matches("aB") && !m.matches("a") && !m.matches("ba") && m.matches("aab") && !m.matches(""))256        #expect(b.visible(levels: [.stderr]).map(\.text) == ["Error: file not found"])257        #expect(ConsoleBuffer.render(b.lines[0]).contains("  ERR     Error: file not found"))258    }259260    @Test func assemblerJoinsStreamingFragmentsIntoLines() {261        var a = ConsoleAssembler()262        #expect(a.lines(for: .text("Hel")).isEmpty)263        let first = a.lines(for: .text("lo\nwor"))264        #expect(first.map(\.text) == ["Hello"] && first[0].level == .agent)265        #expect(a.hasPartials)266        #expect(a.flushPartials().map(\.text) == ["wor"])267        #expect(!a.hasPartials)268        let out = a.lines(for: .toolProgress(callID: "c", ToolProgress(stream: .stdout, text: "one\ntwo\n")))269        #expect(out.map(\.text) == ["one", "two"] && out.allSatisfy { $0.level == .stdout })270        let err = a.lines(for: .toolProgress(callID: "c", ToolProgress(stream: .stderr, text: "bad\n")))271        #expect(err.first?.level == .stderr)272    }273274    @Test func assemblerDoesNotShowTheSameThingTwice() {275        var a = ConsoleAssembler()276        let call = ToolCall(id: "call-1", toolID: "shell.script", arguments: ["script": "echo hi"])277        #expect(a.lines(for: .toolStarted(call)).count == 1)278        // The store records the same call a moment later.279        let requested = RunEvent(runID: "r", kind: .toolRequested, text: "shell.script", data: ["callID": "call-1", "toolID": "shell.script"])280        #expect(a.lines(for: requested).isEmpty)281        #expect(a.lines(for: .toolFinished(call, ToolResult(status: .succeeded, summary: "ok", durationMs: 12))).count == 1)282        let finished = RunEvent(runID: "r", kind: .toolFinished, text: "ok", data: ["callID": "call-1", "toolID": "shell.script", "status": "succeeded"])283        #expect(a.lines(for: finished).isEmpty)284        // A call seen only in the store is shown from the store.285        let other = RunEvent(runID: "r", kind: .toolFinished, text: "boom", data: ["callID": "call-2", "toolID": "filesystem.read", "status": "failed", "durationMs": 5])286        let shown = a.lines(for: other)287        #expect(shown.count == 1 && shown[0].level == .error && shown[0].text.contains("filesystem.read failed"))288        // Streamed text is not repeated when the full message is recorded.289        _ = a.lines(for: .text("Done.\n"))290        #expect(a.lines(for: RunEvent(runID: "r", kind: .assistantText, text: "Done.")).isEmpty)291        #expect(a.lines(for: RunEvent(runID: "r", kind: .assistantText, text: "Not streamed.")).map(\.text) == ["Not streamed."])292        // Status repeats collapse.293        #expect(a.lines(for: .status(.running)).count == 1)294        #expect(a.lines(for: RunEvent(runID: "r", kind: .statusChanged, text: "RUNNING", data: ["status": "RUNNING"])).isEmpty)295        #expect(a.lines(for: .finished(.succeeded)).map(\.text) == ["SUCCEEDED"])296    }297}298299@Suite("Unit · runs logic and export")300struct RunsLogicTests {301    func run(_ id: String, status: RunStatus = .succeeded, kind: String = "agent", trigger: String = "manual", started: TimeInterval = 0, duration: Double? = 10,302             cost: Double = 0, complete: Bool = true) -> RunRecord {303        let s = Date(timeIntervalSince1970: started)304        var r = RunRecord(id: id, kind: kind, title: id, trigger: trigger, mode: .guided, status: status, queuedAt: s, startedAt: s, endedAt: duration.map { s.addingTimeInterval($0) })305        r.usage.costUSD = cost; r.usage.costIsComplete = complete306        return r307    }308309    @Test func filterCombinesStatusKindTriggerAndDates() {310        var f = RunFilter()311        #expect(!f.isActive && f.matches(run("a")))312        f.statuses = [.failed, .timedOut]313        #expect(f.storeStatus == nil)314        #expect(f.matches(run("a", status: .failed)) && !f.matches(run("a")))315        f.statuses = [.failed]316        #expect(f.storeStatus == .failed)317        f = RunFilter(); f.kinds = ["workflow"]318        #expect(f.matches(run("a", kind: "workflow")) && !f.matches(run("a")))319        f = RunFilter(); f.triggers = [.schedule]320        #expect(f.matches(run("a", trigger: "cron")) && f.matches(run("a", trigger: "schedule")) && !f.matches(run("a")) && !f.matches(run("a", trigger: "something-else")))321        f = RunFilter(); f.from = Date(timeIntervalSince1970: 100); f.to = Date(timeIntervalSince1970: 200)322        #expect(f.matches(run("a", started: 150)) && !f.matches(run("a", started: 50)) && !f.matches(run("a", started: 250)))323        #expect(f.activeCount == 2)324        #expect(TriggerGroup.of("fileChange") == .fileChange && TriggerGroup.of("login") == .systemEvent && TriggerGroup.title(raw: "custom") == "custom")325    }326327    @Test func metricsComeFromDaysAndRecords() {328        let day0 = Date(timeIntervalSince1970: 86_400 * 100), day1 = day0.addingTimeInterval(86_400)329        let days = [DailyUsage(date: day0.addingTimeInterval(-86_400), day: "old", runs: 9, succeeded: 9, tokens: 9, costUSD: 9),330                    DailyUsage(date: day0, day: "d0", runs: 3, succeeded: 2, failed: 1, tokens: 1000, costUSD: 0.5),331                    DailyUsage(date: day1, day: "d1", runs: 2, succeeded: 1, failed: 0, tokens: 500, costUSD: 0.25)]332        let runs = [run("a", started: day0.timeIntervalSince1970 + 10, duration: 10), run("b", status: .failed, started: day0.timeIntervalSince1970 + 20, duration: 30),333                    run("c", started: day0.timeIntervalSince1970 + 30, duration: 20, complete: false), run("d", started: day1.timeIntervalSince1970 + 5, duration: 40),334                    run("e", status: .running, started: day1.timeIntervalSince1970 + 6, duration: nil), run("old", started: day0.timeIntervalSince1970 - 50, duration: 1000)]335        let today = PeriodMetrics.aggregate(days: days, runs: runs, period: .today)336        #expect(today.runs == 2 && today.inFlight == 1 && today.succeeded == 1 && today.costUSD == 0.25 && today.costIsComplete)337        #expect(today.successRate == 1 && today.averageDuration == 40 && today.durationSample == 1)338        let week = PeriodMetrics.aggregate(days: days, runs: runs, period: .week)   // only 3 days exist: all of them339        #expect(week.runs == 14 && week.tokens == 1509)340        let two = PeriodMetrics.aggregate(days: Array(days.suffix(2)), runs: runs, period: .week)341        #expect(two.runs == 5 && two.succeeded == 3 && two.failed == 1 && two.tokens == 1500 && two.costUSD == 0.75)342        #expect(!two.costIsComplete)343        #expect(two.successRate == 0.75)             // 3 of the 4 finished runs344        #expect(two.averageDuration == 25 && two.durationSample == 4)345        let none = PeriodMetrics.aggregate(days: [DailyUsage(date: day0, day: "d0")], runs: [], period: .today)346        #expect(none.successRate == nil && none.averageDuration == nil)347    }348349    @Test func toolUsageTotalsPerTool() {350        let calls = [ToolCallRecord(id: "1", toolID: "a.read", arguments: .null, status: .succeeded, summary: "", durationMs: 10),351                     ToolCallRecord(id: "2", toolID: "a.read", arguments: .null, status: .failed, summary: "", durationMs: 30),352                     ToolCallRecord(id: "3", toolID: "b.run", arguments: .null, status: .simulated, summary: "", durationMs: 500)]353        let rows = ToolUsageRow.aggregate(calls)354        #expect(rows.map(\.toolID) == ["b.run", "a.read"])355        #expect(rows[1].calls == 2 && rows[1].failed == 1 && rows[1].totalMs == 40 && rows[0].failed == 0)356        let events = [RunEvent(runID: "r", kind: .toolFinished, text: "x", data: ["callID": "9", "toolID": "c.go", "status": "succeeded", "durationMs": 7, "tier": 1]),357                      RunEvent(runID: "r", kind: .log, text: "ignored")]358        let rebuilt = ToolUsageRow.calls(from: events)359        #expect(rebuilt.count == 1 && rebuilt[0].toolID == "c.go" && rebuilt[0].durationMs == 7 && rebuilt[0].tier == .reversibleWrite)360    }361362    @Test func receiptExportsAsMarkdownAndJSON() throws {363        let start = Date(timeIntervalSince1970: 1_800_000_000)364        var usage = RunUsage(); usage.turns = 3; usage.costUSD = 0.0123; usage.costIsComplete = false365        let receipt = RunReceipt(runID: "ABCDEF12-0000", title: "Weekly: Research / digest!", status: .partiallySucceeded, objective: "Summarise", model: nil,366                                 startedAt: start, endedAt: start.addingTimeInterval(60), usage: usage,367                                 toolCalls: [ToolCallRecord(id: "1", toolID: "filesystem.list", arguments: ["path": "~/x"], status: .succeeded, summary: "3 entries", durationMs: 4, startedAt: start)],368                                 artifacts: [Artifact(path: "/tmp/report.md", bytes: 10, sha256: String(repeating: "ab", count: 32), createdAt: start)],369                                 verifications: [VerificationResult(assertion: "report exists", kind: "file_exists", passed: false, evidence: "not found", checkedAt: start)],370                                 agentSummary: "All done!", limitations: ["Dry run"])371        let md = ReceiptExport.markdown(receipt)372        #expect(md.contains("# Execution receipt — Weekly: Research / digest!"))373        #expect(md.contains("FAIL — report exists — not found"))374        #expect(md.contains("≥ $0.0123"))375        #expect(md.contains("a claim, not evidence"))376        let data = try ReceiptExport.json(receipt)377        let decoder = JSONDecoder(); decoder.dateDecodingStrategy = .iso8601378        #expect(try decoder.decode(RunReceipt.self, from: data) == receipt)379        let text = String(decoding: data, as: UTF8.self)380        #expect(text.contains("\"startedAt\" : \"2027-01-15T08:00:00Z\""))381        #expect(text.contains("/tmp/report.md"))   // slashes are not escaped382        #expect(ReceiptExport.fileName(receipt, ext: "md") == "receipt-weekly-research-digest-ABCDEF12.md")383        #expect(ReceiptExport.fileName(receipt, ext: "json").hasSuffix(".json"))384    }385}386
Files main
Menu

Theme