Repository Public License
1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import FlowEngine67@Suite struct FlowRunnerTests {8 static let prelude = "flow \"x\" version 1\nallow domains \"example.org\"\n"910 @Test func runsTheResearchBriefEndToEnd() async throws {11 let program = try validated(briefSource)12 let host = MockHost()13 await host.setLinks(["https://en.wikipedia.org/wiki/A", "https://evil.test/track", "https://arxiv.org/abs/1", "https://fr.wikipedia.org/wiki/B",14 "https://en.wikipedia.org/wiki/C", "https://en.wikipedia.org/wiki/D", "https://en.wikipedia.org/wiki/E", "https://en.wikipedia.org/wiki/F"])15 let recorder = RunRecorder()16 let record = await FlowRunner(host: host, observers: [recorder]).run(program, request: FlowRunRequest(parameters: ["topic": .text("Swift (language)/α?x#y")], grant: allCapabilities))17 #expect(record.status == .completed && record.failure == nil)18 // The topic is one path component: every reserved character is percent-encoded.19 let opened = await host.calls(of: "open").compactMap { call -> String? in20 if case .url(let url)? = call.arguments["url"] { return url.absoluteString } else { return nil }21 }22 #expect(opened.first == "https://en.wikipedia.org/wiki/Swift%20%28language%29%2F%CE%B1%3Fx%23y")23 // allowed() dropped the off-list link; the loop limit kept five of the remaining seven.24 #expect(Set(opened.dropFirst()) == ["https://en.wikipedia.org/wiki/A", "https://arxiv.org/abs/1", "https://fr.wikipedia.org/wiki/B",25 "https://en.wikipedia.org/wiki/C", "https://en.wikipedia.org/wiki/D"])26 #expect(await host.maximumConcurrency <= 3)27 let summarize = try #require(await host.calls(of: "summarize").first)28 #expect(summarize.arguments["with"] == .option("citations"))29 guard case .list(let sources)? = summarize.arguments["content"] else { Issue.record("no sources"); return }30 // Collected in branch order, whatever order the branches finished in.31 let urls = sources.compactMap { value -> String? in if case .article(let a) = value { return a.url.absoluteString } else { return nil } }32 #expect(urls == [opened[0], "https://en.wikipedia.org/wiki/A", "https://arxiv.org/abs/1", "https://fr.wikipedia.org/wiki/B",33 "https://en.wikipedia.org/wiki/C", "https://en.wikipedia.org/wiki/D"])34 let export = try #require(await host.calls(of: "export").first)35 #expect(export.arguments["format"] == .option("markdown") && export.arguments["destination"] == .option("downloads"))36 #expect(export.spaceName == "Research" && export.policy.domains == ["wikipedia.org", "arxiv.org"] && export.timeoutSeconds <= 30)37 #expect(record.stepsUsed == 19 && record.steps.count == 19)38 #expect(record.steps.allSatisfy { $0.status == .succeeded && $0.finishedAt != nil && $0.error == nil })39 #expect(Set(record.steps.map(\.id)).count == 19)40 #expect(record.steps[0].path == "0" && record.steps[0].summary.hasPrefix("open https://en.wikipedia.org/wiki/Swift"))41 #expect(record.steps.contains { $0.path == "3[4].3" && $0.action == "close" })42 #expect(record.checkpoint.nextStatement == 5 && !record.isResumable)43 #expect(await recorder.history.first?.status == .running)44 #expect(await recorder.history.last == record)45 }4647 @Test func expressionsAndFunctionsEvaluate() async throws {48 let program = try validated(Self.prelude + """49 param n: number = 350 param elsewhere: text = "https://evil.test/b"51 let words = ["b", "a", "b", "c"]52 let page = url("https://sub.example.org/a b")53 if count(unique(words)) == n and contains(words, "c") and not empty(words) { notify "one {n}" }54 if first(words) == "b" and join(take(words, 2), "+") == "b+a" { notify "two" }55 if host(page) == "sub.example.org" or false { notify "three" }56 if upper(trim(" hi ")) == "HI" and lower("ABC") == "abc" and contains("Hello World", "world") { notify "four" }57 if count("héllo") == 5 and text(2.5) == "2.5" and text(true) == "true" { notify "five" }58 if 2 >= 2 and 1 < 2 and 3 != 4 and 500ms < 2s and (true or first(take(words, 0)) == "never evaluated") { notify "six" }59 if count(allowed([url("https://example.org/a"), url(elsewhere), url("https://x.example.org/c")])) == 2 { notify "seven" }60 if count(nothing_yet) == 0 { notify "eight" } else { collect 1 into nothing_yet }61 if page == "https://sub.example.org/a%20b" { notify "nine" }62 """)63 let host = MockHost()64 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: [.notify]))65 #expect(record.failure == nil)66 let messages = await host.calls(of: "notify").map { $0.arguments["message"]?.displayText ?? "" }67 #expect(messages == ["one 3", "two", "three", "four", "five", "six", "seven", "eight", "nine"])68 }6970 @Test func parametersAreCheckedBeforeAnythingRuns() async throws {71 let program = try validated(Self.prelude + "param target: url\nparam note: text = \"n\"\nparam times: number = 2\nopen target as p")72 let host = MockHost()73 let runner = FlowRunner(host: host)74 func failure(_ parameters: [String: FlowValue]) async -> FlowRunError? {75 await runner.run(program, request: FlowRunRequest(parameters: parameters, grant: allCapabilities)).failure76 }77 #expect(await failure([:]) == .invalidParameter(name: "target", reason: "a value is required."))78 #expect(await failure(["target": .number(3)]) == .invalidParameter(name: "target", reason: "expected url, got number."))79 #expect(await failure(["target": .url(URL(string: "https://evil.test/")!)]) == .invalidParameter(name: "target", reason: "https://evil.test/ is not on the allowed domains."))80 #expect(await failure(["target": .text("javascript:alert(1)")]) == .invalidURL("javascript:alert(1)"))81 #expect(await failure(["target": .text("https://example.org"), "bogus": .bool(true)]) == .invalidParameter(name: "bogus", reason: "the workflow has no such parameter."))82 #expect(await failure(["target": .text("https://example.org"), "times": .number(.infinity)]) == .invalidParameter(name: "times", reason: "the number is not finite."))83 #expect(await host.calls.isEmpty)84 let record = await runner.run(program, request: FlowRunRequest(parameters: ["target": .text(" https://www.example.org/ok ")], grant: allCapabilities))85 #expect(record.status == .completed && record.parameters["note"] == .text("n") && record.parameters["target"] == .url(URL(string: "https://www.example.org/ok")!))86 }8788 @Test func domainsAreEnforcedOnRunTimeValuesNotOnlyStatically() async throws {89 // The link list comes from the page: nothing static can know where it points.90 let program = try validated(Self.prelude + """91 open "https://example.org/start" as start92 extract links from start as links93 for link in links limit 5 { open link as p }94 """)95 let host = MockHost()96 await host.setLinks(["https://example.org/ok", "https://evil.test/steal", "https://example.org/never"])97 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities))98 #expect(record.status == .failed)99 #expect(record.failure == .domainNotAllowed(url: "https://evil.test/steal", action: "open"))100 let opened = await host.calls(of: "open").map { $0.arguments["url"]?.displayText ?? "" }101 #expect(opened == ["https://example.org/start", "https://example.org/ok"])102 #expect(record.steps.last?.status == .failed && record.steps.last?.error?.contains("evil.test") == true)103104 // url() built from a parameter, a credentialed URL, a non-web scheme.105 let dynamic = try validated(Self.prelude + "param where: text\nopen url(where) as p")106 for (text, expected) in [("https://evil.test/", FlowRunError.domainNotAllowed(url: "https://evil.test/", action: "open")),107 ("https://example.org@evil.test/", .invalidURL("https://example.org@evil.test/")),108 ("https://example.org.evil.test/", .domainNotAllowed(url: "https://example.org.evil.test/", action: "open")),109 ("https://user:pw@example.org/", .invalidURL("https://user:pw@example.org/")),110 ("file:///etc/passwd", .invalidURL("file:///etc/passwd")), ("not a url", .invalidURL("not a url"))] {111 let fresh = MockHost()112 let result = await FlowRunner(host: fresh).run(dynamic, request: FlowRunRequest(parameters: ["where": .text(text)], grant: allCapabilities))113 #expect(result.failure == expected, "\(text)")114 #expect(await fresh.calls.isEmpty, "\(text)")115 }116 }117118 @Test func aRedirectOutsideTheAllowListFailsTheStep() async throws {119 let program = try validated(Self.prelude + "open \"https://example.org/redirect\" as p\nextract article from p as a")120 let host = MockHost()121 await host.setOverride { call in122 call.action == "open" ? .page(FlowPage(handle: "t", url: URL(string: "https://evil.test/landing")!)) : nil123 }124 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities))125 #expect(record.failure == .domainNotAllowed(url: "https://evil.test/landing", action: "open"))126 #expect(await host.actions() == ["open"])127 }128129 @Test func aStaleOrForgedPageIsRecheckedOnEveryUse() async throws {130 let program = try validated(Self.prelude + "open \"https://example.org/a\" as p\nlet again = p\nextract text from again as t")131 var record = FlowRunRecord(id: UUID(), workflowID: nil, name: "x", sourceHash: program.sourceHash, parameters: [:], grantedCapabilities: [],132 status: .failed, steps: [], checkpoint: FlowCheckpoint(nextStatement: 1, variables: [:], collections: [:]),133 statementCount: 3, stepsUsed: 1, startedAt: .now, updatedAt: .now, finishedAt: nil, failure: nil, resumeCount: 0)134 // A checkpoint is data on disk: a page whose URL is off the list must not reach the host.135 record.checkpoint.variables["p"] = .page(FlowPage(handle: "t", url: URL(string: "https://evil.test/x")!))136 let host = MockHost()137 let resumed = try await FlowRunner(host: host).resume(record, program: program, grant: allCapabilities)138 #expect(resumed.failure == .domainNotAllowed(url: "https://evil.test/x", action: "extract text"))139 #expect(await host.calls.isEmpty)140 }141142 @Test func capabilitiesNotGrantedNeverReachTheHost() async throws {143 let program = try validated(Self.prelude + "open \"https://example.org\" as p\nextract article from p as a\nsummarize a as r")144 let host = MockHost()145 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: [.navigate, .read]))146 #expect(record.failure == .capabilityNotGranted(capability: "ai", action: "summarize"))147 #expect(await host.actions() == ["open", "extract article"])148 #expect(record.steps.map(\.status) == [.succeeded, .succeeded, .failed])149 let none = MockHost()150 let nothing = await FlowRunner(host: none).run(program, request: FlowRunRequest(grant: []))151 #expect(nothing.failure == .capabilityNotGranted(capability: "navigate", action: "open"))152 #expect(await none.calls.isEmpty)153 }154155 @Test func confirmationPausesTheRunAndADenialStopsIt() async throws {156 let program = try validated("flow \"x\" version 1\nallow domains \"example.org\"\nlimit duration 1s\ndownload \"https://example.org/file.zip\" as f\nnotify \"got {f.name}\"")157 let host = MockHost()158 // The user takes longer than the whole duration limit to answer: the pause is not charged to the run.159 await host.setDelay("confirm", .milliseconds(1_300))160 let recorder = RunRecorder()161 let record = await FlowRunner(host: host, observers: [recorder]).run(program, request: FlowRunRequest(grant: allCapabilities))162 #expect(record.status == .completed, "\(String(describing: record.failure))")163 let request = try #require(await host.confirmations.first)164 #expect(request.action == "download" && request.capability == .download && request.summary == "download https://example.org/file.zip" && request.workflowName == "x")165 let statuses = await recorder.statuses()166 #expect(statuses.contains(.awaitingConfirmation))167 #expect(await recorder.history.contains { $0.steps.last?.status == .awaitingConfirmation })168 #expect(await host.calls(of: "notify").first?.arguments["message"] == .text("got file.csv"))169170 let refusing = MockHost()171 await refusing.setConfirm(false)172 let denied = await FlowRunner(host: refusing).run(program, request: FlowRunRequest(grant: allCapabilities))173 #expect(denied.status == .failed && denied.failure == .confirmationDenied(action: "download"))174 #expect(denied.steps.map(\.status) == [.denied])175 #expect(await refusing.calls.isEmpty)176 // Without the capability the user is not even asked.177 let ungranted = MockHost()178 _ = await FlowRunner(host: ungranted).run(program, request: FlowRunRequest(grant: [.notify]))179 #expect(await ungranted.confirmations.isEmpty)180 }181182 @Test func aStepTimesOutAndTheRunDurationIsBounded() async throws {183 let slow = try validated("flow \"x\" version 1\nallow domains \"example.org\"\nlimit timeout 150ms\nopen \"https://example.org\" as p")184 let host = MockHost()185 await host.setDelay("open", .seconds(30))186 let clock = ContinuousClock()187 var record = FlowRunRecord?.none188 let elapsed = await clock.measure { record = await FlowRunner(host: host).run(slow, request: FlowRunRequest(grant: allCapabilities)) }189 #expect(record?.failure == .stepTimedOut(action: "open", seconds: 0.15))190 #expect(record?.steps.first?.status == .timedOut)191 #expect(elapsed < .seconds(5))192193 let long = try validated("flow \"x\" version 1\nlimit duration 300ms, timeout 10s\nfor n in [1, 2, 3, 4, 5, 6, 7, 8] limit 8 { wait 200ms }\nnotify \"done\"")194 let other = MockHost()195 let bounded = await FlowRunner(host: other).run(long, request: FlowRunRequest(grant: allCapabilities))196 #expect(bounded.failure == .durationLimitExceeded(seconds: 0.3))197 #expect(bounded.stepsUsed <= 3)198 #expect(await other.calls.isEmpty)199 }200201 @Test func theStepBudgetStopsARunawayWorkflow() async throws {202 let program = try validated("flow \"x\" version 1\nlimit steps 7\nfor a in [1, 2, 3, 4, 5] limit 5 { for b in [1, 2, 3, 4, 5] limit 5 { notify \"x\" } }")203 let host = MockHost()204 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities))205 #expect(record.failure == .stepLimitExceeded(limit: 7))206 #expect(await host.calls.count == 7 && record.stepsUsed == 7 && record.steps.count == 7)207 }208209 @Test func loopsStopAtTheirStaticLimit() async throws {210 let numbers = (1...60).map(String.init).joined(separator: ", ")211 let program = try validated("flow \"x\" version 1\nlimit steps 100\nfor n in [\(numbers)] limit 4 { notify \"n{n}\" }\nfor m in [] limit 9 { notify \"never\" }")212 let host = MockHost()213 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities))214 #expect(record.status == .completed)215 #expect(await host.calls.map { $0.arguments["message"]?.displayText ?? "" } == ["n1", "n2", "n3", "n4"])216 }217218 @Test func parallelBlocksRespectTheirWidthAndMergeDeterministically() async throws {219 let program = try validated(Self.prelude + """220 limit steps 60221 parallel limit 2 {222 open "https://example.org/1" as a223 open "https://example.org/2" as b224 open "https://example.org/3" as c225 open "https://example.org/4" as d226 }227 for page in [a, b, c, d] limit 4 parallel 3 {228 extract article from page as item229 collect item.url into seen230 }231 notify join([text(first(seen)), d.title], " | ")232 """)233 for _ in 0..<5 {234 let host = MockHost()235 await host.setDelay("open", .milliseconds(30))236 await host.setDelay("extract article", .milliseconds(20))237 let record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities))238 #expect(record.status == .completed, "\(String(describing: record.failure))")239 // Width 3 is the ceiling; under load fewer branches may overlap.240 let concurrency = await host.maximumConcurrency241 #expect(concurrency >= 2 && concurrency <= 3)242 #expect(record.checkpoint.collections["seen"] == (1...4).map { .url(URL(string: "https://example.org/\($0)")!) })243 #expect(await host.calls(of: "notify").first?.arguments["message"] == .text("https://example.org/1 | Title of 4"))244 }245 let narrow = try validated(Self.prelude + "parallel limit 2 {\nopen \"https://example.org/1\" as a\nopen \"https://example.org/2\" as b\nopen \"https://example.org/3\" as c\n}")246 let host = MockHost()247 await host.setDelay("open", .milliseconds(40))248 _ = await FlowRunner(host: host).run(narrow, request: FlowRunRequest(grant: allCapabilities))249 #expect(await host.maximumConcurrency <= 2)250 }251252 @Test func aFailingBranchCancelsItsSiblings() async throws {253 let program = try validated(Self.prelude + "parallel limit 2 {\nopen \"https://example.org/slow\" as a\nextract text from missing_page as b\n}\nnotify \"after\"".replacingOccurrences(of: "extract text from missing_page as b", with: "download \"https://example.org/f\" as b"))254 let host = MockHost()255 await host.setDelay("open", .seconds(20))256 await host.setConfirm(false)257 let clock = ContinuousClock()258 var record = FlowRunRecord?.none259 let elapsed = await clock.measure { record = await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities)) }260 #expect(record?.failure == .confirmationDenied(action: "download"))261 #expect(elapsed < .seconds(5))262 #expect(Set(record?.steps.map(\.status) ?? []) == [.cancelled, .denied])263 #expect(await host.calls(of: "notify").isEmpty)264 }265266 @Test func cancellingTheTaskCancelsTheRun() async throws {267 let program = try validated(Self.prelude + "open \"https://example.org/a\" as p\nnotify \"never\"")268 let host = MockHost()269 await host.setDelay("open", .seconds(30))270 let task = Task { await FlowRunner(host: host).run(program, request: FlowRunRequest(grant: allCapabilities)) }271 try await Task.sleep(for: .milliseconds(150))272 task.cancel()273 let record = await task.value274 #expect(record.status == .cancelled && record.failure == .cancelled)275 #expect(record.steps.map(\.status) == [.cancelled])276 #expect(record.isResumable)277 #expect(await host.actions() == ["open"])278 }279280 @Test func hostErrorsAndContractViolationsFailTheStep() async throws {281 let program = try validated(Self.prelude + "open \"https://example.org/a\" as p")282 let failing = MockHost()283 await failing.setFailures("open", 1)284 let failed = await FlowRunner(host: failing).run(program, request: FlowRunRequest(grant: allCapabilities))285 #expect(failed.failure == .hostFailure(action: "open", message: "scripted failure of open"))286 let lying = MockHost()287 await lying.setOverride { _ in .text("not a page") }288 let violated = await FlowRunner(host: lying).run(program, request: FlowRunRequest(grant: allCapabilities))289 #expect(violated.failure == .hostContractViolation(action: "open", expected: "page", got: "text"))290 let huge = try validated(Self.prelude + "open \"https://example.org/a\" as p\nextract links from p as links")291 let flooding = MockHost()292 await flooding.setOverride { call in293 call.action == "extract links" ? .list((0..<3_000).map { .url(URL(string: "https://example.org/\($0)")!) }) : nil294 }295 let flooded = await FlowRunner(host: flooding).run(huge, request: FlowRunRequest(grant: allCapabilities))296 #expect(flooded.failure == .valueTooLarge("A list exceeds 2000 items."))297 let empty = try validated(Self.prelude + "param elsewhere: text = \"https://evil.test/\"\nlet none = allowed([url(elsewhere)])\nopen first(none) as p")298 let none = MockHost()299 #expect(await FlowRunner(host: none).run(empty, request: FlowRunRequest(grant: allCapabilities)).failure == .evaluation("“first” was given an empty list."))300 }301302 @Test func aFailedRunResumesFromTheLastCompletedTopLevelStatement() async throws {303 let database = try await NavigatorDatabase.inMemory()304 let store = FlowRunStore(database: database)305 let program = try validated(Self.prelude + """306 param tag: text307 open "https://example.org/{tag}" as page308 extract article from page as article309 collect article.title into titles310 summarize article as report311 export report as markdown to downloads312 """)313 let host = MockHost()314 await host.setFailures("summarize", 1)315 let workflowID = WorkflowID()316 let runner = FlowRunner(host: host, observers: [store])317 let first = await runner.run(program, request: FlowRunRequest(parameters: ["tag": .text("one")], grant: allCapabilities, workflowID: workflowID))318 #expect(first.status == .failed && first.isResumable)319 #expect(first.checkpoint.nextStatement == 3)320 #expect(Set(first.checkpoint.variables.keys) == ["tag", "page", "article"])321 #expect(first.checkpoint.collections["titles"] == [.text("Title of one")])322323 // What is on disk is what a relaunched app would find.324 let stored = try #require(try await store.run(first.id))325 #expect(stored == first)326 #expect(try await store.resumable().map(\.id) == [first.id])327 await #expect(throws: FlowRunError.notResumable("the workflow was edited since this run.")) {328 try await runner.resume(stored, program: try validated(Self.prelude + "param tag: text\nnotify tag"), grant: allCapabilities)329 }330 let resumed = try await runner.resume(stored, program: program, grant: allCapabilities)331 #expect(resumed.status == .completed && resumed.id == first.id && resumed.resumeCount == 1 && resumed.failure == nil)332 // Completed statements were not executed again; the failed one ran again.333 #expect(await host.actions() == ["open", "extract article", "summarize", "summarize", "export"])334 #expect(resumed.steps.map(\.action) == ["open", "extract article", "summarize", "summarize", "export"])335 #expect(resumed.steps.map(\.status) == [.succeeded, .succeeded, .failed, .succeeded, .succeeded])336 #expect(Set(resumed.steps.map(\.id)).count == 5 && resumed.stepsUsed == 5)337 #expect(resumed.checkpoint.collections["titles"] == [.text("Title of one")])338 let final = try #require(try await store.run(first.id))339 #expect(final == resumed)340 #expect(try await store.resumable().isEmpty)341 await #expect(throws: FlowRunError.notResumable("it already completed.")) { try await runner.resume(final, program: program, grant: allCapabilities) }342 #expect(await store.lastSaveError == nil)343 await database.close()344 }345346 @Test func runStoreKeepsItsOwnTableAndVersion() async throws {347 let database = try await NavigatorDatabase.inMemory()348 let store = FlowRunStore(database: database)349 #expect(try await database.settings.value(FlowRunStore.schemaVersionKey) == 0)350 try await store.prepare()351 try await store.prepare()352 #expect(try await database.settings.value(FlowRunStore.schemaVersionKey) == 1)353 // A second store on the same database finds the table already there.354 let second = FlowRunStore(database: database)355 let program = try validated("flow \"x\" version 1\nnotify \"a\"")356 let workflow = WorkflowID()357 var ids: [UUID] = []358 for index in 0..<5 {359 let record = await FlowRunner(host: MockHost(), observers: [index % 2 == 0 ? store : second])360 .run(program, request: FlowRunRequest(grant: [.notify], workflowID: index < 3 ? workflow : nil))361 ids.append(record.id)362 }363 #expect(try await second.runs().count == 5)364 #expect(try await store.runs(workflow: workflow).count == 3)365 #expect(try await store.runs(limit: 2).count == 2)366 try await store.delete(ids[0])367 #expect(try await store.run(ids[0]) == nil)368 #expect(try await store.prune(keeping: 2) == 2)369 #expect(try await store.deleteAll() == 2)370 #expect(try await store.runs().isEmpty)371 // The module's table lives next to, not inside, the Persistence schema.372 #expect(try await database.schemaVersion() >= 2)373 await database.close()374 }375376 @Test func aRunWithoutObserversLeavesNoTrace() async throws {377 let database = try await NavigatorDatabase.inMemory()378 let program = try validated("flow \"x\" version 1\nnotify \"private\"")379 _ = await FlowRunner(host: MockHost()).run(program, request: FlowRunRequest(grant: [.notify]))380 let tables = try await database.sqlite.read { try $0.query("SELECT name FROM sqlite_master WHERE name LIKE 'flow%'").count }381 #expect(tables == 0)382 await database.close()383 }384}385386@Suite struct FlowDryRunTests {387 @Test func thePlanListsEveryStepWithoutTouchingAnyHost() throws {388 let program = try validated(briefSource)389 let plan = FlowRunner.plan(program, parameters: ["topic": .text("Alan Turing")], grant: [.navigate, .read])390 #expect(plan.name == "Research brief" && plan.spaceName == "Research")391 #expect(plan.steps.map(\.action) == ["open", "extract article", "open", "extract article", "close", "summarize", "export"])392 #expect(plan.steps[0].summary == "open https://en.wikipedia.org/wiki/Alan%20Turing")393 #expect(plan.steps[0].urls == [FlowPlannedURL(text: "https://en.wikipedia.org/wiki/Alan%20Turing", isResolved: true, isAllowed: true)])394 #expect(plan.steps[2].urls == [FlowPlannedURL(text: "link", isResolved: false, isAllowed: nil)])395 #expect(plan.steps[2].maximumRepetitions == 5 && plan.steps[2].isParallel && !plan.steps[2].isConditional)396 #expect(plan.steps[5].isConditional && plan.steps[5].maximumRepetitions == 1 && !plan.steps[5].isGranted)397 #expect(plan.steps[6].summary == "export report as markdown to downloads" && plan.steps[6].capability == .writeFile)398 #expect(plan.requiredCapabilities == [.ai, .navigate, .read, .writeFile])399 #expect(plan.missingCapabilities == [.ai, .writeFile])400 #expect(plan.worstCaseSteps == 19 && plan.limits.maximumSteps == 40 && plan.allowedDomains == ["wikipedia.org", "arxiv.org"])401 #expect(plan.maximumConfirmations == 0)402 #expect(!plan.isRunnable && plan.problems.count == 2)403 #expect(FlowRunner.plan(program, parameters: ["topic": .text("x")], grant: allCapabilities).isRunnable)404 #expect(FlowRunner.plan(program, grant: allCapabilities).problems == ["Parameter “topic”: a value is required."])405 }406407 @Test func thePlanCountsConfirmationsAndFlagsURLParametersOffTheList() throws {408 let program = try validated("""409 flow "x" version 1410 param target: url411 allow domains "example.org"412 for n in [1, 2, 3] limit 3 { download target as f }413 click "#go" on missing414 """.replacingOccurrences(of: "click \"#go\" on missing", with: "open target as p\nclick \"#go\" on p"))415 let plan = FlowRunner.plan(program, parameters: ["target": .url(URL(string: "https://example.org/f.zip")!)], grant: allCapabilities)416 #expect(plan.maximumConfirmations == 4)417 #expect(plan.steps.map(\.needsConfirmation) == [true, false, true])418 #expect(plan.steps[0].urls.first?.isAllowed == true)419 #expect(plan.isRunnable)420 let bad = FlowRunner.plan(program, parameters: ["target": .url(URL(string: "https://evil.test/f.zip")!)], grant: allCapabilities)421 #expect(bad.problems == ["Parameter “target”: https://evil.test/f.zip is not on the allowed domains."])422 }423}424