SPB Git

Repository Public

DocumentHost.swift 9.3 KB 194 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Docs9// File             : Packages/ORIXDocsAI/Sources/DocAgent/DocumentHost.swift10// Description      : The only door between an agent and a document. The app11//                    implements `DocumentHost` over the live document on the12//                    main actor; `InMemoryDocumentHost` implements it for13//                    tests, previews and headless automation. Every mutation is14//                    a command-engine transaction.15// Module           : DocAgent16// 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 DocModel94import DocCommands9596/// What a host reports after applying a batch: the transaction and the audit records its executor produced for it.97public struct HostApplyResult: Sendable {98    public var transaction: DocTransactionResult99    /// Content-free records emitted by the host's executor while applying (empty when the host keeps no audit trail).100    public var audit: [DocAuditEntry]101    public init(transaction: DocTransactionResult, audit: [DocAuditEntry] = []) { self.transaction = transaction; self.audit = audit }102}103104/// What the host did with a file an agent produced.105public struct ArtifactReceipt: Sendable, Codable, Hashable {106    public var name: String107    public var mimeType: String108    public var bytes: Int109    /// The host's own words ("Offered in a save panel", "Kept in memory", "Refused").110    public var disposition: String111    public init(name: String, mimeType: String, bytes: Int, disposition: String) { self.name = name; self.mimeType = mimeType; self.bytes = bytes; self.disposition = disposition }112}113114/// The document an agent works on. Agents never see a file path and never write anything themselves.115public protocol DocumentHost: Sendable {116    /// Identifier recorded in audit entries and checkpoints.117    func documentID() async -> String118    /// The current model and its revision.119    func snapshot() async -> DocumentState120    /// Applies the requests as ONE atomic transaction and ONE undo step, or throws `DocTransactionError` / `DocCommandError` and changes nothing.121    /// `options.baseRevision` with the `reject` policy must make the host refuse when the document moved since that revision.122    func apply(_ requests: [DocCommandRequest], context: DocCommandContext, options: DocExecutionOptions) async throws -> HostApplyResult123    /// Undoes the step that produced `revision`, only if the document is still at that revision. Returns the state after the undo.124    func undo(revision: Int) async throws -> DocumentState125    /// Receives a file produced by `document.export`. Whether and where it is written is the host's decision.126    func deliver(_ artifact: DocArtifact) async -> ArtifactReceipt127}128129/// A document held in memory. Used by the tests, and usable by a headless API server that owns its documents.130public actor InMemoryDocumentHost: DocumentHost {131    public private(set) var state: DocumentState132    public private(set) var artifacts: [DocArtifact] = []133    /// Every audit record the executor produced, in order.134    public private(set) var auditTrail: [DocAuditEntry] = []135    /// Number of successful `apply` calls: the number of undo steps created.136    public private(set) var applyCount = 0137    private var undoStack: [(revision: Int, before: DocumentModel)] = []138    private let id: String139    private let registry: DocCommandRegistry140141    public init(_ model: DocumentModel, revision: Int = 0, documentID: String = "memory", registry: DocCommandRegistry = .standard) {142        state = DocumentState(model: model, revision: revision); id = documentID; self.registry = registry143    }144145    public func documentID() async -> String { id }146    public func snapshot() async -> DocumentState { state }147148    public func apply(_ requests: [DocCommandRequest], context: DocCommandContext, options: DocExecutionOptions) async throws -> HostApplyResult {149        let collected = Locked<[DocAuditEntry]>([])150        let executor = DocCommandExecutor(registry: registry, audit: { entry in collected.withLock { $0.append(entry) } })151        var working = state152        let before = state.model153        defer { auditTrail.append(contentsOf: collected.value) }154        let result = try executor.transaction(requests, on: &working, context: context, options: options)155        if options.mode == .apply, result.changed {156            state = working157            undoStack.append((working.revision, before))158            applyCount += 1159        }160        return HostApplyResult(transaction: result, audit: collected.value)161    }162163    public func undo(revision: Int) async throws -> DocumentState {164        guard let last = undoStack.last, last.revision == revision, state.revision == revision else {165            throw DocCommandError(.revisionConflict, "The document is no longer at revision \(revision); that step cannot be undone automatically.")166        }167        undoStack.removeLast()168        state = DocumentState(model: last.before, revision: state.revision + 1)169        return state170    }171172    public func deliver(_ artifact: DocArtifact) async -> ArtifactReceipt {173        artifacts.append(artifact)174        return ArtifactReceipt(name: artifact.name, mimeType: artifact.mimeType, bytes: artifact.data.count, disposition: "Kept in memory")175    }176177    /// A change made by someone else (the user typing, another client): the revision advances by one.178    public func externalEdit(_ change: @Sendable (inout DocumentModel) -> Void) {179        var model = state.model180        change(&model)181        state = DocumentState(model: model, revision: state.revision + 1)182    }183184    /// Runs commands as another client would, through the engine.185    @discardableResult186    public func externalCommands(_ requests: [DocCommandRequest], author: String = "Someone else") throws -> DocTransactionResult {187        var working = state188        let result = try DocCommandExecutor(registry: registry).transaction(requests, on: &working,189            context: DocCommandContext(client: author, scopes: Set(DocScope.allCases), author: author))190        state = working191        return result192    }193}194
Files main
Menu

Theme