Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocAgentTests/Support.swift10// Description : Test doubles of the agent layer: a scripted chat provider11// with deterministic tool-call scripts, sample documents,12// recording approvers and hosts that misbehave on purpose.13// Module : DocAgentTests14// Repository : https://git.spboucher.ai/orix-docs15// Created : 2026-11-2216// Last Modified : 2026-11-2217//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Synchronization92import Testing93import AstraCore94import DocModel95import DocCommands96@testable import DocAgent9798// MARK: - Scripted provider99100struct ScriptCall: Sendable {101 var name: String102 var arguments: ModelJSON103 init(_ name: String, _ arguments: ModelJSON = [:]) { self.name = name; self.arguments = arguments }104}105106indirect enum ScriptTurn: Sendable {107 case calls([ScriptCall], text: String = "")108 case text(String)109 /// Starts the answer and never completes it until cancelled.110 case hang111 case fail(AstraError)112 /// Runs the closure (for example an edit by "someone else") before answering with the next turn.113 case after(@Sendable () async -> Void, ScriptTurn)114115 static func call(_ name: String, _ arguments: ModelJSON = [:]) -> ScriptTurn { .calls([ScriptCall(name, arguments)]) }116 static func finish(_ summary: String = "Done.", scope: String = "partial") -> ScriptTurn { .call("finish", ["summary": .string(summary), "scope": .string(scope)]) }117}118119/// A chat provider that plays a script. `responder` answers when the script is empty (used when several agents share the provider).120final class ScriptedProvider: ChatProvider, Sendable {121 let kind: ProviderKind = .openAI122 private struct State { var turns: [ScriptTurn]; var requests: [GenerationRequest] = []; var counter = 0; var active = 0; var peak = 0 }123 private let state: Mutex<State>124 private let responder: (@Sendable (GenerationRequest, Int) -> ScriptTurn)?125 private let usage: TokenUsage?126 /// Seconds each answer takes, to make overlaps observable.127 private let latency: TimeInterval128129 init(_ turns: [ScriptTurn] = [], usage: TokenUsage? = TokenUsage(inputTokens: 100, outputTokens: 20), latency: TimeInterval = 0,130 responder: (@Sendable (GenerationRequest, Int) -> ScriptTurn)? = nil) {131 state = Mutex(State(turns: turns)); self.responder = responder; self.usage = usage; self.latency = latency132 }133134 var requests: [GenerationRequest] { state.withLock { $0.requests } }135 /// Largest number of answers in progress at the same time.136 var peakConcurrency: Int { state.withLock { $0.peak } }137138 func listModels() async throws -> [ModelInfo] { [] }139 func verify() async throws -> ConnectionStatus { ConnectionStatus(ok: true, detail: "scripted") }140141 func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {142 let (turn, base): (ScriptTurn, Int) = state.withLock { s in143 s.requests.append(request)144 s.active += 1; s.peak = max(s.peak, s.active)145 let n = s.requests.count146 s.counter += 100147 if !s.turns.isEmpty { return (s.turns.removeFirst(), s.counter) }148 return (responder?(request, n) ?? .fail(.protocolViolation("the script has no more turns")), s.counter)149 }150 let usage = usage, latency = latency151 return AsyncThrowingStream { continuation in152 let task = Task {153 defer { self.state.withLock { $0.active -= 1 } }154 var turn = turn155 while case .after(let action, let next) = turn { await action(); turn = next }156 if latency > 0 { try? await Task.sleep(nanoseconds: UInt64(latency * 1_000_000_000)) }157 continuation.yield(.messageStarted(MessageStart(responseID: "r", reportedModel: "scripted")))158 switch turn {159 case .calls(let calls, let text):160 if !text.isEmpty { continuation.yield(.textDelta(text)) }161 for (i, c) in calls.enumerated() {162 let call = ToolCall(id: "call-\(base + i)", name: c.name, arguments: c.arguments)163 continuation.yield(.toolCallStarted(id: call.id, name: call.name))164 continuation.yield(.toolCallCompleted(call))165 }166 if let usage { continuation.yield(.usage(usage)) }167 continuation.yield(.messageCompleted(.toolCalls)); continuation.finish()168 case .text(let text):169 continuation.yield(.textDelta(text))170 if let usage { continuation.yield(.usage(usage)) }171 continuation.yield(.messageCompleted(.endOfTurn)); continuation.finish()172 case .hang:173 try? await Task.sleep(nanoseconds: 60_000_000_000)174 continuation.finish(throwing: CancellationError())175 case .fail(let error): continuation.finish(throwing: error)176 case .after: continuation.finish()177 }178 }179 continuation.onTermination = { _ in task.cancel() }180 }181 }182183 /// Tool results the model received in its `n`-th request (0-based), in order.184 func toolResults(request n: Int) -> [PromptMessage] { requests[n].messages.filter { $0.role == .tool } }185 /// The last tool result delivered before the `n`-th request.186 func lastToolResult(request n: Int) -> String { toolResults(request: n).last?.text ?? "" }187}188189// MARK: - Documents190191/// A small paper: headings, a citation, an equation, a cross-reference to a heading, and a table.192func sampleDocument() -> DocumentModel {193 var doc = DocumentModel()194 doc.meta.title = "Sample"195 doc.bibliography = [BibEntry(key: "smith2020", authors: [PersonName(family: "Smith", given: "Ann")], year: 2020, fields: ["title": "On Things", "container-title": "Journal of Things", "volume": "1", "page": "1-10"]),196 BibEntry(key: "lee2019", type: "book", authors: [PersonName(family: "Lee", given: "Bo")], year: 2019, fields: ["title": "A Book", "publisher": "Press"])]197 let intro = Paragraph(id: "p-intro", runs: [Run("The result is known "), Run(inline: .citation(Citation("smith2020"))), Run(" and "), Run("important", props: CharProps(bold: true)), Run(".")])198 let eq = Paragraph(id: "p-eq", runs: [Run("Energy is "), Run(inline: .equation(Equation(latex: "E = mc^2"))), Run(" always.")])199 let ref = Paragraph(id: "p-ref", runs: [Run("See section "), Run(inline: .crossRef(CrossRef(target: "h-methods", display: .text))), Run(" for details.")])200 doc.body = [201 .paragraph(Paragraph(id: "h-intro", style: StyleID.heading(1), runs: [Run("Introduction")])),202 .paragraph(intro),203 .paragraph(eq),204 .paragraph(ref),205 .paragraph(Paragraph(id: "h-methods", style: StyleID.heading(1), runs: [Run("Methods")])),206 .paragraph(Paragraph(id: "p-methods", runs: [Run("We measured émotions 😀 twice.")])),207 .paragraph(Paragraph(id: "h-sub", style: StyleID.heading(2), runs: [Run("Sampling")])),208 .paragraph(Paragraph(id: "p-sub", runs: [Run("Random sampling was used.")])),209 .paragraph(Paragraph(id: "h-results", style: StyleID.heading(1), runs: [Run("Results")])),210 .table(Table(id: "t-1", columnWidths: [200, 200], rows: [TableRow(cells: [TableCell("Name", bold: true), TableCell("Value", bold: true)], isHeader: true),211 TableRow(cells: [TableCell("a"), TableCell("1")])])),212 .paragraph(Paragraph(id: "p-end", runs: [Run("The end.")])),213 ]214 return doc215}216217/// A long report: `sections` level-1 headings with `paragraphs` paragraphs each, every section about its own topic.218func longDocument(sections: Int = 12, paragraphs: Int = 3) -> DocumentModel {219 let topics = ["glaciers", "volcanoes", "monsoons", "tundra", "estuaries", "canyons", "reefs", "deserts", "wetlands", "fjords", "savannas", "geysers",220 "plateaus", "lagoons", "steppes", "deltas"]221 var doc = DocumentModel()222 doc.meta.title = "Long report"223 doc.bibliography = [BibEntry(key: "atlas2021", authors: [PersonName(family: "Atlas", given: "Ed")], year: 2021, fields: ["title": "World Atlas", "publisher": "Maps"])]224 var body: [Block] = []225 for s in 0..<sections {226 let topic = topics[s % topics.count]227 body.append(.paragraph(Paragraph(id: "h\(s)", style: StyleID.heading(1), runs: [Run("Chapter \(s + 1): \(topic.capitalized)")])))228 for p in 0..<paragraphs {229 var runs = [Run("Paragraph \(p + 1) about \(topic): the \(topic) of region \(s) were surveyed in detail and their extent recorded")]230 if p == 0 { runs += [Run(" "), Run(inline: .citation(Citation("atlas2021")))] }231 runs.append(Run("."))232 body.append(.paragraph(Paragraph(id: "s\(s)p\(p)", runs: runs)))233 }234 }235 doc.body = body236 return doc237}238239func text(of id: String, in model: DocumentModel) -> String {240 let index = DocIndex(model)241 guard let a = index.paragraphs[id], let p = model.blocks(in: a.story).paragraph(at: a.path) else { return "<missing>" }242 return DocRender.text(p)243}244245// MARK: - Approvers246247/// Records what it is asked and answers from closures.248final class RecordingApprover: ChangeApprover, Sendable {249 private struct State { var proposals: [ChangeProposal] = []; var actions: [ActionRequest] = []; var questions: [UserQuestion] = [] }250 private let state = Mutex(State())251 private let onReview: @Sendable (ChangeProposal, Int) async -> ProposalDecision252 private let onAuthorize: @Sendable (ActionRequest) async -> Bool253 private let onAnswer: @Sendable (UserQuestion) async -> String?254255 init(review: @escaping @Sendable (ChangeProposal, Int) async -> ProposalDecision = { _, _ in .acceptAll },256 authorize: @escaping @Sendable (ActionRequest) async -> Bool = { _ in true },257 answer: @escaping @Sendable (UserQuestion) async -> String? = { _ in nil }) {258 onReview = review; onAuthorize = authorize; onAnswer = answer259 }260 convenience init(always decision: ProposalDecision) { self.init(review: { _, _ in decision }) }261262 var proposals: [ChangeProposal] { state.withLock { $0.proposals } }263 var actions: [ActionRequest] { state.withLock { $0.actions } }264 var questions: [UserQuestion] { state.withLock { $0.questions } }265266 func review(_ proposal: ChangeProposal) async -> ProposalDecision {267 let n = state.withLock { s in s.proposals.append(proposal); return s.proposals.count }268 return await onReview(proposal, n)269 }270 func authorize(_ request: ActionRequest) async -> Bool { state.withLock { $0.actions.append(request) }; return await onAuthorize(request) }271 func answer(_ question: UserQuestion) async -> String? { state.withLock { $0.questions.append(question) }; return await onAnswer(question) }272}273274// MARK: - Hosts that misbehave275276/// Wraps a host and, on `apply`, runs one more command than was approved: the document it leaves is not the one that was previewed.277actor TamperingHost: DocumentHost {278 let inner: InMemoryDocumentHost279 let extra: DocCommandRequest280 private(set) var undone = 0281 init(_ inner: InMemoryDocumentHost, extra: DocCommandRequest) { self.inner = inner; self.extra = extra }282 func documentID() async -> String { await inner.documentID() }283 func snapshot() async -> DocumentState { await inner.snapshot() }284 func apply(_ requests: [DocCommandRequest], context: DocCommandContext, options: DocExecutionOptions) async throws -> HostApplyResult {285 var wide = context; wide.scopes = Set(DocScope.allCases)286 return try await inner.apply(requests + [extra], context: wide, options: options)287 }288 func undo(revision: Int) async throws -> DocumentState { undone += 1; return try await inner.undo(revision: revision) }289 func deliver(_ artifact: DocArtifact) async -> ArtifactReceipt { await inner.deliver(artifact) }290}291292/// Wraps a host and takes its time applying, counting how many applications overlap.293actor SlowHost: DocumentHost {294 let inner: InMemoryDocumentHost295 private var active = 0296 private(set) var peak = 0297 private(set) var applies = 0298 init(_ inner: InMemoryDocumentHost) { self.inner = inner }299 func documentID() async -> String { await inner.documentID() }300 func snapshot() async -> DocumentState { await inner.snapshot() }301 func apply(_ requests: [DocCommandRequest], context: DocCommandContext, options: DocExecutionOptions) async throws -> HostApplyResult {302 active += 1; peak = max(peak, active); applies += 1303 defer { active -= 1 }304 try? await Task.sleep(nanoseconds: 30_000_000)305 return try await inner.apply(requests, context: context, options: options)306 }307 func undo(revision: Int) async throws -> DocumentState { try await inner.undo(revision: revision) }308 func deliver(_ artifact: DocArtifact) async -> ArtifactReceipt { await inner.deliver(artifact) }309}310311// MARK: - Builders312313let testModel = ModelRef(provider: .openAI, modelID: "scripted-1")314let everyScope = DocScope.allDocument315/// Edits within every document scope are applied without asking.316let unattended = AutonomyPolicy(.advanced(preauthorized: DocScope.allDocument, sections: nil))317318struct Rig {319 var agent: DocumentAgent320 var host: InMemoryDocumentHost321 var provider: ScriptedProvider322 var approver: RecordingApprover323 var checkpoints: InMemoryCheckpointStore324}325326func makeRig(_ turns: [ScriptTurn], document: DocumentModel = sampleDocument(), revision: Int = 7, scopes: Set<DocScope> = everyScope,327 autonomy: AutonomyPolicy = unattended, budget: AgentBudget = AgentBudget(), approver: RecordingApprover = RecordingApprover(),328 objective: String = "Improve the document.", configure: (inout AgentConfiguration) -> Void = { _ in },329 services configureServices: (inout AgentServices) -> Void = { _ in }, provider: ScriptedProvider? = nil, host: InMemoryDocumentHost? = nil) -> Rig {330 let host = host ?? InMemoryDocumentHost(document, revision: revision)331 let provider = provider ?? ScriptedProvider(turns)332 let checkpoints = InMemoryCheckpointStore()333 var configuration = AgentConfiguration(objective: objective, model: testModel, scopes: scopes, autonomy: autonomy, budget: budget)334 configure(&configuration)335 var services = AgentServices(provider: provider, host: host, approver: approver, checkpoints: checkpoints)336 configureServices(&services)337 return Rig(agent: DocumentAgent(configuration: configuration, services: services), host: host, provider: provider, approver: approver, checkpoints: checkpoints)338}339340extension Array where Element == AgentTimelineEvent {341 var errors: [String] { compactMap { if case .error(let m) = $0.kind { m } else { nil } } }342 var recoveries: [String] { compactMap { if case .recovery(let m) = $0.kind { m } else { nil } } }343 var proposals: [ChangeProposal] { compactMap { if case .changesProposed(let p) = $0.kind { p } else { nil } } }344 var applied: [AppliedBatch] { compactMap { if case .changesApplied(let b) = $0.kind { b } else { nil } } }345 var validations: [(stage: String, result: IntegrityResult)] { compactMap { if case .validation(let s, let r) = $0.kind { (s, r) } else { nil } } }346 var suspicious: [(source: String, findings: Int)] { compactMap { if case .suspiciousContent(let s, let f) = $0.kind { (s, f.count) } else { nil } } }347 var finishedTools: [(tool: String, isError: Bool, result: String)] { compactMap { if case .toolFinished(_, let t, let r, let e, _) = $0.kind { (t, e, r) } else { nil } } }348 var steps: Int { filter { if case .stepStarted = $0.kind { true } else { false } }.count }349}350