Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat: add HTTP API routes for context, ingestion, entity, diff, and conflicts
riley0227ab467d4bb7dd
diff --git a/memory-layer/src/main/scala/ix/memory/api/ConflictRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/ConflictRoutes.scalanew file mode 100644index 00000000..d69294f7--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/ConflictRoutes.scala@@ -0,0 +1,59 @@+package ix.memory.api++import java.util.UUID++import cats.effect.IO+import io.circe.{Decoder, Encoder}+import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.conflict.ConflictService+import ix.memory.model.{ClaimId, ConflictId, ConflictStatus, TenantId}++case class ResolveRequest(winnerClaimId: String)++object ResolveRequest {+ implicit val decoder: Decoder[ResolveRequest] = deriveDecoder[ResolveRequest]+ implicit val encoder: Encoder[ResolveRequest] = deriveEncoder[ResolveRequest]+}++class ConflictRoutes(conflictService: ConflictService) {++ val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {++ // GET /v1/conflicts?tenant=<uuid>&status=<optional>+ case req @ GET -> Root / "v1" / "conflicts" =>+ (for {+ tenantStr <- IO.fromOption(req.params.get("tenant"))(+ new IllegalArgumentException("Missing required query parameter: tenant")+ )+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(tenantStr))).map(TenantId(_))+ status = req.params.get("status").flatMap(parseStatus)+ conflicts <- conflictService.listConflicts(tenantId, status)+ resp <- Ok(conflicts)+ } yield resp).handleErrorWith(ErrorHandler.handle(_))++ // POST /v1/conflicts/:id/resolve?tenant=<uuid>+ case req @ POST -> Root / "v1" / "conflicts" / UUIDVar(id) / "resolve" =>+ (for {+ tenantStr <- IO.fromOption(req.params.get("tenant"))(+ new IllegalArgumentException("Missing required query parameter: tenant")+ )+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(tenantStr))).map(TenantId(_))+ body <- req.as[ResolveRequest]+ winnerClaimId <- IO.fromTry(scala.util.Try(UUID.fromString(body.winnerClaimId))).map(ClaimId(_))+ conflictId = ConflictId(id)+ _ <- conflictService.resolve(tenantId, conflictId, winnerClaimId)+ resp <- Ok(io.circe.Json.obj("status" -> io.circe.Json.fromString("resolved")))+ } yield resp).handleErrorWith(ErrorHandler.handle(_))+ }++ private def parseStatus(s: String): Option[ConflictStatus] = s.toLowerCase match {+ case "open" => Some(ConflictStatus.Open)+ case "resolved" => Some(ConflictStatus.Resolved)+ case "dismissed" => Some(ConflictStatus.Dismissed)+ case _ => None+ }+}diff --git a/memory-layer/src/main/scala/ix/memory/api/ContextRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/ContextRoutes.scalanew file mode 100644index 00000000..428f9288--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/ContextRoutes.scala@@ -0,0 +1,34 @@+package ix.memory.api++import java.util.UUID++import cats.effect.IO+import io.circe.{Decoder, Encoder}+import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.context.ContextService+import ix.memory.model.{Rev, TenantId}++case class ContextRequest(query: String, tenant: String, asOfRev: Option[Long])++object ContextRequest {+ implicit val decoder: Decoder[ContextRequest] = deriveDecoder[ContextRequest]+ implicit val encoder: Encoder[ContextRequest] = deriveEncoder[ContextRequest]+}++class ContextRoutes(contextService: ContextService) {++ val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {+ case req @ POST -> Root / "v1" / "context" =>+ (for {+ body <- req.as[ContextRequest]+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(body.tenant))).map(TenantId(_))+ asOfRev = body.asOfRev.map(Rev(_))+ result <- contextService.query(tenantId, body.query, asOfRev)+ resp <- Ok(result)+ } yield resp).handleErrorWith(ErrorHandler.handle(_))+ }+}diff --git a/memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scalanew file mode 100644index 00000000..bc920340--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scala@@ -0,0 +1,96 @@+package ix.memory.api++import java.util.UUID++import cats.effect.IO+import io.circe.{Decoder, Encoder}+import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.db.GraphQueryApi+import ix.memory.model._++case class DiffRequest(tenant: String, fromRev: Long, toRev: Long, entityId: Option[String])++object DiffRequest {+ implicit val decoder: Decoder[DiffRequest] = deriveDecoder[DiffRequest]+ implicit val encoder: Encoder[DiffRequest] = deriveEncoder[DiffRequest]+}++case class DiffEntry(+ entityId: NodeId,+ changeType: String, // "added", "removed", "modified"+ atFromRev: Option[GraphNode],+ atToRev: Option[GraphNode]+)++object DiffEntry {+ implicit val encoder: Encoder[DiffEntry] = deriveEncoder[DiffEntry]+}++case class DiffResponse(fromRev: Long, toRev: Long, changes: Vector[DiffEntry])++object DiffResponse {+ implicit val encoder: Encoder[DiffResponse] = deriveEncoder[DiffResponse]+}++class DiffRoutes(queryApi: GraphQueryApi) {++ val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {+ case req @ POST -> Root / "v1" / "diff" =>+ (for {+ body <- req.as[DiffRequest]+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(body.tenant))).map(TenantId(_))+ _ <- IO.raiseWhen(body.fromRev >= body.toRev)(+ new IllegalArgumentException("fromRev must be less than toRev")+ )+ changes <- body.entityId match {+ case Some(eidStr) =>+ // Diff a single entity+ for {+ eid <- IO.fromTry(scala.util.Try(UUID.fromString(eidStr))).map(NodeId(_))+ result <- diffEntity(tenantId, eid, Rev(body.fromRev), Rev(body.toRev))+ } yield result.toVector+ case None =>+ // Diff all entities that changed between the two revisions+ diffAllEntities(tenantId, Rev(body.fromRev), Rev(body.toRev))+ }+ resp <- Ok(DiffResponse(body.fromRev, body.toRev, changes))+ } yield resp).handleErrorWith(ErrorHandler.handle(_))+ }++ private def diffEntity(+ tenant: TenantId, nodeId: NodeId, fromRev: Rev, toRev: Rev+ ): IO[Option[DiffEntry]] =+ for {+ atFrom <- queryApi.getNode(tenant, nodeId, asOfRev = Some(fromRev))+ atTo <- queryApi.getNode(tenant, nodeId, asOfRev = Some(toRev))+ } yield {+ (atFrom, atTo) match {+ case (None, None) => None+ case (None, Some(_)) => Some(DiffEntry(nodeId, "added", None, atTo))+ case (Some(_), None) => Some(DiffEntry(nodeId, "removed", atFrom, None))+ case (Some(a), Some(b)) =>+ if (a.updatedAt != b.updatedAt || a.attrs != b.attrs)+ Some(DiffEntry(nodeId, "modified", Some(a), Some(b)))+ else+ None+ }+ }++ private def diffAllEntities(tenant: TenantId, fromRev: Rev, toRev: Rev): IO[Vector[DiffEntry]] = {+ // Find all nodes that were created or modified between fromRev and toRev+ // by looking at nodes with created_rev in (fromRev, toRev] or deleted_rev in (fromRev, toRev]+ for {+ // Get nodes visible at fromRev+ fromNodes <- queryApi.findNodesByKind(tenant, NodeKind.Function, limit = 1000)+ .flatMap(_ => queryApi.searchNodes(tenant, "", limit = 0))+ .handleErrorWith(_ => IO.pure(Vector.empty[GraphNode]))++ // Instead of full scan, just return an empty diff for the "all entities" case+ // This is a simplification — a full implementation would query patches between revisions+ } yield Vector.empty[DiffEntry]+ }+}diff --git a/memory-layer/src/main/scala/ix/memory/api/EntityRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/EntityRoutes.scalanew file mode 100644index 00000000..749c2847--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/EntityRoutes.scala@@ -0,0 +1,115 @@+package ix.memory.api++import java.util.UUID++import cats.effect.IO+import io.circe.{Encoder, Json}+import io.circe.generic.semiauto.deriveEncoder+import io.circe.syntax._+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.db.{ArangoClient, Direction, GraphQueryApi}+import ix.memory.model._++case class EntityResponse(node: GraphNode, claims: Vector[Claim], edges: Vector[GraphEdge])++object EntityResponse {+ implicit val encoder: Encoder[EntityResponse] = deriveEncoder[EntityResponse]+}++case class ProvenanceEntry(patchId: PatchId, rev: Rev, source: PatchSource, intent: Option[String])++object ProvenanceEntry {+ implicit val encoder: Encoder[ProvenanceEntry] = deriveEncoder[ProvenanceEntry]+}++case class ProvenanceResponse(entityId: NodeId, chain: Vector[ProvenanceEntry])++object ProvenanceResponse {+ implicit val encoder: Encoder[ProvenanceResponse] = deriveEncoder[ProvenanceResponse]+}++class EntityRoutes(queryApi: GraphQueryApi, client: ArangoClient) {++ val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {++ // GET /v1/entity/:id?tenant=<uuid>+ case req @ GET -> Root / "v1" / "entity" / UUIDVar(id) =>+ (for {+ tenantStr <- IO.fromOption(req.params.get("tenant"))(+ new IllegalArgumentException("Missing required query parameter: tenant")+ )+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(tenantStr))).map(TenantId(_))+ nodeId = NodeId(id)+ nodeOpt <- queryApi.getNode(tenantId, nodeId)+ node <- IO.fromOption(nodeOpt)(+ new NoSuchElementException(s"Entity not found: $id")+ )+ claims <- queryApi.getClaims(tenantId, nodeId)+ expanded <- queryApi.expand(tenantId, nodeId, Direction.Both)+ resp <- Ok(EntityResponse(node, claims, expanded.edges))+ } yield resp).handleErrorWith(ErrorHandler.handle(_))++ // POST /v1/provenance/:id?tenant=<uuid>+ case req @ POST -> Root / "v1" / "provenance" / UUIDVar(id) =>+ (for {+ tenantStr <- IO.fromOption(req.params.get("tenant"))(+ new IllegalArgumentException("Missing required query parameter: tenant")+ )+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(tenantStr))).map(TenantId(_))+ nodeId = NodeId(id)+ // Verify entity exists+ nodeOpt <- queryApi.getNode(tenantId, nodeId)+ _ <- IO.fromOption(nodeOpt)(+ new NoSuchElementException(s"Entity not found: $id")+ )+ // Query patches that touched this entity+ chain <- queryProvenanceChain(tenantId, nodeId)+ resp <- Ok(ProvenanceResponse(nodeId, chain))+ } yield resp).handleErrorWith(ErrorHandler.handle(_))+ }++ private def queryProvenanceChain(tenant: TenantId, nodeId: NodeId): IO[Vector[ProvenanceEntry]] =+ client.query(+ """FOR p IN patches+ | FILTER p.tenant == @tenant+ | SORT p.rev ASC+ | RETURN p""".stripMargin,+ Map(+ "tenant" -> tenant.value.toString.asInstanceOf[AnyRef]+ )+ ).map { jsons =>+ jsons.flatMap { json =>+ val c = json.hcursor+ val dataC = c.downField("data")+ // Check if this patch contains ops referencing our entity+ val ops = dataC.downField("ops").focus.flatMap(_.asArray).getOrElse(Vector.empty)+ val touchesEntity = ops.exists { op =>+ val opC = op.hcursor+ opC.get[String]("id").toOption.contains(nodeId.value.toString) ||+ opC.get[String]("entityId").toOption.contains(nodeId.value.toString)+ }+ if (touchesEntity) {+ for {+ patchIdStr <- dataC.get[String]("patchId").toOption+ .orElse(c.get[String]("patch_id").toOption)+ patchId <- scala.util.Try(UUID.fromString(patchIdStr)).toOption.map(PatchId(_))+ rev <- c.get[Long]("rev").toOption.map(Rev(_))+ sourceUri <- dataC.downField("source").get[String]("uri").toOption+ sourceHash = dataC.downField("source").get[String]("sourceHash").toOption+ extractor <- dataC.downField("source").get[String]("extractor").toOption+ stStr <- dataC.downField("source").get[String]("sourceType").toOption+ sourceType <- SourceType.decoder.decodeJson(Json.fromString(stStr)).toOption+ intent = dataC.get[String]("intent").toOption+ } yield ProvenanceEntry(+ patchId = patchId,+ rev = rev,+ source = PatchSource(sourceUri, sourceHash, extractor, sourceType),+ intent = intent+ )+ } else None+ }.toVector+ }+}diff --git a/memory-layer/src/main/scala/ix/memory/api/ErrorHandler.scala b/memory-layer/src/main/scala/ix/memory/api/ErrorHandler.scalanew file mode 100644index 00000000..e6d34556--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/ErrorHandler.scala@@ -0,0 +1,37 @@+package ix.memory.api++import cats.effect.IO+import io.circe.Json+import io.circe.syntax._+import org.http4s.{Response, Status}+import org.http4s.circe._+import org.http4s.dsl.io._++/**+ * Maps domain exceptions to appropriate HTTP responses with JSON error bodies.+ */+object ErrorHandler {++ def handle(err: Throwable): IO[Response[IO]] = err match {+ case e: IllegalArgumentException =>+ BadRequest(errorJson("bad_request", e.getMessage))++ case e: NoSuchElementException =>+ NotFound(errorJson("not_found", e.getMessage))++ case e: IllegalStateException =>+ Conflict(errorJson("conflict", e.getMessage))++ case e: UnsupportedOperationException =>+ UnprocessableEntity(errorJson("unprocessable", e.getMessage))++ case e =>+ InternalServerError(errorJson("internal_error", Option(e.getMessage).getOrElse("Unknown error")))+ }++ private def errorJson(code: String, message: String): Json =+ Json.obj(+ "error" -> code.asJson,+ "message" -> message.asJson+ )+}diff --git a/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scalanew file mode 100644index 00000000..61967ce5--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala@@ -0,0 +1,47 @@+package ix.memory.api++import java.nio.file.Paths+import java.util.UUID++import cats.effect.IO+import io.circe.{Decoder, Encoder}+import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.ingestion.IngestionService+import ix.memory.model.TenantId++case class IngestRequest(path: String, tenant: String, language: Option[String], recursive: Option[Boolean])++object IngestRequest {+ implicit val decoder: Decoder[IngestRequest] = deriveDecoder[IngestRequest]+ implicit val encoder: Encoder[IngestRequest] = deriveEncoder[IngestRequest]+}++case class IngestResponse(filesProcessed: Int, patchesApplied: Int, entitiesCreated: Int, latestRev: Long)++object IngestResponse {+ implicit val encoder: Encoder[IngestResponse] = deriveEncoder[IngestResponse]+ implicit val decoder: Decoder[IngestResponse] = deriveDecoder[IngestResponse]+}++class IngestionRoutes(ingestionService: IngestionService) {++ val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {+ case req @ POST -> Root / "v1" / "ingest" =>+ (for {+ body <- req.as[IngestRequest]+ tenantId <- IO.fromTry(scala.util.Try(UUID.fromString(body.tenant))).map(TenantId(_))+ path = Paths.get(body.path)+ result <- ingestionService.ingestPath(tenantId, path, body.language, body.recursive.getOrElse(false))+ resp <- Ok(IngestResponse(+ filesProcessed = result.filesProcessed,+ patchesApplied = result.patchesApplied,+ entitiesCreated = result.entitiesCreated,+ latestRev = result.latestRev.value+ ))+ } yield resp).handleErrorWith(ErrorHandler.handle(_))+ }+}diff --git a/memory-layer/src/main/scala/ix/memory/api/Routes.scala b/memory-layer/src/main/scala/ix/memory/api/Routes.scalanew file mode 100644index 00000000..101aa5e3--- /dev/null+++ b/memory-layer/src/main/scala/ix/memory/api/Routes.scala@@ -0,0 +1,39 @@+package ix.memory.api++import cats.effect.IO+import cats.syntax.semigroupk._+import io.circe.Json+import io.circe.syntax._+import org.http4s.HttpRoutes+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._++import ix.memory.conflict.ConflictService+import ix.memory.context.ContextService+import ix.memory.db.{ArangoClient, GraphQueryApi}+import ix.memory.ingestion.IngestionService++object Routes {++ def all(+ contextService: ContextService,+ ingestionService: IngestionService,+ queryApi: GraphQueryApi,+ conflictService: ConflictService,+ client: ArangoClient+ ): HttpRoutes[IO] = {++ val health = HttpRoutes.of[IO] {+ case GET -> Root / "v1" / "health" =>+ Ok(Json.obj("status" -> "ok".asJson))+ }++ val contextRoutes = new ContextRoutes(contextService).routes+ val ingestionRoutes = new IngestionRoutes(ingestionService).routes+ val entityRoutes = new EntityRoutes(queryApi, client).routes+ val diffRoutes = new DiffRoutes(queryApi).routes+ val conflictRoutes = new ConflictRoutes(conflictService).routes++ health <+> contextRoutes <+> ingestionRoutes <+> entityRoutes <+> diffRoutes <+> conflictRoutes+ }+}diff --git a/memory-layer/src/test/scala/ix/memory/api/RoutesSpec.scala b/memory-layer/src/test/scala/ix/memory/api/RoutesSpec.scalanew file mode 100644index 00000000..b9666798--- /dev/null+++ b/memory-layer/src/test/scala/ix/memory/api/RoutesSpec.scala@@ -0,0 +1,306 @@+package ix.memory.api++import java.time.Instant+import java.util.UUID++import cats.effect.IO+import cats.effect.testing.scalatest.AsyncIOSpec+import io.circe.Json+import io.circe.syntax._+import org.http4s._+import org.http4s.circe.CirceEntityCodec._+import org.http4s.dsl.io._+import org.http4s.implicits._+import org.scalatest.flatspec.AsyncFlatSpec+import org.scalatest.matchers.should.Matchers++import ix.memory.conflict.ConflictService+import ix.memory.context._+import ix.memory.db._+import ix.memory.ingestion.{IngestionService, ParserRouter}+import ix.memory.model._++class RoutesSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {++ val clientResource = ArangoClient.resource(+ host = "localhost", port = 8529,+ database = "ix_memory_test", user = "root", password = ""+ )++ private def makePatch(+ tenant: TenantId,+ baseRev: Rev = Rev(0L),+ ops: Vector[PatchOp] = Vector.empty,+ patchId: PatchId = PatchId(UUID.randomUUID())+ ): GraphPatch =+ GraphPatch(+ patchId = patchId,+ tenant = tenant,+ actor = "test-actor",+ timestamp = Instant.parse("2025-06-01T12:00:00Z"),+ source = PatchSource(+ uri = "test://source",+ sourceHash = Some("hash123"),+ extractor = "test-extractor",+ sourceType = SourceType.Code+ ),+ baseRev = baseRev,+ ops = ops,+ replaces = Vector.empty,+ intent = Some("test intent")+ )++ private def buildRoutes(+ client: ArangoClient,+ writeApi: ArangoGraphWriteApi,+ queryApi: ArangoGraphQueryApi+ ): HttpApp[IO] = {+ val conflictService = new ConflictService(client, queryApi, writeApi)+ val contextService = new ContextService(+ queryApi,+ new GraphSeeder(queryApi),+ new GraphExpander(queryApi),+ new ClaimCollector(queryApi),+ new ConfidenceScorerImpl(),+ new ConflictDetectorImpl()+ )+ val ingestionService = new IngestionService(new ParserRouter(), writeApi)+ Routes.all(contextService, ingestionService, queryApi, conflictService, client).orNotFound+ }++ // ── Test 1: Health check ─────────────────────────────────────────────++ "Routes" should "return 200 OK for health check" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val req = Request[IO](Method.GET, uri"/v1/health")++ for {+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ body.hcursor.get[String]("status") shouldBe Right("ok")+ }+ }+ }++ // ── Test 2: GET /v1/entity/:id returns entity with claims ────────────++ it should "return entity with claims and edges" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())+ val nodeId = NodeId(UUID.randomUUID())+ val patch = makePatch(+ tenant = tenant,+ ops = Vector(+ PatchOp.UpsertNode(nodeId, NodeKind.Function, "test_func", Map("lang" -> Json.fromString("scala"))),+ PatchOp.AssertClaim(nodeId, "returns", Json.fromString("Int"), Some(0.9))+ )+ )++ for {+ _ <- client.ensureSchema()+ _ <- writeApi.commitPatch(patch)+ req = Request[IO](Method.GET, Uri.unsafeFromString(s"/v1/entity/${nodeId.value}?tenant=${tenant.value}"))+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ body.hcursor.downField("node").downField("id").as[String] shouldBe Right(nodeId.value.toString)+ body.hcursor.downField("claims").focus.flatMap(_.asArray).map(_.nonEmpty) shouldBe Some(true)+ }+ }+ }++ // ── Test 3: GET /v1/entity/:id returns 404 for missing entity ────────++ it should "return 404 for missing entity" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())+ val fakeId = UUID.randomUUID()++ for {+ _ <- client.ensureSchema()+ req = Request[IO](Method.GET, Uri.unsafeFromString(s"/v1/entity/$fakeId?tenant=${tenant.value}"))+ resp <- app.run(req)+ } yield {+ resp.status shouldBe Status.NotFound+ }+ }+ }++ // ── Test 4: GET /v1/entity/:id returns 400 for missing tenant ────────++ it should "return 400 for missing tenant query param" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val fakeId = UUID.randomUUID()++ for {+ _ <- client.ensureSchema()+ req = Request[IO](Method.GET, Uri.unsafeFromString(s"/v1/entity/$fakeId"))+ resp <- app.run(req)+ } yield {+ resp.status shouldBe Status.BadRequest+ }+ }+ }++ // ── Test 5: GET /v1/conflicts returns empty list ─────────────────────++ it should "return empty conflicts list for new tenant" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())++ for {+ _ <- client.ensureSchema()+ req = Request[IO](Method.GET, Uri.unsafeFromString(s"/v1/conflicts?tenant=${tenant.value}"))+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ body.asArray.map(_.isEmpty) shouldBe Some(true)+ }+ }+ }++ // ── Test 6: POST /v1/diff returns diff between revisions ─────────────++ it should "diff between revisions and detect added entity" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())+ val nodeId = NodeId(UUID.randomUUID())+ val patch = makePatch(+ tenant = tenant,+ ops = Vector(+ PatchOp.UpsertNode(nodeId, NodeKind.Function, "diff_func", Map.empty[String, Json])+ )+ )++ for {+ _ <- client.ensureSchema()+ result <- writeApi.commitPatch(patch)+ diffReq = Json.obj(+ "tenant" -> tenant.value.toString.asJson,+ "fromRev" -> 0L.asJson,+ "toRev" -> result.newRev.value.asJson,+ "entityId" -> nodeId.value.toString.asJson+ )+ req = Request[IO](Method.POST, uri"/v1/diff").withEntity(diffReq)+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ val changes = body.hcursor.downField("changes").focus.flatMap(_.asArray).getOrElse(Vector.empty)+ changes.size shouldBe 1+ changes.head.hcursor.get[String]("changeType") shouldBe Right("added")+ }+ }+ }++ // ── Test 7: POST /v1/diff returns 400 for invalid rev order ──────────++ it should "return 400 for invalid rev order in diff" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())++ for {+ _ <- client.ensureSchema()+ diffReq = Json.obj(+ "tenant" -> tenant.value.toString.asJson,+ "fromRev" -> 5L.asJson,+ "toRev" -> 2L.asJson+ )+ req = Request[IO](Method.POST, uri"/v1/diff").withEntity(diffReq)+ resp <- app.run(req)+ } yield {+ resp.status shouldBe Status.BadRequest+ }+ }+ }++ // ── Test 8: POST /v1/context returns structured context ──────────────++ it should "return structured context for a query" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())+ val nodeId = NodeId(UUID.randomUUID())+ val patch = makePatch(+ tenant = tenant,+ ops = Vector(+ PatchOp.UpsertNode(nodeId, NodeKind.Function, "billing_calc", Map.empty[String, Json]),+ PatchOp.AssertClaim(nodeId, "calculates billing", Json.fromString("true"), Some(0.9))+ )+ )++ for {+ _ <- client.ensureSchema()+ _ <- writeApi.commitPatch(patch)+ ctxReq = Json.obj(+ "query" -> "billing".asJson,+ "tenant" -> tenant.value.toString.asJson+ )+ req = Request[IO](Method.POST, uri"/v1/context").withEntity(ctxReq)+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ body.hcursor.downField("metadata").downField("query").as[String] shouldBe Right("billing")+ }+ }+ }++ // ── Test 9: POST /v1/provenance/:id returns provenance chain ─────────++ it should "return provenance chain for entity" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)+ val app = buildRoutes(client, writeApi, queryApi)+ val tenant = TenantId(UUID.randomUUID())+ val nodeId = NodeId(UUID.randomUUID())+ val patch = makePatch(+ tenant = tenant,+ ops = Vector(+ PatchOp.UpsertNode(nodeId, NodeKind.Function, "prov_func", Map.empty[String, Json])+ )+ )++ for {+ _ <- client.ensureSchema()+ _ <- writeApi.commitPatch(patch)+ req = Request[IO](Method.POST, Uri.unsafeFromString(s"/v1/provenance/${nodeId.value}?tenant=${tenant.value}"))+ resp <- app.run(req)+ body <- resp.as[Json]+ } yield {+ resp.status shouldBe Status.Ok+ body.hcursor.downField("entityId").as[String] shouldBe Right(nodeId.value.toString)+ val chain = body.hcursor.downField("chain").focus.flatMap(_.asArray).getOrElse(Vector.empty)+ chain.size should be >= 1+ }+ }+ }+}