SPB Git

Repository Public

KnowledgeGraphTests.swift 20.5 KB 385 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/KnowledgeGraphTests.swift3// Description: The knowledge graph: the force layout (deterministic, bounded, finite, converged), the viewport transforms4//              and hit testing, and `GraphModel` against the fake backend (seven views, selection, relations, insights,5//              offline, server error, empty). Also the constellation (server projection, local fallback).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import Foundation11import SPNotesAPI12import SPNotesSync13import Testing14@testable import SPNotesFeatures15@testable import SPNotesFeaturesCatalog1617@Suite("Knowledge: graph layout and viewport")18struct KnowledgeGraphGeometryTests {19    private func ring(_ count: Int) -> ([String], [(String, String)]) {20        let ids = (0 ..< count).map { "n\($0)" }21        return (ids, (0 ..< count).map { (ids[$0], ids[($0 + 1) % count]) })22    }2324    @Test("the layout is deterministic for a seed and differs for another")25    func deterministic() {26        let (ids, edges) = ring(12)27        let a = GraphForceLayout.layout(nodes: ids, edges: edges, options: .init(seed: 7))28        let b = GraphForceLayout.layout(nodes: ids, edges: edges, options: .init(seed: 7))29        let c = GraphForceLayout.layout(nodes: ids, edges: edges, options: .init(seed: 8))30        #expect(a == b)31        #expect(a != c)32        #expect(GraphForceLayout.seed(for: ids) == GraphForceLayout.seed(for: ids.reversed()))33    }3435    @Test("every position is finite and inside the unit box; no two nodes overlap", arguments: [1, 2, 3, 25, 120])36    func bounded(count: Int) {37        var random = GraphRandom(seed: UInt64(count))38        let ids = (0 ..< count).map { "n\($0)" }39        var edges: [(String, String)] = []40        for i in 0 ..< count where count > 1 { edges.append((ids[i], ids[Int(random.next() % UInt64(count))])) }41        edges.append(("ghost", ids[0]))          // unknown ids are ignored42        edges.append((ids[0], ids[0]))           // self-loops too43        let layout = GraphForceLayout.layout(nodes: ids + [ids[0]], edges: edges)44        #expect(layout.count == count)45        for point in layout.values {46            #expect(point.x.isFinite && point.y.isFinite)47            #expect(abs(point.x) <= 1.000001 && abs(point.y) <= 1.000001)48        }49        let points = Array(layout.values)50        for i in 0 ..< points.count { for j in (i + 1) ..< points.count { #expect(hypot(points[i].x - points[j].x, points[i].y - points[j].y) > 1e-4) } }51    }5253    @Test("empty and degenerate inputs")54    func degenerate() {55        #expect(GraphForceLayout.layout(nodes: [], edges: []).isEmpty)56        #expect(GraphForceLayout.layout(nodes: ["a"], edges: [])["a"] == .zero)57        let zero = GraphForceLayout.layout(nodes: ["a", "b", "c"], edges: [("a", "b")], options: .init(iterations: 0))58        #expect(zero.values.allSatisfy { $0.x.isFinite && $0.y.isFinite })59    }6061    @Test("convergence: linked nodes end closer than unlinked ones, and two communities separate")62    func converges() {63        let a = (0 ..< 6).map { "a\($0)" }, b = (0 ..< 6).map { "b\($0)" }64        var edges: [(String, String)] = []65        for group in [a, b] { for i in 0 ..< group.count { for j in (i + 1) ..< group.count { edges.append((group[i], group[j])) } } }66        edges.append((a[0], b[0]))67        let layout = GraphForceLayout.layout(nodes: a + b, edges: edges)68        #expect(GraphForceLayout.cohesion(layout, edges: edges) < 0)69        func centroid(_ ids: [String]) -> CGPoint {70            let points = ids.compactMap { layout[$0] }71            return CGPoint(x: points.map(\.x).reduce(0, +) / CGFloat(points.count), y: points.map(\.y).reduce(0, +) / CGFloat(points.count))72        }73        func spread(_ ids: [String]) -> CGFloat { let c = centroid(ids); return ids.compactMap { layout[$0] }.map { hypot($0.x - c.x, $0.y - c.y) }.max() ?? 0 }74        let ca = centroid(a), cb = centroid(b)75        #expect(hypot(ca.x - cb.x, ca.y - cb.y) > max(spread(a), spread(b)))76        // More iterations do not blow up: the result stays the same picture up to small moves.77        let longer = GraphForceLayout.layout(nodes: a + b, edges: edges, options: .init(iterations: 600))78        #expect(GraphForceLayout.cohesion(longer, edges: edges) < 0)79    }8081    @Test("the computation off the main actor gives the same result")82    func background() async {83        let (ids, edges) = ring(20)84        let direct = GraphForceLayout.layout(nodes: ids, edges: edges)85        let detached = await GraphForceLayout.layoutInBackground(nodes: ids, edges: edges)86        #expect(direct == detached)87    }8889    @Test("viewport: view ↔ world round trip, zoom keeps the anchor, limits, hit test")90    func viewport() {91        let size = CGSize(width: 800, height: 600)92        var viewport = GraphViewport()93        #expect(viewport.toView(.zero, in: size) == CGPoint(x: 400, y: 300))94        let world = CGPoint(x: 0.4, y: -0.3)95        viewport.pan(by: CGSize(width: 30, height: -12))96        let before = viewport.toView(world, in: size)97        viewport.zoom(by: 2, anchor: before, in: size)98        let after = viewport.toView(world, in: size)99        #expect(abs(before.x - after.x) < 1e-6 && abs(before.y - after.y) < 1e-6)100        #expect(viewport.scale == 2)101        let back = viewport.toWorld(after, in: size)102        #expect(abs(back.x - world.x) < 1e-9 && abs(back.y - world.y) < 1e-9)103        viewport.zoom(by: 1000, anchor: before, in: size)104        #expect(viewport.scale == GraphViewport.maxScale)105        viewport.zoom(by: 1e-6, anchor: before, in: size)106        #expect(viewport.scale == GraphViewport.minScale)107        viewport.zoom(by: .nan, anchor: before, in: size)108        #expect(viewport.scale == GraphViewport.minScale)109        viewport.reset()110        let positions = ["a": CGPoint(x: -0.5, y: 0), "b": CGPoint(x: 0.5, y: 0)]111        #expect(viewport.hitTest(viewport.toView(positions["a"]!, in: size), positions: positions, in: size) == "a")112        #expect(viewport.hitTest(CGPoint(x: viewport.toView(positions["b"]!, in: size).x + 10, y: 300), positions: positions, in: size) == "b")113        #expect(viewport.hitTest(CGPoint(x: 400, y: 20), positions: positions, in: size) == nil)114        viewport.center(on: positions["b"]!, in: size)115        #expect(viewport.toView(positions["b"]!, in: size) == CGPoint(x: 400, y: 300))116    }117}118119@Suite("Knowledge: GraphModel")120@MainActor121struct KnowledgeGraphModelTests {122    @Test("happy path: the global view is loaded, laid out, selectable; neighbours and AI suggestions are identified")123    func happy() async throws {124        let world = try await FeatureWorld()125        let router = FeatureRouterRecorder()126        let model = GraphModel(repositories: world.repositories, router: router)127        #expect(model.phase == .idle)128        await model.load()129        #expect(model.phase == .loaded)130        #expect(model.nodes.count == 21)131        #expect(model.positions.count == 21)132        #expect(model.freshness?.fromCache == false)133        #expect(model.layoutGeneration == 1)134        let size = CGSize(width: 900, height: 700)135        let hub = try #require(model.nodes.first)136        model.tap(at: model.viewport.toView(model.positions[hub.id]!, in: size), in: size)137        #expect(model.selectedNodeId == hub.id)138        #expect(model.neighbours(of: hub.id).count == hub.degree)139        model.tap(at: CGPoint(x: -500, y: -500), in: size)140        #expect(model.selectedNodeId == nil)141        let suggestions = model.edges.filter(GraphModel.isSuggestion)142        #expect(suggestions.count == 2)143        #expect(suggestions.allSatisfy { GraphModel.isAI($0) && GraphModel.isDecidable($0) && !GraphModel.isEditable($0) })144        #expect(model.edges.filter { $0.kind == GraphEdgeKind.link }.allSatisfy { !GraphModel.isEditable($0) && !GraphModel.isDecidable($0) })145        model.open(hub)146        #expect(router.calls == [.page(id: hub.entityUUID, blockId: nil)])147        // Same graph → same picture.148        let again = GraphModel(repositories: world.repositories)149        await again.load()150        #expect(again.positions == model.positions)151    }152153    @Test("the seven views ask the server with the right parameters; local and project need a page")154    func views() async throws {155        let world = try await FeatureWorld()156        let model = GraphModel(repositories: world.repositories)157        await model.setView(GraphView.local)158        #expect(model.needsFocus)159        #expect(model.phase == .loaded && model.isEmpty)160        #expect(world.fake.count("GET", "^/api/graph$") == 0)161        await model.setView(GraphView.global)162        model.select(nodeId: model.nodes.first?.id)163        for view in [GraphView.local, GraphView.project, GraphView.timeline, GraphView.concepts, GraphView.documents, GraphView.references] {164            await model.setView(view)165            #expect(model.phase == .loaded, "\(view)")166            #expect(model.graph?.view == view)167            #expect(model.positions.count == model.nodes.count)168        }169        #expect(model.focusPageId != nil)170        let queries = world.fake.requests.filter { $0.path == "/api/graph" }.map(\.query)171        #expect(queries.contains { $0.contains("view=local") && $0.contains("pageId=") })172        #expect(queries.contains { $0.contains("view=timeline") })173        await model.setView(GraphView.timeline)174        #expect(model.graph?.buckets?.isEmpty == false || model.view == GraphView.timeline)175        await model.setView(GraphView.global)176        await model.setIncludeSuggestions(false)177        #expect(world.fake.requests.last { $0.path == "/api/graph" }?.query.contains("suggestions=0") == true)178        await model.setHideOrphans(true)179        #expect(world.fake.requests.last { $0.path == "/api/graph" }?.query.contains("hideOrphans=1") == true)180    }181182    @Test("relations: create, edit, accept, reject and delete go to the server; an existing relation is explained")183    func relations() async throws {184        let world = try await FeatureWorld()185        let model = GraphModel(repositories: world.repositories)186        await model.load()187        let from = try #require(model.nodes.first), to = try #require(model.nodes.last)188        model.beginRelation(from: from)189        #expect(model.form?.toId == "")190        #expect(await model.submitForm() == false)          // no target chosen: nothing sent191        #expect(world.fake.count("POST", "^/api/graph/relations$") == 0)192        model.form?.toId = to.id193        model.form?.relType = RelationType.supports194        model.form?.note = "Parce que"195        #expect(await model.submitForm())196        #expect(model.form == nil)197        #expect(world.fake.count("POST", "^/api/graph/relations$") == 1)198199        let typed = try #require(model.edges.first(where: GraphModel.isEditable))200        model.beginEditing(typed)201        model.form?.relType = RelationType.contradicts202        #expect(await model.submitForm())203        #expect(world.fake.count("PATCH", "^/api/graph/relations/\(typed.id)$") == 1)204205        let suggestion = try #require(model.edges.first(where: GraphModel.isDecidable))206        #expect(await model.accept(suggestion))207        #expect(await model.reject(suggestion))208        #expect(world.fake.count("PATCH", "^/api/graph/relations/\(suggestion.id)$") == 2)209        let link = try #require(model.edges.first { $0.kind == GraphEdgeKind.link })210        #expect(await model.accept(link) == false)211        #expect(await model.delete(link) == false)           // a document link is not deletable here212        #expect(await model.delete(typed))213        #expect(world.fake.count("DELETE", "^/api/graph/relations/") == 1)214215        world.fake.stub("POST", path: "^/api/graph/relations$", json: FeatureSamples.text("graph", "relation-exists"), status: 409)216        model.beginRelation(from: from, to: to)217        #expect(await model.submitForm() == false)218        #expect(model.actionFailure?.code == "relation_exists")219        #expect(model.form != nil)                            // the form stays open with the explanation220    }221222    @Test("offline: the cached view is shown with its date; a write fails calmly and nothing changes")223    func offline() async throws {224        let world = try await FeatureWorld()225        let model = GraphModel(repositories: world.repositories)226        await model.load()227        await model.loadInsights()228        world.setOffline(true)229        await model.load()230        #expect(model.phase == .loaded)231        #expect(model.freshness?.fromCache == true)232        #expect(model.nodes.count == 21)233        await model.loadInsights()234        #expect(model.insightsFreshness?.fromCache == true)235        let suggestion = try #require(model.edges.first(where: GraphModel.isDecidable))236        #expect(await model.accept(suggestion) == false)237        #expect(model.actionFailure?.kind == .offline)238        #expect(await model.runDeterministicInsights() == false)239        #expect(model.actionFailure?.isOffline == true)240        // A view never fetched: a calm "not cached" state, no spinner.241        await model.setView(GraphView.concepts)242        #expect(model.phase.failure?.kind == .notCached)243        #expect(model.phase.isLoading == false)244    }245246    @Test("server error and empty graph")247    func errorAndEmpty() async throws {248        let world = try await FeatureWorld(samples: false)249        let model = GraphModel(repositories: world.repositories)250        world.fake.stub("GET", path: "^/api/graph$", json: #"{"error":"boom","code":"internal"}"#, status: 500)251        await model.load()252        #expect(model.phase.failure?.kind == .server)253        world.fake.stub("GET", path: "^/api/graph$", json: #"{"view":"global","nodes":[],"edges":[],"center":null,"stats":{"pages":0,"edges":0}}"#)254        await model.load()255        #expect(model.phase == .loaded)256        #expect(model.isEmpty && model.focusNode == nil)257        // A 2.x server: the feature is known to be missing.258        let legacy = try await FeatureWorld(samples: false, apiLevel: 2)259        _ = await legacy.sync()260        let old = GraphModel(repositories: legacy.repositories)261        await old.load()262        #expect(old.phase.failure?.kind == .unsupported)263    }264265    @Test("insights: the list, the free deterministic run, the explicit AI run, accept and dismiss")266    func insights() async throws {267        let world = try await FeatureWorld()268        let router = FeatureRouterRecorder()269        let model = GraphModel(repositories: world.repositories, router: router)270        await model.loadInsights()271        #expect(model.insightsPhase == .loaded)272        let findings = try #require(model.insights?.insights)273        #expect(findings.count == 5)274        #expect(findings.first?.isAI == true)275        #expect(world.fake.count("POST", "^/api/graph/insights/run$") == 0)      // nothing is run by loading276        #expect(await model.runDeterministicInsights())277        #expect(model.lastRun?.queued == false)278        #expect(model.lastRunSummary?.contains("3") == true)279        #expect(await model.runAIInsights())280        #expect(model.lastRun?.queued == true)281        #expect(world.fake.count("POST", "^/api/graph/insights/run$") == 2)282        model.openPages(of: findings[0])283        #expect(router.calls == [.page(id: KnowledgeSamples.uuid(15), blockId: "b-cas-1")])284        #expect(await model.decide(findings[1], accept: false))285        #expect(await model.decide(findings[2], accept: true))286        #expect(world.fake.count("PATCH", "^/api/graph/insights/") == 2)287    }288}289290@Suite("Knowledge: constellation")291@MainActor292struct KnowledgeConstellationTests {293    @Test("the server projection is used when a source provides it, and labelled as such")294    func server() async throws {295        let world = try await FeatureWorld()296        let router = FeatureRouterRecorder()297        let model = ConstellationModel(repositories: world.repositories, router: router, projection: FeatureCatalog.sampleConstellationSource(world))298        await model.load()299        #expect(model.phase == .loaded)300        let map = try #require(model.map)301        #expect(!map.isLocal)302        #expect(map.stars.count == 4 && map.groups.count == 1 && map.links.count == 4)303        #expect(map.missing == 5)                                     // 9 pages, 4 embedded304        #expect(map.stars.allSatisfy { abs($0.position.x) <= 1 && abs($0.position.y) <= 1 })305        #expect(model.caption?.contains("Projection du serveur") == true)306        let size = CGSize(width: 600, height: 600)307        model.tap(at: model.viewport.toView(map.stars[0].position, in: size), in: size)308        #expect(model.selected?.id == map.stars[0].id)309        model.open(map.stars[0])310        #expect(router.calls == [.page(id: map.stars[0].id, blockId: nil)])311        // Offline afterwards: the cached projection, with its date.312        world.setOffline(true)313        await model.load()314        #expect(model.map?.isLocal == false && model.freshness?.fromCache == true)315    }316317    @Test("the default source asks the route only when /api/meta lists « constellation »; otherwise the local layout, labelled")318    func fallback() async throws {319        let world = try await FeatureWorld()320        let model = ConstellationModel(repositories: world.repositories)321        await model.load()322        #expect(world.fake.count("GET", "^/api/graph/constellation$") == 0)323        let map = try #require(model.map)324        #expect(map.isLocal)325        #expect(map.stars.count == 21)326        #expect(map.groups.count == 3)327        #expect(model.looseStars.count == 21 - 16)328        #expect(model.caption?.contains("Disposition locale") == true)329        #expect(Set(map.stars.map(\.id)).count == 21)330        #expect(map.stars.allSatisfy { abs($0.position.x) <= 1.0001 && abs($0.position.y) <= 1.0001 })331        // Deterministic.332        let again = ConstellationModel(repositories: world.repositories)333        await again.load()334        #expect(again.map == map)335    }336337    @Test("a server that advertises the feature is asked; an empty projection falls back with the reason")338    func advertised() async throws {339        // No sync here: the engine has not asked /api/meta, so the features are the ones just refreshed.340        let world = try await FeatureWorld(samples: false)341        FeatureSamples.install(on: world)342        world.fake.stub("GET", path: "^/api/meta$", json: #"{"api":3,"version":"3.0.0","features":["entities","graph-v2","insights","constellation"]}"#)343        _ = try await world.repositories.context.refreshFeatures()344        let model = ConstellationModel(repositories: world.repositories)345        await model.load()346        #expect(world.fake.count("GET", "^/api/graph/constellation$") == 1)347        #expect(model.map?.isLocal == false)348        world.fake.stub("GET", path: "^/api/graph/constellation$",349                        json: #"{"model":"m","computedAt":null,"cached":false,"signature":null,"explained":[0,0],"stats":{"pages":9,"embedded":0,"shown":0,"links":0,"truncated":false},"points":[],"clusters":[],"links":[],"projects":[],"tags":[]}"#)350        await model.load()351        #expect(model.map?.isLocal == true)352        #expect(model.fallbackReason != nil)353    }354355    @Test("offline with nothing cached, server error, empty workspace")356    func failures() async throws {357        let world = try await FeatureWorld(samples: false)358        let model = ConstellationModel(repositories: world.repositories)359        world.setOffline(true)360        await model.load()361        #expect(model.phase.failure?.isOffline == true)362        world.setOffline(false)363        world.fake.stub("GET", path: "^/api/graph$", json: #"{"error":"boom","code":"internal"}"#, status: 500)364        await model.load()365        #expect(model.phase.failure?.kind == .server)366        world.fake.stub("GET", path: "^/api/graph$", json: #"{"view":"global","nodes":[],"edges":[],"center":null,"stats":{"pages":0,"edges":0}}"#)367        world.fake.stub("GET", path: "^/api/graph/insights$", json: #"{"insights":[]}"#)368        await model.load()369        #expect(model.phase == .loaded && model.isEmpty)370    }371372    @Test("local layout: clusters do not swallow each other and members stay near their centre")373    func localLayoutGeometry() throws {374        let graph = try APIJSON.decoder().decode(KnowledgeGraph.self, from: Data(KnowledgeSamples.globalGraphJSON.utf8))375        let insights = try APIJSON.decoder().decode(GraphInsights.self, from: Data(KnowledgeSamples.insightsJSON.utf8))376        let map = ConstellationLocalLayout.map(graph: graph, clusters: insights.intelligence?.clusters ?? [])377        for group in map.groups {378            for star in map.stars where star.cluster == group.id {379                #expect(hypot(star.position.x - group.center.x, star.position.y - group.center.y) <= group.radius + 1e-9)380            }381        }382        #expect(ConstellationLocalLayout.map(graph: graph, clusters: []).groups.isEmpty)383    }384}385
Files main
Menu

Theme