Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat(context): run decision evaluators on ContextGraph backend (#2133)
ordinary being008d7b1c139a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5515f297..a06cef48 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added-- `DecisionRecorder` and `AgentContext` gain opt-in `evaluators`/`eval_config` constructor parameters that run `semantica.evals` evaluators (e.g. `decision_scores`) automatically during `record_decision()`, storing `eval_score`/`eval_passed`/`eval_details` in `Decision.metadata`. Fully backward-compatible: omitting `evaluators` leaves recording behavior unchanged. Evaluator failures are logged and never block decision persistence. Wired for the `graph_store` backend only; the `context_graph` `AgentContext` backend is a known follow-up.+- `DecisionRecorder` and `AgentContext` gain opt-in `evaluators`/`eval_config` constructor parameters that run `semantica.evals` evaluators (e.g. `decision_scores`) automatically during `record_decision()`, storing `eval_score`/`eval_passed`/`eval_details` in `Decision.metadata`. Fully backward-compatible: omitting `evaluators` leaves recording behavior unchanged. Evaluator failures are logged and never block decision persistence. Both the `graph_store` and `context_graph` `AgentContext` decision backends run the hook.- **Trust-tier grading of retrieved context** (#1703, phase 2 of #1557) by @pkupt- `ContextRetriever` now grades every retrieved fact on evidence quality and records the tier in `RetrievedContext.metadata["trust_tier"]` (`quarantine` / `bronze` / `silver` / `gold`). Tiers are computed at query time from signals already present in the result — graph node confidence and, when a `provenance_manager` is configured, the number of distinct sources from `get_all_sources` — and are never persisted, so grades stay current as source sets change- New `filter_by_tier(minimum, include_unscored=False)` on `ContextRetriever`, alongside the existing score/type/date filters. Graph facts without readable signals grade to `quarantine` (missing evidence is never trusted as high confidence); DRIFT's verified local facts are graded the same way as graph edges. Community-report summaries from global and DRIFT search carry no per-fact signals and stay unscored, and a threshold keeps them rather than emptying the response. Without a `provenance_manager` there is no corroboration signal, so facts grade `bronze` at best and a `silver` or `gold` threshold needs onediff --git a/semantica/context/agent_context.py b/semantica/context/agent_context.pyindex d714b833..b531b74c 100644--- a/semantica/context/agent_context.py+++ b/semantica/context/agent_context.py@@ -81,7 +81,7 @@ from .agent_memory import AgentMemoryfrom .context_retriever import ContextRetriever, RetrievedContextfrom .entity_linker import EntityLinkerfrom .decision_models import Decision-from .decision_recorder import DecisionRecorder+from .decision_recorder import DecisionRecorder, evaluate_and_enrich_decisionfrom .decision_query import DecisionQueryfrom .causal_analyzer import CausalChainAnalyzerfrom .policy_engine import PolicyEngine@@ -1756,7 +1756,28 @@ class AgentContext:if not hasattr(self.knowledge_graph, "record_decision"):raise RuntimeError("Decision tracking backend does not support decisions")- # Delegate to ContextGraph+ # Delegate to ContextGraph. Run the same opt-in evaluator hook as the+ # DecisionRecorder path before persisting, so eval_* metadata is+ # available on both decision backends.+ if self.evaluators:+ evaluate_and_enrich_decision(+ decision, self.evaluators, self.eval_config, self.logger+ )+ metadata = dict(decision.metadata or {})+ # ContextGraph rejects metadata values whose str() exceeds 1000+ # characters. An evaluator's diagnostic detail can cross that limit+ # (for example a long outcome echoed into a mismatch reason), and the+ # evaluator hook is explicitly non-blocking, so keep the compact score+ # and pass/fail fields and omit the oversized diagnostic payload.+ if "eval_details" in metadata and len(str(metadata["eval_details"])) > 1000:+ self.logger.warning(+ f"Decision evaluation details for {decision.decision_id} exceed "+ "ContextGraph's metadata value limit; storing eval_score and "+ "eval_passed without eval_details"+ )+ metadata.pop("eval_details", None)+ if cross_system_context:+ metadata["cross_system_context"] = cross_system_contextdecision_id = self.knowledge_graph.record_decision(category=category,scenario=scenario,@@ -1767,9 +1788,10 @@ class AgentContext:decision_maker=decision_maker,valid_from=valid_from,valid_until=valid_until,- metadata={"cross_system_context": cross_system_context} if cross_system_context else None+ decision_id=decision.decision_id,+ metadata=metadata or None,)-+return decision_iddef find_precedents(diff --git a/semantica/context/context_graph.py b/semantica/context/context_graph.pyindex 63184ff8..6594b97b 100644--- a/semantica/context/context_graph.py+++ b/semantica/context/context_graph.py@@ -4437,6 +4437,7 @@ class ContextGraph:metadata: Optional[Dict[str, Any]] = None,valid_from: Optional[Union[str, int, float, datetime]] = None,valid_until: Optional[Union[str, int, float, datetime]] = None,+ decision_id: Optional[str] = None,**kwargs) -> str:"""@@ -4451,6 +4452,11 @@ class ContextGraph:entities: Related entitiesdecision_maker: Who made the decisionmetadata: Additional metadata+ valid_from: Start of the decision's validity window+ valid_until: End of the decision's validity window+ decision_id: Optional pre-generated decision ID. When omitted, a+ UUID is generated. A caller-supplied ID must not already+ exist in this graph.**kwargs: Additional decision dataReturns:@@ -4525,7 +4531,15 @@ class ContextGraph:if len(str(value)) > 1000:raise ValueError("Additional field values must be 1000 characters or less")- decision_id = str(uuid.uuid4())+ if decision_id is not None:+ if not isinstance(decision_id, str) or not decision_id.strip():+ raise ValueError("Decision ID must be a non-empty string")+ if decision_id in self.nodes or decision_id in getattr(+ self, "_decisions", {}+ ):+ raise ValueError(f"Decision ID {decision_id!r} already exists")+ else:+ decision_id = str(uuid.uuid4())timestamp = datetime.now().timestamp()# Sanitize inputsdiff --git a/semantica/context/decision_recorder.py b/semantica/context/decision_recorder.pyindex 5a69ad83..d2a2424b 100644--- a/semantica/context/decision_recorder.py+++ b/semantica/context/decision_recorder.py@@ -86,6 +86,71 @@ from .decision_models import (from .context_graph import ContextGraph+def evaluate_and_enrich_decision(+ decision: Decision,+ evaluators: Optional[List[str]],+ eval_config: Optional[Dict[str, Any]],+ logger: Any,+) -> None:+ """Run opt-in ``semantica.evals`` evaluators and enrich ``decision.metadata``.++ Shared by :class:`DecisionRecorder` and ``AgentContext``'s ContextGraph+ decision backend so both recording paths apply the same evaluator contract.+ No-op when ``evaluators`` is empty. Evaluator failures are logged and never+ prevent the decision from being recorded.+ """+ if not evaluators:+ return++ # Decision.metadata defaults to {} but callers may pass metadata=None+ # explicitly; normalize before writing eval_* keys below so recording+ # never crashes on that (mirrors record_decision()'s own tolerance+ # for a missing metadata dict).+ if decision.metadata is None:+ decision.metadata = {}++ case = {"id": decision.decision_id, "actual": decision}+ try:+ # Lazy import: semantica.evals is only exercised when evaluators=+ # is configured, and resolving it here (rather than at module+ # import time) lets callers/tests monkeypatch semantica.evals.evaluate.+ from ..evals import evaluate++ summary = evaluate([case], evaluators=evaluators, config=eval_config or {})+ except Exception as exc:+ # Deliberate, narrow exception to just the evaluate() call: this+ # hook is an optional quality check, and a broken evaluator must+ # never prevent the decision itself from being recorded. Logs and+ # returns (does not re-raise). Per-evaluator failures are already+ # converted to CaseResult(status="error") inside evaluate();+ # reaching here means evaluate() itself failed outright.+ logger.warning(+ f"Decision evaluation failed for {decision.decision_id}: {exc}",+ exc_info=True,+ )+ return++ # Outside the try: a summary-shape change here is a bug in this hook,+ # not an evaluator failure, and must not be swallowed as one.+ case_result = summary.cases[0]+ if case_result.status == "error":+ # A named evaluator itself errored (unknown name, or it raised) --+ # evaluate() already downgraded that to CaseResult(status="error")+ # instead of propagating, so without this log the only trace is+ # eval_details on the stored decision.+ logger.warning(+ f"Decision evaluator(s) errored for {decision.decision_id}: "+ f"{case_result.details}"+ )+ scores = [metric.score for metric in case_result.metrics.values()]+ decision.metadata["eval_score"] = sum(scores) / len(scores) if scores else 0.0+ decision.metadata["eval_passed"] = case_result.status == "pass"+ decision.metadata["eval_details"] = {+ name: {"score": metric.score, "passed": metric.passed, "meta": metric.meta}+ for name, metric in case_result.metrics.items()+ }++class DecisionRecorder:"""Records decisions with full context, policy applications, and provenance.@@ -133,65 +198,10 @@ class DecisionRecorder:self.logger = get_logger(__name__)def _evaluate_and_enrich_decision(self, decision: Decision) -> None:- """- Run configured semantica.evals evaluators over a decision and store the- result in its metadata. No-op when no evaluators are configured.-- Args:- decision: Decision to evaluate; mutated in place (decision.metadata).- """- if not self.evaluators:- return-- # Decision.metadata defaults to {} but callers may pass metadata=None- # explicitly; normalize before writing eval_* keys below so recording- # never crashes on that (mirrors record_decision()'s own tolerance- # for a missing metadata dict).- if decision.metadata is None:- decision.metadata = {}-- case = {"id": decision.decision_id, "actual": decision}- try:- # Lazy import: semantica.evals is only exercised when evaluators=- # is configured, and resolving it here (rather than at module- # import time) lets callers/tests monkeypatch semantica.evals.evaluate.- from ..evals import evaluate-- summary = evaluate(- [case], evaluators=self.evaluators, config=self.eval_config- )- except Exception as exc:- # Deliberate, narrow exception to just the evaluate() call: this- # hook is an optional quality check, and a broken evaluator must- # never prevent the decision itself from being recorded. Logs and- # returns (does not re-raise). Per-evaluator failures are already- # converted to CaseResult(status="error") inside evaluate();- # reaching here means evaluate() itself failed outright.- self.logger.warning(- f"Decision evaluation failed for {decision.decision_id}: {exc}",- exc_info=True,- )- return-- # Outside the try: a summary-shape change here is a bug in this hook,- # not an evaluator failure, and must not be swallowed as one.- case_result = summary.cases[0]- if case_result.status == "error":- # A named evaluator itself errored (unknown name, or it raised) --- # evaluate() already downgraded that to CaseResult(status="error")- # instead of propagating, so without this log the only trace is- # eval_details on the stored decision.- self.logger.warning(- f"Decision evaluator(s) errored for {decision.decision_id}: "- f"{case_result.details}"- )- scores = [metric.score for metric in case_result.metrics.values()]- decision.metadata["eval_score"] = sum(scores) / len(scores) if scores else 0.0- decision.metadata["eval_passed"] = case_result.status == "pass"- decision.metadata["eval_details"] = {- name: {"score": metric.score, "passed": metric.passed, "meta": metric.meta}- for name, metric in case_result.metrics.items()- }+ """Run configured evaluators over a decision and enrich its metadata."""+ evaluate_and_enrich_decision(+ decision, self.evaluators, self.eval_config, self.logger+ )def record_decision(self,diff --git a/tests/context/test_context_graph_decisions.py b/tests/context/test_context_graph_decisions.pyindex e3537f3c..f4ebb7d9 100644--- a/tests/context/test_context_graph_decisions.py+++ b/tests/context/test_context_graph_decisions.py@@ -81,6 +81,43 @@ class TestContextGraphDecisions:assert isinstance(id_from_object, str) and len(id_from_object) > 0assert isinstance(id_from_kwargs, str) and len(id_from_kwargs) > 0+ def test_record_decision_accepts_explicit_decision_id(self, context_graph):+ """Callers that pre-generate an ID (e.g. for an eval case) keep it."""+ decision_id = context_graph.record_decision(+ category="loan",+ scenario="mortgage application",+ reasoning="strong credit history",+ outcome="approved",+ confidence=0.9,+ decision_id="custom-decision-id",+ )++ assert decision_id == "custom-decision-id"+ assert "custom-decision-id" in context_graph.nodes+ assert context_graph._decisions[decision_id]["category"] == "loan"++ def test_record_decision_rejects_duplicate_explicit_decision_id(+ self, context_graph+ ):+ context_graph.record_decision(+ category="loan",+ scenario="mortgage application",+ reasoning="strong credit history",+ outcome="approved",+ confidence=0.9,+ decision_id="custom-decision-id",+ )++ with pytest.raises(ValueError, match="already exists"):+ context_graph.record_decision(+ category="loan",+ scenario="another application",+ reasoning="another reason",+ outcome="approved",+ confidence=0.8,+ decision_id="custom-decision-id",+ )+def test_add_decision_with_embeddings(self, context_graph):"""Test adding decision with embeddings."""decision = Decision(diff --git a/tests/context/test_decision_eval_hook.py b/tests/context/test_decision_eval_hook.pyindex d77ad7a1..9e310b49 100644--- a/tests/context/test_decision_eval_hook.py+++ b/tests/context/test_decision_eval_hook.py@@ -12,6 +12,7 @@ from unittest.mock import Mockimport pytestfrom semantica.context.agent_context import AgentContext+from semantica.context.context_graph import ContextGraphfrom semantica.context.decision_models import Decisionfrom semantica.context.decision_recorder import DecisionRecorderfrom semantica.evals.types import CaseResult, EvalMetric, EvalSummary@@ -277,3 +278,161 @@ class TestAgentContextEvalHookWiring:assert context._decision_recorder.evaluators is Noneassert context._decision_recorder.eval_config == {}+++class TestAgentContextContextGraphEvalHook:+ """Evaluators must run on the ContextGraph backend too.++ ``AgentContext`` documents ``evaluators``/``eval_config`` as applying to+ the graph_store decision backend in 0.8.0, leaving the ContextGraph+ backend as a known follow-up. The constructor accepts the options either+ way, so the ContextGraph path must not silently ignore them.+ """++ @pytest.fixture(autouse=True)+ def _stub_node_embedder(self, monkeypatch):+ monkeypatch.setattr(+ "semantica.vector_store.decision_embedding_pipeline.NodeEmbedder", Mock()+ )+ monkeypatch.setattr("semantica.context.decision_query.NodeEmbedder", Mock())++ @pytest.fixture+ def vector_store(self):+ store = Mock()+ store.add = Mock()+ store.search = Mock(return_value=[])+ return store++ def _record(self, vector_store, cross_system_context=None, **context_kwargs):+ graph = ContextGraph()+ context = AgentContext(+ vector_store=vector_store,+ knowledge_graph=graph,+ decision_tracking=True,+ **context_kwargs,+ )+ decision_id = context.record_decision(+ category="loan",+ scenario="mortgage application",+ reasoning="strong credit history",+ outcome="approved",+ confidence=0.95,+ decision_maker="loan_officer",+ cross_system_context=cross_system_context,+ )+ return graph, decision_id++ def test_evaluators_run_for_context_graph_backend(self, vector_store):+ graph, decision_id = self._record(+ vector_store,+ evaluators=["decision_scores"],+ eval_config={"decision_scores": {"expected_outcome": "approved"}},+ )++ props = graph.nodes[decision_id].properties+ assert props["eval_score"] == pytest.approx(5 / 6)+ assert props["eval_passed"] is False # no provenance in this path+ assert props["eval_details"]["decision_scores"]["meta"]["provenance"] is False++ def test_no_evaluators_leaves_context_graph_decision_unchanged(self, vector_store):+ graph, decision_id = self._record(vector_store)++ props = graph.nodes[decision_id].properties+ assert "eval_score" not in props+ assert "eval_passed" not in props+ assert "eval_details" not in props++ def test_cross_system_context_and_eval_metadata_are_merged(self, vector_store):+ graph, decision_id = self._record(+ vector_store,+ cross_system_context={"ticket": "T-1"},+ evaluators=["decision_scores"],+ )++ props = graph.nodes[decision_id].properties+ assert props["cross_system_context"] == {"ticket": "T-1"}+ assert props["eval_passed"] is False+ assert "eval_details" in props++ def test_evaluator_failure_does_not_block_context_graph_recording(+ self, vector_store, monkeypatch, caplog+ ):+ monkeypatch.setattr(+ "semantica.evals.evaluate",+ Mock(side_effect=RuntimeError("boom")),+ )++ with caplog.at_level(logging.WARNING):+ graph, decision_id = self._record(+ vector_store, evaluators=["decision_scores"]+ )++ assert decision_id in graph.nodes+ props = graph.nodes[decision_id].properties+ assert "eval_score" not in props+ assert "eval_passed" not in props+ assert any(+ "Decision evaluation failed" in record.message for record in caplog.records+ )++ def test_evaluator_sees_the_persisted_decision_id(self, vector_store, monkeypatch):+ seen = {}++ def fake_evaluate(cases, evaluators, config):+ seen["decision_id"] = cases[0]["actual"].decision_id+ return EvalSummary(+ total=1,+ passed=1,+ failed=0,+ errors=0,+ pass_rate=1.0,+ cases=[+ CaseResult(+ case_id=seen["decision_id"],+ status="pass",+ metrics={"decision_scores": EvalMetric(1.0, True, {})},+ details={},+ )+ ],+ )++ monkeypatch.setattr("semantica.evals.evaluate", fake_evaluate)++ graph, decision_id = self._record(vector_store, evaluators=["decision_scores"])++ assert seen["decision_id"] == decision_id+ assert decision_id in graph.nodes++ def test_long_eval_details_are_omitted_without_blocking_recording(+ self, vector_store, caplog+ ):+ # ContextGraph caps metadata values at 1,000 characters; the evaluator+ # echoes a valid but long outcome into its mismatch reason.+ long_outcome = "approved" + "x" * 990++ graph = ContextGraph()+ context = AgentContext(+ vector_store=vector_store,+ knowledge_graph=graph,+ decision_tracking=True,+ evaluators=["decision_scores"],+ eval_config={"decision_scores": {"expected_outcome": "approved"}},+ )+ with caplog.at_level(logging.WARNING):+ decision_id = context.record_decision(+ category="loan",+ scenario="mortgage application",+ reasoning="strong credit history",+ outcome=long_outcome,+ confidence=0.95,+ decision_maker="loan_officer",+ )++ assert decision_id in graph.nodes+ props = graph.nodes[decision_id].properties+ assert props["eval_score"] < 1.0+ assert props["eval_passed"] is False+ assert "eval_details" not in props+ assert any(+ "metadata value limit" in record.message for record in caplog.records+ )