SPB Git

Repository Public

ChangeProposal.swift 18.0 KB 360 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/ChangeProposal.swift10// Description      : What an agent submits before changing a document: the11//                    commands, the block-by-block difference computed by a12//                    preview of the command engine, and the decisions a person13//                    can take on it (accept, reject, accept some, edit a text).14//                    Built from the preview, never from the model's15//                    description.16// Module           : DocAgent17// Repository       : https://git.spboucher.ai/orix-docs18// Created          : 2026-11-2219// Last Modified    : 2026-11-2220//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import DocModel95import DocCommands9697public struct ProposedCommand: Sendable, Codable, Hashable, Identifiable {98    /// Position in the batch; `{{N.path}}` references use it.99    public var index: Int100    public var id: Int { index }101    /// Identifier of the model's tool call.102    public var callID: String103    public var command: String104    public var title: String105    public var arguments: DocJSON106    /// One line for a list.107    public var summary: String108    /// Name of the argument that holds the text a person may edit before applying ("text", "content", "replacement"); nil when there is none.109    public var editableArgument: String?110    public var editableText: String?111    /// Commands of the batch whose output this one uses. Accepting this command without them is impossible.112    public var dependsOn: [Int]113    /// Blocks this command changed in the preview.114    public var changedBlocks: [String]115    public var warnings: [String]116}117118public struct ProposedBlockChange: Sendable, Codable, Hashable, Identifiable {119    public enum Kind: String, Sendable, Codable { case inserted, deleted, modified, moved }120    public var kind: Kind121    public var block: String122    public var blockType: String123    public var id: String { "\(kind.rawValue)-\(block)" }124    /// Text before the change (nil for an insertion).125    public var original: String?126    /// Text after the change (nil for a deletion).127    public var proposed: String?128    public var styleBefore: String?129    public var styleAfter: String?130    /// Same text, different formatting or anchors (a comment, a style).131    public var formattingOnly: Bool132    public var citationsAdded: [String]133    public var citationsRemoved: [String]134    /// Equations, images, notes and cross-references added or removed, as their tokens.135    public var objectsAdded: [String]136    public var objectsRemoved: [String]137    /// The section the block belongs to (after the change; before it for a deletion).138    public var section: String?139}140141public struct ChangeProposal: Sendable, Codable, Hashable, Identifiable {142    public var id: String143    public var agent: String144    /// Revision of the document the preview ran on. The batch is applied only if the document is still at this revision.145    public var baseRevision: Int146    public var commands: [ProposedCommand]147    /// Net difference of the whole batch, block by block, in document order.148    public var blocks: [ProposedBlockChange]149    /// Document-wide parts that would change: "styles", "pageSetup", "bibliography", "notes", "comments", "metadata", "settings", "lists", "assets".150    public var parts: [String]151    public var insertedTables: Int152    public var pagesBefore: Int?153    public var pagesAfter: Int?154    public var warnings: [String]155    /// Why approval is asked.156    public var reason: String157    /// True when the edits will be recorded as tracked changes.158    public var tracked: Bool159    /// Author recorded on the edits ("ORIX AI (model)").160    public var author: String161162    /// Pairs (command, missing dependency) that make a selection impossible to apply.163    public func missingDependencies(selecting selected: Set<Int>) -> [(command: Int, needs: Int)] {164        commands.filter { selected.contains($0.index) }.flatMap { c in c.dependsOn.filter { !selected.contains($0) }.map { (c.index, $0) } }165    }166}167168/// A text a person rewrote in a proposal.169public struct ProposalEdit: Sendable, Codable, Hashable {170    public var command: Int171    public var text: String172    public init(command: Int, text: String) { self.command = command; self.text = text }173}174175public enum ProposalDecision: Sendable, Codable, Hashable {176    case acceptAll177    case reject(reason: String?)178    /// Apply only these commands (by index), as one transaction.179    case acceptSelected(commands: [Int])180    /// Apply with edited texts; `commands` restricts to a selection when set.181    case acceptEdited(edits: [ProposalEdit], commands: [Int]?)182}183184/// A side effect other than a document change that needs a yes or a no (an export, a workflow, a command a Custom mode asks about).185public struct ActionRequest: Sendable, Codable, Hashable, Identifiable {186    public var id: String187    public var agent: String188    public var tool: String189    public var title: String190    /// The arguments, shortened.191    public var summary: String192    public var reason: String193    public var warnings: [String]194}195196public struct UserQuestion: Sendable, Codable, Hashable, Identifiable {197    public var id: String198    public var agent: String199    public var question: String200    public var options: [String]201}202203/// The person, as the agent reaches them. The app implements it with its approval sheet; nothing in a document can answer in their place,204/// because the loop only ever calls this object.205public protocol ChangeApprover: Sendable {206    func review(_ proposal: ChangeProposal) async -> ProposalDecision207    func authorize(_ request: ActionRequest) async -> Bool208    /// The answer to a question; nil when the person declines to answer.209    func answer(_ question: UserQuestion) async -> String?210}211212/// Refuses everything. The default: an agent started without an approver can read and can never change anything that needs approval.213public struct RejectingApprover: ChangeApprover {214    public init() {}215    public func review(_ proposal: ChangeProposal) async -> ProposalDecision { .reject(reason: "No approver is attached to this run.") }216    public func authorize(_ request: ActionRequest) async -> Bool { false }217    public func answer(_ question: UserQuestion) async -> String? { nil }218}219220public struct ClosureApprover: ChangeApprover {221    private let onReview: @Sendable (ChangeProposal) async -> ProposalDecision222    private let onAuthorize: @Sendable (ActionRequest) async -> Bool223    private let onAnswer: @Sendable (UserQuestion) async -> String?224    public init(review: @escaping @Sendable (ChangeProposal) async -> ProposalDecision,225                authorize: @escaping @Sendable (ActionRequest) async -> Bool = { _ in false },226                answer: @escaping @Sendable (UserQuestion) async -> String? = { _ in nil }) {227        onReview = review; onAuthorize = authorize; onAnswer = answer228    }229    public func review(_ proposal: ChangeProposal) async -> ProposalDecision { await onReview(proposal) }230    public func authorize(_ request: ActionRequest) async -> Bool { await onAuthorize(request) }231    public func answer(_ question: UserQuestion) async -> String? { await onAnswer(question) }232}233234// MARK: - References between the commands of a batch235236enum BatchReferences {237    /// The command index of a `{{N.path}}` string, with the same reading as the command engine's substitution.238    static func target(of s: String) -> Int? {239        guard s.hasPrefix("{{"), s.hasSuffix("}}"), s.count > 4 else { return nil }240        guard let first = s.dropFirst(2).dropLast(2).split(separator: ".", omittingEmptySubsequences: false).first, !first.isEmpty, first.allSatisfy(\.isNumber) else { return nil }241        return Int(first)242    }243244    static func targets(in value: DocJSON) -> Set<Int> {245        switch value {246        case .string(let s): return target(of: s).map { [$0] } ?? []247        case .array(let a): return a.reduce(into: []) { $0.formUnion(targets(in: $1)) }248        case .object(let o): return o.values.reduce(into: []) { $0.formUnion(targets(in: $1)) }249        default: return []250        }251    }252253    /// Rewrites `{{N.path}}` to the command's new position. A reference to a command that is not in `mapping` is left as it is (the caller checks first).254    static func renumber(_ value: DocJSON, _ mapping: [Int: Int]) -> DocJSON {255        switch value {256        case .string(let s):257            guard let n = target(of: s), let m = mapping[n] else { return value }258            let rest = s.dropFirst(2).dropLast(2).drop { $0 != "." }259            return .string("{{\(m)\(rest)}}")260        case .array(let a): return .array(a.map { renumber($0, mapping) })261        case .object(let o): return .object(o.mapValues { renumber($0, mapping) })262        default: return value263        }264    }265266    /// Keeps the requests at `indexes` (ascending) and renumbers their references.267    static func subset(_ requests: [DocCommandRequest], keeping indexes: [Int]) -> [DocCommandRequest] {268        let mapping = Dictionary(uniqueKeysWithValues: indexes.enumerated().map { ($1, $0) })269        return indexes.map { DocCommandRequest(requests[$0].command, renumber(requests[$0].arguments, mapping)) }270    }271272    /// Groups of commands linked by references, each in ascending order, ordered by their first command.273    static func components(_ requests: [DocCommandRequest]) -> [[Int]] {274        var parent = Array(requests.indices)275        func find(_ i: Int) -> Int { var i = i; while parent[i] != i { i = parent[i] }; return i }276        for (i, r) in requests.enumerated() { for t in targets(in: r.arguments) where requests.indices.contains(t) && t != i { parent[find(i)] = find(t) } }277        var groups: [Int: [Int]] = [:]278        for i in requests.indices { groups[find(i), default: []].append(i) }279        return groups.values.sorted { ($0.first ?? 0) < ($1.first ?? 0) }280    }281}282283// MARK: - Building a proposal from a preview284285enum ProposalBuilder {286    static let editableArguments = ["text", "content", "replacement"]287288    static func editableArgument(of spec: DocCommandSpec) -> String? {289        editableArguments.first { spec.input["properties"][$0]["type"].stringValue == "string" }290    }291292    /// One line describing a command call, without dumping long texts.293    static func summary(_ request: DocCommandRequest, title: String) -> String {294        var parts: [String] = []295        for (key, value) in (request.arguments.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) {296            let text: String297            switch value {298            case .string(let s): text = "\"\(s.replacingOccurrences(of: "\n", with: " ").clipped(60))\""299            default: text = value.text().clipped(80)300            }301            parts.append("\(key): \(text)")302        }303        return parts.isEmpty ? title : "\(title) (\(parts.joined(separator: ", ")))"304    }305306    /// Parts that really differ: the modification date changes with every edit and is not a change to report.307    static func meaningfulParts(_ parts: [String], before: DocumentModel, after: DocumentModel) -> [String] {308        parts.filter { part in309            guard part == "metadata" else { return true }310            var a = before.meta, b = after.meta311            a.modified = Date(timeIntervalSince1970: 0); b.modified = a.modified312            return a != b313        }314    }315316    static func blockChanges(_ changes: DocChangeSet, before: DocumentStructure, after: DocumentStructure) -> [ProposedBlockChange] {317        changes.blocks.map { c in318            let old = c.before ?? "", new = c.after ?? ""319            let kind = ProposedBlockChange.Kind(rawValue: c.kind.rawValue) ?? .modified320            // A moved block is reported with its text as "after" only; it gains and loses nothing.321            let compare = kind != .moved322            return ProposedBlockChange(323                kind: kind, block: c.blockID, blockType: c.blockType, original: c.before, proposed: c.after, styleBefore: c.styleBefore, styleAfter: c.styleAfter,324                formattingOnly: c.formattingOnly,325                citationsAdded: compare ? InlineTokens.added(from: InlineTokens.citationKeys(in: old), to: InlineTokens.citationKeys(in: new)) : [],326                citationsRemoved: compare ? InlineTokens.added(from: InlineTokens.citationKeys(in: new), to: InlineTokens.citationKeys(in: old)) : [],327                objectsAdded: compare ? InlineTokens.added(from: InlineTokens.objects(in: old), to: InlineTokens.objects(in: new)) : [],328                objectsRemoved: compare ? InlineTokens.added(from: InlineTokens.objects(in: new), to: InlineTokens.objects(in: old)) : [],329                section: kind == .deleted ? before.sectionOfBlock[c.blockID] : after.sectionOfBlock[c.blockID])330        }331    }332333    static func build(id: String, agent: String, calls: [(callID: String, request: DocCommandRequest)], registry: DocCommandRegistry, preview: DocTransactionResult,334                      before: DocumentState, reason: String, tracked: Bool, author: String, extraWarnings: [String]) -> ChangeProposal {335        let beforeStructure = DocumentStructure(before.model), afterStructure = DocumentStructure(preview.resultingModel)336        var warnings = extraWarnings337        var commands: [ProposedCommand] = []338        for (i, call) in calls.enumerated() {339            let spec = registry[call.request.command]?.spec340            let editable = spec.flatMap(editableArgument)341            let result = preview.results.indices.contains(i) ? preview.results[i] : nil342            let own = result?.warnings ?? []343            warnings.append(contentsOf: own.map { "\(call.request.command): \($0)" })344            commands.append(ProposedCommand(345                index: i, callID: call.callID, command: call.request.command, title: spec?.title ?? call.request.command, arguments: call.request.arguments,346                summary: summary(call.request, title: spec?.title ?? call.request.command), editableArgument: editable,347                editableText: editable.flatMap { call.request.arguments[$0].stringValue },348                dependsOn: BatchReferences.targets(in: call.request.arguments).filter { $0 < i }.sorted(),349                changedBlocks: result?.changes.blocks.map(\.blockID) ?? [], warnings: own))350        }351        let blocks = blockChanges(preview.changes, before: beforeStructure, after: afterStructure)352        let removed = blocks.flatMap(\.citationsRemoved)353        if !removed.isEmpty { warnings.append("Citations removed: \(Array(Set(removed)).sorted().joined(separator: ", ")).") }354        return ChangeProposal(id: id, agent: agent, baseRevision: before.revision, commands: commands, blocks: blocks,355                              parts: meaningfulParts(preview.changes.parts, before: before.model, after: preview.resultingModel),356                              insertedTables: blocks.filter { $0.kind == .inserted && $0.blockType == "table" }.count,357                              pagesBefore: preview.changes.pagesBefore, pagesAfter: preview.changes.pagesAfter, warnings: warnings, reason: reason, tracked: tracked, author: author)358    }359}360
Files main
Menu

Theme