Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAgent/ContextEngine.swift10// Description : Hierarchical context for long documents: structure11// analysis, section summaries cached by content hash,12// lexical retrieval of passages with citation provenance,13// assembly under a token budget, and exact accounting of14// what was supplied to the model.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 AstraCore94import DocModel95import DocCommands9697// MARK: - Structure9899public struct SectionInfo: Sendable, Codable, Hashable, Identifiable {100 /// Identifier of the heading that opens the section; "preamble" for what precedes the first heading; "after:<id>" after a section break.101 public var id: String102 public var title: String103 /// Outline level of the heading (0 when the section has no heading).104 public var level: Int105 /// The heading that contains this section, if any.106 public var parent: String?107 /// Identifiers of the section's own blocks, heading included, up to the next heading of any level.108 public var blocks: [String]109 /// Blocks with content to examine (text paragraphs and tables), heading excluded.110 public var contentBlocks: [String]111 public var words: Int112 /// Hash of the section's rendered text: the cache key of its summary.113 public var contentHash: String114}115116/// The outline of a document as the agent reasons about it: leaf sections, the section of every block, and the content of every block.117public struct DocumentStructure: Sendable {118 public private(set) var sections: [SectionInfo] = []119 public private(set) var sectionOfBlock: [String: String] = [:]120 /// Rendered text of every body block (inline objects as tokens).121 public private(set) var textOfBlock: [String: String] = [:]122 public private(set) var hashOfBlock: [String: String] = [:]123 private var index: [String: Int] = [:]124125 public static let preambleID = "preamble"126127 public init(_ doc: DocumentModel) {128 var current = SectionInfo(id: Self.preambleID, title: "", level: 0, parent: nil, blocks: [], contentBlocks: [], words: 0, contentHash: "")129 var stack: [(id: String, level: Int)] = []130 var texts: [String] = []131 func close(_ s: inout SectionInfo, _ texts: inout [String], into out: inout [SectionInfo]) {132 guard !s.blocks.isEmpty else { texts = []; return }133 s.contentHash = ContentHash.of(texts.joined(separator: "\n"))134 out.append(s); texts = []135 }136 for block in doc.body {137 let text = DocRender.summary(block)138 textOfBlock[block.id] = text139 hashOfBlock[block.id] = ContentHash.of(text)140 var isHeading = false141 if let p = block.paragraph {142 let level = DocRender.outlineLevel(p, doc)143 if level > 0 {144 close(¤t, &texts, into: §ions)145 while let top = stack.last, top.level >= level { stack.removeLast() }146 current = SectionInfo(id: p.id, title: DocRender.text(p), level: level, parent: stack.last?.id, blocks: [], contentBlocks: [], words: 0, contentHash: "")147 stack.append((p.id, level))148 isHeading = true149 }150 }151 if case .sectionBreak(let s) = block {152 // The command engine ends a heading's section at a section break; what follows belongs to no heading.153 current.blocks.append(block.id); sectionOfBlock[block.id] = current.id154 close(¤t, &texts, into: §ions)155 stack = []156 current = SectionInfo(id: "after:\(s.id)", title: "", level: 0, parent: nil, blocks: [], contentBlocks: [], words: 0, contentHash: "")157 continue158 }159 current.blocks.append(block.id)160 sectionOfBlock[block.id] = current.id161 texts.append(text)162 let hasContent: Bool163 switch block {164 case .paragraph: hasContent = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty165 case .table: hasContent = true166 default: hasContent = false167 }168 if hasContent {169 if !isHeading { current.contentBlocks.append(block.id) }170 current.words += Self.words(text)171 }172 }173 close(¤t, &texts, into: §ions)174 for (i, s) in sections.enumerated() { index[s.id] = i }175 }176177 public func section(_ id: String) -> SectionInfo? { index[id].map { sections[$0] } }178179 /// The section and every heading above it.180 public func lineage(of sectionID: String) -> [String] {181 var out: [String] = [], cursor: String? = sectionID, guardCount = 0182 while let id = cursor, guardCount < 64 { out.append(id); cursor = section(id)?.parent; guardCount += 1 }183 return out184 }185186 /// True when the block lies under one of the whitelisted headings (directly or through a parent heading).187 public func isBlock(_ blockID: String, inside whitelist: Set<String>) -> Bool {188 guard let section = sectionOfBlock[blockID] else { return false }189 return lineage(of: section).contains { whitelist.contains($0) }190 }191192 /// Every block with content to examine, in document order.193 public var contentBlocks: [String] { sections.flatMap(\.contentBlocks) }194195 static func words(_ s: String) -> Int {196 var n = 0197 s.enumerateSubstrings(in: s.startIndex..., options: [.byWords, .substringNotRequired]) { _, _, _, _ in n += 1 }198 return n199 }200}201202// MARK: - Tokens of inline objects203204enum InlineTokens {205 private static let citation = try! NSRegularExpression(pattern: #"\[@[^\]\n]+\]"#)206 private static let object = try! NSRegularExpression(pattern: #"\$\$[^$\n]+\$\$|\$[^$\n]+\$|!\[[^\]\n]*\]\(image:[^)\n]+\)|\[\^[^\]\n]+\]|\[ref:[^\]\n]+\]"#)207208 private static func matches(_ regex: NSRegularExpression, _ text: String) -> [String] {209 let ns = text as NSString210 return regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { ns.substring(with: $0.range) }211 }212213 /// Citation keys in a rendered text, in order of appearance, repeated when cited several times.214 static func citationKeys(in text: String) -> [String] {215 matches(citation, text).flatMap { token in216 token.dropFirst().dropLast().split(separator: ";").compactMap { part -> String? in217 let t = part.trimmingCharacters(in: .whitespaces)218 guard t.hasPrefix("@") else { return nil }219 return String(t.dropFirst().prefix { $0 != "," }).trimmingCharacters(in: .whitespaces)220 }221 }222 }223224 /// Equations, images, notes and cross-references in a rendered text, as their tokens.225 static func objects(in text: String) -> [String] { matches(object, text) }226227 /// Elements of `b` that `a` lacks, counting repetitions.228 static func added(from a: [String], to b: [String]) -> [String] {229 var have: [String: Int] = [:]230 for x in a { have[x, default: 0] += 1 }231 var out: [String] = []232 for x in b { if let n = have[x], n > 0 { have[x] = n - 1 } else { out.append(x) } }233 return out234 }235}236237// MARK: - Summaries238239public protocol SectionSummarizer: Sendable {240 /// A summary of one section, at most about `maxWords` words. It must describe only what the text says.241 func summarize(title: String, text: String, maxWords: Int) async throws -> String242}243244/// Summarises without a model: the leading sentences of the section, cut at the word limit. Always available and never invents anything.245public struct ExtractiveSummarizer: SectionSummarizer {246 public init() {}247 public func summarize(title: String, text: String, maxWords: Int) async throws -> String {248 var words: [Substring] = []249 var cut = false250 for line in text.split(separator: "\n") where line != title[...] {251 for word in line.split(separator: " ") {252 if words.count >= maxWords { cut = true; break }253 words.append(word)254 }255 if cut { break }256 }257 return words.joined(separator: " ") + (cut ? " …" : "")258 }259}260261/// Summaries keyed by the hash of the text they summarise: a section that did not change is never summarised twice.262public final class SectionSummaryCache: Sendable {263 public struct Statistics: Sendable, Hashable { public var computed = 0; public var reused = 0 }264 private struct State: Sendable { var entries: [String: String] = [:]; var stats = Statistics() }265 private let state: Locked<State>266267 public init(entries: [String: String] = [:]) { state = Locked(State(entries: entries)) }268269 /// The cache as a dictionary, for persistence beside the document.270 public var entries: [String: String] { state.value.entries }271 public var statistics: Statistics { state.value.stats }272273 func lookup(_ key: String) -> String? {274 state.withLock { s in275 guard let hit = s.entries[key] else { return nil }276 s.stats.reused += 1277 return hit278 }279 }280 func store(_ key: String, _ summary: String) { state.withLock { $0.entries[key] = summary; $0.stats.computed += 1 } }281}282283// MARK: - Retrieval284285public struct Passage: Sendable, Codable, Hashable {286 /// Identifier of the block the text came from: the provenance of everything quoted from it.287 public var block: String288 public var section: String289 public var sectionTitle: String290 public var text: String291 /// Citation keys present in the passage, so a claim can be traced to the paragraph that cites its source.292 public var citations: [String]293 public var score: Double294}295296/// Hook for semantic retrieval: when supplied, passages are re-ranked by cosine similarity with the query.297public protocol PassageEmbedder: Sendable {298 func embed(_ texts: [String]) async throws -> [[Float]]299}300301/// BM25 over the blocks of a document.302struct LexicalIndex: Sendable {303 private var postings: [String: [(doc: Int, tf: Int)]] = [:]304 private var lengths: [Int] = []305 private var average: Double = 0306 let ids: [String]307308 static func terms(_ text: String) -> [String] {309 let folded = text.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)310 var out: [String] = []311 folded.enumerateSubstrings(in: folded.startIndex..., options: .byWords) { word, _, _, _ in312 if let word, word.count > 1 || word.first?.isNumber == true { out.append(word) }313 }314 return out315 }316317 init(_ blocks: [(id: String, text: String)]) {318 ids = blocks.map(\.id)319 for (i, block) in blocks.enumerated() {320 let terms = Self.terms(block.text)321 lengths.append(terms.count)322 var tf: [String: Int] = [:]323 for t in terms { tf[t, default: 0] += 1 }324 for (t, n) in tf { postings[t, default: []].append((i, n)) }325 }326 average = lengths.isEmpty ? 0 : Double(lengths.reduce(0, +)) / Double(lengths.count)327 }328329 func search(_ query: String, limit: Int) -> [(id: String, score: Double)] {330 let k1 = 1.2, b = 0.75331 var scores: [Int: Double] = [:]332 for term in Set(Self.terms(query)) {333 guard let list = postings[term] else { continue }334 let idf = log(1 + (Double(lengths.count) - Double(list.count) + 0.5) / (Double(list.count) + 0.5))335 for (doc, tf) in list {336 let norm = Double(tf) * (k1 + 1) / (Double(tf) + k1 * (1 - b + b * Double(lengths[doc]) / max(1, average)))337 scores[doc, default: 0] += idf * norm338 }339 }340 // Ties are broken by document order so results are deterministic.341 return scores.sorted { $0.value != $1.value ? $0.value > $1.value : $0.key < $1.key }.prefix(limit).map { (ids[$0.key], $0.value) }342 }343}344345// MARK: - Engine346347public struct SectionOverview: Sendable, Codable, Hashable {348 public var id: String349 public var title: String350 public var level: Int351 public var words: Int352 public var blocks: Int353 public var summary: String354}355356/// A bounded context: what fits, and exactly what it contains.357public struct ContextBundle: Sendable, Hashable {358 public var text: String359 public var estimatedTokens: Int360 /// Sections whose summary is in the bundle.361 public var summarizedSections: [String]362 /// Passages in the bundle, in order.363 public var passages: [Passage]364 /// Sections left out because the budget was reached.365 public var omittedSections: [String]366 public var totalSections: Int367}368369public final class DocumentContextEngine: Sendable {370 public let summarizer: any SectionSummarizer371 public let embedder: (any PassageEmbedder)?372 public let cache: SectionSummaryCache373 public let summaryWords: Int374375 public init(summarizer: any SectionSummarizer = ExtractiveSummarizer(), embedder: (any PassageEmbedder)? = nil,376 cache: SectionSummaryCache = SectionSummaryCache(), summaryWords: Int = 60) {377 self.summarizer = summarizer; self.embedder = embedder; self.cache = cache; self.summaryWords = summaryWords378 }379380 /// Token estimate with a margin: the estimator already rounds up, structured text costs a little more than prose.381 public static func tokens(_ text: String) -> Int { Int((Double(TokenEstimator.estimate(text)) * 1.15).rounded(.up)) + 4 }382383 func sectionText(_ section: SectionInfo, _ structure: DocumentStructure) -> String {384 section.blocks.compactMap { structure.textOfBlock[$0] }.joined(separator: "\n")385 }386387 /// The summary of one section, from the cache when its text did not change.388 public func summary(of section: SectionInfo, in structure: DocumentStructure) async -> String {389 if section.contentBlocks.isEmpty { return "" }390 if let hit = cache.lookup(section.contentHash) { return hit }391 let text = section.contentBlocks.compactMap { structure.textOfBlock[$0] }.joined(separator: "\n")392 // A summariser that fails must not stop the run: the extractive summary is always possible.393 var summary = (try? await summarizer.summarize(title: section.title, text: text, maxWords: summaryWords)) ?? ""394 if summary.isEmpty { summary = (try? await ExtractiveSummarizer().summarize(title: section.title, text: text, maxWords: summaryWords)) ?? "" }395 cache.store(section.contentHash, summary)396 return summary397 }398399 /// The outline with word counts and one summary per section.400 public func overview(_ structure: DocumentStructure, maxSections: Int = 60) async -> (sections: [SectionOverview], truncated: Bool) {401 var out: [SectionOverview] = []402 for section in structure.sections.prefix(maxSections) {403 out.append(SectionOverview(id: section.id, title: section.title, level: section.level, words: section.words, blocks: section.blocks.count,404 summary: await summary(of: section, in: structure)))405 }406 return (out, structure.sections.count > maxSections)407 }408409 /// The passages most relevant to a query, best first.410 public func retrieve(_ structure: DocumentStructure, query: String, limit: Int = 8) async -> [Passage] {411 let blocks = structure.contentBlocks.map { (id: $0, text: structure.textOfBlock[$0] ?? "") }412 let index = LexicalIndex(blocks)413 var hits = index.search(query, limit: embedder == nil ? limit : max(limit * 4, 24))414 if let embedder, !hits.isEmpty, let vectors = try? await embedder.embed([query] + hits.map { structure.textOfBlock[$0.id] ?? "" }), vectors.count == hits.count + 1 {415 // Hybrid score: the lexical score normalised to 0…1 plus the cosine similarity with the query.416 let top = hits.map(\.score).max() ?? 1417 hits = hits.enumerated().map { i, hit in (hit.id, hit.score / max(top, 1e-9) + Double(Self.cosine(vectors[0], vectors[i + 1]))) }418 .sorted { $0.score != $1.score ? $0.score > $1.score : $0.id < $1.id }419 }420 return hits.prefix(limit).map { hit in421 let text = structure.textOfBlock[hit.id] ?? ""422 let sectionID = structure.sectionOfBlock[hit.id] ?? DocumentStructure.preambleID423 return Passage(block: hit.id, section: sectionID, sectionTitle: structure.section(sectionID)?.title ?? "", text: text,424 citations: InlineTokens.citationKeys(in: text), score: (hit.score * 1000).rounded() / 1000)425 }426 }427428 static func cosine(_ a: [Float], _ b: [Float]) -> Float {429 guard a.count == b.count, !a.isEmpty else { return 0 }430 var dot: Float = 0, na: Float = 0, nb: Float = 0431 for i in a.indices { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i] }432 return na > 0 && nb > 0 ? dot / (na.squareRoot() * nb.squareRoot()) : 0433 }434435 /// Builds a context for `query` that fits `tokenBudget`: section summaries first (the map of the document), then the best passages.436 /// What does not fit is left out and listed; nothing is cut in the middle.437 public func assemble(_ structure: DocumentStructure, query: String, tokenBudget: Int, passageLimit: Int = 12) async -> ContextBundle {438 var lines: [String] = [], used = 0439 var summarized: [String] = [], omitted: [String] = []440 // Half of the budget at most goes to the map, so passages always have room.441 let mapBudget = tokenBudget / 2442 for section in structure.sections {443 let summary = await summary(of: section, in: structure)444 let title = section.title.isEmpty ? "(no heading)" : section.title445 let line = "- [\(section.id)] \(String(repeating: "#", count: max(1, section.level))) \(title) (\(section.words) words)" + (summary.isEmpty ? "" : ": \(summary)")446 let cost = Self.tokens(line)447 if used + cost > mapBudget { omitted.append(section.id); continue }448 lines.append(line); used += cost449 if !summary.isEmpty { summarized.append(section.id) }450 }451 var passages: [Passage] = []452 var passageLines: [String] = []453 for passage in await retrieve(structure, query: query, limit: passageLimit) {454 let line = "[\(passage.block)] (section \(passage.section)) \(passage.text)"455 let cost = Self.tokens(line)456 if used + cost > tokenBudget { continue }457 passageLines.append(line); passages.append(passage); used += cost458 }459 var text = "SECTIONS (summaries, not the text):\n" + lines.joined(separator: "\n")460 if !omitted.isEmpty { text += "\n(\(omitted.count) section(s) left out: budget reached)" }461 if !passageLines.isEmpty { text += "\n\nPASSAGES (full text of the paragraphs most relevant to the request):\n" + passageLines.joined(separator: "\n") }462 return ContextBundle(text: text, estimatedTokens: used, summarizedSections: summarized, passages: passages, omittedSections: omitted, totalSections: structure.sections.count)463 }464}465466// MARK: - Coverage467468public struct SectionCoverage: Sendable, Codable, Hashable {469 public var id: String470 public var title: String471 public var contentBlocks: Int472 /// Blocks whose current text was supplied to the model in full.473 public var supplied: Int474 public var summarySupplied: Bool475}476477/// What the model was actually shown, measured against the document as it is now.478public struct CoverageReport: Sendable, Codable, Hashable {479 /// Sections that have content to examine.480 public var totalSections: Int481 /// Sections of which at least one block was supplied in full.482 public var examinedSections: Int483 public var fullyExaminedSections: Int484 /// Sections known only through a summary.485 public var summaryOnlySections: Int486 public var totalBlocks: Int487 public var suppliedBlocks: Int488 /// Blocks supplied cut short (an output limit was reached).489 public var partialBlocks: Int490 /// True only when every content block of the document was supplied in full.491 public var wholeDocument: Bool492 public var sections: [SectionCoverage]493494 /// The sentence the report carries. Written by code from the counts above.495 public var statement: String {496 if totalBlocks == 0 { return "The document has no content to examine." }497 if wholeDocument { return "Examined the whole document: all \(totalSections) section(s), \(totalBlocks) block(s) supplied to the model in full." }498 var s = "Examined \(examinedSections) of \(totalSections) section(s)"499 if examinedSections > 0 { s += " (\(fullyExaminedSections) in full, \(examinedSections - fullyExaminedSections) in part)" }500 s += "; \(suppliedBlocks) of \(totalBlocks) block(s) were supplied to the model."501 if summaryOnlySections > 0 { s += " \(summaryOnlySections) more section(s) were seen only as summaries." }502 if partialBlocks > 0 { s += " \(partialBlocks) block(s) were supplied cut short." }503 s += " This is not a whole-document analysis."504 return s505 }506}507508/// Records exactly which blocks and summaries were delivered to the model. Updated only where content is put into a message.509public struct CoverageTracker: Sendable, Codable, Hashable {510 /// Block identifier → hash of the text that was shown.511 public private(set) var shown: [String: String] = [:]512 public private(set) var partial: Set<String> = []513 public private(set) var summarized: Set<String> = []514 public init() {}515516 public mutating func recordFull(block: String, hash: String) { shown[block] = hash; partial.remove(block) }517 public mutating func recordPartial(block: String) { if shown[block] == nil { partial.insert(block) } }518 public mutating func recordSummary(section: String) { summarized.insert(section) }519 public mutating func forget(block: String) { shown[block] = nil; partial.remove(block) }520521 /// Hash of the text the model was shown for a block, if any.522 public func hashShown(for block: String) -> String? { shown[block] }523524 public func report(for structure: DocumentStructure) -> CoverageReport {525 var sections: [SectionCoverage] = []526 var total = 0, supplied = 0, cutShort = 0527 for section in structure.sections where !section.contentBlocks.isEmpty {528 // A block counts only if what was shown is what the document holds now.529 let n = section.contentBlocks.filter { shown[$0] != nil && shown[$0] == structure.hashOfBlock[$0] }.count530 cutShort += section.contentBlocks.filter { partial.contains($0) }.count531 total += section.contentBlocks.count; supplied += n532 sections.append(SectionCoverage(id: section.id, title: section.title, contentBlocks: section.contentBlocks.count, supplied: n, summarySupplied: summarized.contains(section.id)))533 }534 return CoverageReport(totalSections: sections.count, examinedSections: sections.filter { $0.supplied > 0 }.count,535 fullyExaminedSections: sections.filter { $0.supplied == $0.contentBlocks }.count,536 summaryOnlySections: sections.filter { $0.supplied == 0 && $0.summarySupplied }.count,537 totalBlocks: total, suppliedBlocks: supplied, partialBlocks: cutShort, wholeDocument: total == supplied, sections: sections)538 }539}540