SPB Git

Repository Public

LiveAgentTests.swift 12.9 KB 200 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Tests/DocAgentTests/LiveAgentTests.swift10// Description      : A live run of the document agent with a real model on a11//                    real document. Skipped unless ORIXDOCS_LIVE_AGENT=1 and a12//                    provider key are in the environment (the owner's13//                    development keys: `source14//                    ~/Desktop/Cluster/apple/ORIXAstra/Scripts/smoke-env.sh`).15//                    The key is never printed; the run is bounded by a step,16//                    token, cost and time budget.17// Module           : DocAgentTests18// Repository       : https://git.spboucher.ai/orix-docs19// Created          : 2026-11-2220// Last Modified    : 2026-11-2221//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation95import Testing96import AstraCore97import AstraProviders98import DocModel99import DocCommands100@testable import DocAgent101102enum LiveAgent {103    static let env = ProcessInfo.processInfo.environment104    static let enabled = env["ORIXDOCS_LIVE_AGENT"] == "1" && !(env["ANTHROPIC_API_KEY"] ?? "").isEmpty105    static let modelID = env["ORIXDOCS_LIVE_MODEL"] ?? "claude-haiku-5-5"106107    /// A short research note with a disorganised introduction and five citations of three sources.108    static func paper() -> DocumentModel {109        var doc = DocumentModel()110        doc.meta.title = "Remote Work and Team Productivity"111        doc.meta.author = "A. Researcher"112        doc.bibliography = [113            BibEntry(key: "bloom2015", authors: [PersonName(family: "Bloom", given: "Nicholas")], year: 2015,114                     fields: ["title": "Does Working from Home Work? Evidence from a Chinese Experiment", "container-title": "Quarterly Journal of Economics", "volume": "130", "page": "165-218"]),115            BibEntry(key: "yang2022", authors: [PersonName(family: "Yang", given: "Longqi")], year: 2022,116                     fields: ["title": "The Effects of Remote Work on Collaboration Among Information Workers", "container-title": "Nature Human Behaviour", "volume": "6", "page": "43-54"]),117            BibEntry(key: "gibbs2023", authors: [PersonName(family: "Gibbs", given: "Michael")], year: 2023,118                     fields: ["title": "Work from Home and Productivity", "container-title": "Journal of Political Economy Microeconomics", "volume": "1", "page": "7-41"]),119        ]120        func cite(_ key: String) -> Run { Run(inline: .citation(Citation(key))) }121        func p(_ id: String, _ runs: [Run]) -> Block { .paragraph(Paragraph(id: id, runs: runs)) }122        func h(_ id: String, _ text: String) -> Block { .paragraph(Paragraph(id: id, style: StyleID.heading(1), runs: [Run(text)])) }123        doc.body = [124            h("h-intro", "Introduction"),125            p("i1", [Run("Our contribution is a twelve-month panel of 48 software teams that separates output per hour from hours worked. We find that hybrid teams keep their output while fully remote teams lose some of it to coordination.")]),126            p("i2", [Run("Remote work became common very quickly. A randomized experiment in a call centre found a 13 percent performance gain from working at home "), cite("bloom2015"),127                     Run(", but call-centre work is individual and easy to measure.")]),128            p("i3", [Run("For knowledge work the picture is less clear. Firm-wide remote work made collaboration networks more siloed and more static "), cite("yang2022"),129                     Run(", and one study of IT professionals found longer hours with lower output per hour "), cite("gibbs2023"), Run(".")]),130            p("i4", [Run("What is missing is evidence at the level of the team, where coordination costs arise. The earlier results concern either individuals "), cite("bloom2015"),131                     Run(" or whole firms "), cite("yang2022"), Run(".")]),132            h("h-methods", "Data and Method"),133            p("m1", [Run("We follow 48 teams in three firms from January to December 2023. Output is the number of merged changes weighted by review size; hours come from calendar and repository activity.")]),134            p("m2", [Run("Teams are classified as on-site, hybrid (two or three office days) or fully remote. We estimate team fixed-effects regressions with month effects.")]),135            h("h-results", "Results"),136            p("r1", [Run("Hybrid teams produce as much per hour as on-site teams (difference 0.4 percent, not significant). Fully remote teams produce 6.2 percent less per hour and work 3.1 percent more hours.")]),137            p("r2", [Run("The loss is concentrated in teams with more than eight members and in work that crosses team boundaries.")]),138            h("h-conclusion", "Conclusion"),139            p("c1", [Run("Coordination, not individual effort, explains the cost of full remote work in our sample. Two or three shared office days appear to be enough to avoid it.")]),140            .bibliography(BibliographyBlock(title: "References")),141            p("p-last", [Run("")]),142        ]143        return doc144    }145146    static func citations(in model: DocumentModel) -> [String] {147        model.body.flatMap { InlineTokens.citationKeys(in: DocRender.summary($0)) }.sorted()148    }149}150151@Suite(.serialized) struct LiveAgentTests {152    @Test(.enabled(if: LiveAgent.enabled, "set ORIXDOCS_LIVE_AGENT=1 and ANTHROPIC_API_KEY"))153    func aRealModelRestructuresTheIntroductionAndAddsAnExecutiveSummary() async throws {154        let key = LiveAgent.env["ANTHROPIC_API_KEY"] ?? ""155        let provider = AnthropicProvider(transport: URLSessionTransport(), apiKey: { key })156        let model = ModelRef(provider: .anthropic, modelID: LiveAgent.modelID)157        let pricing = (try? await provider.listModels())?.first { $0.ref.modelID == LiveAgent.modelID }?.pricing158        let original = LiveAgent.paper()159        let host = InMemoryDocumentHost(original, revision: 1, documentID: "live-paper")160        let approver = RecordingApprover()   // accepts every proposal, as a person clicking "Accept all" would161        let configuration = AgentConfiguration(162            objective: "Restructure the introduction so that it goes from context, to what is known, to the gap, to our contribution, and add an executive summary of about 80 words "163                + "as a new first section of the document. Preserve every citation; do not add sources or change any number.",164            model: model, scopes: [.documentRead, .documentWrite, .documentReferences, .documentReview], autonomy: AutonomyPolicy(.balanced),165            budget: AgentBudget(maxSteps: 30, maxTokens: 600_000, maxCostUSD: 0.60, maxWallClock: 420, maxOutputTokensPerTurn: 8_000),166            pricing: pricing, parameters: GenerationParameters(reasoning: .off))167        let agent = DocumentAgent(configuration: configuration, services: AgentServices(provider: provider, host: host, approver: approver))168        let report = await agent.run()169        let final = await host.state.model170171        // The record of the run, for docs/v2/AGENT_SYSTEM.md. No key, no header, nothing but the outcome.172        let before = LiveAgent.citations(in: original), after = LiveAgent.citations(in: final)173        print("LIVE model=\(LiveAgent.modelID) status=\(report.status.label) steps=\(report.budget.steps) batches=\(report.totals.batches) proposals=\(approver.proposals.count)")174        print("LIVE tools=\(report.toolCalls.sorted { $0.key < $1.key }.map { "\($0.key)×\($0.value)" }.joined(separator: " "))")175        print("LIVE tokens input=\(report.budget.inputTokens) output=\(report.budget.outputTokens) estimated=\(report.budget.tokensEstimated) costUSD=\(String(format: "%.4f", report.budget.costUSD)) costComplete=\(report.budget.costComplete) priced=\(pricing != nil) seconds=\(Int(report.budget.elapsed))")176        print("LIVE citations before=\(before) after=\(after) survived=\(before == after)")177        print("LIVE totals inserted=\(report.totals.inserted) modified=\(report.totals.modified) deleted=\(report.totals.deleted) moved=\(report.totals.moved) revisions=\(report.revisionAtStart)→\(report.revisionAtEnd)")178        print("LIVE coverage: \(report.coverage.statement) claimed=\(report.modelClaimedScope ?? "none") overstated=\(report.modelOverstatedCoverage)")179        print("LIVE integrity issues=\(report.integrityIssues.count) rejected=\(report.rejected.count) suspicious=\(report.suspiciousPassages) errors=\(report.errors.count)")180        for error in report.errors { print("LIVE error: \(error.clipped(300))") }181        let toolErrors = agent.timeline.events.finishedTools.filter(\.isError)182        print("LIVE tool errors=\(toolErrors.count): \(toolErrors.map { "\($0.tool): \($0.result.clipped(160))" })")183        for line in report.changeList { print("LIVE change: \(line.clipped(220))") }184        print("LIVE model summary: \(report.modelSummary.clipped(700))")185        print("LIVE final outline:")186        for block in final.body { if let p = block.paragraph { print("LIVE   [\(p.id)] \(p.style): \(DocRender.text(p).clipped(260))") } else { print("LIVE   [\(block.id)] \(DocRender.blockType(block))") } }187188        #expect(report.status == .completed)189        #expect(!report.applied.isEmpty && report.integrityIssues.isEmpty)190        // Citations: none lost, none invented.191        #expect(after == before)192        #expect(final.bibliography.map(\.key) == original.bibliography.map(\.key))193        let headings = final.body.compactMap { $0.paragraph }.filter { DocRender.outlineLevel($0, final) > 0 }.map { DocRender.text($0).lowercased() }194        #expect(headings.first?.contains("summary") == true, "the executive summary should be the first section: \(headings)")195        // The numbers of the paper are still there.196        let text = final.body.map(DocRender.summary).joined(separator: "\n")197        for figure in ["13 percent", "48", "6.2 percent", "3.1 percent", "0.4 percent"] { #expect(text.contains(figure), "\(figure)") }198    }199}200
Files main
Menu

Theme