Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeaturesCatalog/Samples+Knowledge.swift3// Description: Sample data of the « Knowledge » area for the catalogue and the tests (stubs of the fake backend): the4// recorded answers of the scratch backend for the graph views, insights, relations, journal, time machine,5// health, brief, zoom and the constellation, plus a larger hand-made global graph and journal (same shapes6// as API-NEXT) so that the screens can be judged with realistic volumes.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesTestSupport1213public enum KnowledgeSamples {14 /// The page of the recorded time-machine and journal answers.15 public static let timePageId = "5ed512f5-5b9c-443c-a5ce-bf53327d1826"16 public static let timeProjectId = "71d64720-2952-4b06-9da2-7176a5817409"17 /// The page of the recorded outline (`zoom-2`).18 public static let zoomPageId = "730ee617-c8e0-4f8f-ad41-946976578691"19 /// The page of the recorded AI synopsis.20 public static let synopsisPageId = "2eea0ded-b5b8-4abe-b560-75345504be80"21 /// The date of the recorded « middle » time-machine answer.22 public static let timeMachineDate = Date(timeIntervalSince1970: 1_795_113_749.057)2324 static func uuid(_ n: Int) -> String { String(format: "00000000-0000-4000-8000-%012d", n) }2526 /// Pages of the hand-made global graph: (title, icon, section, cluster).27 static let pages: [(String, String?, String, Int)] = [28 ("Volatilité conditionnelle", "📈", "projects", 0), ("Modèles GARCH", nil, "notes", 0), ("Données intrajournalières", "🗄️", "notes", 0),29 ("Revue de littérature", "📚", "projects", 0), ("Effet de levier", nil, "notes", 0), ("Tests de robustesse", nil, "notes", 0),30 ("Courbe des taux", "🏦", "projects", 1), ("Nelson–Siegel", nil, "notes", 1), ("Contrats à terme du Trésor", nil, "notes", 1),31 ("Surprises monétaires", nil, "notes", 1), ("Décisions de la Fed", "🏛️", "notes", 1),32 ("Cours IMM1003", "🎓", "projects", 2), ("Méthode de comparaison", nil, "notes", 2), ("Méthode du revenu", nil, "notes", 2),33 ("Étude de cas : triplex", "🏠", "notes", 2), ("Barème de correction", nil, "notes", 2),34 ("Idées en vrac", "💡", "notes", 3), ("Lectures de novembre", nil, "notes", 3), ("Réunion du 12 novembre", "🗓️", "notes", 3),35 ("Brouillon sans suite", nil, "notes", 4), ("Archive 2024", nil, "notes", 4),36 ]3738 /// (from, to, kind, relType, ai suggestion?)39 static let links: [(Int, Int, String, String?, Bool)] = [40 (0, 1, "typed", "extends", false), (0, 2, "link", nil, false), (0, 3, "link", nil, false), (1, 4, "typed", "supports", false), (1, 5, "link", nil, false),41 (2, 5, "link", nil, false), (3, 1, "typed", "cites", false), (4, 5, "ai_suggested", "related", true),42 (6, 7, "typed", "part_of", false), (6, 8, "link", nil, false), (7, 8, "link", nil, false), (9, 10, "typed", "follows", false), (6, 9, "link", nil, false),43 (9, 0, "ai_suggested", "related", true), (10, 6, "link", nil, false),44 (11, 12, "link", nil, false), (11, 13, "link", nil, false), (13, 14, "typed", "example_of", false), (11, 15, "link", nil, false), (12, 14, "link", nil, false),45 (16, 17, "link", nil, false), (18, 3, "link", nil, false), (17, 3, "typed", "about", false), (14, 6, "typed", "contradicts", false),46 ]4748 public static var globalGraphJSON: String {49 var degree = [Int: Int]()50 for link in links { degree[link.0, default: 0] += 1; degree[link.1, default: 0] += 1 }51 var nodes: [[String: Any]] = pages.enumerated().map { index, page in52 ["id": uuid(index + 1), "entityId": uuid(index + 1), "kind": "page", "title": page.0, "icon": page.1 as Any? ?? NSNull(), "section": page.2,53 "createdAt": "2026-10-0\(index % 9 + 1)T14:00:00.000Z", "updatedAt": "2026-11-1\(index % 9)T10:30:00.000Z", "databaseId": NSNull(),54 "degree": degree[index] ?? 0, "in": (degree[index] ?? 0) / 2, "out": (degree[index] ?? 0) - (degree[index] ?? 0) / 2]55 }56 nodes.sort { ($0["degree"] as! Int) > ($1["degree"] as! Int) }57 let edges: [[String: Any]] = links.enumerated().map { index, link in58 var edge: [String: Any] = ["id": uuid(1000 + index), "source": uuid(link.0 + 1), "target": uuid(link.1 + 1), "kind": link.2, "relType": link.3 as Any? ?? "related",59 "origin": link.4 ? "ai" : (link.2 == "link" ? "system" : "user"), "status": link.4 ? "suggested" : "accepted",60 "createdAt": "2026-11-10T09:00:00.000Z"]61 if link.4 {62 edge["confidence"] = 0.7463 edge["rationale"] = "Les deux notes discutent de la réaction de la volatilité aux annonces."64 edge["model"] = "claude-haiku-5-5"65 }66 if link.3 == "contradicts" { edge["note"] = "Le cas pratique suppose des taux stables" }67 return edge68 }69 let object: [String: Any] = ["view": "global", "nodes": nodes, "edges": edges, "center": NSNull(),70 "stats": ["pages": pages.count, "references": 0, "concepts": 0, "edges": links.count, "suggested": links.filter(\.4).count]]71 return String(decoding: try! JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), as: UTF8.self)72 }7374 /// Clusters matching the hand-made global graph, in the shape of `GET /api/graph/insights` → `intelligence.clusters`,75 /// merged into the recorded insights answer (the stored findings stay the recorded ones, plus one AI contradiction).76 public static var insightsJSON: String {77 guard var object = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("graph", "insights").utf8))) as? [String: Any],78 var intelligence = object["intelligence"] as? [String: Any] else { return FeatureSamples.text("graph", "insights") }79 let names = ["Volatilité conditionnelle", "Courbe des taux", "Cours IMM1003"]80 intelligence["clusters"] = (0 ..< 3).map { cluster -> [String: Any] in81 let ids = pages.enumerated().filter { $0.element.3 == cluster }.map { uuid($0.offset + 1) }82 return ["id": "cluster-\(cluster)", "size": ids.count, "label": names[cluster], "pageIds": ids, "top": ids.prefix(3).map { ["id": $0, "title": names[cluster], "icon": NSNull()] }]83 }84 object["intelligence"] = intelligence85 var insights = object["insights"] as? [[String: Any]] ?? []86 insights.insert(["id": uuid(5001), "kind": "contradiction", "status": "suggested", "title": "Hypothèse de taux incompatible",87 "detail": "« Étude de cas : triplex » suppose des taux stables, alors que « Courbe des taux » documente une hausse.",88 "data": ["pageIds": [uuid(15), uuid(7)], "blockIds": ["b-cas-1", "b-taux-4"], "confidence": 0.71],89 "origin": "ai", "model": "claude-haiku-5-5", "createdAt": "2026-11-19T14:10:00.000Z", "decidedAt": NSNull()], at: 0)90 object["insights"] = insights91 return String(decoding: try! JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), as: UTF8.self)92 }9394 /// A journal of three days (shape of `GET /api/events`), two pages of it.95 public static func journalJSON(cursor: String?) -> String {96 let all: [(String, String, String, String, String, Bool)] = [ // at, kind, summary, actor, device, backfilled97 ("2026-11-19T14:42:00.000Z", "task.completed", "Relire la section 2", "user", "SP Notes · iPhone", false),98 ("2026-11-19T14:05:00.000Z", "ai.applied", "Résumé inséré dans « Volatilité conditionnelle »", "ai", "note.spboucher.ai", false),99 ("2026-11-19T13:30:00.000Z", "relation.created", "Modèles GARCH — appuie → Effet de levier", "user", "SP Notes · Mac", false),100 ("2026-11-19T11:12:00.000Z", "page.edited", "Courbe des taux", "user", "SP Notes · Mac", false),101 ("2026-11-19T09:02:00.000Z", "capture.created", "Idée : comparer aux surprises de la BCE", "user", "SP Notes · iPhone", false),102 ("2026-11-18T21:15:00.000Z", "decision.recorded", "Retenir Nelson–Siegel dynamique", "user", "SP Notes · Mac", false),103 ("2026-11-18T16:40:00.000Z", "agent.applied", "Proposition appliquée : restructuration du plan", "agent", "note.spboucher.ai", false),104 ("2026-11-18T15:03:00.000Z", "reference.added", "Engle (1982) — Autoregressive Conditional Heteroscedasticity", "user", "SP Notes · Mac", false),105 ("2026-11-18T10:20:00.000Z", "tag.added", "Tests de robustesse — #méthode", "user", "SP Notes · Mac", false),106 ("2026-11-17T18:00:00.000Z", "canvas.edited", "Carte du chapitre 2", "user", "SP Notes · iPad", false),107 ("2026-11-17T14:25:00.000Z", "page.version", "Revue de littérature", "system", "", true),108 ("2026-11-17T09:10:00.000Z", "page.created", "Revue de littérature", "system", "", true),109 ]110 let slice = cursor == nil ? Array(all.prefix(8)) : Array(all.dropFirst(8))111 let offset = cursor == nil ? 0 : 8112 let events: [[String: Any]] = slice.enumerated().map { index, event in113 ["id": uuid(7000 + offset + index), "at": event.0, "kind": event.1, "pageId": uuid((offset + index) % 20 + 1), "pageTitle": event.2, "pageIcon": NSNull(),114 "entityKind": "page", "entityId": uuid((offset + index) % 20 + 1), "actor": event.3, "device": event.4.isEmpty ? NSNull() : event.4 as Any, "summary": event.2,115 "data": event.5 ? ["backfilled": true] : [:]]116 }117 let object: [String: Any] = ["events": events, "nextCursor": cursor == nil ? "sample-cursor-2" : NSNull()]118 return String(decoding: try! JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), as: UTF8.self)119 }120}121122extension FeatureSamples {123 static func installKnowledge(on world: FeatureWorld) {124 let fake = world.fake125 // Graph views: the larger hand-made global graph, the recorded answers for the six other views.126 let global = KnowledgeSamples.globalGraphJSON127 fake.stub("GET", path: "^/api/graph$") { request in128 let view = request.query["view"] ?? "global"129 if view == "global" { return .json(global) }130 return .json(FeatureSamples.text("graph", "graph-" + view))131 }132 let insights = KnowledgeSamples.insightsJSON133 fake.stub("GET", path: "^/api/graph/insights$", json: insights)134 fake.stub("POST", path: "^/api/graph/insights/run$") { request in135 let body = String(decoding: request.body, as: UTF8.self)136 if body.contains("\"ai\"") { return .json(#"{"mode":"ai","deterministic":null,"queued":true,"jobId":"00000000-0000-4000-8000-000000009001"}"#, status: 202) }137 return .json(FeatureSamples.text("graph", "insights-run"))138 }139 fake.stub("PATCH", path: "^/api/graph/insights/[^/]+$") { request in140 let accepted = String(decoding: request.body, as: UTF8.self).contains("accepted")141 let id = request.path.split(separator: "/").last.map(String.init) ?? ""142 return .json(#"{"id":"\#(id)","kind":"duplicate","status":"\#(accepted ? "accepted" : "dismissed")","title":"Constat","detail":null,"data":{"pageIds":[]},"origin":"system","model":null,"createdAt":"2026-11-19T18:48:03.864Z","decidedAt":"2026-11-19T19:00:00.000Z"}"#)143 }144 fake.stub("POST", path: "^/api/graph/relations$", json: FeatureSamples.text("graph", "relation-create"), status: 201)145 fake.stub("PATCH", path: "^/api/graph/relations/[^/]+$") { request in146 let body = String(decoding: request.body, as: UTF8.self)147 if body.contains("rejected") { return .json(FeatureSamples.text("graph", "relation-patch-rejected")) }148 if body.contains("accepted") { return .json(FeatureSamples.text("graph", "relation-patch-accepted")) }149 return .json(FeatureSamples.text("graph", "relation-patch"))150 }151 fake.stub("DELETE", path: "^/api/graph/relations/[^/]+$", json: #"{"ok":true}"#)152 // Constellation: the answer recorded from the knowledge workstream's dev server (not advertised in the fake's153 // /api/meta: the tests and the catalogue plug it explicitly).154 fake.stub("GET", path: "^/api/graph/constellation$", json: FeatureSamples.text("graph", "constellation"))155156 // Journal and time machine.157 fake.stub("GET", path: "^/api/events$") { request in158 if request.query["pageId"] != nil { return .json(FeatureSamples.text("timeline", request.query["cursor"] == nil ? "events-page" : "events-page-next")) }159 if let kinds = request.query["kinds"], !kinds.isEmpty {160 // Family filter applied to the sample journal, like the server does.161 let prefixes = kinds.split(separator: ",").map { $0.replacingOccurrences(of: "*", with: "") }162 guard let object = (try? JSONSerialization.jsonObject(with: Data((KnowledgeSamples.journalJSON(cursor: nil)).utf8))) as? [String: Any],163 let first = object["events"] as? [[String: Any]],164 let second = ((try? JSONSerialization.jsonObject(with: Data(KnowledgeSamples.journalJSON(cursor: "x").utf8))) as? [String: Any])?["events"] as? [[String: Any]] else { return nil }165 let kept = (first + second).filter { event in prefixes.contains { (event["kind"] as? String ?? "").hasPrefix($0) } }166 let data = try! JSONSerialization.data(withJSONObject: ["events": kept, "nextCursor": NSNull()], options: [.sortedKeys])167 return .json(String(decoding: data, as: UTF8.self))168 }169 return .json(KnowledgeSamples.journalJSON(cursor: request.query["cursor"]))170 }171 fake.stub("GET", path: "^/api/timemachine$") { request in172 if request.query["projectId"] != nil { return .json(FeatureSamples.text("timeline", "timemachine-project-middle")) }173 return .json(FeatureSamples.text("timeline", "timemachine-page-middle"))174 }175 fake.stub("POST", path: "^/api/pages/[^/]+/versions/[^/]+/restore$", json: FeatureSamples.text("timeline", "restore"))176177 // Health, brief, zoom.178 fake.stub("GET", path: "^/api/health/knowledge$", json: FeatureSamples.text("knowledge", "health"))179 fake.stub("GET", path: "^/api/brief$") { _ in180 // The recorded brief, without the summary a test of the recorder left behind: the catalogue starts with181 // no AI text; it only appears after the explicit request below.182 guard var object = (try? JSONSerialization.jsonObject(with: Data(FeatureSamples.text("knowledge", "brief").utf8))) as? [String: Any] else { return nil }183 object["aiSummary"] = NSNull()184 return .json(String(decoding: try! JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]), as: UTF8.self))185 }186 fake.stub("POST", path: "^/api/brief/summary$", json: #"{"ai":true,"text":"Exemple de résumé du catalogue : une tâche est en retard, une autre arrive le 25 novembre, et une capture attend d'être classée.","model":"exemple-catalogue","at":"2026-11-19T15:00:00.000Z","costUsd":0.0004}"#)187 fake.stub("GET", path: "^/api/pages/[^/]+/zoom$") { request in188 .json(FeatureSamples.text("knowledge", request.query["level"] == "3" ? "zoom-3" : "zoom-2"))189 }190 fake.stub("GET", path: "^/api/pages/[^/]+/zoom/ai$") { request in191 .json(FeatureSamples.text("ai-doc", request.query["cachedOnly"] == "1" ? "zoom-ai-missing" : "zoom-ai-ready"))192 }193 }194}195