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
fix(cli): dispatch reason run and store connect to real APIs (#1372)
BingEdward14d25cabcd11
diff --git a/semantica/cli.py b/semantica/cli.pyindex be0a5514..cb1961c4 100644--- a/semantica/cli.py+++ b/semantica/cli.py@@ -1155,6 +1155,57 @@ def _get_graph_store(cli_ctx: CLIContext) -> Any:return GraphStore(backend=backend, **graph_db)+def _load_rule_definitions(path: str) -> List[str]:+ """Load reasoning rule definitions from a YAML or plain-text rules file.++ YAML files may hold a list of rule strings or a mapping with a ``rules``+ list; anything else (e.g. Datalog) is read as one rule per non-comment+ line. The strings are handed to ``Reasoner.add_rule()`` untouched.+ """+ text = Path(path).read_text(encoding="utf-8")+ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError:+ data = None+ if isinstance(data, dict):+ rules_value = data.get("rules")+ if rules_value is None and "rules" not in data:+ raise click.ClickException(+ f"Rules file '{path}' is a YAML mapping but has no 'rules' key. "+ "Expected either a YAML list or a mapping with a 'rules' list."+ )+ data = rules_value+ if isinstance(data, list):+ return [str(item) for item in data]+ return [line.strip() for line in text.splitlines()+ if line.strip() and not line.lstrip().startswith("#")]+++def _graph_store_facts(cli_ctx: CLIContext) -> List[str]:+ """Read the configured graph store into Reasoner fact strings.++ Follows the same conventions ``Reasoner.add_fact()`` applies to+ KG-style dicts: nodes become ``Label(name)`` and relationships become+ ``TYPE(source, target)``, with internal node ids resolved to names.+ """+ gs = _get_graph_store(cli_ctx)+ nodes = gs.get_nodes(limit=sys.maxsize)+ relationships = gs.get_relationships(limit=sys.maxsize)+ names: Dict[Any, Any] = {}+ facts: List[str] = []+ for node in nodes:+ props = node.get("properties") or {}+ name = props.get("name") or props.get("id") or node.get("id")+ names[node.get("id")] = name+ for label in node.get("labels") or ["Entity"]:+ facts.append(f"{label}({name})")+ for rel in relationships:+ source = names.get(rel.get("start_node_id"), rel.get("start_node_id"))+ target = names.get(rel.get("end_node_id"), rel.get("end_node_id"))+ facts.append(f"{rel.get('type', 'RELATED_TO')}({source}, {target})")+ return facts++# ─── Output helpers ──────────────────────────────────────────────────────────@@ -2212,17 +2263,43 @@ def reason_run(cli_ctx: CLIContext, engine: str, rules: Optional[str],cli_ctx = _require_ctx(cli_ctx)def _action() -> None:+ # Only the forward-chaining production-rule engines run through+ # Reasoner.infer_facts(); the other engines take different inputs+ # (SPARQL/Datalog queries, observations, premises) and are not wired+ # to this command yet. Fail honestly instead of silently+ # forward-chaining under another engine's name.+ if engine not in ("rete", "forward-chain"):+ hint = (" Use 'semantica reason query' for SPARQL/Datalog queries."+ if engine in ("sparql", "datalog") else "")+ raise click.ClickException(+ f"Engine '{engine}' is not wired to 'reason run' yet; "+ f"supported engines: rete, forward-chain.{hint}")try:from .reasoning import Reasoner+ # Reasoner has no run() method (#1354); dispatch to its real+ # API: facts from the configured graph store + rules from the+ # optional --rules file into infer_facts().r = Reasoner(engine=engine, config=cli_ctx.config.to_dict())+ rule_defs = _load_rule_definitions(rules) if rules else None+ facts = _graph_store_facts(cli_ctx)++ def _infer() -> Dict[str, Any]:+ inferred = r.infer_facts(facts, rule_defs)+ return {+ "engine": engine,+ "facts": len(facts),+ "inferred_count": len(inferred),+ "inferred_facts": inferred,+ }+if cli_ctx.quiet or cli_ctx.json_output:- result = r.run(rules_file=rules)+ result = _infer()else:with console.status(f"[{_DIM}]Running {engine} reasoning engine…[/{_DIM}]",spinner="dots",):- result = r.run(rules_file=rules)+ result = _infer()except ImportError as exc:raise click.ClickException(f"Reasoning module not available: {exc}") from excif _is_json(cli_ctx, local_json):@@ -3713,14 +3790,17 @@ def store_connect(cli_ctx: CLIContext, backend: str, uri: Optional[str], local_jdef _action() -> None:try:- from .graph_store import get_graph_store_method- store_cls = get_graph_store_method(backend)+ # get_graph_store_method(task, method_name) is the method+ # registry, not a backend factory (#1354); build the store+ # through GraphStore, which resolves the backend by name.+ from .graph_store import GraphStorecfg = dict(cli_ctx.config.to_dict().get("graph_db", {}))+ cfg.pop("backend", None)if uri:cfg["uri"] = uri- # Attempt instantiation as the minimal connectivity probe; backends- # that require a live connection will fail here if unreachable.- store_instance = store_cls(config=cfg)+ # Instantiation only wires the backend; the probe below performs+ # the live connectivity check and raises if unreachable.+ store_instance = GraphStore(backend=backend, **cfg)for probe in ("health_check", "ping", "connect"):fn = getattr(store_instance, probe, None)if callable(fn):diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.pyindex add37b27..a50868b0 100644--- a/tests/test_cli_commands.py+++ b/tests/test_cli_commands.py@@ -857,6 +857,156 @@ class TestReason:assert result.exit_code != 0assert "Traceback" not in result.output+ def test_run_infers_from_graph_store_facts(self, runner, monkeypatch, tmp_path):+ # reason run used to call Reasoner.run(), which does not exist+ # (#1354); it must feed graph store facts + --rules into+ # Reasoner.infer_facts().+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")+ rules_file = tmp_path / "rules.yaml"+ rules_file.write_text(+ '- IF Person(?x) THEN Human(?x)\n'+ '- IF MANAGES(?x, ?y) THEN Manager(?x)\n'+ '- IF Employee(?x) THEN Staff(?x)\n',+ encoding="utf-8")++ class _FakeStore:+ # Same dict schema as the real backends: nodes carry+ # labels/properties, relationships carry start_node_id/end_node_id.+ def get_nodes(self, limit=None):+ return [{"id": 1, "labels": ["Person"],+ "properties": {"name": "Alice"}},+ {"id": 2, "labels": ["Person", "Employee"],+ "properties": {"name": "Bob"}}]++ def get_relationships(self, limit=None):+ return [{"id": 9, "type": "MANAGES",+ "start_node_id": 1, "end_node_id": 2}]++ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())+ result = runner.invoke(+ cli_module.main,+ ["--json", "reason", "run", "--rules", str(rules_file)],+ )+ _ok(result)+ data = json.loads(result.output.strip())+ # Person(Alice), Person(Bob), Employee(Bob), MANAGES(Alice, Bob)+ assert data["facts"] == 4+ assert "Human(Alice)" in data["inferred_facts"]+ # Relationship endpoints resolve node ids to names.+ assert "Manager(Alice)" in data["inferred_facts"]+ # Secondary labels also become facts.+ assert "Staff(Bob)" in data["inferred_facts"]+ assert data["inferred_count"] == len(data["inferred_facts"])++ def test_run_rejects_unwired_engine(self, runner):+ result = runner.invoke(cli_module.main,+ ["reason", "run", "--engine", "sparql"])+ assert result.exit_code != 0+ assert "not wired" in result.output+ assert "reason query" in result.output+ assert "Traceback" not in result.output++ def test_load_rule_definitions_formats(self, tmp_path):+ yaml_list = tmp_path / "list.yaml"+ yaml_list.write_text('- IF A(?x) THEN B(?x)\n- IF B(?x) THEN C(?x)\n',+ encoding="utf-8")+ assert cli_module._load_rule_definitions(str(yaml_list)) == [+ "IF A(?x) THEN B(?x)", "IF B(?x) THEN C(?x)"]++ yaml_map = tmp_path / "map.yaml"+ yaml_map.write_text('rules:\n - IF A(?x) THEN B(?x)\n', encoding="utf-8")+ assert cli_module._load_rule_definitions(str(yaml_map)) == [+ "IF A(?x) THEN B(?x)"]++ plain = tmp_path / "rules.dl"+ plain.write_text('# comment\nIF A(?x) THEN B(?x)\n\n', encoding="utf-8")+ assert cli_module._load_rule_definitions(str(plain)) == [+ "IF A(?x) THEN B(?x)"]++ def test_run_empty_graph_returns_zero_facts(self, runner, monkeypatch):+ """reason run with an empty graph store should not crash and report 0 facts."""+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")++ class _EmptyStore:+ def get_nodes(self, limit=None): return []+ def get_relationships(self, limit=None): return []++ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())+ result = runner.invoke(cli_module.main, ["--json", "reason", "run"])+ _ok(result)+ data = json.loads(result.output.strip())+ assert data["facts"] == 0+ assert data["inferred_count"] == 0+ assert data["inferred_facts"] == []++ def test_run_graph_store_error_surfaces_cleanly(self, runner, monkeypatch):+ """A graph-store connectivity error must surface as a clean error, not a Traceback."""++ def _bad_store(ctx):+ raise RuntimeError("connection refused")++ monkeypatch.setattr(cli_module, "_get_graph_store", _bad_store)+ result = runner.invoke(cli_module.main, ["reason", "run"])+ assert result.exit_code != 0+ assert "Traceback" not in result.output+ assert "connection refused" in result.output++ def test_run_no_rules_uses_empty_ruleset(self, runner, monkeypatch):+ """reason run without --rules should still succeed (zero rules -> zero inferences)."""+ pytest.importorskip("numpy", reason="semantica.reasoning needs numpy")++ class _FakeStore:+ def get_nodes(self, limit=None):+ return [{"id": 1, "labels": ["Person"], "properties": {"name": "Alice"}}]++ def get_relationships(self, limit=None):+ return []++ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _FakeStore())+ result = runner.invoke(cli_module.main, ["--json", "reason", "run"])+ _ok(result)+ data = json.loads(result.output.strip())+ assert data["facts"] == 1+ assert data["inferred_count"] == 0++ def test_load_rule_definitions_yaml_mapping_without_rules_key_raises(self, tmp_path):+ """A YAML mapping with no 'rules' key must raise ClickException, not silently+ pass the raw YAML lines as rules."""+ bad = tmp_path / "bad.yaml"+ bad.write_text("some_key: some_value\nother_key: other_value\n", encoding="utf-8")+ import click as _click+ with pytest.raises(_click.ClickException, match="no 'rules' key"):+ cli_module._load_rule_definitions(str(bad))++ def test_load_rule_definitions_empty_file_returns_empty_list(self, tmp_path):+ empty = tmp_path / "empty.yaml"+ empty.write_text("", encoding="utf-8")+ assert cli_module._load_rule_definitions(str(empty)) == []++ def test_load_rule_definitions_yaml_rules_null_falls_to_plaintext(self, tmp_path):+ """rules: null is valid YAML with the key present; the null value is+ not a list, so the function falls through to plain-text parsing and+ returns the literal line (one no-op rule). This documents the edge+ case rather than asserting a specific useful behaviour."""+ f = tmp_path / "null_rules.yaml"+ f.write_text("rules: null\n", encoding="utf-8")+ result = cli_module._load_rule_definitions(str(f))+ # Plain-text fallback: the non-comment, non-blank line becomes a rule.+ assert result == ["rules: null"]++ def test_run_rejects_deductive_engine(self, runner, monkeypatch):+ """Engines other than rete/forward-chain must be rejected with a helpful message."""++ class _EmptyStore:+ def get_nodes(self, limit=None): return []+ def get_relationships(self, limit=None): return []++ monkeypatch.setattr(cli_module, "_get_graph_store", lambda ctx: _EmptyStore())+ result = runner.invoke(cli_module.main, ["reason", "run", "--engine", "deductive"])+ assert result.exit_code != 0+ assert "not wired" in result.output+ assert "Traceback" not in result.output+def test_explain_requires_conclusion(self, runner):result = runner.invoke(cli_module.main, ["reason", "explain"])assert result.exit_code != 0@@ -1436,6 +1586,65 @@ class TestStore:result = runner.invoke(cli_module.main, ["store", "connect", "--backend", "neo4j"])_ok(result)+ def test_connect_dispatches_through_graph_store(self, runner, monkeypatch):+ # store connect used to call get_graph_store_method(backend) — the+ # method registry, which needs (task, method_name) — so it raised a+ # TypeError before any connection attempt (#1354).+ calls = {}++ class _FakeGraphStore:+ def __init__(self, backend=None, **cfg):+ calls["backend"] = backend+ calls["cfg"] = cfg++ def connect(self):+ calls["connected"] = True+ return True++ import semantica.graph_store as gs_mod+ monkeypatch.setattr(gs_mod, "GraphStore", _FakeGraphStore)+ result = runner.invoke(cli_module.main, [+ "store", "connect", "--backend", "neo4j",+ "--uri", "bolt://example:7687", "--json"])+ _ok(result)+ data = _json_output(result)+ assert data == {"backend": "neo4j", "connected": True}+ assert calls["backend"] == "neo4j"+ assert calls["cfg"].get("uri") == "bolt://example:7687"+ assert calls.get("connected") is True++ def test_connect_invalid_backend_reports_error_not_dispatch_error(self, runner):+ """An unknown backend name must produce a meaningful backend error, not a+ Python TypeError from the old get_graph_store_method() dispatch (#1354)."""+ result = runner.invoke(cli_module.main,+ ["store", "connect", "--backend", "does-not-exist"])+ # Exit 0 because store_connect always catches and reports errors gracefully.+ _ok(result)+ # The output must mention the backend, not a Python internal error.+ assert "does-not-exist" in result.output+ assert "TypeError" not in result.output+ assert "Traceback" not in result.output++ def test_connect_backend_error_surfaces_in_json(self, runner, monkeypatch):+ """A connect() failure must appear in JSON output as connected=False with an error field."""++ class _FailingStore:+ def __init__(self, backend=None, **cfg):+ pass++ def connect(self):+ raise RuntimeError("auth failed")++ import semantica.graph_store as gs_mod+ monkeypatch.setattr(gs_mod, "GraphStore", _FailingStore)+ result = runner.invoke(cli_module.main, [+ "store", "connect", "--backend", "neo4j", "--json"])+ _ok(result)+ data = _json_output(result)+ assert data["connected"] is False+ assert "auth failed" in data.get("error", "")+ assert data["backend"] == "neo4j"+def test_migrate_dry_run(self, runner):result = runner.invoke(cli_module.main, ["store", "migrate","--from", "faiss", "--to", "qdrant", "--dry-run"])