localhost1978's picture
download
raw
16.2 kB
import Foundation
import Testing
@testable import SSK_DocGen
private struct FailingResourceReader: ACPResourceReading {
func read(_ resource: ACPResourceRegistration) async throws -> String {
throw ACPResourceReadError.unreadableResource
}
}
@Suite("ACP service")
struct ACPServiceTests : ACPResourceReading {
func read(_ resource: ACPResourceRegistration) async throws -> String {
if resource.uri.hasSuffix("docc_index.json") {
return """
{
"entities": [
{
"name": "AggregatorActor",
"usr": "s:AggregatorActor",
"path": "/workspace/AggregatorActor.swift"
}
]
}
"""
} else if resource.uri.hasSuffix("graph.json") {
return """
{
"nodes": ["StorageCoordinator", "IngestionCoordinator"],
"edges": []
}
"""
}
return "{}"
}
private let service = ACPService()
@Test("Initialize uses the current protocol contract")
func initialize() async throws {
let response = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}")
#expect(response["jsonrpc"] as? String == "2.0")
#expect(response["id"] as? Int == 1)
let result = try #require(response["result"] as? [String: Any])
#expect(result["protocolVersion"] as? String == "2024-11-05")
let capabilities = try #require(result["capabilities"] as? [String: Any])
let prompts = try #require(capabilities["prompts"] as? [String: Any])
let tools = try #require(capabilities["tools"] as? [String: Any])
let resources = try #require(capabilities["resources"] as? [String: Any])
#expect(prompts["listChanged"] as? Bool == false)
#expect(tools["listChanged"] as? Bool == false)
#expect(resources["subscribe"] as? Bool == false)
#expect(resources["listChanged"] as? Bool == false)
}
@Test("List methods use the registry")
func listMethods() async throws {
let tools = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}")
let toolResult = try #require(tools["result"] as? [String: Any])
let toolEntries = try #require(toolResult["tools"] as? [[String: Any]])
#expect(toolEntries.map { $0["name"] as? String } == ACPRegistry.current.tools.map(\.name))
let resources = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/list\",\"params\":{}}")
let resourceResult = try #require(resources["result"] as? [String: Any])
let resourceEntries = try #require(resourceResult["resources"] as? [[String: Any]])
#expect(resourceEntries.map { $0["uri"] as? String } == ACPRegistry.current.resources.map(\.uri))
}
@Test("Invalid requests return errors and notifications return nothing")
func invalidAndNotificationRequests() async throws {
let invalid = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"unknown\"}")
let error = try #require(invalid["error"] as? [String: Any])
#expect(error["code"] as? Int == -32601)
let invalidParams = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/list\",\"params\":[]}")
let invalidParamsError = try #require(invalidParams["error"] as? [String: Any])
#expect(invalidParamsError["code"] as? Int == -32602)
let notification = await service.response(for: "{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"params\":{}}")
#expect(notification == nil)
}
@Test("JSON-RPC error codes -32600 through -32603 are correctly encoded and decoded")
func jsonrpcErrorCodes() async throws {
// -32600: Parse error / Invalid Request
let parseError = try await decodedResponse(for: "{invalid-json}")
let err32600 = try #require(parseError["error"] as? [String: Any])
#expect(err32600["code"] as? Int == -32600)
#expect(parseError["jsonrpc"] as? String == "2.0")
#expect(parseError["id"] is NSNull)
let badVersion = try await decodedResponse(for: "{\"jsonrpc\":\"1.0\",\"id\":10,\"method\":\"initialize\"}")
let errBadVer = try #require(badVersion["error"] as? [String: Any])
#expect(errBadVer["code"] as? Int == -32600)
// -32601: Method Not Found
let methodError = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":11,\"method\":\"unknown/method\"}")
let err32601 = try #require(methodError["error"] as? [String: Any])
#expect(err32601["code"] as? Int == -32601)
#expect(methodError["id"] as? Int == 11)
// -32602: Invalid Params
let paramsError = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":12,\"method\":\"tools/list\",\"params\":[]}")
let err32602 = try #require(paramsError["error"] as? [String: Any])
#expect(err32602["code"] as? Int == -32602)
#expect(paramsError["id"] as? Int == 12)
// -32603: Internal Error / Resource Unreadable
let workspace = try makeTemporaryDirectory()
defer { try? FileManager.default.removeItem(at: workspace) }
let context = try ACPRequestContext(workspaceURL: workspace)
let customService = ACPService(context: context, resourceReader: FailingResourceReader())
let unreadableError = try await decodedResponse(
customService,
for: "{\"jsonrpc\":\"2.0\",\"id\":13,\"method\":\"resources/read\",\"params\":{\"uri\":\"file:///SSK_Ledger_Vault/docc_index.json\"}}"
)
let err32603 = try #require(unreadableError["error"] as? [String: Any])
#expect(err32603["code"] as? Int == -32603)
#expect(unreadableError["id"] as? Int == 13)
}
@Test("Request ID preservation for integer, string, and explicit null IDs")
func requestIdPreservation() async throws {
// Integer ID
let intResp = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":42,\"method\":\"initialize\",\"params\":{}}")
#expect(intResp["id"] as? Int == 42)
// String ID
let strResp = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":\"req-uuid-999\",\"method\":\"initialize\",\"params\":{}}")
#expect(strResp["id"] as? String == "req-uuid-999")
// Null ID
let nullResp = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":null,\"method\":\"initialize\",\"params\":{}}")
#expect(nullResp["id"] is NSNull)
}
@Test("Notifications without request IDs produce no response payload")
func notificationsAreIgnored() async throws {
let validNotification = await service.response(for: "{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"params\":{}}")
#expect(validNotification == nil)
let unknownNotification = await service.response(for: "{\"jsonrpc\":\"2.0\",\"method\":\"nonexistent/notification\"}")
#expect(unknownNotification == nil)
let badParamsNotification = await service.response(for: "{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"params\":[]}")
#expect(badParamsNotification == nil)
}
@Test("tools/list returns valid JSON Schema objects with properties and descriptions")
func toolsListJSONSchemas() async throws {
let tools = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":20,\"method\":\"tools/list\",\"params\":{}}")
let result = try #require(tools["result"] as? [String: Any])
let entries = try #require(result["tools"] as? [[String: Any]])
#expect(entries.count == 5)
for entry in entries {
let schema = try #require(entry["inputSchema"] as? [String: Any])
#expect(schema["type"] as? String == "object")
let properties = try #require(schema["properties"] as? [String: Any])
#expect(!properties.isEmpty)
}
}
@Test("Unknown tool names in tools/call return methodNotFound error")
func unknownToolNameError() async throws {
let response = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":21,\"method\":\"tools/call\",\"params\":{\"name\":\"nonexistent_tool\",\"arguments\":{}}}")
let error = try #require(response["error"] as? [String: Any])
#expect(error["code"] as? Int == -32601)
#expect(response["result"] == nil)
}
@Test("Prompt retrieval works for all registered prompts")
func promptRetrieval() async throws {
for promptName in ["explain_pipeline", "analyze_actor_architecture", "verify_zk_claims"] {
let req = "{\"jsonrpc\":\"2.0\",\"id\":30,\"method\":\"prompts/get\",\"params\":{\"name\":\"\(promptName)\"}}"
let response = try await decodedResponse(for: req)
let result = try #require(response["result"] as? [String: Any])
#expect(result["description"] is String)
let messages = try #require(result["messages"] as? [[String: Any]])
#expect(!messages.isEmpty)
let firstMsg = messages[0]
#expect(firstMsg["role"] as? String == "user")
let content = try #require(firstMsg["content"] as? [String: Any])
#expect(content["type"] as? String == "text")
let text = try #require(content["text"] as? String)
#expect(!text.isEmpty)
}
let unknownReq = "{\"jsonrpc\":\"2.0\",\"id\":31,\"method\":\"prompts/get\",\"params\":{\"name\":\"unknown_prompt\"}}"
let unknownResp = try await decodedResponse(for: unknownReq)
let error = try #require(unknownResp["error"] as? [String: Any])
#expect(error["code"] as? Int == -32602)
}
@Test("search_ledger_vault returns bounded matching results without full index")
func searchLedgerVaultBoundedResults() async throws {
let workspace = try makeTemporaryDirectory()
let vault = try makeTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: workspace)
try? FileManager.default.removeItem(at: vault)
}
let context = try ACPRequestContext(workspaceURL: workspace, vaultURL: vault)
let customService = ACPService(context: context, resourceReader: self)
let req = "{\"jsonrpc\":\"2.0\",\"id\":40,\"method\":\"tools/call\",\"params\":{\"name\":\"search_ledger_vault\",\"arguments\":{\"query\":\"Actor\",\"limit\":1}}}"
let response = try await decodedResponse(customService, for: req)
let result = try #require(response["result"] as? [String: Any])
#expect(result["query"] as? String == "Actor")
#expect(result["limit"] as? Int == 1)
#expect(result["totalMatches"] as? Int == 1)
let resultsList = try #require(result["results"] as? [[String: Any]])
#expect(resultsList.count == 1)
#expect(resultsList[0]["name"] as? String == "AggregatorActor")
}
@Test("inspect_codebase_graph filters nodes and bounds output")
func inspectCodebaseGraphBounded() async throws {
let workspace = try makeTemporaryDirectory()
let vault = try makeTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: workspace)
try? FileManager.default.removeItem(at: vault)
}
let context = try ACPRequestContext(workspaceURL: workspace, vaultURL: vault)
let customService = ACPService(context: context, resourceReader: self)
let req = "{\"jsonrpc\":\"2.0\",\"id\":50,\"method\":\"tools/call\",\"params\":{\"name\":\"inspect_codebase_graph\",\"arguments\":{\"filter\":\"Storage\",\"limit\":10}}}"
let response = try await decodedResponse(customService, for: req)
let result = try #require(response["result"] as? [String: Any])
#expect(result["filter"] as? String == "Storage")
#expect(result["totalNodes"] as? Int == 1)
let nodes = try #require(result["nodes"] as? [String])
#expect(nodes == ["StorageCoordinator"])
}
@Test("update_curation_state requires authorization and valid token")
func updateCurationStateAuthorized() async throws {
let workspace = try makeTemporaryDirectory()
let vault = try makeTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: workspace)
try? FileManager.default.removeItem(at: vault)
}
let context = try ACPRequestContext(workspaceURL: workspace, vaultURL: vault)
// Insert a dummy token into curation manager so it succeeds
await context.curationManager.registerToken(id: "token_123")
let customService = ACPService(context: context, resourceReader: self)
// 1. Unauthenticated request
let unauthReq = "{\"jsonrpc\":\"2.0\",\"id\":70,\"method\":\"tools/call\",\"params\":{\"name\":\"update_curation_state\",\"arguments\":{\"tokenId\":\"token_123\",\"state\":\"approved\"}}}"
let unauthResp = try await decodedResponse(customService, for: unauthReq)
let unauthErr = try #require(unauthResp["error"] as? [String: Any])
#expect(unauthErr["code"] as? Int == -32001)
// 2. Authenticated request with valid token
let authReq = "{\"jsonrpc\":\"2.0\",\"id\":71,\"method\":\"tools/call\",\"params\":{\"name\":\"update_curation_state\",\"arguments\":{\"tokenId\":\"token_123\",\"state\":\"approved\",\"authorization\":\"ssk_curation_token_valid\"}}}"
let authResp = try await decodedResponse(customService, for: authReq)
let result = try #require(authResp["result"] as? [String: Any], "Authenticated update_curation_state should return a result object")
#expect(result["tokenId"] as? String == "token_123")
#expect(result["currentState"] as? String == "approved")
}
@Test("synthesize_media requires authorization and returns synthesis result when authorized")
func synthesizeMediaAuthorized() async throws {
let unauthResp = try await decodedResponse(for: "{\"jsonrpc\":\"2.0\",\"id\":60,\"method\":\"tools/call\",\"params\":{\"name\":\"synthesize_media\",\"arguments\":{\"payload\":\"test_payload\"}}}")
let unauthErr = try #require(unauthResp["error"] as? [String: Any])
#expect(unauthErr["code"] as? Int == -32003)
let workspace = try makeTemporaryDirectory()
let vault = try makeTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: workspace)
try? FileManager.default.removeItem(at: vault)
}
let context = try ACPRequestContext(workspaceURL: workspace, vaultURL: vault)
let customService = ACPService(context: context, resourceReader: self)
let req = """
{"jsonrpc":"2.0","id":61,"method":"tools/call","params":{"name":"synthesize_media","arguments":{"payload":"identity_proof_01","authorization":"ssk_synthesis_token_valid","identity":{"age":25},"settlement":{"sealIntact":true}}}}
"""
let authResp = try await decodedResponse(customService, for: req)
let result = try #require(authResp["result"] as? [String: Any])
#expect(result["status"] as? String == "synthesized")
#expect(result["payload"] as? String == "identity_proof_01")
}
private func decodedResponse(
_ customService: ACPService? = nil,
for line: String
) async throws -> [String: Any] {
let activeService = customService ?? service
let responseData = await activeService.response(for: line)
let data = try #require(responseData)
return try JSONSerialization.jsonObject(with: data) as! [String: Any]
}
private func makeTemporaryDirectory() throws -> URL {
let directory = FileManager.default.temporaryDirectory
.appendingPathComponent("SSKDocGen-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
return directory
}
}

Xet Storage Details

Size:
16.2 kB
·
Xet hash:
ba9fa34dd4ee9fc14bce3bd3d24dd31df9ab7d3b9bae5ffc2b55fa04ca3b6713

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.