SPB Git

Repository Public

NotesAPI+Graph.swift 12.9 KB 234 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Notes Core9// File             : Sources/SPNotesAPI/NotesAPI+Graph.swift10// Description      : Routes of the knowledge graph 2.0 (API-NEXT §4.3): graph11//                    views, typed relations, concepts, insights.12// Module           : SPNotesAPI13// Repository       : https://git.spboucher.ai/sp-notes-core14// Created          : 2026-11-1915// Last Modified    : 2026-11-1916//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation9091extension NotesAPI {92    // MARK: - Views9394    /// `GET /api/graph?view=…` — one of the seven 3.0 views. `400 bad_view`, `400 bad_request` (`local` / `project`95    /// without `pageId`, `depth` outside 1…4), `404` unknown page.96    public func graph(_ query: GraphQuery) async throws -> KnowledgeGraph {97        var items = [URLQueryItem(name: "view", value: query.view)]98        if let pageId = query.pageId { items.append(URLQueryItem(name: "pageId", value: pageId)) }99        if let depth = query.depth { items.append(URLQueryItem(name: "depth", value: String(depth))) }100        if let from = query.from { items.append(URLQueryItem(name: "from", value: APIDate.string(from: from))) }101        if let to = query.to { items.append(URLQueryItem(name: "to", value: APIDate.string(from: to))) }102        if !query.includeSuggestions { items.append(URLQueryItem(name: "suggestions", value: "0")) }103        if query.hideOrphans { items.append(URLQueryItem(name: "hideOrphans", value: "1")) }104        return try await client.decode(KnowledgeGraph.self, .get("/api/graph", query: items))105    }106107    /// `GET /api/graph[?pageId=]` — the unchanged 2.x answer (no `view`): pages, tags and attachments, `link`,108    /// `tag`, `attachment` and `ai_suggested` edges; `stats` without `references` / `concepts`.109    public func legacyGraph(pageID: String? = nil) async throws -> KnowledgeGraph {110        let query = pageID.map { [URLQueryItem(name: "pageId", value: $0)] } ?? []111        return try await client.decode(KnowledgeGraph.self, .get("/api/graph", query: query))112    }113114    // MARK: - Relations115116    /// `POST /api/graph/relations` → 201 (`origin: "user"`, `status: "accepted"`). With `draft.id` the creation is117    /// idempotent (`existing`: the stored relation came back untouched). `400 bad_node` (`APIError.badNodeField`),118    /// `400 bad_request` (`validTo` before `validFrom`), `409 relation_exists` (`APIError.existingRelation`),119    /// `409 id_taken`.120    public func createRelation(_ draft: RelationDraft, idempotencyKey: String? = nil) async throws -> Created<GraphRelation> {121        let response = try await client.send(.json(.post, "/api/graph/relations", body: draft, idempotencyKey: idempotencyKey))122        return Created(value: try response.decode(GraphRelation.self), existing: response.isExisting)123    }124125    /// `GET /api/graph/relations` — newest first, ≤ 500; kind `relation` only unless `filter.include` adds families.126    public func relations(_ filter: RelationFilter = RelationFilter()) async throws -> [GraphRelation] {127        var items: [URLQueryItem] = []128        if let nodeId = filter.nodeId { items.append(URLQueryItem(name: "nodeId", value: nodeId)) }129        if let status = filter.status { items.append(URLQueryItem(name: "status", value: status)) }130        if let relType = filter.relType { items.append(URLQueryItem(name: "relType", value: relType)) }131        if let origin = filter.origin { items.append(URLQueryItem(name: "origin", value: origin)) }132        if !filter.include.isEmpty { items.append(URLQueryItem(name: "include", value: filter.include.joined(separator: ","))) }133        return try await client.decode(RelationListEnvelope.self, .get("/api/graph/relations", query: items)).relations134    }135136    /// `GET /api/graph/relations/<id>`.137    public func relation(id: String) async throws -> GraphRelation {138        try await client.decode(GraphRelation.self, .get("/api/graph/relations/\(HTTPRequest.segment(id))"))139    }140141    /// `PATCH /api/graph/relations/<id>`. `409 derived_edge` for `link` / `cites` edges (an `ai_suggested` edge142    /// accepts only `status`), `409 relation_exists` when the new `relType` collides.143    public func updateRelation(id: String, _ changes: RelationChanges, idempotencyKey: String? = nil) async throws -> GraphRelation {144        try await client.decode(GraphRelation.self, .json(.patch, "/api/graph/relations/\(HTTPRequest.segment(id))", body: changes, idempotencyKey: idempotencyKey))145    }146147    /// `DELETE /api/graph/relations/<id>` — kind `relation` only (`409 derived_edge` otherwise). **Not idempotent**:148    /// a second call answers `404`.149    @discardableResult150    public func deleteRelation(id: String, idempotencyKey: String? = nil) async throws -> OKResult {151        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/graph/relations/\(HTTPRequest.segment(id))", idempotencyKey: idempotencyKey))152    }153154    // MARK: - Concepts155156    /// `GET /api/concepts?status=&pageId=` — by name; `status`: `DecisionStatus` or `all` (server default `accepted`).157    /// The rows carry `pages` / `suggestedPages`, not `pageLinks`.158    public func concepts(status: String? = nil, pageID: String? = nil) async throws -> [Concept] {159        var items: [URLQueryItem] = []160        if let status { items.append(URLQueryItem(name: "status", value: status)) }161        if let pageID { items.append(URLQueryItem(name: "pageId", value: pageID)) }162        return try await client.decode(ConceptListEnvelope.self, .get("/api/concepts", query: items)).concepts163    }164165    /// `POST /api/concepts` → 201 concept with `pageLinks`. Idempotent on `draft.id` (`existing`).166    /// `409 concept_exists` (`APIError.existingConcept`), `400 bad_page` (`APIError.unknownPageIDs`).167    public func createConcept(_ draft: ConceptDraft, idempotencyKey: String? = nil) async throws -> Created<Concept> {168        let response = try await client.send(.json(.post, "/api/concepts", body: draft, idempotencyKey: idempotencyKey))169        return Created(value: try response.decode(Concept.self), existing: response.isExisting)170    }171172    /// `GET /api/concepts/<id>` — the concept with its `pageLinks`.173    public func concept(id: String) async throws -> Concept {174        try await client.decode(Concept.self, .get("/api/concepts/\(HTTPRequest.segment(id))"))175    }176177    /// `PATCH /api/concepts/<id>` → the concept with its `pageLinks`. `409 concept_exists` when the new name is taken.178    public func updateConcept(id: String, _ changes: ConceptChanges, idempotencyKey: String? = nil) async throws -> Concept {179        try await client.decode(Concept.self, .json(.patch, "/api/concepts/\(HTTPRequest.segment(id))", body: changes, idempotencyKey: idempotencyKey))180    }181182    private struct ConceptPatchBody: Encodable {183        var id: String184        var changes: ConceptChanges185186        enum CodingKeys: String, CodingKey { case id }187188        func encode(to encoder: Encoder) throws {189            try changes.encode(to: encoder)190            var c = encoder.container(keyedBy: CodingKeys.self)191            try c.encode(id, forKey: .id)192        }193    }194195    /// `PATCH /api/concepts` with the id in the body — the collection form of `updateConcept(id:_:)` (same answer).196    public func patchConcepts(id: String, _ changes: ConceptChanges, idempotencyKey: String? = nil) async throws -> Concept {197        try await client.decode(Concept.self, .json(.patch, "/api/concepts", body: ConceptPatchBody(id: id, changes: changes), idempotencyKey: idempotencyKey))198    }199200    /// `DELETE /api/concepts/<id>` — its page links and the relations touching it go with it. **Not idempotent**:201    /// a second call answers `404`.202    @discardableResult203    public func deleteConcept(id: String, idempotencyKey: String? = nil) async throws -> OKResult {204        try await client.decode(OKResult.self, HTTPRequest(method: .delete, path: "/api/concepts/\(HTTPRequest.segment(id))", idempotencyKey: idempotencyKey))205    }206207    // MARK: - Insights208209    /// `GET /api/graph/insights` — the deterministic intelligence (no model) and the stored findings.210    public func graphInsights(_ query: InsightQuery = InsightQuery()) async throws -> GraphInsights {211        var items: [URLQueryItem] = []212        if let status = query.status { items.append(URLQueryItem(name: "status", value: status)) }213        if let kind = query.kind { items.append(URLQueryItem(name: "kind", value: kind)) }214        if let limit = query.limit { items.append(URLQueryItem(name: "limit", value: String(limit))) }215        if !query.includeIntelligence { items.append(URLQueryItem(name: "intelligence", value: "0")) }216        return try await client.decode(GraphInsights.self, .get("/api/graph/insights", query: items))217    }218219    /// `POST /api/graph/insights/run` — 200, or 202 when the AI job was queued (`queued`).220    /// **Only `InsightRunRequest.deterministic` is free**: `mode` `all` (the server default) and `ai` queue a paid221    /// model job. Results appear in `graphInsights()` as `suggested`.222    public func runGraphInsights(_ request: InsightRunRequest, idempotencyKey: String? = nil) async throws -> InsightRunResult {223        try await client.decode(InsightRunResult.self, .json(.post, "/api/graph/insights/run", body: request, idempotencyKey: idempotencyKey))224    }225226    private struct InsightStatusBody: Encodable { var status: String }227228    /// `PATCH /api/graph/insights/<id>` `{status}` (`InsightStatus.accepted | dismissed | suggested`) → the insight229    /// with `relationId`. Accepting a contradiction between two pages records the relation `contradicts`.230    public func decideInsight(id: String, status: String, idempotencyKey: String? = nil) async throws -> KnowledgeInsight {231        try await client.decode(KnowledgeInsight.self, .json(.patch, "/api/graph/insights/\(HTTPRequest.segment(id))", body: InsightStatusBody(status: status), idempotencyKey: idempotencyKey))232    }233}234
Files main
Menu

Theme