SPB Git

Repository Public

Integrity.swift 7.8 KB 166 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/Integrity.swift10// Description      : Document integrity as the agent checks it around every11//                    mutation: a body that ends with a paragraph, unique12//                    identifiers, and no cross-reference or citation broken by13//                    the step. Problems that existed before a step are not14//                    blamed on it.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 DocCommands9596public struct IntegrityIssue: Sendable, Codable, Hashable {97    public enum Kind: String, Sendable, Codable {98        case emptyBody = "empty_body"99        case bodyDoesNotEndWithParagraph = "body_does_not_end_with_paragraph"100        case duplicateIdentifier = "duplicate_identifier"101        case brokenCrossReference = "broken_cross_reference"102        case unresolvedCitation = "unresolved_citation"103    }104    public var kind: Kind105    /// The paragraph or block concerned, when there is one.106    public var block: String?107    /// The identifier, target or key concerned.108    public var subject: String?109    public var message: String110}111112/// The outcome of a check, as shown in the timeline and kept in the report.113public struct IntegrityResult: Sendable, Codable, Hashable {114    /// Problems the step introduced. Empty when the step is sound.115    public var introduced: [IntegrityIssue]116    /// Problems that were already there before the step (reported, not blamed on it).117    public var preexisting: Int118    public var ok: Bool { introduced.isEmpty }119}120121public enum DocumentIntegrity {122    /// Every integrity problem of a document, found with the command engine's own validators.123    public static func issues(in doc: DocumentModel, registry: DocCommandRegistry = .standard) -> [IntegrityIssue] {124        var out: [IntegrityIssue] = []125        if doc.body.isEmpty {126            out.append(IntegrityIssue(kind: .emptyBody, block: nil, subject: nil, message: "The document body is empty."))127        } else if doc.body.last?.paragraph == nil {128            out.append(IntegrityIssue(kind: .bodyDoesNotEndWithParagraph, block: doc.body.last?.id, subject: nil, message: "The document body does not end with a paragraph."))129        }130        for id in DocIndex(doc).duplicates.sorted() {131            out.append(IntegrityIssue(kind: .duplicateIdentifier, block: id, subject: id, message: "The identifier \"\(id)\" is used by more than one element."))132        }133        let executor = DocCommandExecutor(registry: registry)134        let context = DocCommandContext(client: "Integrity check", scopes: [.documentRead], author: "ORIX Docs")135        var state = DocumentState(model: doc)136        if let broken = try? executor.run(DocCommandRequest("crossref.validate"), on: &state, context: context).output["broken"].arrayValue {137            for item in broken {138                let target = item["target"].stringValue ?? ""139                out.append(IntegrityIssue(kind: .brokenCrossReference, block: item["paragraph"].stringValue, subject: target,140                                          message: "A cross-reference points at \"\(target)\", which does not exist."))141            }142        }143        if let unresolved = try? executor.run(DocCommandRequest("references.validate"), on: &state, context: context).output["unresolvedCitations"].arrayValue {144            for item in unresolved {145                let key = item["key"].stringValue ?? ""146                out.append(IntegrityIssue(kind: .unresolvedCitation, block: item["paragraph"].stringValue, subject: key,147                                          message: "The citation key \"\(key)\" has no bibliography entry."))148            }149        }150        return out151    }152153    /// Compares the document before and after a step and returns what the step broke.154    public static func compare(before: DocumentModel, after: DocumentModel, registry: DocCommandRegistry = .standard) -> IntegrityResult {155        let old = issues(in: before, registry: registry)156        // A multiset difference: a second broken reference to the same target in the same paragraph is a new problem too.157        var remaining: [IntegrityIssue: Int] = [:]158        for issue in old { remaining[issue, default: 0] += 1 }159        var introduced: [IntegrityIssue] = []160        for issue in issues(in: after, registry: registry) {161            if let n = remaining[issue], n > 0 { remaining[issue] = n - 1 } else { introduced.append(issue) }162        }163        return IntegrityResult(introduced: introduced, preexisting: old.count)164    }165}166
Files main
Menu

Theme