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: claim lifecycle management, expanded search, and conflict reduction
riley0227c11a5a89de88
diff --git a/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala b/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scalaindex e47a01c4..9732cfac 100644--- a/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala+++ b/memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala@@ -4,6 +4,7 @@ import java.util.UUIDimport cats.effect.IOimport cats.implicits._+import org.slf4j.LoggerFactoryimport ix.memory.model._trait ConflictDetector {@@ -12,40 +13,46 @@ trait ConflictDetector {class ConflictDetectorImpl(llmJudge: Option[LlmJudge] = None) extends ConflictDetector {+ private val log = LoggerFactory.getLogger(classOf[ConflictDetectorImpl])+/**- * Multi-pass conflict detection.+ * Conflict detection with relevance filtering.*- * Pass 1 – exact contradiction: two active claims on the same entity whose- * statements differ and share NO keyword stems.- * Pass 2 – keyword overlap: two active claims on the same entity whose- * statements differ but share at least one keyword stem (i.e. they- * talk about the same topic yet say different things).+ * Only flags conflicts between claims that share a field prefix+ * (e.g. both start with "calls:") or have keyword-stem overlap.+ * Caps at 20 active claims per entity and 10 conflicts per entity+ * to prevent combinatorial explosion.*/def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport] = {val byEntity = claims.groupBy(_.claim.entityId)byEntity.values.flatMap { entityClaims =>- val activeClaims = entityClaims.filter(_.claim.status == ClaimStatus.Active)+ val activeClaims = entityClaims.filter(_.claim.status == ClaimStatus.Active).take(20)if (activeClaims.size < 2) Vector.emptyelse {val pairs = activeClaims.combinations(2).toVector- pairs.flatMap {+ val conflicts = pairs.flatMap {case Vector(a, b) =>if (a.claim.statement == b.claim.statement) {- // Identical statements are not in conflictNone}- // Pass 1: different statements with keyword overlap (same-topic contradiction)+ else if (shareFieldPrefix(a.claim.statement, b.claim.statement)) {+ Some(makeConflict(a, b, "Contradictory statements (same field)"))+ }else if (keywordsOverlap(a.claim.statement, b.claim.statement)) {Some(makeConflict(a, b, "Contradictory statements (keyword overlap)"))}- // Pass 2: different statements with no keyword overlap (unrelated contradiction)else {- Some(makeConflict(a, b, s"Contradictory statements on entity ${a.claim.entityId.value}"))+ None // unrelated claims — not a conflict}- case _ => None // safety for non-pair combinations+ case _ => None+ }.take(10)++ if (conflicts.nonEmpty) {+ log.warn("Detected {} conflict(s) for entity {}", conflicts.size, entityClaims.head.claim.entityId.value)}+ conflicts}}.toVector}@@ -98,6 +105,13 @@ class ConflictDetectorImpl(llmJudge: Option[LlmJudge] = None) extends ConflictDe}}+ /** Check whether two statements share a field prefix (e.g. both start with "calls:"). */+ private def shareFieldPrefix(a: String, b: String): Boolean = {+ val idxA = a.indexOf(':')+ val idxB = b.indexOf(':')+ idxA > 0 && idxB > 0 && a.substring(0, idxA) == b.substring(0, idxB)+ }+/** Check whether two statement strings share at least one 4-char stem. */private def keywordsOverlap(a: String, b: String): Boolean = {val stemsA = tokenize(a).map(_.take(4).toLowerCase).toSetdiff --git a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scalaindex a9e42b41..fcecef21 100644--- a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala+++ b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala@@ -47,9 +47,35 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {override def searchNodes(text: String, limit: Int = 20): IO[Vector[GraphNode]] =client.query(- """FOR n IN nodes- | FILTER CONTAINS(LOWER(n.name), LOWER(@text))- | AND n.deleted_rev == null+ """LET name_matches = (+ | FOR n IN nodes+ | FILTER CONTAINS(LOWER(n.name), LOWER(@text))+ | AND n.deleted_rev == null+ | RETURN DISTINCT n.logical_id+ |)+ |+ |LET provenance_matches = (+ | FOR n IN nodes+ | FILTER CONTAINS(LOWER(n.provenance.source_uri), LOWER(@text))+ | AND n.deleted_rev == null+ | RETURN DISTINCT n.logical_id+ |)+ |+ |LET claim_matches = (+ | FOR c IN claims+ | FILTER c.deleted_rev == null+ | AND (+ | CONTAINS(LOWER(c.field), LOWER(@text))+ | OR CONTAINS(LOWER(TO_STRING(c.value)), LOWER(@text))+ | )+ | RETURN DISTINCT c.entity_id+ |)+ |+ |LET all_ids = UNION_DISTINCT(name_matches, provenance_matches, claim_matches)+ |+ |FOR id IN all_ids+ | FOR n IN nodes+ | FILTER n.logical_id == id AND n.deleted_rev == null| LIMIT @limit| RETURN n""".stripMargin,Map(diff --git a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scalaindex a382026d..600a71da 100644--- a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala+++ b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala@@ -74,6 +74,8 @@ class ArangoGraphWriteApi(client: ArangoClient) extends GraphWriteApi {for {// Step 5: Execute each op_ <- patch.ops.traverse_(op => executeOp(op, patch, newRev, txId))+ // Step 5b: Retire absent claims (claims from same extractor/entity no longer emitted)+ _ <- retireAbsentClaims(patch, newRev, txId)// Step 6: Store patch_ <- storePatch(patch, newRev, txId)// Step 7: Store idempotency key@@ -258,32 +260,42 @@ class ArangoGraphWriteApi(client: ArangoClient) extends GraphWriteApi {)case PatchOp.AssertClaim(entityId, field, value, confidence) =>- val claimKey = UUID.randomUUID().toStringval provenanceJson = buildProvenance(patch)- client.execute(- """INSERT {- | _key: @key,- | entity_id: @entity_id,- | field: @field,- | value: @value,- | confidence: @confidence,- | status: @status,- | created_rev: @created_rev,- | deleted_rev: null,- | provenance: @provenance- |} INTO claims""".stripMargin,- Map(- "key" -> claimKey.asInstanceOf[AnyRef],- "entity_id" -> entityId.value.toString.asInstanceOf[AnyRef],- "field" -> field.asInstanceOf[AnyRef],- "value" -> jsonToJava(value).asInstanceOf[AnyRef],- "confidence" -> confidence.map(Double.box).orNull.asInstanceOf[AnyRef],- "status" -> "active".asInstanceOf[AnyRef],- "created_rev" -> Long.box(newRev).asInstanceOf[AnyRef],- "provenance" -> parseToJavaMap(provenanceJson.noSpaces).asInstanceOf[AnyRef]- ),- txId = Some(txId)- )+ for {+ // Step 1: Retire active claims for same (entity_id, field) with different value+ _ <- retireClaims(entityId.value.toString, field, value, newRev, txId)+ // Step 2: Check if identical active claim already exists+ hasDuplicate <- hasIdenticalActiveClaim(entityId.value.toString, field, value, txId)+ // Step 3: Only insert if no duplicate+ _ <- if (hasDuplicate) IO.unit+ else {+ val claimKey = UUID.randomUUID().toString+ client.execute(+ """INSERT {+ | _key: @key,+ | entity_id: @entity_id,+ | field: @field,+ | value: @value,+ | confidence: @confidence,+ | status: @status,+ | created_rev: @created_rev,+ | deleted_rev: null,+ | provenance: @provenance+ |} INTO claims""".stripMargin,+ Map(+ "key" -> claimKey.asInstanceOf[AnyRef],+ "entity_id" -> entityId.value.toString.asInstanceOf[AnyRef],+ "field" -> field.asInstanceOf[AnyRef],+ "value" -> jsonToJava(value).asInstanceOf[AnyRef],+ "confidence" -> confidence.map(Double.box).orNull.asInstanceOf[AnyRef],+ "status" -> "active".asInstanceOf[AnyRef],+ "created_rev" -> Long.box(newRev).asInstanceOf[AnyRef],+ "provenance" -> parseToJavaMap(provenanceJson.noSpaces).asInstanceOf[AnyRef]+ ),+ txId = Some(txId)+ )+ }+ } yield ()case PatchOp.RetractClaim(claimId) =>client.execute(@@ -344,6 +356,82 @@ class ArangoGraphWriteApi(client: ArangoClient) extends GraphWriteApi {txId = Some(txId))+ /** Retire active claims for the same (entity_id, field) that have a different value. */+ private def retireClaims(entityId: String, field: String, value: Json, newRev: Long, txId: String): IO[Unit] =+ client.execute(+ """FOR c IN claims+ | FILTER c.entity_id == @entity_id+ | AND c.field == @field+ | AND c.deleted_rev == null+ | AND c.value != @value+ | UPDATE c WITH { status: "retracted", deleted_rev: @deleted_rev } IN claims""".stripMargin,+ Map(+ "entity_id" -> entityId.asInstanceOf[AnyRef],+ "field" -> field.asInstanceOf[AnyRef],+ "value" -> jsonToJava(value).asInstanceOf[AnyRef],+ "deleted_rev" -> Long.box(newRev).asInstanceOf[AnyRef]+ ),+ txId = Some(txId)+ )++ /** Check if an identical active claim already exists (same entity, field, value). */+ private def hasIdenticalActiveClaim(entityId: String, field: String, value: Json, txId: String): IO[Boolean] =+ client.queryOne(+ """FOR c IN claims+ | FILTER c.entity_id == @entity_id+ | AND c.field == @field+ | AND c.value == @value+ | AND c.deleted_rev == null+ | LIMIT 1+ | RETURN 1""".stripMargin,+ Map(+ "entity_id" -> entityId.asInstanceOf[AnyRef],+ "field" -> field.asInstanceOf[AnyRef],+ "value" -> jsonToJava(value).asInstanceOf[AnyRef]+ ),+ txId = Some(txId)+ ).map(_.isDefined)++ /**+ * After all ops execute, retire claims from the same extractor/entity that are+ * no longer emitted (the "absent claims" policy). This handles the case where+ * a re-parsed file no longer contains a previously asserted claim.+ */+ private def retireAbsentClaims(patch: GraphPatch, newRev: Long, txId: String): IO[Unit] = {+ val assertedClaims = patch.ops.collect {+ case PatchOp.AssertClaim(entityId, field, _, _) => (entityId.value.toString, field)+ }++ if (assertedClaims.isEmpty) IO.unit+ else {+ val fieldsByEntity: Map[String, Set[String]] = assertedClaims+ .groupBy(_._1)+ .map { case (eid, pairs) => eid -> pairs.map(_._2).toSet }++ val extractor = patch.source.extractor++ fieldsByEntity.toVector.traverse_ { case (entityId, fields) =>+ val fieldList = new java.util.ArrayList[String]()+ fields.foreach(fieldList.add)+ client.execute(+ """FOR c IN claims+ | FILTER c.entity_id == @entity_id+ | AND c.field NOT IN @fields+ | AND c.deleted_rev == null+ | AND c.provenance.extractor == @extractor+ | UPDATE c WITH { status: "retracted", deleted_rev: @deleted_rev } IN claims""".stripMargin,+ Map(+ "entity_id" -> entityId.asInstanceOf[AnyRef],+ "fields" -> fieldList.asInstanceOf[AnyRef],+ "extractor" -> extractor.asInstanceOf[AnyRef],+ "deleted_rev" -> Long.box(newRev).asInstanceOf[AnyRef]+ ),+ txId = Some(txId)+ )+ }+ }+ }+private def buildProvenance(patch: GraphPatch): Json =Json.obj("source_uri" -> Json.fromString(patch.source.uri),diff --git a/memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala b/memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scalaindex d0c325ea..bec90b28 100644--- a/memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala+++ b/memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala@@ -49,6 +49,12 @@ object ArangoSchema {new PersistentIndexOptions())+ // Indexes — nodes (provenance)+ nodes.ensurePersistentIndex(+ java.util.Arrays.asList("provenance.source_uri"),+ new PersistentIndexOptions().sparse(true)+ )+// Indexes — claimsval claims = db.collection("claims")claims.ensurePersistentIndex(@@ -60,7 +66,11 @@ object ArangoSchema {new PersistentIndexOptions())claims.ensurePersistentIndex(- java.util.Arrays.asList("statement"),+ java.util.Arrays.asList("entity_id", "field", "deleted_rev"),+ new PersistentIndexOptions()+ )+ claims.ensurePersistentIndex(+ java.util.Arrays.asList("field"),new PersistentIndexOptions().sparse(true))diff --git a/memory-layer/src/test/scala/ix/memory/ClaimLifecycleSpec.scala b/memory-layer/src/test/scala/ix/memory/ClaimLifecycleSpec.scalanew file mode 100644index 00000000..8ecb172d--- /dev/null+++ b/memory-layer/src/test/scala/ix/memory/ClaimLifecycleSpec.scala@@ -0,0 +1,243 @@+package ix.memory++import java.time.Instant+import java.util.UUID++import cats.effect.IO+import cats.effect.testing.scalatest.AsyncIOSpec+import io.circe.Json+import org.scalatest.flatspec.AsyncFlatSpec+import org.scalatest.matchers.should.Matchers++import ix.memory.db._+import ix.memory.model._++class ClaimLifecycleSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers with TestDbHelper {++ val clientResource = ArangoClient.resource(+ host = "localhost", port = 8529,+ database = "ix_memory_test", user = "root", password = ""+ )++ private val testEntityId = NodeId(UUID.nameUUIDFromBytes("test:entity1".getBytes("UTF-8")))++ private def makePatch(+ baseRev: Rev = Rev(0L),+ ops: Vector[PatchOp] = Vector.empty,+ patchId: PatchId = PatchId(UUID.randomUUID()),+ source: PatchSource = PatchSource("file:///tmp/test.md", Some("hash1"), "markdown-parser/1.0", SourceType.Doc)+ ): GraphPatch =+ GraphPatch(+ patchId = patchId,+ actor = "test-actor",+ timestamp = Instant.parse("2025-06-01T12:00:00Z"),+ source = source,+ baseRev = baseRev,+ ops = ops,+ replaces = Vector.empty,+ intent = Some("test intent")+ )++ // ── Test 1: Claim Retirement ─────────────────────────────────────────++ "ClaimLifecycle" should "retire old claims when a new value is asserted for the same field" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)++ for {+ _ <- client.ensureSchema()+ _ <- cleanDatabase(client)++ // Step 1: Create node + assert initial content claim+ patch1 = makePatch(+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "content", Json.fromString("hello"), None)+ )+ )+ commit1 <- writeApi.commitPatch(patch1)++ // Verify initial claim exists+ claimsBefore <- queryApi.getClaims(testEntityId)+ _ = {+ commit1.status shouldBe CommitStatus.Ok+ claimsBefore.count(_.status == ClaimStatus.Active) should be >= 1+ claimsBefore.exists(_.statement == "content") shouldBe true+ }++ // Step 2: Re-ingest with changed content+ patch2 = makePatch(+ baseRev = commit1.newRev,+ source = PatchSource("file:///tmp/test.md", Some("hash2"), "markdown-parser/1.0", SourceType.Doc),+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "content", Json.fromString("zzzxqv123"), None)+ )+ )+ commit2 <- writeApi.commitPatch(patch2)++ // Verify: only one active content claim, old one is retracted+ claimsAfter <- queryApi.getClaims(testEntityId)+ } yield {+ commit2.status shouldBe CommitStatus.Ok++ // Only one active content claim+ val activeContentClaims = claimsAfter.filter(c => c.statement == "content" && c.status == ClaimStatus.Active)+ activeContentClaims.size shouldBe 1++ // The old claim should be retired (not returned by getClaims which filters deleted_rev == null)+ // But we can check that no stale content claims exist in active state+ claimsAfter.count(c => c.statement == "content" && c.status == ClaimStatus.Active) shouldBe 1+ }+ }+ }++ // ── Test 2: Search Coverage ──────────────────────────────────────────++ it should "find entities by name, provenance, claim field, and claim value" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)++ for {+ _ <- client.ensureSchema()+ _ <- cleanDatabase(client)++ // Ingest a doc node with claims+ patch = makePatch(+ source = PatchSource("file:///projects/readme.md", Some("abc"), "markdown-parser/1.0", SourceType.Doc),+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "readme.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "language", Json.fromString("markdown"), None),+ PatchOp.AssertClaim(testEntityId, "content", Json.fromString("This is a test document about billing"), None)+ )+ )+ commit <- writeApi.commitPatch(patch)+ _ = commit.status shouldBe CommitStatus.Ok++ // Search by node name+ byName <- queryApi.searchNodes("readme")+ // Search by provenance (source_uri)+ byProvenance <- queryApi.searchNodes("/projects/readme")+ // Search by claim field+ byField <- queryApi.searchNodes("language")+ // Search by claim value+ byValue <- queryApi.searchNodes("markdown")+ // Search by content+ byContent <- queryApi.searchNodes("billing")+ } yield {+ byName should not be empty+ byName.head.id shouldBe testEntityId++ byProvenance should not be empty+ byProvenance.head.id shouldBe testEntityId++ byField should not be empty+ byField.head.id shouldBe testEntityId++ byValue should not be empty+ byValue.head.id shouldBe testEntityId++ byContent should not be empty+ byContent.head.id shouldBe testEntityId+ }+ }+ }++ // ── Test 3: Identical Claim Dedup ────────────────────────────────────++ it should "not create duplicate active claims when the same claim is asserted twice" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)++ for {+ _ <- client.ensureSchema()+ _ <- cleanDatabase(client)++ // Step 1: Assert a claim+ patch1 = makePatch(+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "language", Json.fromString("markdown"), None)+ )+ )+ commit1 <- writeApi.commitPatch(patch1)++ claimsBefore <- queryApi.getClaims(testEntityId)+ langClaimsBefore = claimsBefore.count(c => c.statement == "language" && c.status == ClaimStatus.Active)++ // Step 2: Assert the exact same claim again+ patch2 = makePatch(+ baseRev = commit1.newRev,+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "language", Json.fromString("markdown"), None)+ )+ )+ commit2 <- writeApi.commitPatch(patch2)++ claimsAfter <- queryApi.getClaims(testEntityId)+ langClaimsAfter = claimsAfter.count(c => c.statement == "language" && c.status == ClaimStatus.Active)+ } yield {+ commit1.status shouldBe CommitStatus.Ok+ commit2.status shouldBe CommitStatus.Ok++ // Should have exactly one active language claim, not two+ langClaimsBefore shouldBe 1+ langClaimsAfter shouldBe 1+ }+ }+ }++ // ── Test 4: Absent Claims Retirement ─────────────────────────────────++ it should "retire claims from the same extractor that are no longer emitted" in {+ clientResource.use { client =>+ val writeApi = new ArangoGraphWriteApi(client)+ val queryApi = new ArangoGraphQueryApi(client)++ for {+ _ <- client.ensureSchema()+ _ <- cleanDatabase(client)++ // Step 1: Assert two claims from the same extractor+ patch1 = makePatch(+ source = PatchSource("file:///tmp/test.md", Some("hash1"), "markdown-parser/1.0", SourceType.Doc),+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "language", Json.fromString("markdown"), None),+ PatchOp.AssertClaim(testEntityId, "content", Json.fromString("hello world"), None)+ )+ )+ commit1 <- writeApi.commitPatch(patch1)++ claimsBefore <- queryApi.getClaims(testEntityId)+ _ = {+ claimsBefore.count(_.status == ClaimStatus.Active) shouldBe 2+ }++ // Step 2: Re-ingest from same extractor but only emit "language" (content is absent)+ patch2 = makePatch(+ baseRev = commit1.newRev,+ source = PatchSource("file:///tmp/test.md", Some("hash2"), "markdown-parser/1.0", SourceType.Doc),+ ops = Vector(+ PatchOp.UpsertNode(testEntityId, NodeKind.Doc, "test.md", Map.empty[String, Json]),+ PatchOp.AssertClaim(testEntityId, "language", Json.fromString("markdown"), None)+ )+ )+ commit2 <- writeApi.commitPatch(patch2)++ claimsAfter <- queryApi.getClaims(testEntityId)+ } yield {+ commit2.status shouldBe CommitStatus.Ok++ // Only "language" should remain active; "content" should be retired+ val activeClaims = claimsAfter.filter(_.status == ClaimStatus.Active)+ activeClaims.size shouldBe 1+ activeClaims.head.statement shouldBe "language"+ }+ }+ }+}