SPB Git

Repository Public

LiveNextGraphTests.swift 13.5 KB 231 lines swift

1// SP Notes Core2// File: Tests/SPNotesAPITests/LiveNextGraphTests.swift3// Description: Live tests of the knowledge graph 2.0 against the SCRATCH backend: relations, concepts, views, insights4//              (deterministic only — no model is ever called). Skipped without SPN_LIVE_URL / SPN_LIVE_TOKEN.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112final class LiveNextGraphTests: XCTestCase {13    func testRelationLifecycle() async throws {14        let live = try await LiveNext.make()15        try await live.require(ServerFeature.graphV2)16        let api = live.api17        let a = try await live.page(self, "graphe A", content: LiveNext.document("Première page."))18        let b = try await live.page(self, "graphe B", content: LiveNext.document("Seconde page."))1920        // create → idempotent retry → duplicate21        let id = NotesAPI.newID()22        let from = try XCTUnwrap(APIDate.parse("2026-01-01T00:00:00Z"))23        let draft = RelationDraft(id: id, fromId: a.id, toId: b.id, relType: RelationType.supports, note: "live", validFrom: from)24        let created = try await api.createRelation(draft)25        addTeardownBlock { _ = try? await api.deleteRelation(id: id) }26        XCTAssertFalse(created.existing)27        XCTAssertEqual(created.value.id, id)28        XCTAssertEqual(created.value.status, DecisionStatus.accepted)29        XCTAssertEqual(created.value.origin, KnowledgeOrigin.user)30        XCTAssertEqual(created.value.validFrom, from)31        XCTAssertEqual(created.value.fromTitle, a.title)32        var retry = draft33        retry.note = "changed by a retry"34        let again = try await api.createRelation(retry)35        XCTAssertTrue(again.existing)36        XCTAssertEqual(again.value.note, "live", "a retry never overwrites")37        let duplicate = await captureAPIError { try await api.createRelation(RelationDraft(fromId: a.id, toId: b.id, relType: RelationType.supports)) }38        XCTAssertEqual(duplicate?.existingRelation, ExistingEntity(id: id, status: DecisionStatus.accepted))39        let badNode = await captureAPIError { try await api.createRelation(RelationDraft(fromId: a.id, toId: NotesAPI.newID(), relType: RelationType.related)) }40        XCTAssertEqual(badNode?.badNodeField, "toId")4142        // read → update → list43        let fetched = try await api.relation(id: id)44        XCTAssertEqual(fetched, created.value)45        let updated = try await api.updateRelation(id: id, RelationChanges(relType: RelationType.extends, note: .null))46        XCTAssertEqual(updated.relType, RelationType.extends)47        XCTAssertNil(updated.note)48        XCTAssertGreaterThan(try XCTUnwrap(updated.rev), try XCTUnwrap(created.value.rev))49        let rejected = try await api.updateRelation(id: id, RelationChanges(status: DecisionStatus.rejected))50        XCTAssertEqual(rejected.status, DecisionStatus.rejected)51        let listed = try await api.relations(RelationFilter(nodeId: a.id, status: DecisionStatus.rejected))52        XCTAssertEqual(listed.map(\.id), [id])53        let accepted = try await api.relations(RelationFilter(nodeId: a.id, status: DecisionStatus.accepted))54        XCTAssertTrue(accepted.isEmpty)5556        // the feed carries the edge57        let head = try await api.sync(since: 0, limit: 1, kinds: [SyncKind.edge]).head58        XCTAssertGreaterThanOrEqual(head, try XCTUnwrap(rejected.rev))5960        // delete (idempotent since the integration hardening pass: a second DELETE answers 200)61        let deleted = try await api.deleteRelation(id: id)62        XCTAssertTrue(deleted.ok)63        let deletedTwice = try await api.deleteRelation(id: id)64        XCTAssertTrue(deletedTwice.ok)65        let missing = await captureAPIError { try await api.relation(id: id) }66        XCTAssertEqual(missing?.code, APIError.NextCode.notFound)67    }6869    func testDerivedEdgesCannotBeEdited() async throws {70        let live = try await LiveNext.make()71        try await live.require(ServerFeature.graphV2)72        let api = live.api73        let target = try await live.page(self, "graphe cible")74        let mention = RawJSON(string: #"{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Voir "},{"type":"mention","attrs":{"id":"\#(target.id)","label":"cible"}}]}]}"#)75        let source = try await live.page(self, "graphe source", content: mention)76        let edges = try await api.relations(RelationFilter(nodeId: source.id, include: [RelationKind.link]))77        let link = try XCTUnwrap(edges.first { $0.kind == RelationKind.link }, "saving a mention writes a link edge")78        XCTAssertEqual(link.toId, target.id)79        XCTAssertEqual(link.origin, KnowledgeOrigin.system)80        XCTAssertNotNil(link.sourceBlockId)81        let patch = await captureAPIError { try await api.updateRelation(id: link.id, RelationChanges(note: .value("x"))) }82        XCTAssertEqual(patch?.isDerivedEdge, true)83        let delete = await captureAPIError { try await api.deleteRelation(id: link.id) }84        XCTAssertEqual(delete?.isDerivedEdge, true)85    }8687    func testConceptLifecycle() async throws {88        let live = try await LiveNext.make()89        try await live.require(ServerFeature.graphV2)90        let api = live.api91        let a = try await live.page(self, "concept A")92        let b = try await live.page(self, "concept B")93        let id = NotesAPI.newID()94        let name = "Live · concept \(id.prefix(8))"9596        let created = try await api.createConcept(ConceptDraft(id: id, name: name, description: "créé par un test", pageIds: [a.id]))97        addTeardownBlock { _ = try? await api.deleteConcept(id: id) }98        XCTAssertFalse(created.existing)99        XCTAssertEqual(created.value.pages, 1)100        XCTAssertEqual(created.value.pageLinks?.map(\.pageId), [a.id])101        let again = try await api.createConcept(ConceptDraft(id: id, name: name + " (retry)"))102        XCTAssertTrue(again.existing)103        XCTAssertEqual(again.value.name, name)104        let duplicate = await captureAPIError { try await api.createConcept(ConceptDraft(name: name.uppercased())) }105        XCTAssertEqual(duplicate?.existingConcept?.id, id, "names are unique whatever the case")106        let badPage = await captureAPIError { try await api.createConcept(ConceptDraft(name: name + " bis", pageIds: [NotesAPI.newID()])) }107        XCTAssertEqual(badPage?.unknownPageIDs?.count, 1)108109        let fetched = try await api.concept(id: id)110        XCTAssertEqual(fetched.id, id)111        XCTAssertEqual(fetched.pageLinks?.count, 1)112        let updated = try await api.updateConcept(id: id, ConceptChanges(description: "modifié", addPages: [b.id]))113        XCTAssertEqual(updated.description, "modifié")114        XCTAssertEqual(Set(updated.pageLinks?.map(\.pageId) ?? []), [a.id, b.id])115        XCTAssertEqual(updated.pages, 2)116        let trimmed = try await api.patchConcepts(id: id, ConceptChanges(removePages: [a.id]))117        XCTAssertEqual(trimmed.pageLinks?.map(\.pageId), [b.id])118119        let ofPage = try await api.concepts(pageID: b.id)120        XCTAssertEqual(ofPage.map(\.id), [id])121        XCTAssertNil(ofPage.first?.pageLinks)122        let all = try await api.concepts(status: "all")123        XCTAssertTrue(all.contains { $0.id == id })124125        // A relation may end on a concept; the concepts view shows the page ↔ concept link.126        let relation = try await api.createRelation(RelationDraft(fromId: a.id, toId: id, relType: RelationType.exampleOf, targetKind: GraphEntityKind.concept)).value127        XCTAssertEqual(relation.targetKind, GraphEntityKind.concept)128        XCTAssertEqual(relation.toTitle, name)129        let view = try await api.graph(GraphQuery(view: GraphView.concepts))130        XCTAssertTrue(view.nodes.contains { $0.id == "concept:\(id)" && $0.kind == GraphNodeKind.concept })131        XCTAssertTrue(view.edges.contains { $0.kind == GraphEdgeKind.about && $0.source == b.id && $0.target == "concept:\(id)" })132133        let deleted = try await api.deleteConcept(id: id)134        XCTAssertTrue(deleted.ok)135        let gone = await captureAPIError { try await api.concept(id: id) }136        XCTAssertEqual(gone?.isNotFound, true)137        let orphaned = await captureAPIError { try await api.relation(id: relation.id) }138        XCTAssertEqual(orphaned?.isNotFound, true, "the relations touching a deleted concept go with it")139    }140141    func testViews() async throws {142        let live = try await LiveNext.make()143        try await live.require(ServerFeature.graphV2)144        let api = live.api145        let root = try await live.page(self, "vues projet", section: .projects)146        let child = try await live.page(self, "vues enfant", parentId: root.id, section: .projects, content: LiveNext.document("Enfant."))147        let other = try await live.page(self, "vues autre", parentId: root.id, section: .projects)148        let relation = try await api.createRelation(RelationDraft(fromId: child.id, toId: other.id, relType: RelationType.precedes)).value149        addTeardownBlock { _ = try? await api.deleteRelation(id: relation.id) }150151        let local = try await api.graph(.local(pageId: child.id, depth: 1))152        XCTAssertEqual(local.view, GraphView.local)153        XCTAssertEqual(local.center, child.id)154        XCTAssertEqual(Set(local.nodes.map(\.id)), [child.id, other.id])155        let edge = try XCTUnwrap(local.edges.first)156        XCTAssertEqual(edge.id, relation.id)157        XCTAssertEqual(edge.kind, GraphEdgeKind.typed)158        XCTAssertEqual(edge.relType, RelationType.precedes)159        XCTAssertEqual(local.stats.edges, 1)160161        let project = try await api.graph(.project(pageId: root.id))162        XCTAssertEqual(project.center, root.id)163        XCTAssertEqual(Set(project.nodes.map(\.id)), [root.id, child.id, other.id])164165        let now = Date()166        let timeline = try await api.graph(.timeline(from: now.addingTimeInterval(-3600), to: now.addingTimeInterval(60)))167        XCTAssertNotNil(timeline.range)168        XCTAssertTrue(timeline.nodes.contains { $0.id == child.id })169        XCTAssertTrue(timeline.edges.contains { $0.id == relation.id })170        XCTAssertGreaterThanOrEqual(timeline.buckets?.map(\.created).reduce(0, +) ?? 0, 3)171172        for view in [GraphView.global, GraphView.documents, GraphView.references, GraphView.concepts] {173            let graph = try await api.graph(GraphQuery(view: view, hideOrphans: view == GraphView.global))174            XCTAssertEqual(graph.view, view)175            let ids = Set(graph.nodes.map(\.id))176            XCTAssertTrue(graph.edges.allSatisfy { ids.contains($0.source) && ids.contains($0.target) }, view)177        }178179        let legacy = try await api.legacyGraph(pageID: child.id)180        XCTAssertNil(legacy.view)181        XCTAssertEqual(legacy.center, child.id)182        XCTAssertNil(legacy.stats.references)183184        let badView = await captureAPIError { try await api.graph(GraphQuery(view: "galaxy")) }185        XCTAssertEqual(badView?.code, APIError.NextCode.badView)186        let noPage = await captureAPIError { try await api.graph(GraphQuery(view: GraphView.local)) }187        XCTAssertEqual(noPage?.code, APIError.NextCode.badRequest)188    }189190    func testDeterministicInsights() async throws {191        let live = try await LiveNext.make()192        try await live.require(ServerFeature.insights)193        let api = live.api194        // Two pages with the same title and the same text: a duplicate the deterministic pass must find.195        let text = "Live \(NotesAPI.newID().prefix(8)) un deux trois quatre cinq six sept."196        let title = "doublon \(NotesAPI.newID().prefix(8))"197        let first = try await live.page(self, title, content: LiveNext.document(text))198        let second = try await live.page(self, title, content: LiveNext.document(text))199200        let run = try await api.runGraphInsights(.deterministic)201        XCTAssertEqual(run.mode, InsightRunMode.deterministic)202        XCTAssertFalse(run.queued, "the deterministic mode never queues the AI job")203        XCTAssertNil(run.jobId)204        XCTAssertGreaterThanOrEqual(run.deterministic?.created ?? 0, 1)205206        let answer = try await api.graphInsights(InsightQuery(kind: InsightKind.duplicate, limit: 100))207        let intelligence = try XCTUnwrap(answer.intelligence)208        XCTAssertTrue(intelligence.duplicates.contains { Set($0.pageIds) == [first.id, second.id] })209        XCTAssertTrue(intelligence.orphans.contains { $0.id == first.id })210        let mine = answer.insights.filter { Set($0.pageIds) == [first.id, second.id] }211        XCTAssertFalse(mine.isEmpty)212        XCTAssertTrue(mine.allSatisfy { $0.kind == InsightKind.duplicate && $0.origin == KnowledgeOrigin.system && $0.status == InsightStatus.suggested })213214        let accepted = try await api.decideInsight(id: mine[0].id, status: InsightStatus.accepted)215        XCTAssertEqual(accepted.status, InsightStatus.accepted)216        XCTAssertNotNil(accepted.decidedAt)217        for insight in mine {218            let dismissed = try await api.decideInsight(id: insight.id, status: InsightStatus.dismissed)219            XCTAssertEqual(dismissed.status, InsightStatus.dismissed)220        }221        let after = try await api.graphInsights(InsightQuery(status: InsightStatus.dismissed, includeIntelligence: false))222        XCTAssertNil(after.intelligence)223        XCTAssertTrue(Set(mine.map(\.id)).isSubset(of: Set(after.insights.map(\.id))))224        // A dismissed finding does not come back.225        let again = try await api.runGraphInsights(InsightRunRequest(mode: InsightRunMode.deterministic, pageIds: [first.id, second.id]))226        XCTAssertEqual(again.deterministic?.created, 0)227        let unknown = await captureAPIError { try await api.decideInsight(id: NotesAPI.newID(), status: InsightStatus.dismissed) }228        XCTAssertEqual(unknown?.isNotFound, true)229    }230}231
Files main
Menu

Theme