Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeaturesCatalog/Samples+Assistant.swift3// Description: Sample data of the « Assistant » area (ask, model picker, research, citations) for the catalogue and the4// tests. Recorded from the scratch backend: the model catalogue (nine models of the live answer of5// 2026-11-19 with probes / benchmark removed, plus the OpenRouter example of API-NEXT-AI), the chat streams of6// API-NEXT-AI (grounded answer, « no supporting note »), the research overview, experiments, DOI lookup / add7// and BibTeX import answers. Hand-made, following the DTOs: the conversations, five well-known references of8// the library, the BibTeX and LaTeX export texts (the recorded LaTeX route answered 404 at recording time).9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation13import SPNotesTestSupport1415public enum AssistantSamples {16 /// The page of the recorded grounded answer (« Offre de la banque »).17 public static let askPageId = "2eea0ded-b5b8-4abe-b560-75345504be80"18 public static let askBlockId = "XycxLnbyuq"19 /// The paper page of the recorded research answers.20 public static let projectId = "453049f0-c4ff-4019-8d6d-c24cbe834e01"21 public static let conversationId = "fe873d65-75c5-4827-89d2-37e1e48918f6"22 public static let famaDOI = "10.2307/2325486"2324 static func uuid(_ n: Int) -> String { String(format: "00000000-0000-4000-9000-%012d", n) }2526 /// (citeKey, title, authors, year, journal, doi, volume, number, pages, verified, attached to the project page)27 static let library: [(String, String, [String], Int, String, String, String, String, String, String, Bool)] = [28 ("engle1982autoregressive", "Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation", ["Robert F. Engle"], 1982,29 "Econometrica", "10.2307/1912773", "50", "4", "987--1007", "doi_verified", true),30 ("bollerslev1986generalized", "Generalized Autoregressive Conditional Heteroskedasticity", ["Tim Bollerslev"], 1986,31 "Journal of Econometrics", "10.1016/0304-4076(86)90063-1", "31", "3", "307--327", "doi_verified", true),32 ("nelson1987parsimonious", "Parsimonious Modeling of Yield Curves", ["Charles R. Nelson", "Andrew F. Siegel"], 1987,33 "The Journal of Business", "10.1086/296409", "60", "4", "473--489", "user", false),34 ("black1973pricing", "The Pricing of Options and Corporate Liabilities", ["Fischer Black", "Myron Scholes"], 1973,35 "Journal of Political Economy", "10.1086/260062", "81", "3", "637--654", "user", false),36 ("glosten1993relation", "On the Relation between the Expected Value and the Volatility of the Nominal Excess Return on Stocks", ["Lawrence R. Glosten", "Ravi Jagannathan", "David E. Runkle"], 1993,37 "The Journal of Finance", "10.1111/j.1540-6261.1993.tb05128.x", "48", "5", "1779--1801", "ai_suggested", true),38 ]3940 public static func referenceId(_ index: Int) -> String { uuid(index + 1) }4142 static func bibAuthor(_ name: String) -> String {43 let words = name.split(separator: " ").map(String.init)44 guard words.count > 1 else { return name }45 return words[words.count - 1] + ", " + words.dropLast().joined(separator: " ")46 }4748 static func bibtex(_ item: (String, String, [String], Int, String, String, String, String, String, String, Bool)) -> String {49 "@article{\(item.0),\n author = {\(item.2.map(bibAuthor).joined(separator: " and "))},\n title = {\(item.1)},\n journal = {\(item.4)},\n year = {\(item.3)},\n volume = {\(item.6)},\n number = {\(item.7)},\n pages = {\(item.8)},\n doi = {\(item.5)}\n}"50 }5152 static func reference(_ index: Int) -> [String: Any] {53 let item = library[index]54 return ["id": referenceId(index), "workspaceId": uuid(900), "pageId": item.10 ? projectId : NSNull(), "citeKey": item.0, "entryType": "article", "title": item.1,55 "authors": item.2, "year": item.3, "journal": item.4, "doi": item.5, "url": "https://doi.org/" + item.5, "bibtex": bibtex(item),56 "fields": ["volume": item.6, "number": item.7, "pages": item.8], "verified": item.9, "attachmentId": NSNull(),57 "createdAt": "2026-11-0\(index + 1)T14:00:00.000Z", "updatedAt": "2026-11-1\(index)T09:30:00.000Z", "deletedAt": NSNull(), "rev": 100 + index]58 }5960 static func json(_ object: Any) -> String {61 String(data: (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data("null".utf8), encoding: .utf8) ?? "null"62 }6364 public static var bibExport: String { library.map(bibtex).joined(separator: "\n\n") + "\n" }6566 public static let texExport = """67 \\documentclass[11pt]{article}68 \\usepackage[utf8]{inputenc}69 \\usepackage{natbib}70 \\title{Volatilité conditionnelle}71 \\begin{document}72 \\maketitle73 \\section{Introduction}74 Les modèles ARCH \\citep{engle1982autoregressive} et GARCH \\citep{bollerslev1986generalized} décrivent la variance conditionnelle.75 \\section{Effet de levier}76 L'asymétrie est documentée par \\citet{glosten1993relation}.77 \\bibliographystyle{apalike}78 \\bibliography{references}79 \\end{document}8081 """8283 /// One `text/event-stream` body from JSON events.84 public static func sse(_ events: [String]) -> Data {85 Data((events.map { "data: " + $0.replacingOccurrences(of: "\n", with: "") + "\n\n" }.joined() + "data: [DONE]\n\n").utf8)86 }8788 static func event(_ name: String) -> String {89 // re-serialised on one line (the recorded files are pretty-printed)90 guard let object = try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("ai-doc", name).utf8)) else { return "{}" }91 return json(object)92 }9394 static func text(_ delta: String) -> String { json(["type": "text", "delta": delta]) }9596 /// The recorded grounded answer: meta (one source with its block), three deltas, done (the cited source).97 public static var groundedStream: Data {98 // The published `done` example abbreviates its source (« …same source… »): the complete one of `meta` is put back.99 let meta = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("ai-doc", "chat-page-meta").utf8)) as? [String: Any]) ?? [:]100 var done = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("ai-doc", "chat-page-done").utf8)) as? [String: Any]) ?? [:]101 done["sources"] = meta["sources"] ?? [Any]()102 return sse([json(meta), text("La"), text(" pénalité de rembours"), text("ement anticipé équivaut à trois mois d'intérêts [1]."), json(done)])103 }104105 /// The recorded « no supporting note » answer: no provider called, cost 0.106 public static var noEvidenceStream: Data { sse([event("chat-none-meta"), event("chat-none-done")]) }107108 /// A model answered without citing: the server withholds the answer (API-NEXT-AI, guarantee 4).109 public static var insufficientStream: Data {110 var meta = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("ai-doc", "chat-page-meta").utf8)) as? [String: Any]) ?? [:]111 meta["clientId"] = "sample-insufficient"112 var done = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("ai-doc", "chat-page-done").utf8)) as? [String: Any]) ?? [:]113 done["content"] = "**No supporting note found.** The model wrote an answer without citing any of the retrieved passages, …"114 done["evidence"] = "insufficient"115 done["uncited"] = true116 done["sources"] = [Any]()117 return sse([json(meta), text("Selon moi, la pénalité est élevée."), json(done)])118 }119120 public static var conversations: String {121 json([122 ["id": conversationId, "title": "Pénalité de remboursement anticipé", "pageId": askPageId, "model": "claude-haiku-5-5", "routing": "manual", "pinned": true,123 "createdAt": "2026-11-19T13:10:00.000Z", "updatedAt": "2026-11-19T13:12:00.000Z", "deletedAt": NSNull()],124 ["id": uuid(801), "title": "Hypothèses du modèle GARCH", "pageId": NSNull(), "model": NSNull(), "routing": "auto", "pinned": false,125 "createdAt": "2026-11-17T09:00:00.000Z", "updatedAt": "2026-11-17T09:20:00.000Z", "deletedAt": NSNull()],126 ["id": uuid(802), "title": "", "pageId": NSNull(), "model": NSNull(), "routing": "auto", "pinned": false,127 "createdAt": "2026-11-10T16:00:00.000Z", "updatedAt": "2026-11-10T16:05:00.000Z", "deletedAt": NSNull()],128 ])129 }130131 public static var conversationDetail: String {132 // Flat, as Core's `AIConversationDetail` reads it (the conversation's fields + `messages`).133 json(["id": conversationId, "title": "Pénalité de remboursement anticipé", "pageId": askPageId, "model": "claude-haiku-5-5", "routing": "manual", "pinned": true,134 "createdAt": "2026-11-19T13:10:00.000Z", "updatedAt": "2026-11-19T13:12:00.000Z", "deletedAt": NSNull(),135 "messages": [136 ["id": uuid(811), "conversationId": conversationId, "role": "user", "content": "Quelle est la pénalité de remboursement anticipé ?", "createdAt": "2026-11-19T13:10:00.000Z"],137 ["id": "e52caff5-2aa9-4bea-aafe-46431bc80021", "conversationId": conversationId, "role": "assistant",138 "content": "La pénalité de remboursement anticipé équivaut à trois mois d'intérêts [1].", "model": "claude-haiku-5-5", "provider": "anthropic",139 "sources": [["chunkId": "a8a64c4b-bafb-4afe-b4a6-2594f911b667", "pageId": askPageId, "blockId": askBlockId, "title": "Offre de la banque",140 "excerpt": "La pénalité de remboursement anticipé équivaut à trois mois d intérêts.", "score": 0.0167]],141 "costUsd": 0.0000723, "latencyMs": 1213, "meta": ["evidence": "ok"], "createdAt": "2026-11-19T13:10:02.000Z"],142 ]])143 }144}145146extension FeatureSamples {147 static func installAssistant(on world: FeatureWorld) {148 let fake = world.fake149 // Model catalogue.150 fake.stub("GET", path: "^/api/ai/models$", json: FeatureSamples.text("ai", "models-catalog"))151152 // Ask: the stream depends on what is asked — a project scope finds nothing (recorded), « sans citer » is withheld,153 // « tout le dossier » is announced as expensive until confirmed, anything else gets the recorded grounded answer.154 fake.stub("POST", path: "^/api/ai/chat$") { request in155 let body = (try? JSONSerialization.jsonObject(with: request.body) as? [String: Any]) ?? [:]156 let message = (body["message"] as? String ?? "").lowercased()157 let headers = ["content-type": "text/event-stream; charset=utf-8"]158 if message.contains("tout le dossier"), body["confirmExpensive"] as? Bool != true {159 return .json(#"{"error":"This request is expensive: confirm to send it.","code":"confirm_expensive","plan":{"model":"claude-fable-5-1","estCostUsd":1.84,"reason":"large context (212 000 tokens)"}}"#, status: 409)160 }161 if body["scope"] as? String == "project" { return .init(body: AssistantSamples.noEvidenceStream, headers: headers) }162 if message.contains("sans citer") { return .init(body: AssistantSamples.insufficientStream, headers: headers) }163 return .init(body: AssistantSamples.groundedStream, headers: headers)164 }165 fake.stub("GET", path: "^/api/ai/conversations$") { request in166 .json(request.query["id"] == nil ? AssistantSamples.conversations : AssistantSamples.conversationDetail)167 }168 fake.stub("PATCH", path: "^/api/ai/conversations$", json: #"{"ok":true}"#)169 fake.stub("DELETE", path: "^/api/ai/conversations$", json: #"{"ok":true}"#)170171 // Research: the library is in the entity feed (local copy after a sync) and behind the REST routes.172 for index in AssistantSamples.library.indices {173 fake.webPutEntity(kind: "reference", id: AssistantSamples.referenceId(index), json: AssistantSamples.json(AssistantSamples.reference(index)))174 }175 fake.stub("GET", path: "^/api/research/references$") { request in176 var rows = AssistantSamples.library.indices.map(AssistantSamples.reference)177 if let ids = request.query["ids"] {178 let wanted = Set(ids.split(separator: ",").map { $0.lowercased() })179 rows = rows.filter { wanted.contains(($0["id"] as? String ?? "").lowercased()) }.map { row in180 var row = row181 row["label"] = NSNull()182 return row183 }184 } else if request.query["projectId"] != nil || request.query["pageId"] != nil {185 rows = rows.filter { $0["pageId"] is String }186 }187 return .json(AssistantSamples.json(rows))188 }189 fake.stub("POST", path: "^/api/research/references$") { request in190 guard var body = try? JSONSerialization.jsonObject(with: request.body) as? [String: Any] else { return .error(400, code: "validation") }191 var row = AssistantSamples.reference(0)192 for (key, value) in body { row[key] = value }193 if body["citeKey"] == nil || body["citeKey"] is NSNull { body["citeKey"] = "nouvelle2026"; row["citeKey"] = "nouvelle2026" }194 row["doi"] = body["doi"] ?? NSNull(); row["url"] = body["url"] ?? NSNull(); row["journal"] = body["journal"] ?? NSNull(); row["year"] = body["year"] ?? NSNull()195 row["authors"] = body["authors"] ?? [String](); row["fields"] = [String: Any](); row["bibtex"] = NSNull(); row["verified"] = "user"; row["rev"] = 500196 return .json(AssistantSamples.json(row), status: 201)197 }198 fake.stub("PATCH", path: "^/api/research/references/[^/]+$") { request in199 let id = request.path.split(separator: "/").last.map(String.init) ?? ""200 guard let index = AssistantSamples.library.indices.first(where: { AssistantSamples.referenceId($0) == id }),201 let body = try? JSONSerialization.jsonObject(with: request.body) as? [String: Any] else { return .error(404, code: "not_found") }202 var row = AssistantSamples.reference(index)203 for (key, value) in body { row[key] = value }204 // like the server: a key taken by another reference is de-duplicated with a letter, never refused205 if let key = body["citeKey"] as? String, AssistantSamples.library.enumerated().contains(where: { $0.offset != index && $0.element.0 == key }) { row["citeKey"] = key + "b" }206 row["rev"] = 600207 return .json(AssistantSamples.json(row))208 }209 fake.stub("DELETE", path: "^/api/research/references/[^/]+$", json: #"{"ok":true}"#)210 fake.stub("POST", path: "^/api/research/references/[^/]+$") { request in // ?action=restore211 let id = request.path.split(separator: "/").last.map(String.init) ?? ""212 guard let index = AssistantSamples.library.indices.first(where: { AssistantSamples.referenceId($0) == id }) else { return .error(404, code: "not_found") }213 return .json(AssistantSamples.json(AssistantSamples.reference(index)))214 }215 fake.stub("GET", path: "^/api/research/references/doi$") { request in216 request.query["doi"] == AssistantSamples.famaDOI ? .json(FeatureSamples.text("research", "doi-lookup")) : .error(404, code: "doi_not_found", message: "DOI not found")217 }218 fake.stub("POST", path: "^/api/research/references/doi$", json: FeatureSamples.text("research", "doi-add"), status: 201)219 fake.stub("POST", path: "^/api/research/references/import-bibtex$") { request in220 let body = (try? JSONSerialization.jsonObject(with: request.body) as? [String: Any]) ?? [:]221 return .json(FeatureSamples.text("research", body["dryRun"] as? Bool == true ? "bibtex-dry-run" : "bibtex-import"))222 }223 fake.stub("GET", path: "^/api/research/references/export\\.bib$") { _ in224 .init(body: Data(AssistantSamples.bibExport.utf8), headers: ["content-type": "application/x-bibtex; charset=utf-8", "content-disposition": "attachment; filename=\"library.bib\"",225 "x-export-count": String(AssistantSamples.library.count)])226 }227 fake.stub("GET", path: "^/api/research/export\\.tex$") { _ in228 .init(body: Data(AssistantSamples.texExport.utf8), headers: ["content-type": "application/x-tex; charset=utf-8", "content-disposition": "attachment; filename=\"volatilite-conditionnelle.tex\"",229 "x-export-report": #"{"pages":3,"sections":2,"citeKeys":3,"missingKeys":1,"missingRefs":0,"figures":0,"hypotheses":0,"experiments":1,"unknownNodes":["mermaid"]}"#])230 }231 fake.stub("GET", path: "^/api/research/experiments$", json: FeatureSamples.text("research", "experiment-list"))232 fake.stub("GET", path: "^/api/research/overview$", json: FeatureSamples.text("research", "overview"))233 }234}235