Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/GraphRepository.swift3// Description: Knowledge graph for the apps: views and insights cached as read models, relations and concepts read offline from the entity copy and written online (the answer updates the local copy; offline → RepositoryError.offline, nothing queued).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SPNotesAPI9import SPNotesStore1011public struct GraphRepository: Sendable {12 let context: RepositoryContext13 public init(context: RepositoryContext) { self.context = context }1415 // MARK: read models (cached)1617 /// A graph view (`global | local | project | timeline | concepts | documents | references`), cached per view and scope.18 public func view(_ query: GraphQuery, policy: CachePolicy = .networkFirst) async throws -> Cached<KnowledgeGraph> {19 try await context.require(ServerFeature.graphV2)20 let scope = [query.pageId, query.depth.map(String.init), query.from.map(APIDate.string(from:)), query.to.map(APIDate.string(from:)),21 query.includeSuggestions ? nil : "nosug", query.hideOrphans ? "noorph" : nil].compactMap { $0 }.joined(separator: "|")22 return try await context.read(CacheKey.graph(view: query.view, scope: scope.isEmpty ? nil : scope), policy: policy) { try await context.api.graph(query) }23 }2425 /// The server's projection of the page embeddings (Thought Constellation), cached. **Feature-gated**: unless the26 /// server is known to list `ServerFeature.constellation` this throws `.unsupported` without any request (unknown27 /// features = not asked either: the route exists on few servers) — fall back on a local layout.28 public func constellation(refresh: Bool = false, policy: CachePolicy = .networkFirst) async throws -> Cached<ConstellationProjection> {29 guard let meta = await context.knownFeatures(), meta.has(ServerFeature.constellation) else { throw RepositoryError.unsupported(feature: ServerFeature.constellation) }30 return try await context.read(CacheKey.constellation, policy: policy) { try await context.api.graphConstellation(refresh: refresh) }31 }3233 /// Deterministic intelligence + stored findings awaiting a decision.34 public func insights(_ query: InsightQuery = InsightQuery(), policy: CachePolicy = .networkFirst) async throws -> Cached<GraphInsights> {35 try await context.require(ServerFeature.insights)36 let key = CacheKey.insights + "." + [query.status ?? "-", query.kind ?? "-", query.limit.map(String.init) ?? "-", query.includeIntelligence ? "i" : "n"].joined(separator: ".")37 return try await context.read(key, policy: policy) { try await context.api.graphInsights(query) }38 }3940 /// Runs the analysis. The default is the deterministic part only (free, done in the request); `mode: all | ai`41 /// queues one paid model job — call it only on an explicit user action.42 public func runInsights(_ request: InsightRunRequest = .deterministic) async throws -> InsightRunResult {43 try await context.online { try await context.api.runGraphInsights(request) }44 }4546 /// Accepts or dismisses a finding (`InsightStatus`). Accepting a contradiction records the relation: it is cached.47 @discardableResult48 public func decideInsight(id: String, status: String) async throws -> KnowledgeInsight {49 let insight = try await context.online { try await context.api.decideInsight(id: id, status: status) }50 _ = try? await context.store.removeCached(prefix: CacheKey.insights)51 return insight52 }5354 // MARK: relations (offline read, online write)5556 /// The typed relations and links touching a node, from the local copy (works offline). Rows the device cannot57 /// read are skipped.58 public func localRelations(touching nodeId: String) async throws -> [GraphRelation] {59 do { return context.decodeEntities(GraphRelation.self, try await context.store.edges(touching: nodeId)) } catch { throw RepositoryError.from(error) }60 }6162 /// Pages linking to `pageId` (accepted edges whose target is the page), from the local copy.63 public func localBacklinks(pageId: String) async throws -> [GraphRelation] {64 do {65 return context.decodeEntities(GraphRelation.self, try await context.store.edges(to: pageId)).filter { $0.status == DecisionStatus.accepted }66 } catch { throw RepositoryError.from(error) }67 }6869 /// The relations as the server lists them (with titles); the rows refresh the local copy.70 public func relations(_ filter: RelationFilter = RelationFilter()) async throws -> [GraphRelation] {71 let rows = try await context.online { try await context.api.relations(filter) }72 for row in rows { await cache(row) }73 return rows74 }7576 /// Creates a typed relation (user origin, accepted). Online only. `409 relation_exists` → `.server(error)` with77 /// `error.existingRelation`.78 @discardableResult79 public func createRelation(_ draft: RelationDraft) async throws -> GraphRelation {80 var draft = draft81 if draft.id == nil { draft.id = NotesAPI.newID() } // a retry after a lost answer returns the stored relation82 let sent = draft83 let created = try await context.online { try await context.api.createRelation(sent) }84 await cache(created.value)85 return created.value86 }8788 /// Accepts a suggested relation (AI relations stay marked `origin: ai`).89 @discardableResult90 public func accept(relationId: String) async throws -> GraphRelation { try await update(relationId: relationId, RelationChanges(status: DecisionStatus.accepted)) }9192 @discardableResult93 public func reject(relationId: String) async throws -> GraphRelation { try await update(relationId: relationId, RelationChanges(status: DecisionStatus.rejected)) }9495 @discardableResult96 public func update(relationId: String, _ changes: RelationChanges) async throws -> GraphRelation {97 let row = try await context.online { try await context.api.updateRelation(id: relationId, changes) }98 await cache(row)99 return row100 }101102 /// Deletes a typed relation (`409 derived_edge` for a link that comes from a document).103 public func deleteRelation(id: String) async throws {104 do { _ = try await context.api.deleteRelation(id: id) } catch let error as APIError where error.isNotFound {} catch { throw RepositoryError.from(error) }105 await context.uncacheEntity(kind: .edge, id: id)106 }107108 private func cache(_ relation: GraphRelation) async {109 await context.cacheEntity(kind: .edge, id: relation.id, row: relation, rev: relation.rev, index: EntityIndex(scope: relation.fromId, ref: relation.toId))110 }111112 // MARK: concepts (offline read, online write)113114 /// The concepts of the local copy, by name (works offline; page links are read online with `concept(id:)`).115 public func localConcepts(includeSuggested: Bool = false) async throws -> [Concept] {116 do {117 return context.decodeEntities(Concept.self, try await context.store.concepts())118 .filter { includeSuggested ? $0.status != DecisionStatus.rejected : $0.status == DecisionStatus.accepted }119 .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }120 } catch { throw RepositoryError.from(error) }121 }122123 public func concepts(status: String? = nil, pageId: String? = nil) async throws -> [Concept] {124 try await context.online { try await context.api.concepts(status: status, pageID: pageId) }125 }126127 /// A concept with its page links.128 public func concept(id: String) async throws -> Concept {129 let concept = try await context.online { try await context.api.concept(id: id) }130 await cache(concept)131 return concept132 }133134 /// Creates a concept. `409 concept_exists` → `.server(error)` with `error.existingConcept`.135 @discardableResult136 public func createConcept(name: String, description: String? = nil, pageIds: [String]? = nil) async throws -> Concept {137 let draft = ConceptDraft(id: NotesAPI.newID(), name: name, description: description, pageIds: pageIds)138 let created = try await context.online { try await context.api.createConcept(draft) }139 await cache(created.value)140 return created.value141 }142143 @discardableResult144 public func updateConcept(id: String, _ changes: ConceptChanges) async throws -> Concept {145 let concept = try await context.online { try await context.api.updateConcept(id: id, changes) }146 await cache(concept)147 return concept148 }149150 public func deleteConcept(id: String) async throws {151 do { _ = try await context.api.deleteConcept(id: id) } catch let error as APIError where error.isNotFound {} catch { throw RepositoryError.from(error) }152 await context.uncacheEntity(kind: .concept, id: id)153 }154155 private func cache(_ concept: Concept) async {156 await context.cacheEntity(kind: .concept, id: concept.id, row: concept, rev: concept.rev)157 }158}159