Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/ConstellationModel.swift3// Description: The Thought Constellation. When the server advertises the feature `constellation` the map is its4// projection of the page embeddings (`GET /api/graph/constellation`: deterministic PCA, no model called at5// read time). Otherwise — or when no page is embedded yet — the screen shows a LOCAL deterministic layout6// built from the graph clusters, and says so: it is an arrangement, not a semantic map.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import Foundation12import Observation13import SPNotesAPI14import SPNotesSync1516public struct ConstellationMap: Sendable, Equatable {17 public enum Origin: Sendable, Equatable {18 /// The server's projection of the embeddings.19 case server(model: String?, computedAt: Date?, explained: [Double])20 /// A local arrangement of the graph clusters (no semantic meaning in the distances).21 case local22 }2324 public struct Star: Sendable, Equatable, Identifiable {25 public var id: String26 public var title: String27 public var icon: String?28 public var position: CGPoint29 public var cluster: Int30 public var degree: Int31 public var tags: [String]32 }3334 public struct Group: Sendable, Equatable, Identifiable {35 public var id: Int36 public var center: CGPoint37 public var radius: CGFloat38 public var label: String39 public var size: Int40 }4142 public struct Link: Sendable, Equatable, Identifiable {43 public var id: String44 public var source: String45 public var target: String46 public var isAI: Bool47 }4849 public var origin: Origin50 public var stars: [Star]51 public var groups: [Group]52 public var links: [Link]53 /// Pages of the workspace that are not on the map (not embedded yet, or over the server's cap).54 public var missing: Int5556 public var isLocal: Bool { origin == .local }57 public var positions: [String: CGPoint] { Dictionary(stars.map { ($0.id, $0.position) }, uniquingKeysWith: { a, _ in a }) }5859 public init(projection: ConstellationProjection) {60 origin = .server(model: projection.model, computedAt: projection.computedAt, explained: projection.explained ?? [])61 stars = projection.points.map {62 Star(id: $0.id, title: KnowledgeVocabulary.title($0.title), icon: $0.icon, position: CGPoint(x: $0.x, y: $0.y), cluster: $0.cluster, degree: $0.degree ?? 0, tags: $0.tags ?? [])63 }64 groups = projection.clusters.map {65 Group(id: $0.id, center: CGPoint(x: $0.x, y: $0.y), radius: CGFloat($0.r), label: KnowledgeVocabulary.title($0.label), size: $0.size)66 }67 links = projection.links.map { Link(id: $0.id, source: $0.source, target: $0.target, isAI: $0.origin == KnowledgeOrigin.ai) }68 missing = max(0, projection.stats.pages - projection.stats.shown)69 }7071 public init(origin: Origin, stars: [Star], groups: [Group], links: [Link], missing: Int) {72 self.origin = origin73 self.stars = stars74 self.groups = groups75 self.links = links76 self.missing = missing77 }78}7980/// The local, deterministic arrangement: clusters on a circle (largest first), their pages packed in a disc around the81/// cluster centre, the pages of no cluster on an outer ring. Pure; the same input gives the same map.82public enum ConstellationLocalLayout {83 public static func map(graph: KnowledgeGraph, clusters: [GraphCluster]) -> ConstellationMap {84 let pages = graph.nodes.filter { ![GraphNodeKind.reference, GraphNodeKind.concept, GraphNodeKind.attachment, GraphNodeKind.tag].contains($0.kind) }85 let known = Dictionary(pages.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })86 var assigned = Set<String>()87 var stars: [ConstellationMap.Star] = []88 var groups: [ConstellationMap.Group] = []89 let ordered = clusters.sorted { ($0.size, $1.id) > ($1.size, $0.id) }90 let golden = Double.pi * (3 - 5.0.squareRoot())91 let total = max(1, ordered.count)9293 // Clusters sit on a circle (a single one in the middle); their discs are sized so that neighbours never overlap.94 let ring = 0.595 let room = total == 1 ? 0.6 : (total == 2 ? 0.42 : ring * sin(Double.pi / Double(total)) * 0.92)96 for (index, cluster) in ordered.enumerated() {97 let members = cluster.pageIds.sorted().filter { known[$0] != nil && !assigned.contains($0) }98 guard !members.isEmpty else { continue }99 let angle = 2 * Double.pi * Double(index) / Double(total) - Double.pi / 2100 let center = total == 1 ? CGPoint.zero : CGPoint(x: cos(angle) * ring, y: sin(angle) * ring)101 let radius = min(room, 0.14 + 0.07 * Double(members.count).squareRoot())102 for (position, id) in members.enumerated() {103 assigned.insert(id)104 // Sunflower packing inside the cluster disc.105 let r = members.count == 1 ? 0 : radius * 0.85 * ((Double(position) + 0.5) / Double(members.count)).squareRoot()106 let a = Double(position) * golden + angle107 let node = known[id]!108 stars.append(.init(id: id, title: KnowledgeVocabulary.title(node.title), icon: node.icon,109 position: CGPoint(x: center.x + cos(a) * r, y: center.y + sin(a) * r), cluster: index, degree: node.degree ?? 0, tags: []))110 }111 groups.append(.init(id: index, center: center, radius: CGFloat(radius), label: KnowledgeVocabulary.title(cluster.label), size: members.count))112 }113114 let loose = pages.map(\.id).sorted().filter { !assigned.contains($0) }115 for (position, id) in loose.enumerated() {116 let angle = 2 * Double.pi * Double(position) / Double(max(1, loose.count)) - Double.pi / 2117 let node = known[id]!118 stars.append(.init(id: id, title: KnowledgeVocabulary.title(node.title), icon: node.icon, position: CGPoint(x: cos(angle) * 0.95, y: sin(angle) * 0.95),119 cluster: -1, degree: node.degree ?? 0, tags: []))120 }121122 let onMap = Set(stars.map(\.id))123 let links = graph.edges.filter { onMap.contains($0.source) && onMap.contains($0.target) && $0.status != DecisionStatus.rejected }124 .map { ConstellationMap.Link(id: $0.id, source: $0.source, target: $0.target, isAI: $0.origin == KnowledgeOrigin.ai || $0.kind == GraphEdgeKind.aiSuggested) }125 return ConstellationMap(origin: .local, stars: stars, groups: groups, links: links, missing: 0)126 }127}128129/// Where a server projection comes from. The default asks the repositories' API client when the server advertises the130/// feature; a host or a test can plug another source (nil = the server has no projection).131public typealias ConstellationProjectionSource = @Sendable (_ refresh: Bool) async throws -> Cached<ConstellationProjection>?132133@Observable @MainActor134public final class ConstellationModel {135 /// The feature name in `/api/meta` (`src/lib/meta.ts` of the knowledge workstream).136 public nonisolated static let serverFeature = ServerFeature.constellation137138 public private(set) var map: ConstellationMap?139 public private(set) var phase: LoadPhase = .idle140 public private(set) var freshness: Freshness?141 /// Why the local layout is shown although the server has projections (e.g. nothing embedded yet); nil otherwise.142 public private(set) var fallbackReason: String?143 public var viewport = GraphViewport()144 public private(set) var selectedId: String?145 public private(set) var generation = 0146147 private let graph: GraphRepository148 private let projection: ConstellationProjectionSource149 private weak var router: (any FeatureRouter)?150151 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, projection: ConstellationProjectionSource? = nil) {152 graph = repositories.graph153 self.router = router154 self.projection = projection ?? Self.serverSource(repositories)155 }156157 /// `GraphRepository.constellation`: asked only when `/api/meta` lists the feature (nil otherwise → local layout).158 public nonisolated static func serverSource(_ repositories: NotesRepositories) -> ConstellationProjectionSource {159 let graph = repositories.graph160 return { refresh in161 do { return try await graph.constellation(refresh: refresh) } catch RepositoryError.unsupported { return nil }162 }163 }164165 public var selected: ConstellationMap.Star? { map?.stars.first { $0.id == selectedId } }166 public var isEmpty: Bool { map?.stars.isEmpty ?? true }167168 public func members(of group: ConstellationMap.Group) -> [ConstellationMap.Star] {169 (map?.stars ?? []).filter { $0.cluster == group.id }.sorted { ($0.degree, $1.title) > ($1.degree, $0.title) }170 }171172 public var looseStars: [ConstellationMap.Star] {173 guard let map else { return [] }174 let groups = Set(map.groups.map(\.id))175 return map.stars.filter { !groups.contains($0.cluster) }176 }177178 public func load(refresh: Bool = false) async {179 phase = .loading180 fallbackReason = nil181 do {182 if let cached = try await projection(refresh) {183 if cached.value.points.isEmpty {184 fallbackReason = cached.value.stats.pages == 0 ? nil : L("Aucune page n'a encore d'empreinte sémantique sur le serveur : la carte ci-dessous est une disposition locale.")185 } else {186 apply(ConstellationMap(projection: cached.value), Freshness(cached))187 return188 }189 }190 try await loadLocal()191 } catch {192 let failure = FeatureFailure(error)193 // The projection could not be read (offline and never fetched…): the local layout may still be cached.194 if failure.isOffline, (try? await loadLocal()) != nil { return }195 phase = .failed(failure)196 }197 }198199 private func loadLocal() async throws {200 let view = try await graph.view(GraphQuery(view: GraphView.global, includeSuggestions: false))201 let clusters = (try? await graph.insights(InsightQuery(status: InsightStatus.suggested)))?.value.intelligence?.clusters ?? []202 let value = view.value203 let map = await Task.detached { ConstellationLocalLayout.map(graph: value, clusters: clusters) }.value204 apply(map, Freshness(view))205 }206207 private func apply(_ map: ConstellationMap, _ freshness: Freshness) {208 self.map = map209 self.freshness = freshness210 if let selectedId, !map.stars.contains(where: { $0.id == selectedId }) { self.selectedId = nil }211 generation += 1212 phase = .loaded213 }214215 public func select(_ id: String?) { selectedId = id }216217 public func tap(at location: CGPoint, in size: CGSize) {218 selectedId = viewport.hitTest(location, positions: map?.positions ?? [:], in: size)219 }220221 public func open(_ star: ConstellationMap.Star) { router?.openPage(id: star.id, blockId: nil) }222223 /// The honest caption of the map.224 public var caption: String? {225 guard let map else { return nil }226 switch map.origin {227 case .local:228 return L("Disposition locale : les pages sont regroupées d'après les liens du graphe. Les distances n'ont pas de sens sémantique.")229 case .server(_, _, let explained):230 let share = Int((explained.prefix(2).reduce(0, +) * 100).rounded())231 var text = LF("Projection du serveur : les pages proches parlent de sujets proches (les deux axes portent %lld %% de la variance).", share)232 if map.missing > 0 { text += " " + LF("%lld page(s) sans empreinte ne figurent pas sur la carte.", map.missing) }233 return text234 }235 }236}237