Repository Public
1// SP Notes Core2// File: Sources/SPNotesAPI/KnowledgeModels.swift3// Description: Models of knowledge health, the brief, living blocks (`POST /api/query`) and semantic zoom4// (API-NEXT §4.5, §4.6, §4.7, §4.9; level 1 of the zoom: API-NEXT-AI §4).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Knowledge health1112/// One section of the health report: `count` is the real total, `ids` and `items` are capped at 200.13public struct HealthSection<Item: Codable & Sendable & Equatable>: Codable, Sendable, Equatable {14 public var count: Int15 /// Page ids (task ids for `openTasks`).16 public var ids: [String]17 public var items: [Item]18}1920/// A link, a block anchor or a file that leads nowhere (`brokenLinks`).21public struct BrokenLink: Codable, Sendable, Equatable {22 /// The page that holds the link.23 public var pageId: String24 public var title: String?25 /// `page`, `block` (an anchor that no longer exists in its page) or `file` (a missing attachment).26 public var kind: String27 public var targetId: String?28 public var targetBlockId: String?29 /// The block that holds the link.30 public var blockId: String?31 /// `missing` or `trashed`.32 public var reason: String?33}3435/// A `citation` whose reference is gone (`missingReferences`).36public struct MissingReference: Codable, Sendable, Equatable {37 public var pageId: String38 public var title: String?39 public var refId: String40 public var blockId: String?41 /// `missing` or `deleted`.42 public var reason: String?43}4445/// A page without a real title (`untitled`).46public struct UntitledPage: Codable, Sendable, Equatable, Identifiable {47 public var id: String48 public var section: String?49 public var updatedAt: Date?50 /// Whether the page has no content either.51 public var empty: Bool?52}5354/// A top-level project whose whole subtree has not changed for `inactiveDays` (`inactiveProjects`).55public struct InactiveProject: Codable, Sendable, Equatable, Identifiable {56 public var id: String57 public var title: String?58 public var icon: String?59 public var lastActivityAt: Date?60 public var idleDays: Int?61}6263/// An open task of the health report (≤ 100).64public struct HealthTask: Codable, Sendable, Equatable, Identifiable {65 public var id: String66 public var title: String67 public var dueAt: Date?68 public var pageId: String?69 public var priority: String?70 public var overdue: Bool?71}7273/// `openTasks` of the health report.74public struct OpenTasksSection: Codable, Sendable, Equatable {75 public var count: Int76 public var overdue: Int77 public var withoutDate: Int78 public var ids: [String]79 public var items: [HealthTask]80}8182/// `score` of the health report: `issues` = the sum of the section counts, with overdue tasks in place of all open ones.83public struct HealthScore: Codable, Sendable, Equatable {84 public var pages: Int85 public var issues: Int86 /// True when the scan was cut (the 50 000 most recent pages): the counts are a lower bound. Absent on older servers.87 public var truncated: Bool?88}8990/// `GET /api/health/knowledge` — computed from real data at each call, no model.91public struct KnowledgeHealth: Codable, Sendable, Equatable {92 public var computedAt: Date?93 public var inactiveDays: Int94 public var score: HealthScore95 /// Live pages without any accepted edge.96 public var orphans: HealthSection<KnowledgePageRef>97 public var brokenLinks: HealthSection<BrokenLink>98 public var missingReferences: HealthSection<MissingReference>99 public var potentialDuplicates: HealthSection<DuplicateGroup>100 public var untitled: HealthSection<UntitledPage>101 public var inactiveProjects: HealthSection<InactiveProject>102 public var openTasks: OpenTasksSection103}104105// MARK: - Brief106107/// A recently modified page (`recentNotes`).108public struct BriefNote: Codable, Sendable, Equatable, Identifiable {109 public var id: String110 public var title: String?111 public var icon: String?112 public var section: String?113 /// `page`, `database`, `canvas`, `research`.114 public var type: String?115 public var updatedAt: Date?116 public var wordCount: Int?117}118119/// A project with a change in its subtree in the last 14 days (`activeProjects`).120public struct BriefProject: Codable, Sendable, Equatable, Identifiable {121 public var id: String122 public var title: String?123 public var icon: String?124 public var lastActivityAt: Date?125 public var pages: Int?126 public var openTasks: Int?127}128129/// A task of the brief.130public struct BriefTask: Codable, Sendable, Equatable, Identifiable {131 public var id: String132 public var title: String133 public var status: String?134 public var priority: String?135 public var dueAt: Date?136 public var pageId: String?137 public var pageTitle: String?138 public var blockId: String?139 public var project: String?140}141142/// `tasks` of the brief; « today » is the calendar day in the requested time zone, `dueSoon` the 6 days after it.143public struct BriefTasks: Codable, Sendable, Equatable {144 public var overdue: [BriefTask]145 public var dueToday: [BriefTask]146 public var dueSoon: [BriefTask]147}148149/// A capture still in the inbox (`unfiledCaptures.items`, ≤ 10).150public struct BriefCapture: Codable, Sendable, Equatable, Identifiable {151 public var id: String152 public var title: String?153 public var icon: String?154 /// `note`, `tasks`, `link`, `photo`, `file`, `audio`.155 public var kind: String?156 public var inboxAt: Date?157}158159/// A counted list of the brief (`count` is the real total, `items` is capped).160public struct BriefList<Item: Codable & Sendable & Equatable>: Codable, Sendable, Equatable {161 public var count: Int162 public var items: [Item]163}164165/// The last summary explicitly requested (`aiSummary` of the brief, answer of `POST /api/brief/summary`).166/// Always AI-made: show it as such.167public struct BriefSummary: Codable, Sendable, Equatable {168 public var ai: Bool?169 public var text: String170 public var model: String?171 public var at: Date?172 /// Answer of `POST /api/brief/summary` only.173 public var costUsd: Double?174}175176/// `GET /api/brief` — no model is called.177public struct DailyBrief: Codable, Sendable, Equatable {178 public var generatedAt: Date?179 /// The calendar day in `timeZone` (`YYYY-MM-DD`).180 public var date: String181 public var timeZone: String182 public var recentNotes: [BriefNote]183 public var activeProjects: [BriefProject]184 public var tasks: BriefTasks185 public var unfiledCaptures: BriefList<BriefCapture>186 /// Suggested page ↔ page edges awaiting a decision (≤ 5), each `ai: true`. Items are kept raw: no real answer187 /// with a suggestion could be recorded.188 public var linkSuggestions: BriefList<RawJSON>189 /// ≤ 8 connected pages nobody opened or edited for 30 days. Items are kept raw (not observed).190 public var toRevisit: [RawJSON]191 public var aiSummary: BriefSummary?192}193194// MARK: - Living blocks195196/// `source` of `POST /api/query`.197public enum LiveQuerySource {198 public static let tasks = "tasks"199 public static let pages = "pages"200 public static let database = "database"201 public static let references = "references"202 public static let backlinks = "backlinks"203 public static let all = [tasks, pages, database, references, backlinks]204}205206/// `type` of a column of a query result.207public enum LiveQueryColumnType {208 public static let text = "text"209 public static let number = "number"210 public static let date = "date"211 public static let checkbox = "checkbox"212 public static let select = "select"213 public static let page = "page"214 public static let tags = "tags"215 public static let url = "url"216 public static let json = "json"217}218219/// `filter` of `POST /api/query`. What each field means depends on the source (API-NEXT §4.7 table).220public struct LiveQueryFilter: Codable, Sendable, Equatable {221 public var tag: String?222 public var section: String?223 /// tasks: `open` (default) | `todo` | `doing` | `done` | `all`; pages: `active` (default) | `archived` | `pinned`224 /// | `all` | a `properties.status` value; references: the `verified` value.225 public var status: String?226 public var parentId: String?227 public var text: String?228 /// Exclusive; ISO date or datetime.229 public var dueBefore: String?230 /// Inclusive.231 public var dueAfter: String?232233 public init(tag: String? = nil, section: String? = nil, status: String? = nil, parentId: String? = nil, text: String? = nil, dueBefore: String? = nil, dueAfter: String? = nil) {234 self.tag = tag235 self.section = section236 self.status = status237 self.parentId = parentId238 self.text = text239 self.dueBefore = dueBefore240 self.dueAfter = dueAfter241 }242}243244/// Body of `POST /api/query` — the same fields as the attrs of a `queryView` node.245public struct LiveQuery: Codable, Sendable, Equatable {246 /// `LiveQuerySource`.247 public var source: String248 /// `database`: the database id or its host page id.249 public var databaseId: String?250 public var viewId: String?251 /// `backlinks`: the page.252 public var pageId: String?253 /// 1…500 (server default 25).254 public var limit: Int?255 public var filter: LiveQueryFilter?256257 public init(source: String, databaseId: String? = nil, viewId: String? = nil, pageId: String? = nil, limit: Int? = nil, filter: LiveQueryFilter? = nil) {258 self.source = source259 self.databaseId = databaseId260 self.viewId = viewId261 self.pageId = pageId262 self.limit = limit263 self.filter = filter264 }265266 public static func tasks(_ filter: LiveQueryFilter? = nil, limit: Int? = nil) -> LiveQuery { LiveQuery(source: LiveQuerySource.tasks, limit: limit, filter: filter) }267 public static func pages(_ filter: LiveQueryFilter? = nil, limit: Int? = nil) -> LiveQuery { LiveQuery(source: LiveQuerySource.pages, limit: limit, filter: filter) }268 public static func database(_ id: String, viewId: String? = nil, text: String? = nil, limit: Int? = nil) -> LiveQuery {269 LiveQuery(source: LiveQuerySource.database, databaseId: id, viewId: viewId, limit: limit, filter: text.map { LiveQueryFilter(text: $0) })270 }271 public static func references(_ filter: LiveQueryFilter? = nil, limit: Int? = nil) -> LiveQuery { LiveQuery(source: LiveQuerySource.references, limit: limit, filter: filter) }272 public static func backlinks(pageId: String, filter: LiveQueryFilter? = nil, limit: Int? = nil) -> LiveQuery {273 LiveQuery(source: LiveQuerySource.backlinks, pageId: pageId, limit: limit, filter: filter)274 }275}276277/// A column of a query result. For `database` the `key` is the property id.278public struct LiveQueryColumn: Codable, Sendable, Equatable {279 public var key: String280 public var label: String281 /// `LiveQueryColumnType`.282 public var type: String283}284285/// One row of a query result: `id`, `pageId` and the typed values by column key, kept as raw JSON.286public struct LiveQueryRow: Codable, Sendable, Equatable, Identifiable {287 /// Task id, page id, database row id or reference id, depending on the source.288 public var id: String289 /// The page to open (`nil` for a task or a reference without page).290 public var pageId: String?291 /// The complete row as the server sent it.292 public var json: RawJSON293 private var fields: [String: JSONValue]294295 public init(from decoder: Decoder) throws {296 let value = try JSONValue(from: decoder)297 guard case .object(let object) = value, let id = object["id"]?.stringValue else {298 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "query row without id"))299 }300 self.id = id301 pageId = object["pageId"]?.stringValue302 fields = object303 json = value.raw()304 }305306 public func encode(to encoder: Encoder) throws { try json.encode(to: encoder) }307308 public static func == (lhs: LiveQueryRow, rhs: LiveQueryRow) -> Bool { lhs.fields == rhs.fields }309310 /// The typed value of a column (`nil` when absent or JSON `null`).311 public func value(_ key: String) -> RawJSON? {312 guard let value = fields[key], !value.isNull else { return nil }313 return value.raw()314 }315316 public func string(_ key: String) -> String? { fields[key]?.stringValue }317 public func number(_ key: String) -> Double? { fields[key]?.doubleValue }318 public func bool(_ key: String) -> Bool? { fields[key]?.boolValue }319 /// A date column (`date` type): ISO 8601.320 public func date(_ key: String) -> Date? { fields[key]?.stringValue.flatMap(APIDate.parse) }321 /// A `tags` column (or `via` of the backlinks).322 public func strings(_ key: String) -> [String]? {323 guard case .array(let items)? = fields[key] else { return nil }324 return items.compactMap(\.stringValue)325 }326}327328/// One cell of the flattened table of a query result.329public enum LiveQueryCell: Codable, Sendable, Equatable {330 case null331 case text(String)332 case number(Double)333 case bool(Bool)334335 public init(from decoder: Decoder) throws {336 let c = try decoder.singleValueContainer()337 if c.decodeNil() { self = .null }338 else if let b = try? c.decode(Bool.self) { self = .bool(b) }339 else if let n = try? c.decode(Double.self) { self = .number(n) }340 else if let s = try? c.decode(String.self) { self = .text(s) }341 else { self = .text(String(decoding: try APIJSON.encoder().encode(JSONValue(from: decoder)), as: UTF8.self)) }342 }343344 public func encode(to encoder: Encoder) throws {345 var c = encoder.singleValueContainer()346 switch self {347 case .null: try c.encodeNil()348 case .text(let s): try c.encode(s)349 case .number(let n): try c.encode(n)350 case .bool(let b): try c.encode(b)351 }352 }353354 /// What to show: the text, the number without a useless `.0`, `true` / `false`, or `nil`.355 public var text: String? {356 switch self {357 case .null: return nil358 case .text(let s): return s359 case .number(let n): return n == n.rounded() && abs(n) < 1e15 ? String(Int64(n)) : String(n)360 case .bool(let b): return b ? "true" : "false"361 }362 }363}364365/// The same data flattened: ready for a `chart` node's `columns` / `rows`, or a native table.366public struct LiveQueryTable: Codable, Sendable, Equatable {367 /// Column labels.368 public var columns: [String]369 public var rows: [[LiveQueryCell]]370}371372/// `POST /api/query` → 200.373public struct LiveQueryResult: Codable, Sendable, Equatable {374 public var source: String375 public var columns: [LiveQueryColumn]376 public var rows: [LiveQueryRow]377 /// Counts beyond `limit`.378 public var total: Int379 public var limit: Int380 public var table: LiveQueryTable381 public var resolvedAt: Date?382 /// `database` only: the database id (not the host page id), the view used and the database name.383 public var databaseId: String?384 public var viewId: String?385 public var name: String?386}387388// MARK: - Semantic zoom389390/// One section of the outline (zoom level 2): a top-level heading and what follows it. The text before the first391/// heading is a section with `heading == nil`, `level == 0`.392public struct ZoomSection: Codable, Sendable, Equatable {393 /// The block of the heading (of the first block for the leading section).394 public var blockId: String?395 /// 0…6.396 public var level: Int397 public var heading: String?398 /// First sentence of the first non-empty block (≤ 240 characters).399 public var firstSentence: String?400 public var words: Int?401 /// Non-empty body blocks.402 public var blocks: Int?403}404405/// `status` of a synopsis.406public enum SynopsisStatus {407 public static let ready = "ready"408 /// `cachedOnly` and nothing valid is cached.409 public static let missing = "missing"410 /// The page has no text: no model was called.411 public static let empty = "empty"412}413414/// The AI synopsis of a page (zoom level 1; `GET | POST /api/pages/<id>/zoom/ai`), cached by content hash.415/// `ai == true` when a model wrote `synopsis`: show it as AI-made.416public struct ZoomSynopsis: Codable, Sendable, Equatable {417 public var pageId: String418 public var level: Int?419 /// Any edit or rename changes it and invalidates the synopsis.420 public var contentHash: String?421 public var ai: Bool422 /// `SynopsisStatus`.423 public var status: String424 public var synopsis: String?425 public var model: String?426 public var provider: String?427 public var generatedAt: Date?428 /// Whether the answer came from the cache (no provider call).429 public var cached: Bool?430 public var costUsd: Double?431}432433/// `GET /api/pages/<id>/zoom?level=1|2|3`: the synopsis (1), the outline (2) or the full document (3).434public struct PageZoom: Codable, Sendable, Equatable {435 public var level: Int436 public var pageId: String437 /// Levels 2 and 3.438 public var title: String?439 public var version: Int?440 public var updatedAt: Date?441 /// `false` for levels 2 and 3 (computed without any model).442 public var ai: Bool443 /// Level 2.444 public var sections: [ZoomSection]?445 /// Level 3: the document.446 public var content: RawJSON?447 /// Level 1: the AI synopsis (the answer has the shape of `ZoomSynopsis`).448 public var synopsis: ZoomSynopsis?449450 enum CodingKeys: String, CodingKey { case level, pageId, title, version, updatedAt, ai, sections, content }451452 public init(from decoder: Decoder) throws {453 let c = try decoder.container(keyedBy: CodingKeys.self)454 level = try c.decode(Int.self, forKey: .level)455 pageId = try c.decode(String.self, forKey: .pageId)456 title = try c.decodeIfPresent(String.self, forKey: .title)457 version = try c.decodeIfPresent(Int.self, forKey: .version)458 updatedAt = try c.decodeIfPresent(Date.self, forKey: .updatedAt)459 ai = try c.decodeIfPresent(Bool.self, forKey: .ai) ?? false460 sections = try c.decodeIfPresent([ZoomSection].self, forKey: .sections)461 content = try c.decodeIfPresent(RawJSON.self, forKey: .content)462 synopsis = level == 1 ? try? ZoomSynopsis(from: decoder) : nil463 }464465 public func encode(to encoder: Encoder) throws {466 if let synopsis { try synopsis.encode(to: encoder) }467 var c = encoder.container(keyedBy: CodingKeys.self)468 try c.encode(level, forKey: .level)469 try c.encode(pageId, forKey: .pageId)470 try c.encodeIfPresent(title, forKey: .title)471 try c.encodeIfPresent(version, forKey: .version)472 try c.encodeIfPresent(updatedAt, forKey: .updatedAt)473 try c.encode(ai, forKey: .ai)474 try c.encodeIfPresent(sections, forKey: .sections)475 try c.encodeIfPresent(content, forKey: .content)476 }477}478