diff --git a/Sources/Library.swift b/Sources/Library.swift index 5b23064..37c7acb 100644 --- a/Sources/Library.swift +++ b/Sources/Library.swift @@ -427,11 +427,45 @@ enum KnowledgeInventory { static func matches(_ prompt: String) -> Bool { let words = Set(prompt.lowercased().split { !$0.isLetter }) - let inventory = !words.isDisjoint(with: ["list", "show", "browse", "what", "which"]) - let subjects = !words.isDisjoint(with: ["topics", "documents", "files", "sources", "contents", "indexed"]) + let inventory = !words.isDisjoint(with: ["list", "show", "browse", "what", "which", "summarize", "categorize"]) + let subjects = !words.isDisjoint(with: ["topics", "documents", "files", "sources", "contents", "indexed", "categories", "overview", "summaries"]) return words.contains("knowledge") && inventory && subjects } + static func wantsTopics(_ prompt: String) -> Bool { + let words = Set(prompt.lowercased().split { !$0.isLetter }) + return !words.isDisjoint(with: ["topics", "categories", "overview", "summaries"]) + } + + static func topicOverview(_ sources: [String]) -> String { + let categories: [(String, String, Set)] = [ + ("Development standards", "Standards, guidelines, conventions, and policies.", ["standards", "guidelines", "conventions", "policies"]), + ("PHP and Laravel", "PHP applications, Laravel, and related frameworks and packages.", ["php", "laravel", "symfony", "composer", "eloquent"]), + ("Python and data science", "Python programming, data analysis, and scientific computing.", ["python", "pandas", "numpy", "jupyter", "scipy"]), + ("Databases", "Database design, SQL, and data storage.", ["sql", "database", "databases", "mysql", "postgresql", "sqlite", "db2", "redis"]), + ("Web development", "Web interfaces, JavaScript, and browser technologies.", ["javascript", "typescript", "react", "vue", "html", "css", "web"]), + ("Infrastructure and operations", "Deployment, containers, operating systems, and automation.", ["docker", "kubernetes", "linux", "devops", "deployment", "ansible", "terraform"]), + ("AI and machine learning", "Models, machine learning, and AI tooling.", ["ai", "llm", "mlx", "ollama", "machine", "tensorflow", "pytorch"]), + ("Software engineering", "Architecture, patterns, testing, and general programming.", ["design", "patterns", "architecture", "testing", "programming", "engineering"]) + ] + var grouped: [Int: [String]] = [:] + for source in sources { + let words = Set(source.lowercased().split { !$0.isLetter }.map(String.init)) + let category = categories.indices.first { !words.isDisjoint(with: categories[$0].2) } ?? categories.count + grouped[category, default: []].append(source) + } + var lines = ["Topic overview for \(sources.count.formatted()) indexed sources. Categories are inferred from document paths."] + for index in (0...categories.count) { + guard let entries = grouped[index] else { continue } + let title = index < categories.count ? categories[index].0 : "Other indexed documents" + let summary = index < categories.count ? categories[index].1 : "Paths without a clear match to the named topics." + lines.append("**\(title)** · \(entries.count.formatted()) sources\n\(summary)") + lines.append(entries.prefix(3).map { "• " + $0 }.joined(separator: "\n")) + } + lines.append("Ask “List all documents in our knowledge base” for the full inventory.") + return lines.joined(separator: "\n\n") + } + static func sources(client: any MCPToolClient) async throws -> [String] { struct Page: Decodable { let sources: [String] diff --git a/Sources/StudioModel.swift b/Sources/StudioModel.swift index 0c23bfc..0e485d1 100644 --- a/Sources/StudioModel.swift +++ b/Sources/StudioModel.swift @@ -142,7 +142,8 @@ final class StudioModel: ObservableObject { let chat = try selected ?? create(String(text.prefix(48))) let user = Message(role: .user, content: text) let recent = messages.suffix(32).map { message in - guard message.backend.hasPrefix("Knowledge Inventory · ") else { return message } + guard message.backend.hasPrefix("Knowledge Inventory · "), + message.content.hasPrefix("The knowledge base contains") else { return message } var summary = message summary.content = String(message.content.prefix(while: { !$0.isNewline })) return summary @@ -531,9 +532,15 @@ final class StudioModel: ObservableObject { } let sources = try await KnowledgeInventory.sources(client: server.toolset.client) try Task.checkCancellation() - let content = sources.isEmpty ? "The connected knowledge base has no indexed sources." : - "The knowledge base contains \(sources.count.formatted()) indexed sources. The inventory lists document paths.\n\n" + - sources.map { "• " + $0 }.joined(separator: "\n") + let content: String + if sources.isEmpty { + content = "The connected knowledge base has no indexed sources." + } else if KnowledgeInventory.wantsTopics(text) { + content = KnowledgeInventory.topicOverview(sources) + } else { + content = "The knowledge base contains \(sources.count.formatted()) indexed sources. The inventory lists document paths.\n\n" + + sources.map { "• " + $0 }.joined(separator: "\n") + } let reply = Message(role: .assistant, content: content, backend: "Knowledge Inventory · " + server.toolset.name) try store.save(reply, in: chat) if selected == chat { messages.append(reply) } diff --git a/Tests/StudioTests.swift b/Tests/StudioTests.swift index f9a0ee4..eb84ca0 100644 --- a/Tests/StudioTests.swift +++ b/Tests/StudioTests.swift @@ -879,7 +879,7 @@ final class ConnectedChatTests: XCTestCase { let studio = StudioModel() studio.open(databaseURL: folder.appending(path: "studio.sqlite")) studio.connectMCP(.profile("local-knowledge"), name: "local-knowledge") { try profile.makeClient() } - studio.prompt = "List all topics in our knowledge base" + studio.prompt = "List all documents in our knowledge base" studio.send(endpoint: "", model: "", mlxPath: "", thinking: .off, failover: false, mlxOnly: false, compatible: false, recall: false, useDocuments: false, instructions: "", settings: GenerationSettings()) @@ -892,6 +892,16 @@ final class ConnectedChatTests: XCTestCase { let listed = reply.content.split(separator: "\n").filter { $0.hasPrefix("• ") } XCTAssertGreaterThan(listed.count, 200) XCTAssertEqual(Set(listed).count, listed.count) + studio.prompt = "List all topics in our knowledge base" + studio.send(endpoint: "", model: "", mlxPath: "", thinking: .off, failover: false, + mlxOnly: false, compatible: false, recall: false, useDocuments: false, + instructions: "", settings: GenerationSettings()) + while studio.running && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(50)) } + XCTAssertFalse(studio.running) + let overview = try XCTUnwrap(studio.messages.last) + XCTAssertTrue(overview.content.contains("Topic overview for \(listed.count.formatted()) indexed sources")) + XCTAssertTrue(overview.content.contains("**Development standards**")) + XCTAssertTrue(overview.content.contains("**PHP and Laravel**")) } func testLiveLocalKnowledgeSearch() async throws {