Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat: add conflict detection and resolution service

riley022790f5e86dd363
diff --git a/memory-layer/src/main/scala/ix/memory/conflict/ConflictService.scala b/memory-layer/src/main/scala/ix/memory/conflict/ConflictService.scala
new file mode 100644
index 00000000..0e24408c
--- /dev/null
+++ b/memory-layer/src/main/scala/ix/memory/conflict/ConflictService.scala
@@ -0,0 +1,97 @@
+package ix.memory.conflict
+
+import cats.effect.IO
+import cats.syntax.traverse._
+import ix.memory.db.{ArangoClient, GraphQueryApi, GraphWriteApi}
+import ix.memory.model._
+import ix.memory.context.ConflictDetector
+
+class ConflictService(client: ArangoClient, queryApi: GraphQueryApi, writeApi: GraphWriteApi) {
+
+ def detectAndStore(tenant: TenantId, claims: Vector[ScoredClaim],
+ detector: ConflictDetector): IO[Vector[ConflictReport]] = {
+ val reports = detector.detect(claims)
+ // Store conflict sets in DB for each report
+ reports.traverse { report =>
+ storeConflictSet(tenant, report).map(_ => report)
+ }
+ }
+
+ private def storeConflictSet(tenant: TenantId, report: ConflictReport): IO[Unit] = {
+ client.execute(
+ """INSERT {
+ | _key: @key,
+ | id: @id,
+ | reason: @reason,
+ | status: "open",
+ | candidate_claims: @candidates,
+ | winner_claim_id: null,
+ | tenant: @tenant,
+ | created_rev: 0
+ |} INTO conflict_sets OPTIONS { overwriteMode: "ignore" }""".stripMargin,
+ Map(
+ "key" -> report.id.value.toString.asInstanceOf[AnyRef],
+ "id" -> report.id.value.toString.asInstanceOf[AnyRef],
+ "reason" -> report.reason.asInstanceOf[AnyRef],
+ "candidates" -> java.util.Arrays.asList(
+ report.claimA.value.toString, report.claimB.value.toString
+ ).asInstanceOf[AnyRef],
+ "tenant" -> tenant.value.toString.asInstanceOf[AnyRef]
+ )
+ )
+ }
+
+ def listConflicts(tenant: TenantId, status: Option[ConflictStatus] = None): IO[Vector[ConflictSet]] = {
+ val statusFilter = status.map(_ => " AND cs.status == @status").getOrElse("")
+ val statusVar: Map[String, AnyRef] = status.map { s =>
+ val str = s match {
+ case ConflictStatus.Open => "open"
+ case ConflictStatus.Resolved => "resolved"
+ case ConflictStatus.Dismissed => "dismissed"
+ }
+ Map("status" -> str.asInstanceOf[AnyRef])
+ }.getOrElse(Map.empty)
+
+ client.query(
+ s"""FOR cs IN conflict_sets
+ | FILTER cs.tenant == @tenant$statusFilter
+ | RETURN cs""".stripMargin,
+ Map("tenant" -> tenant.value.toString.asInstanceOf[AnyRef]) ++ statusVar
+ ).map(_.flatMap(parseConflictSet).toVector)
+ }
+
+ def resolve(tenant: TenantId, conflictId: ConflictId, winnerClaimId: ClaimId): IO[Unit] = {
+ client.execute(
+ """FOR cs IN conflict_sets
+ | FILTER cs._key == @key AND cs.tenant == @tenant
+ | UPDATE cs WITH { status: "resolved", winner_claim_id: @winner } IN conflict_sets""".stripMargin,
+ Map(
+ "key" -> conflictId.value.toString.asInstanceOf[AnyRef],
+ "tenant" -> tenant.value.toString.asInstanceOf[AnyRef],
+ "winner" -> winnerClaimId.value.toString.asInstanceOf[AnyRef]
+ )
+ )
+ }
+
+ private def parseConflictSet(json: io.circe.Json): Option[ConflictSet] = {
+ val c = json.hcursor
+ for {
+ idStr <- c.get[String]("id").toOption
+ id <- scala.util.Try(java.util.UUID.fromString(idStr)).toOption.map(ConflictId(_))
+ reason <- c.get[String]("reason").toOption
+ statusStr <- c.get[String]("status").toOption
+ status = statusStr match {
+ case "resolved" => ConflictStatus.Resolved
+ case "dismissed" => ConflictStatus.Dismissed
+ case _ => ConflictStatus.Open
+ }
+ candidates <- c.get[Vector[String]]("candidate_claims").toOption
+ candidateIds = candidates.flatMap(s =>
+ scala.util.Try(java.util.UUID.fromString(s)).toOption.map(ClaimId(_)))
+ winnerStr = c.get[String]("winner_claim_id").toOption
+ winnerId = winnerStr.flatMap(s =>
+ scala.util.Try(java.util.UUID.fromString(s)).toOption.map(ClaimId(_)))
+ createdRev <- c.get[Long]("created_rev").toOption.map(Rev(_))
+ } yield ConflictSet(id, reason, status, candidateIds, winnerId, createdRev)
+ }
+}
diff --git a/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala b/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala
index faba71b4..8954af37 100644
--- a/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala
+++ b/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala
@@ -1,14 +1,50 @@
package ix.memory.context
+import java.util.UUID
import ix.memory.model._
trait ConflictDetector {
def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport]
}
-/** Stub implementation for Phase 1 -- Task 9 will replace this. */
-class DefaultConflictDetector extends ConflictDetector {
+class ConflictDetectorImpl extends ConflictDetector {
+ def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport] = {
+ // Group claims by entityId
+ val grouped = claims.groupBy(_.claim.entityId)
+
+ grouped.values.flatMap { entityClaims =>
+ // Only consider active claims
+ val active = entityClaims.filter(_.claim.status == ClaimStatus.Active)
+ // Find pairs with different statements (same entity, different facts)
+ if (active.size < 2) Vector.empty
+ else {
+ val pairs = for {
+ i <- active.indices
+ j <- (i + 1) until active.size
+ a = active(i)
+ b = active(j)
+ if a.claim.statement != b.claim.statement
+ } yield {
+ // The higher-confidence claim is the recommended winner
+ val (winner, _) = if (a.confidence.score >= b.confidence.score) (a, b) else (b, a)
+ ConflictReport(
+ id = ConflictId(UUID.randomUUID()),
+ claimA = a.claim.id,
+ claimB = b.claim.id,
+ reason = s"Contradictory statements on entity ${a.claim.entityId.value}: " +
+ s"'${a.claim.statement}' vs '${b.claim.statement}'",
+ recommendation = s"Prefer '${winner.claim.statement}' (confidence: ${winner.confidence.score})"
+ )
+ }
+ pairs.toVector
+ }
+ }.toVector
+ }
+}
+
+/** Stub kept for backward compatibility -- prefer ConflictDetectorImpl. */
+class DefaultConflictDetector extends ConflictDetector {
def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport] =
- Vector.empty // No conflict detection yet
+ Vector.empty
}
diff --git a/memory-layer/src/test/scala/ix/memory/conflict/ConflictDetectorSpec.scala b/memory-layer/src/test/scala/ix/memory/conflict/ConflictDetectorSpec.scala
new file mode 100644
index 00000000..e4e4260f
--- /dev/null
+++ b/memory-layer/src/test/scala/ix/memory/conflict/ConflictDetectorSpec.scala
@@ -0,0 +1,116 @@
+package ix.memory.conflict
+
+import java.time.Instant
+import java.util.UUID
+import org.scalatest.flatspec.AnyFlatSpec
+import org.scalatest.matchers.should.Matchers
+import ix.memory.model._
+import ix.memory.context.ConflictDetectorImpl
+
+class ConflictDetectorSpec extends AnyFlatSpec with Matchers {
+ val detector = new ConflictDetectorImpl()
+
+ private def makeScoredClaim(entityId: NodeId, statement: String,
+ score: Double, sourceType: SourceType = SourceType.Code): ScoredClaim = {
+ val claim = Claim(
+ id = ClaimId(UUID.randomUUID()),
+ entityId = entityId,
+ statement = statement,
+ status = ClaimStatus.Active,
+ provenance = Provenance("test.py", Some("abc"), "test", sourceType, Instant.now()),
+ createdRev = Rev(1L),
+ deletedRev = None
+ )
+ val breakdown = ConfidenceBreakdown(
+ baseAuthority = Factor(score, "test"),
+ verification = Factor(1.0, "test"),
+ recency = Factor(1.0, "test"),
+ corroboration = Factor(1.0, "test"),
+ conflictPenalty = Factor(1.0, "test")
+ )
+ ScoredClaim(claim, breakdown)
+ }
+
+ "ConflictDetector" should "detect conflicting claims on same entity" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val claim1 = makeScoredClaim(entityId, "returns String", 0.90)
+ val claim2 = makeScoredClaim(entityId, "returns Int", 0.75)
+
+ val conflicts = detector.detect(Vector(claim1, claim2))
+
+ conflicts.size shouldBe 1
+ conflicts.head.reason should include("Contradictory")
+ conflicts.head.recommendation should include("returns String")
+ }
+
+ it should "not flag claims on different entities" in {
+ val entity1 = NodeId(UUID.randomUUID())
+ val entity2 = NodeId(UUID.randomUUID())
+ val claim1 = makeScoredClaim(entity1, "returns String", 0.90)
+ val claim2 = makeScoredClaim(entity2, "returns Int", 0.75)
+
+ val conflicts = detector.detect(Vector(claim1, claim2))
+
+ conflicts shouldBe empty
+ }
+
+ it should "not flag claims with the same statement" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val claim1 = makeScoredClaim(entityId, "returns String", 0.90)
+ val claim2 = makeScoredClaim(entityId, "returns String", 0.85)
+
+ val conflicts = detector.detect(Vector(claim1, claim2))
+
+ conflicts shouldBe empty
+ }
+
+ it should "recommend the higher-confidence claim" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val highConf = makeScoredClaim(entityId, "returns String", 0.95)
+ val lowConf = makeScoredClaim(entityId, "returns Int", 0.40)
+
+ val conflicts = detector.detect(Vector(highConf, lowConf))
+
+ conflicts.head.recommendation should include("returns String")
+ conflicts.head.recommendation should include("0.95")
+ }
+
+ it should "detect multiple conflicts in a group" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val claim1 = makeScoredClaim(entityId, "returns String", 0.90)
+ val claim2 = makeScoredClaim(entityId, "returns Int", 0.75)
+ val claim3 = makeScoredClaim(entityId, "returns Boolean", 0.60)
+
+ val conflicts = detector.detect(Vector(claim1, claim2, claim3))
+
+ conflicts.size shouldBe 3 // 3 pairs from 3 different statements
+ }
+
+ it should "ignore retracted claims" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val activeClaim = makeScoredClaim(entityId, "returns String", 0.90)
+ val retractedClaim = {
+ val sc = makeScoredClaim(entityId, "returns Int", 0.75)
+ sc.copy(claim = sc.claim.copy(status = ClaimStatus.Retracted))
+ }
+
+ val conflicts = detector.detect(Vector(activeClaim, retractedClaim))
+
+ conflicts shouldBe empty
+ }
+
+ it should "return empty for single claim" in {
+ val entityId = NodeId(UUID.randomUUID())
+ val claim = makeScoredClaim(entityId, "returns String", 0.90)
+
+ val conflicts = detector.detect(Vector(claim))
+
+ conflicts shouldBe empty
+ }
+
+ it should "return empty for empty input" in {
+ val conflicts = detector.detect(Vector.empty)
+
+ conflicts shouldBe empty
+ }
+}
diff --git a/memory-layer/src/test/scala/ix/memory/context/ContextServiceSpec.scala b/memory-layer/src/test/scala/ix/memory/context/ContextServiceSpec.scala
index 0677a958..73a8b971 100644
--- a/memory-layer/src/test/scala/ix/memory/context/ContextServiceSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/context/ContextServiceSpec.scala
@@ -47,7 +47,7 @@ class ContextServiceSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
val expander = new GraphExpander(queryApi)
val collector = new ClaimCollector(queryApi)
val scorer = new DefaultConfidenceScorer()
- val detector = new DefaultConflictDetector()
+ val detector = new ConflictDetectorImpl()
new ContextService(queryApi, seeder, expander, collector, scorer, detector)
}
@@ -190,9 +190,9 @@ class ContextServiceSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
}
}
- // ── Test 6: DefaultConflictDetector returns empty ──────────────────
+ // ── Test 6: No conflicts when only one claim per entity ────────────
- it should "return empty conflicts with default detector" in {
+ it should "return empty conflicts when no contradictions exist" in {
clientResource.use { client =>
val writeApi = new ArangoGraphWriteApi(client)
val queryApi = new ArangoGraphQueryApi(client)