SPB Git

Repository Public License

Generators.swift 8.9 KB 162 lines swift

1// ORIX OS Automation2// File: Packages/ORIXWorkflowEngine/Tests/ORIXWorkflowEngineTests/Generators.swift3// Description: Seeded random generators of workflow documents and JSON values for the property tests (deterministic: no system randomness).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXCore9@testable import ORIXWorkflowEngine1011/// SplitMix64: small, deterministic, good enough for test data.12struct SeededRNG: RandomNumberGenerator {13    var state: UInt6414    init(seed: UInt64) { state = seed }15    mutating func next() -> UInt64 {16        state &+= 0x9E3779B97F4A7C1517        var z = state18        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B919        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB20        return z ^ (z >> 31)21    }22}2324struct DocumentGenerator {25    var rng: SeededRNG26    private var counter = 027    init(seed: UInt64) { rng = SeededRNG(seed: seed) }2829    static let trickyStrings: [String] = [30        "", " ", "plain", "two words", "true", "false", "null", "~", "Null", "123", "-7", "1.5", "1e3", "007", ".inf", "0x1F",31        "- dash", "-", "a: b", "a:b", "key:", "#hash", "a #b", "a#b", "[x]", "{y}", "a,b", "\"quoted\"", "it's", "'single'",32        "back\\slash", "tab\there", "line1\nline2", "line1\nline2\n", "trailing\n\n", "\nleading", "  indented\nnext", "a\n\nb",33        "multi\n  keep indent\nend", "sp \nline", "emoji 🚀 ok", "accentué çà", "~/ORIX Samples/x", "/abs/path with space/f.txt",34        "${{ params.folder }}/out.pdf", "${{ steps.a.output.items }}", "0 9 * * MON", "*.pdf", "&anchor", "*alias", "!tag", "@at", "`tick`",35        "%percent", "|pipe", ">gt", "?q", "x: ", " lead", "trail ", "a\rb", "ctrl\u{01}x", "nbsp\u{A0}x", "ls\u{2028}x", "---", "...",36        "on", "yes", "no", "https://example.com/a?b=c#d", "{\"json\": [1, 2]}", "end:",37    ]3839    mutating func int(_ range: ClosedRange<Int>) -> Int { Int.random(in: range, using: &rng) }40    mutating func bool(_ p: Double = 0.5) -> Bool { Double.random(in: 0..<1, using: &rng) < p }41    mutating func pick<T>(_ a: [T]) -> T { a[int(0...(a.count - 1))] }4243    mutating func string() -> String {44        if bool(0.7) { return pick(Self.trickyStrings) }45        let alphabet = Array("abc XYZ019_-.:/#'\"\\{}[],\n$~é🙂")46        return String((0..<int(0...12)).map { _ in pick(alphabet) })47    }4849    mutating func ident() -> String {50        counter += 151        return pick(["step", "s", "fetch", "render", "check_it", "a-b"]) + "\(counter)"52    }5354    mutating func double() -> Double {55        pick([0, 1, -1, 0.5, 2.25, 1e-7, 123456.789, 1e20, -3.0e-12, 30, 0.1 + 0.2, Double(int(-1000...1000)) / 7])56    }5758    mutating func json(depth: Int = 0) -> JSONValue {59        let top = depth >= 3 ? 4 : 660        switch int(0...top) {61        case 0: return .null62        case 1: return .bool(bool())63        case 2: return .int(pick([0, 1, -1, 42, Int.max, Int.min, int(-100000...100000)]))64        case 3: return .number(double())65        case 4: return .string(string())66        case 5: return .array((0..<int(0...4)).map { _ in json(depth: depth + 1) })67        default: return .object(object(depth: depth + 1))68        }69    }7071    mutating func object(depth: Int = 0) -> [String: JSONValue] {72        var o: [String: JSONValue] = [:]73        for _ in 0..<int(0...4) { o[bool(0.8) ? pick(["path", "source", "destination", "url", "args", "recursive", "pattern"]) : string()] = json(depth: depth + 1) }74        return o75    }7677    mutating func strings(_ max: Int = 3) -> [String] { (0..<int(0...max)).map { _ in string() } }7879    mutating func assertion() -> WorkflowAssertion {80        switch int(0...6) {81        case 0: return .fileExists(path: string())82        case 1: return .fileNonEmpty(path: string())83        case 2: return .fileContains(path: string(), text: string())84        case 3: return .dirNonEmpty(path: string())85        case 4: return .equals(json(), json())86        case 5: return .truthy(json())87        default: return .stepSucceeded(string())88        }89    }9091    mutating func step(depth: Int = 0) -> WorkflowStep {92        let kind: WorkflowStepKind93        let maxKind = depth >= 2 ? 12 : 1594        switch int(0...maxKind) {95        case 0: kind = .tool(ToolStep(tool: pick(["filesystem.list", "shell.run", "http.request", string()]), arguments: object()))96        case 1:97            let ref: AgentReference = bool() ? .profile(string()) : .inline(InlineAgent(instructions: string(), model: bool() ? string() : nil, tools: strings()))98            kind = .agent(AgentStep(agent: ref, objective: string(), inputs: object(), expect: (0..<int(0...2)).map { _ in assertion() }))99        case 2: kind = .condition(ConditionStep(condition: string(), then: strings(), otherwise: strings()))100        case 3: kind = .switch(SwitchStep(on: string(), cases: (0..<int(0...3)).map { _ in SwitchCase(value: json(), steps: strings()) }, defaultSteps: strings()))101        case 4: kind = .approval(ApprovalStep(message: string()))102        case 5: kind = .delay(DelayStep(seconds: pick([.int(int(0...60)), .number(double()), .string(string())])))103        case 6: kind = .set(SetStep(values: object()))104        case 7: kind = .transform(TransformStep(expression: string(), into: bool() ? string() : nil))105        case 8: kind = .verify(VerifyStep(assertions: (0..<int(0...3)).map { _ in assertion() }))106        case 9: kind = .subworkflow(SubworkflowStep(workflow: string(), inputs: object()))107        case 10: kind = .notify(NotifyStep(message: string(), title: bool() ? string() : nil))108        case 11: kind = .fail(FailStep(message: string()))109        case 12: kind = .output(OutputStep(values: object(), artifacts: strings()))110        case 13:111            let items: JSONValue = bool() ? .string(string()) : .array((0..<int(0...3)).map { _ in json(depth: 2) })112            kind = .foreach(ForeachStep(items: items, itemName: bool(0.7) ? "item" : string(), concurrency: int(1...4),113                                        steps: steps(depth: depth + 1, max: 3), collect: bool(0.3) ? string() : nil))114        case 14:115            kind = .parallel(ParallelStep(branches: (0..<int(0...3)).map { _ in ParallelBranch(name: string(), steps: steps(depth: depth + 1, max: 2)) }))116        default: kind = .loop(LoopStep(condition: string(), maxIterations: int(1...50), steps: steps(depth: depth + 1, max: 2)))117        }118        return WorkflowStep(119            id: bool(0.9) ? ident() : string(), name: bool(0.4) ? string() : nil, needs: bool(0.5) ? strings() : [],120            when: bool(0.3) ? string() : nil,121            retry: bool(0.3) ? WorkflowRetryPolicy(maxAttempts: int(1...5), backoffSeconds: pick([0, 1, 0.5]), backoffMultiplier: pick([1, 2, 1.5]), force: bool()) : nil,122            timeoutSeconds: bool(0.3) ? double() : nil, continueOnError: bool(0.2), onError: bool(0.2) ? string() : nil, kind: kind)123    }124125    mutating func steps(depth: Int, max: Int) -> [WorkflowStep] { (0..<int(0...max)).map { _ in step(depth: depth) } }126127    mutating func trigger() -> WorkflowTrigger {128        switch int(0...6) {129        case 0: return .manual130        case 1: return .schedule(cron: string(), timezone: bool() ? string() : nil)131        case 2: return .once(at: string())132        case 3: return .interval(seconds: double())133        case 4: return .fileChange(path: string(), glob: bool() ? string() : nil, debounceSeconds: bool() ? double() : nil)134        case 5: return .login135        default: return .appLaunch(bundleID: string())136        }137    }138139    mutating func document() -> WorkflowDocument {140        var spec = WorkflowSpec()141        spec.triggers = (0..<int(0...3)).map { _ in trigger() }142        spec.parameters = (0..<int(0...3)).map { _ in143            WorkflowParameter(name: string(), type: pick(WorkflowParameterType.allCases), defaultValue: bool() ? json() : nil, description: string(), required: bool())144        }145        if bool(0.7) {146            spec.permissions = WorkflowPermissions(147                filesystem: .init(read: strings(), write: strings(), delete: strings()), processes: strings(), scripts: strings(),148                apps: .init(automation: strings(), accessibility: strings(), control: strings()), network: strings(), browser: strings(),149                secrets: strings(), clipboard: .init(read: bool(), write: bool()), notifications: bool(), screen: strings())150        }151        if bool(0.6) {152            spec.budget = WorkflowBudget(maxDurationSeconds: bool() ? double() : nil, maxProviderCostUSD: bool() ? double() : nil,153                                         maxToolCalls: bool() ? int(0...500) : nil, maxTokens: bool() ? int(0...1_000_000) : nil)154        }155        spec.variables = object()156        spec.steps = steps(depth: 0, max: 6)157        spec.onError = bool(0.3) ? steps(depth: 1, max: 2) : []158        for _ in 0..<int(0...3) { spec.layout[string()] = WorkflowNodePosition(x: double(), y: double()) }159        return WorkflowDocument(metadata: WorkflowMetadata(id: string(), name: string(), description: string(), tags: strings()), spec: spec)160    }161}162
Files main
Menu

Theme