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/AgentLoopTests.swift10// Description : Tests of the agent loop with a scripted model and an11// in-memory document: the tool catalog, autonomy modes,12// approval decisions, revision safety, integrity validation13// and rollback, budgets, cancellation, and recovery from14// invalid tool calls.15// Module : DocAgentTests16// Repository : https://git.spboucher.ai/orix-docs17// Created : 2026-11-2218// Last Modified : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import Foundation93import Synchronization94import Testing95import AstraCore96import DocModel97import DocCommands98@testable import DocAgent99100let read = ScriptTurn.call("document_read")101func insert(_ text: String, into paragraph: String = "p-end") -> ScriptCall {102 ScriptCall("text_insert", ["position": ["paragraph": .string(paragraph), "at": "end"], "text": .string(text)])103}104105func waitUntil(_ timeout: TimeInterval = 5, _ condition: @Sendable () async -> Bool) async -> Bool {106 let deadline = Date().addingTimeInterval(timeout)107 while Date() < deadline {108 if await condition() { return true }109 try? await Task.sleep(nanoseconds: 5_000_000)110 }111 return false112}113114@Suite(.serialized) struct ToolCatalogTests {115 @Test func everyCommandIsExposedUnderAProviderSafeNameAndMapsBack() throws {116 let specs = DocCommandRegistry.standard.specs117 let catalog = DocToolCatalog(scopes: Set(DocScope.allCases))118 #expect(specs.count >= 57)119 let pattern = try NSRegularExpression(pattern: "^[A-Za-z0-9_-]{1,64}$")120 for spec in specs {121 let name = ToolNaming.modelName(spec.id)122 #expect(pattern.firstMatch(in: name, range: NSRange(location: 0, length: name.utf16.count)) != nil, "\(name)")123 let tool = try #require(catalog.tool(named: name), "\(spec.id) is not exposed")124 #expect(tool.id == spec.id && tool.isCommand)125 #expect(tool.scopes == spec.permissions)126 #expect(tool.effect == (spec.mutates ? .mutate : spec.sideEffect == .producesArtifact ? .artifact : .read))127 // The schema survives the trip to the model's JSON type and back, and the description comes from the specification.128 #expect(JSONBridge.doc(tool.definition.parameters) == spec.input, "\(spec.id)")129 #expect(tool.definition.summary.hasPrefix(spec.summary))130 #expect(tool.timeout != nil)131 }132 #expect(Set(catalog.names).count == catalog.tools.count)133 #expect(catalog.tools.filter(\.isCommand).count == specs.count)134 for id in AgentToolID.all { #expect(catalog.tool(id: id) != nil, "\(id)") }135 #expect(catalog.tool(named: "plan_update")?.id == "plan.update" && catalog.tool(named: "workflow_execute")?.id == "workflow.execute")136 }137138 @Test func toolsAreFilteredByGrantedScopes() {139 let readOnly = DocToolCatalog(scopes: [.documentRead])140 #expect(readOnly.tools.allSatisfy { $0.effect != .mutate && $0.effect != .artifact && $0.effect != .workflow })141 #expect(readOnly.tool(named: "text_insert") == nil && readOnly.tool(named: "document_export") == nil && readOnly.tool(named: "workflow_execute") == nil)142 #expect(readOnly.tool(named: "document_read") != nil && readOnly.tool(named: "context_retrieve") != nil && readOnly.tool(named: "finish") != nil)143 let writer = DocToolCatalog(scopes: [.documentRead, .documentWrite])144 #expect(writer.tool(named: "text_rewrite") != nil && writer.tool(named: "style_apply") == nil && writer.tool(named: "citation_insert") == nil)145 let subset = DocToolCatalog(scopes: Set(DocScope.allCases), options: .init(commandAllowlist: ["document.read", "text.rewrite"], deniedCommands: ["text.rewrite"]))146 #expect(subset.tools.filter(\.isCommand).map(\.id) == ["document.read"])147 }148149 @Test func thereIsNoFileSystemOrShellTool() {150 let catalog = DocToolCatalog(scopes: Set(DocScope.allCases))151 for tool in catalog.tools {152 let name = tool.name.lowercased()153 for word in ["shell", "exec_", "bash", "file", "path", "http", "fetch", "eval"] { #expect(!name.contains(word), "\(name)") }154 }155 }156157 @Test func modelNumbersBecomeIntegersForTheCommandEngine() {158 #expect(JSONBridge.doc(["a": 3, "b": 1.5, "c": [true, nil, "x"]]) == ["a": .int(3), "b": .double(1.5), "c": [true, nil, "x"]])159 }160}161162@Suite(.serialized) struct AutonomyTests {163 @Test func guidedAsksForEveryCommandSeparately() async {164 let rig = makeRig([read, .calls([insert(" One."), insert(" Two.", into: "p-sub")]), .finish()], autonomy: AutonomyPolicy(.guided))165 let report = await rig.agent.run()166 #expect(report.status == .completed)167 #expect(rig.approver.proposals.count == 2 && rig.approver.proposals.allSatisfy { $0.commands.count == 1 })168 let v1 = await rig.host.applyCount169 #expect(v1 == 2)170 #expect(report.applied.map(\.approval) == ["approved", "approved"])171 let v2 = await rig.host.state.model172 #expect(text(of: "p-end", in: v2) == "The end. One." && text(of: "p-sub", in: v2) == "Random sampling was used. Two.")173 }174175 @Test func guidedKeepsLinkedCommandsTogether() async {176 let turns: [ScriptTurn] = [read, .calls([ScriptCall("content_insert", ["placement": ["after": "p-end"], "content": "Appendix."]),177 ScriptCall("text_insert", ["position": ["paragraph": "{{0.ids.0}}"], "text": " Linked."]),178 insert(" Alone.")]), .finish()]179 let rig = makeRig(turns, autonomy: AutonomyPolicy(.guided))180 _ = await rig.agent.run()181 #expect(rig.approver.proposals.map { $0.commands.count } == [2, 1])182 #expect(rig.approver.proposals[0].commands[1].dependsOn == [0])183 let v3 = await rig.host.state.model.body184 #expect(v3.compactMap { $0.paragraph }.map(DocRender.text).contains("Appendix. Linked."))185 }186187 @Test func balancedReadsFreelyAndAsksOncePerBatch() async {188 let rig = makeRig([.calls([ScriptCall("document_inspect"), ScriptCall("document_outline"), ScriptCall("document_read")]),189 .calls([insert(" One."), insert(" Two.", into: "p-sub")]), .finish()], autonomy: AutonomyPolicy(.balanced))190 let report = await rig.agent.run()191 #expect(rig.approver.proposals.count == 1 && rig.approver.proposals[0].commands.count == 2)192 #expect(rig.approver.actions.isEmpty)193 // One batch is one transaction: one revision, one undo step.194 let v4 = await rig.host.applyCount195 let v5 = await rig.host.state.revision196 #expect(v4 == 1 && v5 == 8)197 #expect(report.applied.count == 1 && report.applied[0].revisionBefore == 7 && report.applied[0].revisionAfter == 8)198 }199200 @Test func balancedWithoutApproverChangesNothing() async {201 let host = InMemoryDocumentHost(sampleDocument(), revision: 7)202 let provider = ScriptedProvider([read, .calls([insert(" One.")]), .finish()])203 let agent = DocumentAgent(configuration: AgentConfiguration(objective: "x", model: testModel, scopes: everyScope),204 services: AgentServices(provider: provider, host: host))205 let report = await agent.run()206 #expect(report.applied.isEmpty && report.rejected.count == 1)207 let v6 = await host.state.revision208 #expect(v6 == 7)209 #expect(provider.lastToolResult(request: 2).contains("rejected_by_user"))210 }211212 @Test func advancedAppliesWithinPreauthorizedScopesAndRefusesOutsideTheSectionWhitelist() async {213 let policy = AutonomyPolicy(.advanced(preauthorized: [.documentRead, .documentWrite], sections: ["h-methods"]))214 let rig = makeRig([read,215 .calls([insert(" Inside.", into: "p-methods")]), // under h-methods216 .calls([insert(" Nested.", into: "p-sub")]), // under h-sub, itself under h-methods217 .calls([insert(" Outside.", into: "p-intro")]), // under h-intro: refused218 .calls([ScriptCall("content_insert", ["placement": ["at": "end"], "content": "Tail."])]), // lands under h-results: refused219 .calls([ScriptCall("document_setMetadata", ["title": "Hijacked"])]), // document-wide: refused220 .calls([ScriptCall("style_apply", ["style": "Quote", "paragraphs": ["p-methods"]])]), // format scope is granted, not pre-authorised: asks221 .finish()], autonomy: policy)222 let report = await rig.agent.run()223 let model = await rig.host.state.model224 #expect(text(of: "p-methods", in: model).hasSuffix("twice. Inside.") && text(of: "p-sub", in: model).hasSuffix(" Nested."))225 #expect(text(of: "p-intro", in: model) == text(of: "p-intro", in: sampleDocument()) && model.meta.title == "Sample")226 #expect(!model.body.compactMap { $0.paragraph }.map(DocRender.text).contains("Tail."))227 #expect(rig.provider.lastToolResult(request: 4).contains("outside_authorised_sections"))228 #expect(rig.provider.lastToolResult(request: 5).contains("outside_authorised_sections"))229 #expect(rig.provider.lastToolResult(request: 6).contains("outside_authorised_sections"))230 // Only the formatting change reached the approver; the refusals never did.231 #expect(rig.approver.proposals.count == 1 && rig.approver.proposals[0].commands[0].command == "style.apply")232 #expect(report.applied.map(\.approval) == ["pre-authorized", "pre-authorized", "approved"])233 }234235 @Test func customRulesAllowAskAndDenyPerScopeAndPerCommand() async {236 let policy = AutonomyPolicy(.custom(scopes: [.documentWrite: .allow, .documentFormat: .ask, .documentReferences: .deny],237 commands: ["block.delete": .deny, "text.replaceAll": .ask]))238 let rig = makeRig([read,239 .calls([insert(" Allowed.")]),240 .calls([ScriptCall("style_apply", ["style": "Quote", "paragraphs": ["p-end"]])]),241 .calls([ScriptCall("text_replaceAll", ["query": "sampling", "replacement": "selection"])]),242 .calls([ScriptCall("block_delete", ["blocks": ["p-end"]])]),243 .calls([ScriptCall("citation_insert", ["position": ["paragraph": "p-end"], "items": [["key": "lee2019"]]])]),244 .finish()], autonomy: policy)245 #expect(rig.agent.catalog.tool(named: "block_delete") == nil && rig.agent.catalog.tool(named: "citation_insert") == nil)246 #expect(rig.agent.catalog.tool(named: "bibliography_list") != nil) // a read under no denied scope247 let report = await rig.agent.run()248 #expect(rig.approver.proposals.map { $0.commands[0].command } == ["style.apply", "text.replaceAll"])249 #expect(report.applied.map(\.approval) == ["pre-authorized", "approved", "approved"])250 #expect(rig.provider.lastToolResult(request: 5).contains("unknown_tool") && rig.provider.lastToolResult(request: 6).contains("unknown_tool"))251 let v7 = await rig.host.state.model.body252 #expect(v7.contains { $0.id == "p-end" })253 }254255 @Test func exportProducesAnArtifactHandedToTheHostAfterApproval() async {256 let rig = makeRig([read, .call("document_export", ["format": "txt"]), .finish()], autonomy: AutonomyPolicy(.balanced))257 let report = await rig.agent.run()258 #expect(rig.approver.actions.map(\.tool) == ["document.export"])259 let v8 = await rig.host.artifacts.count260 #expect(v8 == 1 && report.artifacts.count == 1 && report.artifacts[0].disposition == "Kept in memory")261 #expect(report.applied.isEmpty && report.revisionAtEnd == 7)262263 let refused = makeRig([read, .call("document_export", ["format": "txt"]), .finish()], autonomy: AutonomyPolicy(.balanced),264 approver: RecordingApprover(authorize: { _ in false }))265 let second = await refused.agent.run()266 let v9 = await refused.host.artifacts.isEmpty267 #expect(v9 && second.artifacts.isEmpty)268 #expect(refused.provider.lastToolResult(request: 2).contains("not_approved"))269 }270}271272@Suite(.serialized) struct ApprovalTests {273 static let three: [ScriptTurn] = [read, .calls([insert(" One."), insert(" Two.", into: "p-sub"), insert(" Three.", into: "p-methods")]), .finish()]274275 @Test func proposalDescribesTheChangesFromThePreview() async throws {276 let rig = makeRig([read, .calls([ScriptCall("text_rewrite", ["paragraph": "p-intro", "text": "The result is well known [@smith2020] [@lee2019] and important."]),277 ScriptCall("table_insert", ["placement": ["after": "p-end"], "rows": [["A", "B"], ["1", "2"]]]),278 ScriptCall("style_apply", ["style": "Quote", "paragraphs": ["p-end"]])]), .finish()],279 autonomy: AutonomyPolicy(.balanced), configure: { $0.includePagination = true; $0.trackChanges = true })280 _ = await rig.agent.run()281 let p = try #require(rig.approver.proposals.first)282 #expect(p.baseRevision == 7 && p.tracked && p.author == "ORIX AI (scripted-1)")283 let intro = try #require(p.blocks.first { $0.block == "p-intro" })284 #expect(intro.kind == .modified && intro.original == "The result is known [@smith2020] and important.")285 #expect(intro.citationsAdded == ["lee2019"] && intro.citationsRemoved.isEmpty)286 #expect(p.insertedTables == 1)287 let styled = try #require(p.blocks.first { $0.block == "p-end" })288 #expect(styled.styleAfter == "Quote" && styled.styleBefore != "Quote")289 #expect(p.pagesBefore == 1 && p.pagesAfter != nil)290 #expect(p.commands.map(\.editableArgument) == ["text", nil, nil])291 #expect(!p.parts.contains("metadata")) // the modification date is not a change to approve292 // Applied as tracked changes under the agent's name, whatever the document's own setting.293 let model = await rig.host.state.model294 #expect(model.settings.trackChanges == false)295 #expect(model.trackedChanges().contains { $0.author == "ORIX AI (scripted-1)" })296 }297298 @Test func acceptAllAppliesOneUndoStep() async {299 let rig = makeRig(Self.three, autonomy: AutonomyPolicy(.balanced))300 let report = await rig.agent.run()301 let v10 = await rig.host.applyCount302 let v11 = await rig.host.state.revision303 #expect(v10 == 1 && v11 == 8)304 #expect(report.totals.modified == 3 && report.changeList.count == 3)305 // Undoing that one step restores the original document.306 let restored = try? await rig.host.undo(revision: 8)307 #expect(restored?.model.body.map(DocRender.summary) == sampleDocument().body.map(DocRender.summary))308 }309310 @Test func rejectChangesNothingAndTellsTheModelWhy() async {311 let rig = makeRig(Self.three, autonomy: AutonomyPolicy(.balanced), approver: RecordingApprover(always: .reject(reason: "Too wordy.")))312 let report = await rig.agent.run()313 let v12 = await rig.host.applyCount314 let v13 = await rig.host.state.revision315 #expect(v12 == 0 && v13 == 7)316 #expect(report.applied.isEmpty && report.rejected.count == 1 && report.rejected[0].reason == "Too wordy.")317 let results = rig.provider.toolResults(request: 2).suffix(3)318 #expect(results.allSatisfy { $0.toolIsError && $0.text.contains("rejected_by_user") && $0.text.contains("Too wordy.") })319 }320321 @Test func acceptSelectedAppliesOnlyTheSelectionAsOneTransaction() async {322 let rig = makeRig(Self.three, autonomy: AutonomyPolicy(.balanced), approver: RecordingApprover(always: .acceptSelected(commands: [0, 2])))323 let report = await rig.agent.run()324 let model = await rig.host.state.model325 #expect(text(of: "p-end", in: model) == "The end. One." && text(of: "p-methods", in: model).hasSuffix(" Three."))326 #expect(text(of: "p-sub", in: model) == "Random sampling was used.")327 let v14 = await rig.host.applyCount328 #expect(v14 == 1 && report.applied[0].commands.count == 2 && report.applied[0].approval == "approved (selection)")329 let results = Array(rig.provider.toolResults(request: 2).suffix(3))330 #expect(!results[0].toolIsError && results[1].toolIsError && results[1].text.contains("not_selected") && !results[2].toolIsError)331 }332333 @Test func aSelectionThatDependsOnARejectedCommandIsRefusedWithTheReason() async {334 let turns: [ScriptTurn] = [read, .calls([ScriptCall("content_insert", ["placement": ["after": "p-end"], "content": "Appendix."]),335 ScriptCall("text_insert", ["position": ["paragraph": "{{0.ids.0}}"], "text": " Linked."])]), .finish()]336 let rig = makeRig(turns, autonomy: AutonomyPolicy(.balanced), approver: RecordingApprover(always: .acceptSelected(commands: [1])))337 let report = await rig.agent.run()338 let v15 = await rig.host.applyCount339 #expect(v15 == 0)340 #expect(rig.approver.proposals[0].missingDependencies(selecting: [1]).map(\.needs) == [0])341 #expect(report.rejected[0].reason.contains("uses the output of change 0"))342 #expect(rig.provider.lastToolResult(request: 2).contains("uses the output of change 0"))343 }344345 @Test func aSelectionRenumbersReferencesBetweenTheKeptCommands() async {346 let turns: [ScriptTurn] = [read, .calls([insert(" Dropped."),347 ScriptCall("content_insert", ["placement": ["after": "p-end"], "content": "Appendix."]),348 ScriptCall("text_insert", ["position": ["paragraph": "{{1.ids.0}}"], "text": " Linked."])]), .finish()]349 let rig = makeRig(turns, autonomy: AutonomyPolicy(.balanced), approver: RecordingApprover(always: .acceptSelected(commands: [1, 2])))350 _ = await rig.agent.run()351 let texts = await rig.host.state.model.body.compactMap { $0.paragraph }.map(DocRender.text)352 #expect(texts.contains("Appendix. Linked.") && texts.contains("The end."))353 }354355 @Test func anEditedTextIsWhatGetsAppliedAndTheModelIsTold() async {356 let rig = makeRig(Self.three, autonomy: AutonomyPolicy(.balanced),357 approver: RecordingApprover(always: .acceptEdited(edits: [ProposalEdit(command: 0, text: " Uno.")], commands: nil)))358 let report = await rig.agent.run()359 let v16 = await rig.host.state.model360 #expect(text(of: "p-end", in: v16) == "The end. Uno.")361 #expect(report.applied[0].approval == "approved (edited)" && report.applied[0].commands.count == 3)362 let first = rig.provider.toolResults(request: 2).suffix(3).first363 #expect(first?.text.contains("editedByUser") == true && first?.text.contains("Uno.") == true)364 }365366 @Test func aBatchThatChangesNothingNeedsNoApproval() async {367 let rig = makeRig([read, .calls([ScriptCall("document_setMetadata", ["title": "Sample"])]), .finish()], autonomy: AutonomyPolicy(.guided))368 let report = await rig.agent.run()369 #expect(rig.approver.proposals.isEmpty && report.applied.isEmpty)370 #expect(rig.provider.lastToolResult(request: 2).contains("changed nothing"))371 }372}373374@Suite(.serialized) struct RevisionSafetyTests {375 @Test func aMutationBeforeAnyReadIsRefused() async {376 let rig = makeRig([.calls([insert(" Blind.")]), read, .calls([insert(" Seen.")]), .finish()])377 let report = await rig.agent.run()378 #expect(rig.provider.lastToolResult(request: 1).contains("inspect_first"))379 let v17 = await rig.host.state.model380 #expect(text(of: "p-end", in: v17) == "The end. Seen." && report.applied.count == 1)381 }382383 @Test func aWriteAfterSomeoneElseEditedIsRefusedThenReplanned() async {384 let host = InMemoryDocumentHost(sampleDocument(), revision: 7)385 // The model reads at revision 7; before its next turn the user rewrites the paragraph it is about to change.386 let rewrite = ScriptCall("text_rewrite", ["paragraph": "p-methods", "text": "We measured emotions three times.", "expect": "We measured émotions 😀 twice."])387 let turns: [ScriptTurn] = [read,388 .after({ _ = try? await host.externalCommands([DocCommandRequest("text.rewrite", ["paragraph": "p-methods", "text": "We measured émotions 😀 four times, carefully."])]) },389 .calls([rewrite])),390 .calls([ScriptCall("text_rewrite", ["paragraph": "p-methods", "text": "We measured emotions four times, carefully and blind."])]),391 .finish()]392 let rig = makeRig(turns, host: host)393 let report = await rig.agent.run()394 // The stale edit never reached the document: it was refused before any preview, with the current text of the block.395 let conflict = rig.provider.lastToolResult(request: 2)396 #expect(conflict.contains("revision_conflict") && conflict.contains("four times, carefully") && conflict.contains("revision 7 → 8"))397 #expect(rig.provider.toolResults(request: 2).last?.toolIsError == true)398 let events = rig.agent.timeline.events399 #expect(events.errors.contains { $0.contains("changed since the model read it") } && events.recoveries.contains { $0.contains("Read 1 affected block") })400 // The re-planned edit, made from the fresh text, is applied on top of the user's change.401 let v18 = await rig.host.state.model402 #expect(text(of: "p-methods", in: v18) == "We measured emotions four times, carefully and blind.")403 #expect(report.applied.count == 1 && report.applied[0].revisionBefore == 8 && report.applied[0].revisionAfter == 9)404 #expect(report.externalChanges == 1 && report.revisionAtStart == 7 && report.revisionAtEnd == 9)405 let v19 = await host.applyCount406 #expect(v19 == 1)407 }408409 @Test func aBlockThatChangedSinceItWasShownCannotBeOverwrittenEvenAfterALaterRead() async {410 let host = InMemoryDocumentHost(sampleDocument(), revision: 7)411 // The model saw p-end at revision 7. The user changes it; the model then reads something else (so it knows revision 8) and rewrites p-end from memory.412 let turns: [ScriptTurn] = [read,413 .after({ _ = try? await host.externalCommands([DocCommandRequest("text.rewrite", ["paragraph": "p-end", "text": "The real end."])]) }, .call("document_outline")),414 .calls([ScriptCall("text_rewrite", ["paragraph": "p-end", "text": "The end, at last."])]),415 .finish()]416 let rig = makeRig(turns, host: host)417 let report = await rig.agent.run()418 #expect(rig.provider.lastToolResult(request: 3).contains("stale_content") && rig.provider.lastToolResult(request: 3).contains("The real end."))419 let v20 = await host.state.model420 #expect(text(of: "p-end", in: v20) == "The real end." && report.applied.isEmpty)421 }422423 @Test func anEditMadeWhileTheApprovalSheetIsOpenCancelsTheBatch() async {424 let host = InMemoryDocumentHost(sampleDocument(), revision: 7)425 let approver = RecordingApprover(review: { _, n in426 if n == 1 { await host.externalEdit { $0.meta.subject = "typed meanwhile" } }427 return .acceptAll428 })429 let rig = makeRig([read, .calls([insert(" One.")]), .calls([insert(" One.")]), .finish()], autonomy: AutonomyPolicy(.balanced), approver: approver, host: host)430 let report = await rig.agent.run()431 #expect(rig.provider.lastToolResult(request: 2).contains("revision_conflict"))432 // The second attempt was previewed on the new revision and approved again.433 #expect(approver.proposals.map(\.baseRevision) == [7, 8])434 let v21 = await host.state.model435 #expect(report.applied.count == 1 && text(of: "p-end", in: v21) == "The end. One.")436 }437}438439@Suite(.serialized) struct IntegrityTests {440 @Test func integrityIssuesAreFoundWithTheEnginesValidators() {441 var doc = sampleDocument()442 #expect(DocumentIntegrity.issues(in: doc).isEmpty)443 doc.body.removeAll { $0.id == "h-methods" }444 doc.bibliography.removeAll { $0.key == "smith2020" }445 doc.body.append(.paragraph(Paragraph(id: "p-end", runs: [Run("Twin.")])))446 let kinds = Set(DocumentIntegrity.issues(in: doc).map(\.kind))447 #expect(kinds == [.brokenCrossReference, .unresolvedCitation, .duplicateIdentifier])448 // Problems that were already there are not blamed on a later step.449 var later = doc450 later.meta.title = "x"451 #expect(DocumentIntegrity.compare(before: doc, after: later).ok && DocumentIntegrity.compare(before: doc, after: later).preexisting == 3)452 #expect(!DocumentIntegrity.compare(before: sampleDocument(), after: doc).ok)453 }454455 @Test func aBatchThatWouldBreakACrossReferenceOrACitationIsRefusedBeforeApplying() async {456 let rig = makeRig([read,457 .calls([ScriptCall("block_delete", ["blocks": ["h-methods"]])]),458 .calls([ScriptCall("bibliography_remove", ["keys": ["smith2020"], "force": true])]),459 // Removing the reference together with its target is sound.460 .calls([ScriptCall("block_delete", ["blocks": ["h-methods", "p-ref"]])]),461 .finish()])462 let report = await rig.agent.run()463 #expect(rig.provider.lastToolResult(request: 2).contains("integrity_violation") && rig.provider.lastToolResult(request: 2).contains("broken_cross_reference"))464 #expect(rig.provider.lastToolResult(request: 3).contains("unresolved_citation"))465 #expect(report.applied.count == 1 && report.integrityIssues.isEmpty)466 let v22 = await rig.host.state.model.bibliography.count467 #expect(v22 == 2)468 let stages = rig.agent.timeline.events.validations469 #expect(stages.map(\.stage) == ["preview", "preview", "preview", "applied"] && stages.map(\.result.ok) == [false, false, true, true])470 }471472 @Test func aStepThatLeavesTheDocumentBrokenIsRolledBack() async {473 let inner = InMemoryDocumentHost(sampleDocument(), revision: 7)474 // The host applies more than was previewed: the heading a cross-reference points at disappears.475 let host = TamperingHost(inner, extra: DocCommandRequest("block.delete", ["blocks": ["h-methods"]]))476 let provider = ScriptedProvider([read, .calls([insert(" One.")]), .finish()])477 let agent = DocumentAgent(configuration: AgentConfiguration(objective: "x", model: testModel, scopes: everyScope, autonomy: unattended),478 services: AgentServices(provider: provider, host: host))479 let report = await agent.run()480 let v23 = await host.undone481 #expect(v23 == 1)482 let v24 = await inner.state.model.body483 #expect(v24.map(DocRender.summary) == sampleDocument().body.map(DocRender.summary))484 #expect(provider.lastToolResult(request: 2).contains("integrity_violation") && provider.lastToolResult(request: 2).contains("undone"))485 #expect(report.applied.count == 1 && report.applied[0].undone && report.totals.batches == 0 && report.changeList.isEmpty)486 #expect(agent.timeline.events.recoveries.contains { $0.contains("was undone") })487 #expect(report.integrityIssues.isEmpty && report.externalChanges == 0)488 }489}490491@Suite(.serialized) struct BudgetTests {492 static let endless: @Sendable (GenerationRequest, Int) -> ScriptTurn = { _, _ in .call("document_outline") }493494 @Test func stepBudget() async {495 let rig = makeRig([], budget: AgentBudget(maxSteps: 3), provider: ScriptedProvider(responder: Self.endless))496 let report = await rig.agent.run()497 #expect(report.status == .budgetExhausted(.steps) && report.budget.steps == 3 && rig.provider.requests.count == 3)498 }499500 @Test func tokenBudgetUsesReportedUsage() async {501 let rig = makeRig([], budget: AgentBudget(maxSteps: 50, maxTokens: 300), provider: ScriptedProvider(responder: Self.endless))502 let report = await rig.agent.run()503 // 120 tokens a turn: the third turn crosses 300 and no fourth is started.504 #expect(report.status == .budgetExhausted(.tokens) && report.budget.totalTokens == 360 && !report.budget.tokensEstimated)505 }506507 @Test func tokensAreEstimatedWhenTheProviderReportsNone() async {508 let rig = makeRig([], budget: AgentBudget(maxSteps: 2), provider: ScriptedProvider(usage: nil, responder: Self.endless))509 let report = await rig.agent.run()510 #expect(report.budget.tokensEstimated && report.budget.inputTokens > 1_000 && !report.budget.costComplete)511 }512513 @Test func costBudgetFromPublishedPrices() async {514 let pricing = Pricing(inputPerMTok: 1_000, outputPerMTok: 5_000, asOf: "2026-11-22") // 0.1 + 0.1 = 0.2 USD a turn515 let rig = makeRig([], budget: AgentBudget(maxSteps: 50, maxCostUSD: 0.5), configure: { $0.pricing = pricing }, provider: ScriptedProvider(responder: Self.endless))516 let report = await rig.agent.run()517 #expect(report.status == .budgetExhausted(.cost) && report.budget.steps == 3 && abs(report.budget.costUSD - 0.6) < 1e-9 && report.budget.costComplete)518 }519520 @Test func aCostBudgetWithoutAPriceStopsRatherThanRunUnmetered() async {521 let rig = makeRig([], budget: AgentBudget(maxSteps: 50, maxCostUSD: 5), provider: ScriptedProvider(responder: Self.endless))522 let report = await rig.agent.run()523 #expect(report.status == .budgetExhausted(.cost) && report.budget.steps == 1 && !report.budget.costComplete)524 }525526 @Test func wallClockBudgetStopsAHangingModel() async {527 let rig = makeRig([read, .hang], budget: AgentBudget(maxWallClock: 0.4))528 let started = Date()529 let report = await rig.agent.run()530 #expect(report.status == .budgetExhausted(.wallClock) && Date().timeIntervalSince(started) < 5)531 }532533 @Test func aSlowToolTimesOutAndTheModelIsTold() async {534 let rig = makeRig([read, .call("workflow_execute", ["workflow": "slow"]), .finish()], configure: { $0.toolTimeout = 0.2 },535 services: { $0.workflow = { _, _ in try? await Task.sleep(nanoseconds: 20_000_000_000); return "late" } })536 let started = Date()537 let report = await rig.agent.run()538 #expect(report.status == .completed && Date().timeIntervalSince(started) < 5)539 #expect(rig.provider.lastToolResult(request: 2).contains("\"code\":\"timeout\""))540 }541542 @Test func aWorkflowRunsThroughTheInjectedHookOnly() async {543 let rig = makeRig([read, .call("workflow_execute", ["workflow": "wordcount", "input": ["unit": "words"]]), .finish()],544 services: { $0.workflow = { name, input in ["ran": .string(name), "unit": input["unit"]] } })545 _ = await rig.agent.run()546 #expect(rig.provider.lastToolResult(request: 2).contains("\"ran\":\"wordcount\""))547 // Without a hook the tool does not exist.548 let bare = makeRig([.call("workflow_execute", ["workflow": "wordcount"]), .finish()])549 _ = await bare.agent.run()550 #expect(bare.agent.catalog.tool(named: "workflow_execute") == nil && bare.provider.lastToolResult(request: 1).contains("unknown_tool"))551 }552}553554@Suite(.serialized) struct CancellationAndRecoveryTests {555 @Test func cancellingMidRunStopsAtOnceAndKeepsWhatWasCommitted() async {556 let rig = makeRig([read, .calls([insert(" One.")]), .hang])557 let task = rig.agent.start()558 #expect(await waitUntil { rig.agent.timeline.events.steps == 3 })559 rig.agent.cancel()560 let report = await task.value561 #expect(report.status == .cancelled)562 let v25 = await rig.host.state.model563 #expect(report.applied.count == 1 && text(of: "p-end", in: v25) == "The end. One.")564 let v26 = await rig.checkpoints.latest?.isComplete565 #expect(v26 == false)566 }567568 @Test func cancellingWhileWaitingForApprovalAppliesNothing() async {569 let approver = RecordingApprover(review: { _, _ in try? await Task.sleep(nanoseconds: 30_000_000_000); return .acceptAll })570 let rig = makeRig([read, .calls([insert(" One.")]), .finish()], autonomy: AutonomyPolicy(.balanced), approver: approver)571 let task = rig.agent.start()572 #expect(await waitUntil { !rig.agent.timeline.events.proposals.isEmpty })573 // The checkpoint written while waiting carries the proposal, so an app that restarts can show it again.574 #expect(await waitUntil { await rig.checkpoints.latest?.pendingProposal != nil })575 rig.agent.cancel()576 let report = await task.value577 #expect(report.status == .cancelled && report.applied.isEmpty)578 let v27 = await rig.host.state.revision579 #expect(v27 == 7)580 }581582 @Test func schemaInvalidToolCallsAreReturnedToTheModelWhichCorrectsThem() async {583 let rig = makeRig([read,584 .calls([ScriptCall("text_insert", ["position": ["paragraph": "p-end"]])]), // missing "text"585 .calls([ScriptCall("text_insert", ["position": ["paragraph": 3], "text": "x", "bogus": true])]), // wrong type, unknown member586 .calls([ScriptCall("plan_update", ["steps": [["title": "a", "status": "almost"]]])]), // agent tool, bad enum587 .calls([ScriptCall("text_insert", ["position": ["paragraph": "ghost"], "text": "x"])]), // valid schema, unknown identifier588 .calls([insert(" Fixed.")]), .finish()])589 let report = await rig.agent.run()590 let first = rig.provider.lastToolResult(request: 2)591 #expect(first.contains("invalid_arguments") && first.contains("is missing the required member") && first.contains("\"violations\""))592 #expect(rig.provider.lastToolResult(request: 3).contains("unknown member"))593 #expect(rig.provider.lastToolResult(request: 4).contains("invalid_arguments") && rig.provider.lastToolResult(request: 4).contains("/steps/0/status"))594 #expect(rig.provider.lastToolResult(request: 5).contains("not_found"))595 #expect(rig.provider.toolResults(request: 5).suffix(4).allSatisfy { $0.toolIsError })596 let v28 = await rig.host.state.model597 #expect(report.status == .completed && report.applied.count == 1 && text(of: "p-end", in: v28) == "The end. Fixed.")598 }599600 @Test func oneInvalidCommandCancelsItsWholeBatch() async {601 let rig = makeRig([read, .calls([insert(" One."), ScriptCall("text_insert", ["position": ["paragraph": "ghost"], "text": "x"])]), .finish()])602 let report = await rig.agent.run()603 let results = Array(rig.provider.toolResults(request: 2).suffix(2))604 #expect(results[0].text.contains("batch_not_applied") && results[1].text.contains("not_found"))605 let v29 = await rig.host.state.revision606 #expect(report.applied.isEmpty && v29 == 7)607 }608609 @Test func aTransientModelFailureIsRetriedAndAPermanentOneEndsTheRun() async {610 let rig = makeRig([read, .fail(.overloaded(nil)), .fail(.overloaded(nil)), .finish()])611 let report = await rig.agent.run()612 #expect(report.status == .completed && rig.agent.timeline.events.recoveries.contains("Retrying the model call."))613 let failing = makeRig([read, .fail(.unauthorized(nil))])614 let failed = await failing.agent.run()615 if case .failed(let why) = failed.status { #expect(why.contains("API key")) } else { Issue.record("expected a failure, got \(failed.status)") }616 }617618 @Test func planQuestionAndPlainTextEnding() async {619 let approver = RecordingApprover(answer: { q in q.question.contains("audience") ? "Specialists." : nil })620 let rig = makeRig([.calls([ScriptCall("plan_update", ["steps": [["title": "Read", "status": "in_progress"], ["title": "Edit", "status": "pending"]]]),621 ScriptCall("ask_user", ["question": "Who is the audience?", "options": ["Specialists", "Students"]])]),622 .call("ask_user", ["question": "And the deadline?"]),623 .text("Nothing to change.")], approver: approver)624 let report = await rig.agent.run()625 #expect(report.status == .completed && report.modelSummary == "Nothing to change." && report.modelClaimedScope == nil)626 let results = rig.provider.toolResults(request: 1)627 // The person's answer is delivered as theirs, outside the data markers; everything else is inside them.628 #expect(results[1].text == "ANSWER FROM THE USER (given in the application):\nSpecialists." && results[0].text.contains("ASTRA_TOOL_RESULT"))629 #expect(rig.provider.lastToolResult(request: 2).contains("\"answered\":false"))630 #expect(approver.questions.map(\.options.count) == [2, 0])631 let plans = rig.agent.timeline.events.compactMap { if case .planUpdated(let p) = $0.kind { p } else { nil } }632 #expect(plans.count == 1 && plans[0].steps.map(\.title) == ["Read", "Edit"])633 }634}635636@Suite(.serialized) struct TimelineAndReportTests {637 @Test func theTimelineIsOrderedCodableAndReplayable() async throws {638 let rig = makeRig([.calls([ScriptCall("document_inspect"), ScriptCall("document_read")], text: "Looking."), .calls([insert(" One.")]), .finish("Added a sentence.")],639 autonomy: AutonomyPolicy(.balanced))640 let live = Task { () -> [AgentTimelineEvent] in var out: [AgentTimelineEvent] = []; for await e in rig.agent.timeline.stream() { out.append(e) }; return out }641 let report = await rig.agent.run()642 let streamed = await live.value643 let events = rig.agent.timeline.events644 #expect(streamed == events && events.map(\.id) == Array(1...events.count))645 func position(_ match: (AgentTimelineEvent.Kind) -> Bool) -> Int { events.firstIndex { match($0.kind) } ?? -1 }646 let order = [position { if case .runStarted = $0 { true } else { false } }, position { if case .modelText("Looking.") = $0 { true } else { false } },647 position { if case .sectionsExamined = $0 { true } else { false } }, position { if case .validation("preview", _) = $0 { true } else { false } },648 position { if case .changesProposed = $0 { true } else { false } }, position { if case .approvalResolved(_, "approved", _) = $0 { true } else { false } },649 position { if case .changesApplied = $0 { true } else { false } }, position { if case .finalReport = $0 { true } else { false } }]650 #expect(order == order.sorted() && !order.contains(-1), "\(order)")651 #expect(events.contains { if case .budget(let u) = $0.kind { u.steps == 1 } else { false } })652 #expect(events.contains { if case .toolStarted(_, "text.insert", let a) = $0.kind { a.contains("One.") } else { false } })653 // Persisted and restored without loss; a stream opened afterwards replays everything and ends.654 let restored = try AgentTimeline.decode(try rig.agent.timeline.encoded())655 #expect(restored.events == events)656 var replayed = 0657 for await _ in rig.agent.timeline.stream() { replayed += 1 }658 #expect(replayed == events.count)659 if case .finalReport(let r) = events.last(where: { if case .finalReport = $0.kind { true } else { false } })?.kind { #expect(r == report) }660 }661662 @Test func theReportListsWhatTheEngineRecordedNotWhatTheModelClaims() async throws {663 // The model claims a rewrite of the whole introduction; it actually added one sentence, and one of its batches was rejected.664 let approver = RecordingApprover(review: { _, n in n == 1 ? .acceptAll : .reject(reason: "No.") })665 let rig = makeRig([read, .calls([insert(" One.")]), .calls([ScriptCall("block_delete", ["blocks": ["p-sub"]])]),666 .finish("I rewrote the whole introduction and removed the sampling section.")], autonomy: AutonomyPolicy(.balanced), approver: approver)667 let report = await rig.agent.run()668 #expect(report.modelSummary.contains("rewrote the whole introduction"))669 #expect(report.changeList == ["r8 [Document agent] modified paragraph p-end: \"The end.\" → \"The end. One.\""])670 #expect(report.totals == ChangeTotals(batches: 1, inserted: 0, deleted: 0, modified: 1, moved: 0, formattingOnly: 0, parts: [], citationsAdded: [], citationsRemoved: []))671 #expect(report.rejected.map(\.commands) == [["block.delete"]])672 let batch = try #require(report.applied.first)673 #expect(batch.audit.contains { $0.command == "transaction(1)" && $0.mode == "apply" && $0.revisionBefore == 7 && $0.revisionAfter == 8 && $0.changed })674 #expect(batch.audit.allSatisfy { $0.client == "Agent: Document agent" })675 // The run's audit trail holds the reads and previews too, and never any document text.676 #expect(report.audit.contains { $0.command == "document.read" } && report.audit.contains { $0.mode == "preview" && $0.command.hasPrefix("transaction") })677 let encoded = String(decoding: try JSONEncoder().encode(report.audit), as: UTF8.self)678 #expect(!encoded.contains("The end"))679 #expect(report.toolCalls["text.insert"] == 1 && report.toolCalls["document.read"] == 1)680 #expect(try JSONDecoder().decode(AgentReport.self, from: try JSONEncoder().encode(report)) == report)681 }682}683