Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocAutomation/WorkflowStores.swift3// Description: On-disk stores of the automation engine: the bounded execution history and the user's saved workflows (JSON files4// under Application Support), plus the built-in workflows.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112public enum AutomationPaths {13 /// `~/Library/Application Support/ORIX Docs/Automation` (created on demand by the stores).14 /// The environment variable `ORIX_AUTOMATION_HOME` moves it elsewhere (tests, scripted environments).15 public static var supportDirectory: URL {16 if let custom = ProcessInfo.processInfo.environment["ORIX_AUTOMATION_HOME"], !custom.isEmpty {17 return URL(fileURLWithPath: (custom as NSString).expandingTildeInPath, isDirectory: true)18 }19 let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first20 ?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")21 return base.appendingPathComponent("ORIX Docs", isDirectory: true).appendingPathComponent("Automation", isDirectory: true)22 }23 public static var historyFile: URL { supportDirectory.appendingPathComponent("history.json") }24 public static var workflowsDirectory: URL { supportDirectory.appendingPathComponent("Workflows", isDirectory: true) }25}2627/// The execution history: a JSON file holding the most recent runs, newest first. Safe to use from any thread.28public final class WorkflowHistoryStore: @unchecked Sendable {29 public let url: URL30 public let limit: Int31 private let lock = NSLock()3233 public static let shared = WorkflowHistoryStore(url: AutomationPaths.historyFile) // resolved once, at first use3435 public init(url: URL, limit: Int = 200) {36 self.url = url37 self.limit = max(1, limit)38 }3940 private static let encoder: JSONEncoder = {41 let e = JSONEncoder()42 e.dateEncodingStrategy = .iso860143 e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]44 return e45 }()46 private static let decoder: JSONDecoder = {47 let d = JSONDecoder()48 d.dateDecodingStrategy = .iso860149 return d50 }()5152 private func read() -> [WorkflowRun] {53 guard let data = try? Data(contentsOf: url), data.count < 64 * 1024 * 1024 else { return [] }54 return (try? WorkflowHistoryStore.decoder.decode([WorkflowRun].self, from: data)) ?? []55 }5657 private func write(_ runs: [WorkflowRun]) {58 try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)59 if let data = try? WorkflowHistoryStore.encoder.encode(runs) { try? data.write(to: url, options: .atomic) }60 }6162 /// Newest first.63 public func load() -> [WorkflowRun] { lock.lock(); defer { lock.unlock() }; return read() }6465 public func append(_ run: WorkflowRun) {66 lock.lock(); defer { lock.unlock() }67 var runs = read()68 runs.insert(run, at: 0)69 if runs.count > limit { runs.removeLast(runs.count - limit) }70 write(runs)71 }7273 public func clear() { lock.lock(); defer { lock.unlock() }; write([]) }74}7576/// The user's saved workflows: one validated JSON file per workflow.77public struct WorkflowLibrary: Sendable {78 public let directory: URL79 public init(directory: URL = AutomationPaths.workflowsDirectory) { self.directory = directory }8081 public struct Entry: Sendable, Identifiable {82 public var url: URL83 public var workflow: Workflow?84 /// Why the file was refused, when it was.85 public var problem: String?86 public var id: String { url.path }87 }8889 /// Every `.json` file of the folder, valid or not (an invalid one carries its problem and cannot be run).90 public func entries() -> [Entry] {91 let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []92 return files.filter { $0.pathExtension.lowercased() == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }.map { url in93 do { return Entry(url: url, workflow: try Workflow.load(contentsOf: url), problem: nil) }94 catch { return Entry(url: url, workflow: nil, problem: "\(error)") }95 }96 }9798 @discardableResult99 public func save(_ workflow: Workflow) throws -> URL {100 try workflow.validate()101 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)102 let slug = Workflow.slug(workflow.name)103 let url = directory.appendingPathComponent((slug.isEmpty ? workflow.id : slug) + ".json")104 try workflow.jsonData().write(to: url, options: .atomic)105 return url106 }107}108109public enum BuiltinWorkflows {110 public static let docxToStyledPDF = Workflow(111 id: "docx-to-styled-pdf", name: "DOCX → styled PDF",112 summary: "Opens a Word document, applies the ORIX theme, adds a table of contents, audits it and publishes a PDF.",113 steps: [.importDocument(path: nil), .applyTheme(name: Theme.orix.name), .tableOfContents(title: nil, maxLevel: 3),114 .audit(profile: .standard, failOnErrors: false), .export(format: .pdf, fileName: nil, pdf: PDFExportOptions(outline: true, tagged: true))])115116 public static let markdownToPDF = Workflow(117 id: "markdown-to-pdf", name: "Markdown → PDF with template",118 summary: "Opens a Markdown file, gives it the styles of the Research Report template on A4 and publishes a PDF.",119 steps: [.importDocument(path: nil), .applyTemplateStyles(templateID: "research-report"), .setPageSetup(PageSetupOptions(paper: "a4", margins: 72)),120 .tableOfContents(title: nil, maxLevel: 2), .insertBibliography(title: nil), .export(format: .pdf, fileName: nil, pdf: nil)])121122 public static let cleanReviewCopy = Workflow(123 id: "clean-review-copy", name: "Clean review copy",124 summary: "Accepts every tracked change, removes the comments and writes a clean Word document.",125 steps: [.importDocument(path: nil), .acceptAllChanges, .removeComments, .recalculateTables, .export(format: .docx, fileName: "{name}-clean.docx", pdf: nil)])126127 public static let auditOnly = Workflow(128 id: "audit-only", name: "Audit only",129 summary: "Audits the document and writes the findings as a Markdown report and as JSON. The document itself is not exported.",130 steps: [.importDocument(path: nil), .audit(profile: .standard, failOnErrors: false), .writeAuditReport(format: "md", fileName: nil),131 .writeAuditReport(format: "json", fileName: nil)])132133 public static let all: [Workflow] = [docxToStyledPDF, markdownToPDF, cleanReviewCopy, auditOnly]134135 public static func named(_ name: String) -> Workflow? {136 let key = name.lowercased()137 return all.first { $0.id == key || $0.name.lowercased() == key }138 }139}140