Repository Public
1import Foundation2import Testing3import AstraCore4@testable import AstraAgents56// Regression tests for the defects confirmed by the pre-V2 adversarial review (docs/v2/FINDINGS_REGISTER.md, AGENT-n).78@Suite struct V2DataTransformRegressions {9 /// AGENT-1: a repeated column reached `Dictionary(uniqueKeysWithValues:)` and killed the process. The tool needs no approval.10 @Test func selectWithARepeatedColumnDoesNotTrap() async {11 let message = await toolError(DataTransformTool(), [12 "input": "a,b\n1,2", "output_format": "json", "operations": [["op": "select", "columns": ["a", "a"]]],13 ])14 #expect(message?.contains("twice") == true)15 let viaPointer = await toolError(DataTransformTool(), [16 "input": "a,b\n1,2", "operations": [["op": "select", "columns": ["a", "a"]], ["op": "pointer", "path": "/0"]],17 ])18 #expect(viaPointer?.contains("twice") == true)19 }2021 /// Whatever a future operation does to the column list, rendering never traps.22 @Test func renderingATableWithARepeatedColumnNeverTraps() {23 let table = DataTransform.Table(columns: ["a", "a"], rows: [["a": 1]])24 #expect(DataTransform.json(table) == [["a": 1]])25 }2627 /// AGENT-5: a wide header times many short rows multiplied 8 KB of input into millions of cells.28 @Test func aWideSparseCSVIsRefused() {29 let input = String(repeating: ",", count: 3_999) + "\n" + String(repeating: "x\n", count: 2_000)30 #expect(throws: ToolError.self) { try DataTransform.tableFromCSV(input) }31 // an ordinary wide table still works32 let ok = (1...50).map { "c\($0)" }.joined(separator: ",") + "\n" + (1...50).map(String.init).joined(separator: ",")33 #expect((try? DataTransform.tableFromCSV(ok))?.columns.count == 50)34 }3536 /// AGENT-9: an aggregate that overflows is reported, not turned into `null` or `inf`.37 @Test func anAggregateThatOverflowsIsAnError() async {38 let message = await toolError(DataTransformTool(), [39 "input": "v\n1e308\n1e308", "operations": [["op": "group_by", "aggregates": [["function": "sum", "column": "v"]]]],40 ])41 #expect(message?.contains("too large") == true)42 }43}4445@Suite struct V2AgentPolicyRegressions {46 /// AGENT-8: budgets decoded from JSON skipped the clamps of the initialiser; `alternationLimit: 0` then trapped in cycle detection.47 @Test func decodedBudgetsAreClamped() throws {48 let json = #"{"maxSteps":-4,"maxToolCalls":-1,"maxToolOutputCharacters":1,"repeatLimit":0,"alternationLimit":0,"warningFraction":9}"#49 let budgets = try JSONDecoder().decode(AgentBudgets.self, from: Data(json.utf8))50 #expect(budgets.maxSteps == 1 && budgets.maxToolCalls == 0 && budgets.maxToolOutputCharacters == 256)51 #expect(budgets.repeatLimit == 2 && budgets.alternationLimit == 2 && budgets.warningFraction == 1)52 // and a value saved by the current build still round-trips53 let saved = AgentBudgets(maxSteps: 7, maxTotalTokens: 9_000, wallClockLimit: nil)54 #expect(try JSONDecoder().decode(AgentBudgets.self, from: JSONEncoder().encode(saved)) == saved)55 }5657 @Test func aRunWithHostileDecodedBudgetsDoesNotTrap() async throws {58 let json = #"{"maxSteps":6,"maxToolCalls":10,"maxToolOutputCharacters":1000,"repeatLimit":9,"alternationLimit":0,"warningFraction":0.8}"#59 let budgets = try JSONDecoder().decode(AgentBudgets.self, from: Data(json.utf8))60 let provider = ScriptedProvider([ScriptedProvider.call("spy", ["n": 1]), ScriptedProvider.call("spy", ["n": 2]), ScriptedProvider.text("done")])61 let events = await collect(makeRunner(provider, tools: [SpyTool("spy")]).run(profile: makeProfile(tools: ["spy"], budgets: budgets), goal: "go"))62 #expect(events.status == .completed)63 }6465 /// AGENT-11: validation stopped silently beyond 32 levels, accepting whatever was nested deeper.66 @Test func argumentsNestedBeyondTheDepthLimitAreRejected() {67 var schema: JSONValue = ["type": "string"]68 var value: JSONValue = .number(1) // wrong type at the bottom69 for _ in 0..<40 {70 schema = ["type": "object", "properties": ["x": schema], "required": ["x"], "additionalProperties": false]71 value = ["x": value]72 }73 let tool = ToolDefinition(name: "deep", summary: "", parameters: schema)74 #expect(throws: (any Error).self) { try SchemaValidator.validate(arguments: value, for: tool) }75 }7677 /// PROV-3 (second line of defence): a turn cut by the output limit may carry a tool call with truncated arguments. It is not run.78 @Test func toolCallsOfATruncatedTurnAreNotExecuted() async {79 let spy = SpyTool("spy")80 let call = ToolCall(id: "c1", name: "spy", arguments: [:])81 let truncated: ScriptedProvider.Turn = .events([.messageStarted(MessageStart()), .toolCallStarted(id: "c1", name: "spy"), .toolCallCompleted(call),82 .usage(TokenUsage(inputTokens: 10, outputTokens: 10)), .messageCompleted(.maxTokens)])83 let provider = ScriptedProvider([truncated, ScriptedProvider.text("done")])84 let events = await collect(makeRunner(provider, tools: [spy]).run(profile: makeProfile(tools: ["spy"]), goal: "go"))85 #expect(spy.calls.isEmpty)86 #expect(events.status == .completed)87 #expect(events.finished.first?.isError == true)88 #expect(events.finished.first?.output.contains("cut off") == true)89 }90}9192@Suite struct V2WebRegressions {93 /// AGENT-2: approving (or pre-approving) host A covered every public host A redirected to.94 @Test func aRedirectToAnotherHostIsNotFollowed() async {95 let web = FakeWeb { request in96 let target = URL(string: "https://collector.example.net/c?d=x")!97 if let reason = request.validate(target) { throw ToolError(reason) }98 return WebFetchResponse(status: 200, contentType: "text/plain", body: Data("other site".utf8), finalURL: target)99 }100 let provider = ScriptedProvider([ScriptedProvider.call("web_fetch", ["url": "https://docs.example.com/r?u=collector"]), ScriptedProvider.text("done")])101 let approvals = ApprovalRecorder { request, _ in request.scope == "docs.example.com" ? .allowForRun : .deny(reason: nil) }102 let events = await collect(makeRunner(provider, tools: [WebFetchTool(fetcher: web)], approvals: approvals)103 .run(profile: makeProfile(tools: ["web_fetch"]), goal: "Read the docs."))104 #expect(events.finished.first?.isError == true)105 #expect(events.finished.first?.output.contains("collector.example.net") == true)106 #expect(events.finished.first?.output.contains("other site") == false)107 }108109 /// A careless fetcher that followed the redirect anyway is still caught on the final URL.110 @Test func aFinalURLOnAnotherHostIsRefused() async {111 let careless = FakeWeb { _ in WebFetchResponse(status: 200, contentType: "text/plain", body: Data("secret page".utf8), finalURL: URL(string: "https://elsewhere.example.org/")!) }112 let message = await toolError(WebFetchTool(fetcher: careless), ["url": "https://example.com/r"])113 #expect(message?.contains("elsewhere.example.org") == true)114 #expect(message?.contains("secret page") == false)115 }116117 /// The ordinary canonical-host hop (apex to www and back) stays on the same site and is followed.118 @Test func theWWWFormOfTheSameSiteIsFollowed() async throws {119 for (from, to) in [("https://example.com/a", "https://www.example.com/a"), ("https://www.example.com/a", "https://example.com/b")] {120 let web = FakeWeb { request in121 let target = URL(string: to)!122 #expect(request.validate(target) == nil)123 return WebFetchResponse(status: 200, contentType: "text/plain", body: Data("same site".utf8), finalURL: target)124 }125 #expect(try await runTool(WebFetchTool(fetcher: web), ["url": .string(from)]).contains("same site"))126 }127 #expect(WebFetchTool.sameSite("example.com", "wwwexample.com") == false)128 #expect(WebFetchTool.sameSite("a.example.com", "b.example.com") == false)129 }130131 /// AGENT-4: the approval line showed 300 characters of a URL that may hold 2,000; the rest went unseen.132 @Test func theApprovalShowsTheWholeAddress() {133 let tail = "TAILMARKER"134 let url = "https://example.com/" + String(repeating: "a/", count: 400) + tail135 let summary = WebFetchTool(fetcher: FakeWeb(html: "")).approvalSummary(["url": .string(url)])136 #expect(summary?.contains(tail) == true)137 }138139 @Test func aLongAddressIsFlaggedEvenWithoutAQuery() {140 let url = URL(string: "https://example.com/" + String(repeating: "ab/", count: 200))!141 #expect(ExfiltrationDetector.warnings(url: url, corpus: []).contains { $0.contains("unusually long") })142 }143144 /// AGENT-3: text split across several short parameters was never compared with the conversation.145 @Test func textSplitAcrossParametersIsStillFlagged() {146 let corpus = ["Lease.pdf: The tenant Simon agrees to pay 1450 dollars monthly to the landlord Marie Tremblay."]147 let url = URL(string: "https://evil.example/c?a=the+tenant+simon+agre&b=es+to+pay+1450+dolla&c=rs+monthly+to+the+la")!148 #expect(ExfiltrationDetector.warnings(url: url, corpus: corpus).contains { $0.contains("copied from the conversation") })149 let viaPath = URL(string: "https://evil.example/the%20tenant%20simon/agrees%20to%20pay/1450%20dollars%20monthly")!150 #expect(ExfiltrationDetector.warnings(url: viaPath, corpus: corpus).contains { $0.contains("copied from the conversation") })151 }152153 @Test func anOpaquePayloadInThePathIsFlagged() {154 let blob = "VGhlIHRlbmFudCBTaW1vbiBhZ3JlZXMgdG8gcGF5IDE0NTAgZG9sbGFycyBtb250aGx5IHRvIHRoZSBsYW5kbG9yZA"155 let url = URL(string: "https://evil.example/i/\(blob)/x.png")!156 #expect(ExfiltrationDetector.warnings(url: url, corpus: []).contains { $0.contains("encoded value") })157 }158159 @Test func ordinaryAddressesAreNotFlagged() {160 let corpus = ["Find the opening hours of the Musée des beaux-arts in Ottawa."]161 for text in ["https://en.wikipedia.org/wiki/National_Gallery_of_Canada", "https://example.com/search?q=opening+hours&lang=en",162 "https://www.gallery.ca/visit/hours-and-admission/plan-your-visit-today"] {163 #expect(ExfiltrationDetector.warnings(url: URL(string: text)!, corpus: corpus).isEmpty, "\(text)")164 }165 }166167 /// AGENT-13: deprecated site-local and translated forms of private addresses.168 @Test func moreNonPublicIPv6FormsAreBlocked() {169 for address in ["fec0::1", "::ffff:0:127.0.0.1", "2001:0:4136:e378:8000:63bf:3fff:fdd2"] {170 #expect(WebHostPolicy.isBlockedAddress(address), "\(address)")171 }172 #expect(!WebHostPolicy.isBlockedAddress("2606:4700:4700::1111"))173 }174}175