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): remap temporal subcommands onto the v0.7.0 engine APIs (#1987)
Charan Rathore14c1daf5e32a
diff --git a/semantica/cli.py b/semantica/cli.pyindex dc3b610a..3937c689 100644--- a/semantica/cli.py+++ b/semantica/cli.py@@ -32,6 +32,7 @@ if sys.platform == "win32":sys.stderr.reconfigure(encoding="utf-8", errors="replace")from dataclasses import asdict, dataclass, field, is_dataclass+from datetime import datetime, timezonefrom pathlib import Path, PurePosixPath, PureWindowsPathfrom types import SimpleNamespacefrom typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List,@@ -3680,13 +3681,88 @@ def temporal(ctx: click.Context) -> None:click.echo(ctx.get_help())+def _load_temporal_kg(cli_ctx: CLIContext) -> Dict[str, Any]:+ """Load the CLI's persisted graph in the ``{"entities", "relationships"}``+ shape the temporal engines consume."""+ if not _uses_memory_graph(cli_ctx):+ raise click.ClickException(+ "The temporal commands read the CLI's persisted memory-backend "+ "graph and are not wired for the "+ f"{_resolve_graph_backend(cli_ctx)!r} backend yet."+ )+ from .kg.temporal_model import parse_temporal_value++ graph = _load_context_graph(cli_ctx).to_kg_dict()+ # The export keeps ``recorded_at`` inside properties/metadata, but the+ # temporal engines read temporal fields at the fact's top level. Lift it+ # (normalised to UTC) so a fact recorded without explicit validity dates+ # still has a history event.+ for fact in (*graph.get("entities", []), *graph.get("relationships", [])):+ if "recorded_at" in fact:+ continue+ recorded_at = (fact.get("properties") or {}).get("recorded_at") or (+ fact.get("metadata") or {}+ ).get("recorded_at")+ parsed = parse_temporal_value(recorded_at) if recorded_at is not None else None+ if parsed is not None:+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ fact["recorded_at"] = parsed.isoformat()+ return graph+++def _parse_allen_interval(spec: str) -> Any:+ """Parse a ``start/end`` interval spec into a ``TemporalInterval``.++ Values keep their exact precision instead of being normalised to a+ granularity: expanding the end to the last microsecond of its second (as+ ``normalize_interval`` does) makes an end that equals the next interval's+ start report ``overlaps`` where Allen algebra says ``meets``.+ """+ from .kg.temporal_model import (+ TemporalBound,+ parse_temporal_bound,+ parse_temporal_value,+ )+ from .kg.temporal_reasoning import TemporalInterval++ parts = spec.split("/", 1)+ if len(parts) != 2 or not parts[0].strip() or not parts[1].strip():+ raise click.ClickException(+ f"Interval must be given as start/end, got: {spec!r}"+ )+ start = parse_temporal_value(parts[0].strip())+ if start is None:+ raise click.ClickException(f"Invalid interval start: {parts[0].strip()!r}")+ end: Any = parse_temporal_bound(parts[1].strip(), default=TemporalBound.OPEN)+ if end is not TemporalBound.OPEN:+ end = parse_temporal_value(end)+ if end is None:+ raise click.ClickException(f"Invalid interval end: {parts[1].strip()!r}")+ # Keep naive values comparable with aware ones inside relation().+ if start.tzinfo is None:+ start = start.replace(tzinfo=timezone.utc)+ if isinstance(end, datetime) and end.tzinfo is None:+ end = end.replace(tzinfo=timezone.utc)+ if isinstance(end, datetime) and end < start:+ raise click.ClickException(f"Interval end precedes its start: {spec!r}")+ return TemporalInterval(start=start, end=end)++@temporal.command("snapshot")@click.option("--at", "at_time", required=True, help="ISO 8601 datetime.")[email protected]("--format", "fmt", type=click.Choice(["json", "table"]),- default="json", show_default=True)+ "--format",+ "fmt",+ type=click.Choice(["json", "table"]),+ default="json",+ show_default=True,+)@click.option("--json", "local_json", is_flag=True, default=False)@click.pass_obj-def temporal_snapshot(cli_ctx: CLIContext, at_time: str, fmt: str, local_json: bool) -> None:+def temporal_snapshot(+ cli_ctx: CLIContext, at_time: str, fmt: str, local_json: bool+) -> None:"""Graph state at a specific point in time.\b@@ -3698,10 +3774,13 @@ def temporal_snapshot(cli_ctx: CLIContext, at_time: str, fmt: str, local_json: bdef _action() -> None:try:from .kg import TemporalGraphQuery- tgq = TemporalGraphQuery(config=cli_ctx.config.to_dict())- result = tgq.snapshot(at=at_time)except ImportError as exc:- raise click.ClickException(f"KG temporal module not available: {exc}") from exc+ raise click.ClickException(+ f"KG temporal module not available: {exc}"+ ) from exc+ graph = _load_temporal_kg(cli_ctx)+ tgq = TemporalGraphQuery()+ result = tgq.reconstruct_at_time(graph, at_time)if _is_json(cli_ctx, local_json) or fmt == "json":_jecho(result if isinstance(result, dict) else {"snapshot": str(result)})else:@@ -3712,21 +3791,41 @@ def temporal_snapshot(cli_ctx: CLIContext, at_time: str, fmt: str, local_json: b@temporal.command("query")@click.argument("query_str")+ "--at",+ "at_time",+ default=None,+ help="ISO 8601 datetime to query at (defaults to the current time).",+)@click.option("--json", "local_json", is_flag=True, default=False)@click.pass_obj-def temporal_query(cli_ctx: CLIContext, query_str: str, local_json: bool) -> None:- """Temporal-aware graph query."""+def temporal_query(+ cli_ctx: CLIContext, query_str: str, at_time: Optional[str], local_json: bool+) -> None:+ """Temporal-aware graph query.++ \b+ Note: the query string is reserved for future query parsing; the result is+ currently the graph slice valid at --at regardless of its content.+ """cli_ctx = _require_ctx(cli_ctx)def _action() -> None:try:from .kg import TemporalGraphQuery- tgq = TemporalGraphQuery(config=cli_ctx.config.to_dict())- result = tgq.query(query_str)except ImportError as exc:- raise click.ClickException(f"KG temporal module not available: {exc}") from exc+ raise click.ClickException(+ f"KG temporal module not available: {exc}"+ ) from exc+ graph = _load_temporal_kg(cli_ctx)+ tgq = TemporalGraphQuery()+ result = tgq.query_at_time(+ graph, query_str, at_time or datetime.now(timezone.utc)+ )if _is_json(cli_ctx, local_json):- _jecho(result if isinstance(result, (dict, list)) else {"result": str(result)})+ _jecho(+ result if isinstance(result, (dict, list)) else {"result": str(result)}+ )else:_pprint(cli_ctx, result)@@ -3739,8 +3838,13 @@ def temporal_query(cli_ctx: CLIContext, query_str: str, local_json: bool) -> Non@click.option("--format", "fmt", type=click.Choice(["table", "json"]), default="table")@click.option("--json", "local_json", is_flag=True, default=False)@click.pass_obj-def temporal_history(cli_ctx: CLIContext, entity_id: str, since: Optional[str],- fmt: str, local_json: bool) -> None:+def temporal_history(+ cli_ctx: CLIContext,+ entity_id: str,+ since: Optional[str],+ fmt: str,+ local_json: bool,+) -> None:"""Change history for an entity.\b@@ -3751,39 +3855,85 @@ def temporal_history(cli_ctx: CLIContext, entity_id: str, since: Optional[str],def _action() -> None:try:- from .kg import TemporalVersionManager- tvm = TemporalVersionManager(config=cli_ctx.config.to_dict())- result = tvm.history(entity_id, since=since)+ from .kg.temporal_reasoning import TemporalReasoningEngine+ from .kg.temporal_model import (+ parse_temporal_value,+ temporal_structure_to_json_ready,+ )except ImportError as exc:- raise click.ClickException(f"KG temporal module not available: {exc}") from exc+ raise click.ClickException(+ f"KG temporal module not available: {exc}"+ ) from exc+ graph = _load_temporal_kg(cli_ctx)+ events = TemporalReasoningEngine().timeline_of(entity_id, graph)+ if since:+ since_dt = parse_temporal_value(since)+ if since_dt is not None:+ if since_dt.tzinfo is None:+ since_dt = since_dt.replace(tzinfo=timezone.utc)++ def _aware(ts: datetime) -> datetime:+ return (+ ts if ts.tzinfo is not None else ts.replace(tzinfo=timezone.utc)+ )++ events = [+ event for event in events if _aware(event["timestamp"]) >= since_dt+ ]if _is_json(cli_ctx, local_json) or fmt == "json":- _jecho(result if isinstance(result, list) else [])+ # Serialize through the kg temporal helpers so timestamps are ISO+ # 8601, consistent with `temporal distance --json`, instead of the+ # space-separated str() form _jecho's default=str produces.+ _jecho(+ temporal_structure_to_json_ready(+ events if isinstance(events, list) else []+ )+ )else:- _pprint(cli_ctx, result)+ _pprint(cli_ctx, events)_run_with_error_handling(_action)@temporal.command("distance")[email protected]("--event1", required=True)[email protected]("--event2", required=True)[email protected]("--history", is_flag=True, default=False)[email protected]("--event1", required=True, help="First timestamp (ISO 8601).")[email protected]("--event2", required=True, help="Second timestamp (ISO 8601).")@click.option("--json", "local_json", is_flag=True, default=False)@click.pass_obj-def temporal_distance(cli_ctx: CLIContext, event1: str, event2: str,- history: bool, local_json: bool) -> None:- """Temporal distance between two events."""+def temporal_distance(+ cli_ctx: CLIContext, event1: str, event2: str, local_json: bool+) -> None:+ """Temporal distance between two timestamps."""cli_ctx = _require_ctx(cli_ctx)def _action() -> None:try:- from .kg import TemporalGraphQuery- tgq = TemporalGraphQuery(config=cli_ctx.config.to_dict())- result = tgq.distance(event1, event2, include_history=history)+ from .kg.temporal_model import parse_temporal_valueexcept ImportError as exc:- raise click.ClickException(f"KG temporal module not available: {exc}") from exc+ raise click.ClickException(+ f"KG temporal module not available: {exc}"+ ) from exc+ # Exact values, not a granularity: rounding to whole seconds first+ # collapses any distance smaller than a second to zero.+ t1 = parse_temporal_value(event1)+ t2 = parse_temporal_value(event2)+ if t1 is None or t2 is None:+ raise click.ClickException(+ f"Could not parse timestamp(s): {event1!r}, {event2!r}"+ )+ if t1.tzinfo is None:+ t1 = t1.replace(tzinfo=timezone.utc)+ if t2.tzinfo is None:+ t2 = t2.replace(tzinfo=timezone.utc)+ seconds = abs((t2 - t1).total_seconds())+ result = {+ "event1": t1.isoformat(),+ "event2": t2.isoformat(),+ "distance_seconds": seconds,+ "distance_days": seconds / 86400,+ }if _is_json(cli_ctx, local_json):- _jecho(result if isinstance(result, dict) else {"distance": str(result)})+ _jecho(result)else:_pprint(cli_ctx, result)@@ -3791,26 +3941,42 @@ def temporal_distance(cli_ctx: CLIContext, event1: str, event2: str,@temporal.command("allen")[email protected]("--interval1", required=True)[email protected]("--interval2", required=True)+ "--interval1", required=True, help="First interval as start/end (ISO 8601)."+)+ "--interval2", required=True, help="Second interval as start/end (ISO 8601)."+)@click.option("--json", "local_json", is_flag=True, default=False)@click.pass_obj-def temporal_allen(cli_ctx: CLIContext, interval1: str, interval2: str,- local_json: bool) -> None:+def temporal_allen(+ cli_ctx: CLIContext, interval1: str, interval2: str, local_json: bool+) -> None:"""Allen interval algebra relation between two intervals."""cli_ctx = _require_ctx(cli_ctx)def _action() -> None:try:- from .reasoning import TemporalReasoningEngine- engine = TemporalReasoningEngine(config=cli_ctx.config.to_dict())- result = engine.allen_relation(interval1, interval2)+ from .kg.temporal_reasoning import TemporalReasoningEngineexcept ImportError as exc:- raise click.ClickException(f"Reasoning module not available: {exc}") from exc+ raise click.ClickException(+ f"Reasoning module not available: {exc}"+ ) from exc+ engine = TemporalReasoningEngine()+ iv1 = _parse_allen_interval(interval1)+ iv2 = _parse_allen_interval(interval2)+ relation = engine.relation(iv1, iv2)+ relation_name = relation.value if hasattr(relation, "value") else str(relation)if _is_json(cli_ctx, local_json):- _jecho({"interval1": interval1, "interval2": interval2, "relation": str(result)})+ _jecho(+ {+ "interval1": interval1,+ "interval2": interval2,+ "relation": relation_name,+ }+ )else:- console.print(f"{interval1} ── {result} ──► {interval2}")+ console.print(f"{interval1} ── {relation_name} ──► {interval2}")_run_with_error_handling(_action)diff --git a/semantica/kg/temporal_query.py b/semantica/kg/temporal_query.pyindex c335c95c..4ebfb290 100644--- a/semantica/kg/temporal_query.py+++ b/semantica/kg/temporal_query.py@@ -198,8 +198,12 @@ class TemporalGraphQuery:for relationship in graph.get("relationships", []):if not self._relationship_active_at_time(relationship, query_time, time_axis=time_axis):continue- source = self._entity_id({"id": relationship.get("source")})- target = self._entity_id({"id": relationship.get("target")})+ source = self._entity_id(+ {"id": relationship.get("source") or relationship.get("source_id")}+ )+ target = self._entity_id(+ {"id": relationship.get("target") or relationship.get("target_id")}+ )if source not in entity_index or target not in entity_index:continuerelationships.append(copy.deepcopy(relationship))diff --git a/semantica/kg/temporal_reasoning.py b/semantica/kg/temporal_reasoning.pyindex f715eeef..6320696b 100644--- a/semantica/kg/temporal_reasoning.py+++ b/semantica/kg/temporal_reasoning.py@@ -172,7 +172,9 @@ class TemporalReasoningEngine:events.extend(self._events_for_fact(fact))for fact in graph.get("relationships", []):- if str(fact.get("source")) != entity_key and str(fact.get("target")) != entity_key:+ source_key = str(fact.get("source") or fact.get("source_id"))+ target_key = str(fact.get("target") or fact.get("target_id"))+ if source_key != entity_key and target_key != entity_key:continueevents.extend(self._events_for_fact(fact))diff --git a/tests/cli/test_cli_temporal.py b/tests/cli/test_cli_temporal.pynew file mode 100644index 00000000..bc675d33--- /dev/null+++ b/tests/cli/test_cli_temporal.py@@ -0,0 +1,312 @@+"""Smoke tests for the 'semantica temporal' CLI subcommands (issue #1809).++All five subcommands crashed on v0.7.0 because the CLI wrappers called methods+that no longer exist on the temporal engine classes. These tests drive each+subcommand through CliRunner against a tiny fixture graph so that class of+drift fails loudly.+"""++import json++from click.testing import CliRunner+import pytest++import semantica.cli as cli_module+++def runner() -> CliRunner:+ return CliRunner()++[email protected](autouse=True)+def silence_logging(monkeypatch):+ monkeypatch.setattr(cli_module, "setup_logging", lambda *a, **kw: None)+++def fixture_graph(monkeypatch):+ """Serve a tiny temporal graph through the memory backend loader."""+ from semantica.context import ContextGraph++ graph = ContextGraph()+ graph.add_node(+ "entity_alice",+ "entity",+ "Alice",+ valid_from="2025-01-01T00:00:00Z",+ valid_until="2025-02-01T00:00:00Z",+ )+ graph.add_node("entity_bob", "entity", "Bob", valid_from="2025-01-10T00:00:00Z")+ graph.add_edge(+ "entity_alice",+ "entity_bob",+ "knows",+ valid_from="2025-01-05T00:00:00Z",+ valid_until="2025-01-20T00:00:00Z",+ )+ monkeypatch.setattr(cli_module, "_load_context_graph", lambda cli_ctx: graph)+ return graph+++class TestTemporalSnapshot:+ def test_snapshot_returns_graph_state_at_time(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main, ["temporal", "snapshot", "--at", "2025-01-15T00:00:00Z"]+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert "entities" in payload+ rel_types = [r.get("type") for r in payload["relationships"]]+ assert "knows" in rel_types++ def test_snapshot_after_edge_expired_excludes_it(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main, ["temporal", "snapshot", "--at", "2025-01-25T00:00:00Z"]+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ rel_types = [r.get("type") for r in payload["relationships"]]+ assert "knows" not in rel_types+++class TestTemporalQuery:+ def test_query_at_time(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main,+ ["temporal", "query", "status", "--at", "2025-01-15T00:00:00Z", "--json"],+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["query"] == "status"+ assert payload["num_relationships"] == 1++ def test_query_defaults_to_now(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main, ["temporal", "query", "status", "--json"]+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert "at_time" in payload+++class TestTemporalHistory:+ def test_history_lists_entity_events(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main, ["temporal", "history", "entity_alice", "--format", "json"]+ )+ assert result.exit_code == 0+ events = json.loads(result.output)+ assert len(events) > 0+ change_types = {event["change_type"] for event in events}+ assert "added" in change_types++ def test_history_since_filter(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "history",+ "entity_alice",+ "--since",+ "2025-01-15",+ "--format",+ "json",+ ],+ )+ assert result.exit_code == 0+ events = json.loads(result.output)+ for event in events:+ assert event["timestamp"] >= "2025-01-15"++ def test_history_unknown_entity_is_empty(self, runner, fixture_graph):+ result = runner.invoke(+ cli_module.main, ["temporal", "history", "nobody", "--format", "json"]+ )+ assert result.exit_code == 0+ assert json.loads(result.output) == []+++class TestTemporalDistance:+ def test_distance_between_timestamps(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "distance",+ "--event1",+ "2025-01-01T00:00:00Z",+ "--event2",+ "2025-01-05T12:00:00Z",+ "--json",+ ],+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["distance_seconds"] == 388800.0+ assert payload["distance_days"] == 4.5++ def test_distance_is_absolute(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "distance",+ "--event1",+ "2025-01-05T12:00:00Z",+ "--event2",+ "2025-01-01T00:00:00Z",+ "--json",+ ],+ )+ assert result.exit_code == 0+ assert json.loads(result.output)["distance_seconds"] == 388800.0++ def test_distance_rejects_garbage_timestamp(self, runner):+ result = runner.invoke(+ cli_module.main,+ ["temporal", "distance", "--event1", "a", "--event2", "b"],+ )+ assert result.exit_code != 0+++class TestTemporalAllen:+ def test_allen_overlaps(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "allen",+ "--interval1",+ "2025-01-01/2025-01-05",+ "--interval2",+ "2025-01-03/2025-01-08",+ "--json",+ ],+ )+ assert result.exit_code == 0+ assert json.loads(result.output)["relation"] == "overlaps"++ def test_allen_before(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "allen",+ "--interval1",+ "2025-01-01/2025-01-02",+ "--interval2",+ "2025-02-01/2025-02-05",+ "--json",+ ],+ )+ assert result.exit_code == 0+ assert json.loads(result.output)["relation"] == "before"++ def test_allen_rejects_malformed_interval(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "allen",+ "--interval1",+ "not-an-interval",+ "--interval2",+ "2025-01-01/2025-01-02",+ ],+ )+ assert result.exit_code != 0+++class TestTemporalPrecisionAndHistoryFixes:+ """Regression tests for review findings on the temporal CLI remap."""++ def test_allen_adjacent_intervals_meet(self, runner):+ # An end that equals the next interval's start is "meets", not+ # "overlaps": end-of-second expansion must not smear the boundary.+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "allen",+ "--interval1",+ "2025-01-01T00:00:00Z/2025-01-01T01:00:00Z",+ "--interval2",+ "2025-01-01T01:00:00Z/2025-01-01T02:00:00Z",+ "--json",+ ],+ )+ assert result.exit_code == 0+ assert json.loads(result.output)["relation"] == "meets"++ def test_allen_rejects_end_before_start(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "allen",+ "--interval1",+ "2025-01-02T00:00:00Z/2025-01-01T00:00:00Z",+ "--interval2",+ "2025-01-01T00:00:00Z/2025-01-03T00:00:00Z",+ ],+ )+ assert result.exit_code != 0++ def test_distance_preserves_subsecond_precision(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "temporal",+ "distance",+ "--event1",+ "2025-01-01T00:00:00.500+00:00",+ "--event2",+ "2025-01-01T00:00:00.900+00:00",+ "--json",+ ],+ )+ assert result.exit_code == 0+ payload = json.loads(result.output)+ assert payload["distance_seconds"] == pytest.approx(0.4)+ assert ".500" in payload["event1"]++ def test_history_includes_recording_event_without_validity_dates(+ self, runner, monkeypatch+ ):+ # A decision recorded without explicit validity dates still has a+ # recorded_at, which must surface in its timeline.+ from semantica.context import ContextGraph++ graph = ContextGraph()+ graph.add_node(+ "decision_1",+ "decision",+ "Approve vendor X",+ recorded_at="2025-03-01T12:00:00Z",+ )+ monkeypatch.setattr(cli_module, "_load_context_graph", lambda cli_ctx: graph)+ result = runner.invoke(+ cli_module.main, ["temporal", "history", "decision_1", "--format", "json"]+ )+ assert result.exit_code == 0+ events = json.loads(result.output)+ assert len(events) == 1+ # ISO 8601 through serialize_temporal_value, consistent with+ # `temporal distance --json`, not the space-separated str() form.+ assert events[0]["timestamp"].startswith("2025-03-01T12:00:00")++ def test_temporal_commands_reject_non_memory_backend(self, runner):+ result = runner.invoke(+ cli_module.main,+ [+ "--store",+ "neo4j",+ "temporal",+ "snapshot",+ "--at",+ "2025-01-15T00:00:00Z",+ ],+ )+ assert result.exit_code != 0+ assert "not wired for the 'neo4j' backend yet" in result.output