Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraPersistence/Sources/PromptStudio.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import GRDB90import AstraCore9192/// `{{variable}}` placeholders: extraction and rendering. Names are letters, digits, `_`, `.` and `-`, with optional spaces93/// inside the braces. Rendering is a single pass: a value containing `{{…}}` is never expanded again.94public enum PromptRenderer {95 public struct Result: Sendable, Hashable {96 public var text: String97 /// Variables the template uses that had no value; their placeholders are left in the text as written.98 public var missing: [String]99 /// Values that were supplied but that the template does not use.100 public var unused: [String]101 public var isComplete: Bool { missing.isEmpty }102 }103104 private static let pattern = try? NSRegularExpression(pattern: #"\{\{\s*([\p{L}\p{N}_][\p{L}\p{N}_.\-]*)\s*\}\}"#)105106 /// Variable names in order of first appearance, without duplicates.107 public static func variables(in template: String) -> [String] {108 guard let pattern else { return [] }109 let text = template as NSString110 var seen = Set<String>(); var out: [String] = []111 for match in pattern.matches(in: template, range: NSRange(location: 0, length: text.length)) {112 let name = text.substring(with: match.range(at: 1))113 if seen.insert(name).inserted { out.append(name) }114 }115 return out116 }117118 public static func render(_ template: String, values: [String: String]) -> Result {119 guard let pattern else { return Result(text: template, missing: [], unused: values.keys.sorted()) }120 let text = template as NSString121 var out = ""; var cursor = 0122 var missing: [String] = []; var used = Set<String>()123 for match in pattern.matches(in: template, range: NSRange(location: 0, length: text.length)) {124 out += text.substring(with: NSRange(location: cursor, length: match.range.location - cursor))125 let name = text.substring(with: match.range(at: 1))126 if let value = values[name] { out += value; used.insert(name) }127 else { out += text.substring(with: match.range); if !missing.contains(name) { missing.append(name) } }128 cursor = match.range.location + match.range.length129 }130 out += text.substring(from: cursor)131 return Result(text: out, missing: missing, unused: values.keys.filter { !used.contains($0) }.sorted())132 }133}134135public extension AstraStore {136 // MARK: Templates137138 /// Creates a template (id nil) or saves a new version of an existing one. Every save appends to the version history.139 @discardableResult140 func saveTemplate(id: String? = nil, name: String, system: String, userTemplate: String, parameters: GenerationParameters = .default,141 note: String? = nil, at date: Date = Date()) async throws -> PromptTemplateRecord {142 try await write { db in143 var template: PromptTemplateRecord144 if let id, let existing = try PromptTemplateRecord.find(db, id: id) {145 template = existing146 template.name = name; template.system = system; template.userTemplate = userTemplate; template.parameters = parameters147 template.currentVersion = try Self.nextTemplateVersion(db, id); template.updatedAt = date148 try template.updateByID(db)149 } else {150 template = PromptTemplateRecord(id: id ?? AstraID.new(), name: name, system: system, userTemplate: userTemplate,151 parameters: parameters, currentVersion: 1, createdAt: date, updatedAt: date)152 try template.insert(db)153 }154 try PromptTemplateVersionRecord(id: AstraID.new(), templateID: template.id, version: template.currentVersion, name: name, system: system,155 userTemplate: userTemplate, parameters: parameters, note: note, createdAt: date).insert(db)156 return template157 }158 }159160 func templates() async throws -> [PromptTemplateRecord] {161 try await read { db in try PromptTemplateRecord.fetchReadable(db, sql: "SELECT * FROM promptTemplate ORDER BY name COLLATE NOCASE, id") }162 }163164 func template(id: String) async throws -> PromptTemplateRecord? { try await read { db in try PromptTemplateRecord.find(db, id: id) } }165166 /// Newest version first.167 func templateVersions(templateID: String) async throws -> [PromptTemplateVersionRecord] {168 try await read { db in169 try PromptTemplateVersionRecord.fetchReadable(db, sql: "SELECT * FROM promptTemplateVersion WHERE templateID = ? ORDER BY version DESC",170 arguments: [templateID])171 }172 }173174 /// Makes an old version current again by saving its content as a new version: history is never rewritten.175 @discardableResult176 func restoreTemplateVersion(templateID: String, version: Int, at date: Date = Date()) async throws -> PromptTemplateRecord {177 try await write { db in178 var template = try PromptTemplateRecord.require(db, id: templateID)179 guard let old = try PromptTemplateVersionRecord.fetchOne(db, sql: "SELECT * FROM promptTemplateVersion WHERE templateID = ? AND version = ?",180 arguments: [templateID, version]) else {181 throw AstraStoreError.notFound("This version")182 }183 template.name = old.name; template.system = old.system; template.userTemplate = old.userTemplate; template.parameters = old.parameters184 template.currentVersion = try Self.nextTemplateVersion(db, templateID); template.updatedAt = date185 try template.updateByID(db)186 try PromptTemplateVersionRecord(id: AstraID.new(), templateID: templateID, version: template.currentVersion, name: old.name,187 system: old.system, userTemplate: old.userTemplate, parameters: old.parameters,188 note: "Restored from version \(version)", createdAt: date).insert(db)189 return template190 }191 }192193 /// Deletes a template with its whole history.194 func deleteTemplate(id: String) async throws { try await write { db in _ = try PromptTemplateRecord.remove(db, id: id) } }195196 // MARK: Presets197198 func savePreset(_ preset: PresetRecord, at date: Date = Date()) async throws {199 var record = preset200 record.updatedAt = date201 let saved = record202 try await write { db in try saved.save(db) }203 }204205 func presets() async throws -> [PresetRecord] {206 try await read { db in try PresetRecord.fetchReadable(db, sql: "SELECT * FROM preset ORDER BY name COLLATE NOCASE, id") }207 }208209 func preset(id: String) async throws -> PresetRecord? { try await read { db in try PresetRecord.find(db, id: id) } }210211 /// Conversations that used the preset keep their own copy of its instruction and parameters; only the link is cleared.212 func deletePreset(id: String) async throws { try await write { db in _ = try PresetRecord.remove(db, id: id) } }213}214215extension AstraStore {216 static func nextTemplateVersion(_ db: Database, _ templateID: String) throws -> Int {217 (try Int.fetchOne(db, sql: "SELECT MAX(version) FROM promptTemplateVersion WHERE templateID = ?", arguments: [templateID]) ?? 0) + 1218 }219}220