Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(cli): serve the memory graph backend from ContextGraph instead of GraphStore (#1765)

Shubham Srivastavaacb67c6cfb12
diff --git a/semantica/cli.py b/semantica/cli.py
index 07921de7..c5840b77 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -6,11 +6,22 @@ enabling users to interact with the framework via terminal commands.
"""
import json
+import contextlib
import os
import re
import sys
import time
+try: # POSIX advisory locking
+ import fcntl
+except ImportError: # pragma: no cover - Windows
+ fcntl = None # type: ignore[assignment]
+
+try: # Windows advisory locking
+ import msvcrt
+except ImportError: # pragma: no cover - POSIX
+ msvcrt = None # type: ignore[assignment]
+
# Reconfigure stdout/stderr to UTF-8 on Windows before any other import
# captures sys.stdout (Rich, Click). This prevents UnicodeEncodeError from
# box-drawing characters and emoji on the default cp1252 code page.
@@ -22,7 +33,9 @@ if sys.platform == "win32":
from dataclasses import asdict, dataclass, field, is_dataclass
from pathlib import Path, PurePosixPath, PureWindowsPath
-from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple
+from types import SimpleNamespace
+from typing import (TYPE_CHECKING, Any, Callable, Dict, Iterator, List,
+ Optional, Sequence, Tuple)
import yaml
@@ -192,6 +205,24 @@ def _load_config_data(file_path: Path) -> Dict[str, Any]:
return config_data
+def default_config_path() -> Path:
+ """The config file `semantica init` writes, loaded when --config is absent."""
+ return Path.home() / ".semantica" / "config.yaml"
+
+
+def _resolve_config_path(config_path: Optional[str]) -> Optional[str]:
+ """Return the config file to load: --config, else init's file if it exists.
+
+ Without this, `semantica init` wrote ``~/.semantica/config.yaml`` and nothing
+ ever read it — so accepting its defaults still left every command using the
+ built-in fallback rather than the backend the user had just chosen (#1481).
+ """
+ if config_path:
+ return config_path
+ default = default_config_path()
+ return str(default) if default.is_file() else None
+
+
def _build_runtime_config(
config_path: Optional[str],
log_level: Optional[str],
@@ -199,8 +230,9 @@ def _build_runtime_config(
"""Resolve CLI config from file plus global flag overrides."""
config_manager = ConfigManager()
- if config_path:
- config_data = _load_config_data(Path(config_path))
+ resolved_path = _resolve_config_path(config_path)
+ if resolved_path:
+ config_data = _load_config_data(Path(resolved_path))
else:
config_data = {}
@@ -409,7 +441,7 @@ def _run_build_command(
allow_file_fallback=False,
)
command_ctx = CLIContext(
- config_path=command_config_path,
+ config_path=_resolve_config_path(command_config_path),
config=cmd_config,
log_level=cli_ctx.log_level,
log_level_override=cli_ctx.log_level_override,
@@ -516,9 +548,7 @@ def _show_startup(cli_ctx: CLIContext) -> None:
if cli_ctx.quiet or cli_ctx.json_output:
return
cfg = cli_ctx.config.to_dict()
- graph_store = (
- cli_ctx.store_backend or cfg.get("graph_db", {}).get("backend", "neo4j")
- )
+ graph_store = _resolve_graph_backend(cli_ctx)
vector_store = (
cli_ctx.vector_store_backend
or cfg.get("vector_store", {}).get("backend", "faiss")
@@ -627,7 +657,7 @@ def main(
global console # noqa: PLW0603
console = Console(no_color=True)
ctx.obj = CLIContext(
- config_path=config_path,
+ config_path=_resolve_config_path(config_path),
config=config,
log_level=effective_log_level,
log_level_override=log_level.upper() if log_level else None,
@@ -902,8 +932,14 @@ def doctor(cli_ctx: CLIContext, local_json: bool, deep_embeddings: bool) -> None
# Graph store reachability
def _graph() -> str:
- cfg = cli_ctx.config.to_dict()
- backend = cli_ctx.store_backend or cfg.get("graph_db", {}).get("backend", "neo4j")
+ backend = _resolve_graph_backend(cli_ctx)
+ if backend == MEMORY_GRAPH_BACKEND:
+ # No server to reach; prove the graph file is readable instead,
+ # which is the only way this backend can actually fail.
+ # Keep this short: the Note column truncates at 80 columns.
+ graph = _load_context_graph(cli_ctx)
+ count = len(graph.get_nodes_by_label("decision"))
+ return f"memory, {count} decision(s)"
gs = _get_graph_store(cli_ctx)
gs.ping() if hasattr(gs, "ping") else gs.connect()
return f"{backend} reachable"
@@ -1223,15 +1259,243 @@ def build_alias(
# ─── Graph store helper ──────────────────────────────────────────────────────
+MEMORY_GRAPH_BACKEND = "memory"
+_NO_RATIONALE = "(no rationale provided)"
+_LOCK_TIMEOUT_SECONDS = 10.0
+# `semantica init` offers memory as its default and ContextGraph serves it
+# without any server, so it is also the fallback when nothing is configured.
+_DEFAULT_GRAPH_BACKEND = MEMORY_GRAPH_BACKEND
+
+
+def _resolve_graph_backend(cli_ctx: CLIContext) -> str:
+ """Return the graph backend this invocation will actually use.
+
+ Single source of truth for the three places that used to resolve this
+ independently (status, ``doctor`` and ``_get_graph_store``) with two
+ different defaults — the inconsistency behind #1481.
+ """
+ graph_db = cli_ctx.config.to_dict().get("graph_db", {})
+ return cli_ctx.store_backend or graph_db.get(
+ "backend", _DEFAULT_GRAPH_BACKEND
+ )
+
+
+def _uses_memory_graph(cli_ctx: CLIContext) -> bool:
+ """True when decisions and exports are served by an in-process ContextGraph.
+
+ ``GraphStore`` has no ``memory`` backend — it supports neo4j, falkordb,
+ age and neptune — so ``memory`` is served by ``ContextGraph``, which
+ already works in memory and is what the Python quickstart uses.
+ """
+ return _resolve_graph_backend(cli_ctx) == MEMORY_GRAPH_BACKEND
+
+
+def _memory_graph_path(cli_ctx: CLIContext) -> Path:
+ """Where the memory backend's graph is persisted between invocations.
+
+ The CLI is one process per command, so an in-memory graph that is never
+ written back would make ``decision record`` pointless. Defaults to
+ ``~/.semantica/context_graph.json`` (beside ``config.yaml``); override with
+ ``graph_db.path`` in the config.
+ """
+ configured = cli_ctx.config.to_dict().get("graph_db", {}).get("path")
+ if configured:
+ return Path(configured).expanduser()
+ return Path.home() / ".semantica" / "context_graph.json"
+
+
+def _load_context_graph(cli_ctx: CLIContext) -> Any:
+ """Return the persisted ContextGraph, or an empty one if none exists yet."""
+ from .context import ContextGraph
+
+ graph = ContextGraph()
+ path = _memory_graph_path(cli_ctx)
+ if path.exists():
+ try:
+ graph.load_from_file(path)
+ except Exception as exc:
+ raise click.ClickException(
+ f"Could not read the graph at {path}: {exc}"
+ ) from exc
+ return graph
+
+
+def _save_context_graph(cli_ctx: CLIContext, graph: Any) -> None:
+ """Persist the ContextGraph so the next command sees this one's writes."""
+ path = _memory_graph_path(cli_ctx)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ graph.save_to_file(path)
+
+
+def _try_lock_exclusive(fd: int) -> bool:
+ """Take an exclusive advisory lock on ``fd`` without blocking."""
+ if fcntl is not None:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return True
+ except OSError:
+ return False
+ if msvcrt is not None: # pragma: no cover - Windows only
+ try:
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
+ return True
+ except OSError:
+ return False
+ # No locking primitive available: proceed rather than refuse to record.
+ return True
+
+
+def _unlock(fd: int) -> None:
+ """Release the advisory lock held on ``fd``."""
+ if fcntl is not None:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ elif msvcrt is not None: # pragma: no cover - Windows only
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+
+
+def _memory_graph_lock(cli_ctx: CLIContext) -> Iterator[None]:
+ """Serialise read-modify-write of the memory graph across CLI processes.
+
+ ``decision record`` loads the whole graph, adds a node and writes it back.
+ Two invocations that load before either saves would silently lose the
+ earlier decision — ``save_to_file`` replaces the file atomically, so the
+ write is never torn, but the lost update is invisible.
+
+ Uses an OS advisory lock (``flock``, or ``msvcrt.locking`` on Windows) on a
+ sidecar ``.lock`` file. The kernel releases it when the holder exits, so
+ there is no staleness timeout to guess at and a crashed writer cannot wedge
+ the CLI. Deliberately never unlinks the file: removing it would let a
+ second process create a fresh inode and lock that instead, re-introducing
+ the double-entry this prevents — which is exactly what an mtime-based
+ "reclaim an old lock" rule does to a writer that is merely slow or
+ suspended.
+ """
+ lock_path = _memory_graph_path(cli_ctx).with_suffix(".lock")
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)
+ deadline = time.monotonic() + _LOCK_TIMEOUT_SECONDS
+ try:
+ while not _try_lock_exclusive(fd):
+ if time.monotonic() >= deadline:
+ raise click.ClickException(
+ f"Timed out waiting for another semantica command to finish "
+ f"writing {_memory_graph_path(cli_ctx)}."
+ )
+ time.sleep(0.05)
+ try:
+ yield
+ finally:
+ _unlock(fd)
+ finally:
+ os.close(fd)
+
+
+def _decision_from_node(node: Dict[str, Any]) -> Dict[str, Any]:
+ """Normalise a ContextGraph decision node to the CLI's decision shape.
+
+ Mirrors the fields the ``GraphStore`` path reads off a ``Decision``
+ (``decision_id``, ``scenario``, ``category``, ``outcome``, ``confidence``)
+ so both backends print identically.
+ """
+ meta = node.get("metadata", {}) or {}
+ # Carry every stored field, not just the ones the tables print:
+ # check_decision_rules() indexes decision["reasoning"] and reads
+ # decision_maker, valid_from/valid_until and nested metadata.
+ decision = {
+ "id": node.get("id", ""),
+ "decision_id": node.get("id", ""),
+ "scenario": meta.get("scenario", node.get("content", "")),
+ "category": meta.get("category", ""),
+ "outcome": meta.get("outcome", ""),
+ "confidence": meta.get("confidence", 0.0),
+ "timestamp": meta.get("timestamp", 0.0),
+ "recorded_at": meta.get("recorded_at", ""),
+ "reasoning": meta.get("reasoning", ""),
+ "decision_maker": meta.get("decision_maker") or "",
+ }
+ for key in ("valid_from", "valid_until", "metadata"):
+ if key in meta:
+ decision[key] = meta[key]
+ return decision
+
+
+def _memory_decisions(cli_ctx: CLIContext, limit: Optional[int] = None) -> List[Dict[str, Any]]:
+ """Decisions from the memory backend, newest first."""
+ graph = _load_context_graph(cli_ctx)
+ decisions = [
+ _decision_from_node(n) for n in graph.get_nodes_by_label("decision")
+ ]
+ decisions.sort(key=lambda d: d.get("timestamp") or 0.0, reverse=True)
+ return decisions[:limit] if limit is not None else decisions
+
+
+def _memory_decision_records(
+ cli_ctx: CLIContext,
+ limit: Optional[int] = None,
+ since_ts: Optional[float] = None,
+) -> List[SimpleNamespace]:
+ """Memory-backend decisions as records with a ``Decision``-shaped surface.
+
+ The commands read ``.decision_id`` / ``.scenario`` / ``.category`` /
+ ``.outcome`` / ``.confidence`` off whatever the store returns, so matching
+ that surface lets both backends share one formatting path.
+ """
+ rows = [
+ d for d in _memory_decisions(cli_ctx)
+ if since_ts is None or (d.get("timestamp") or 0.0) >= since_ts
+ ]
+ if limit is not None:
+ rows = rows[:limit]
+ return [
+ SimpleNamespace(
+ decision_id=d["id"], scenario=d["scenario"], category=d["category"],
+ outcome=d["outcome"], confidence=d["confidence"],
+ )
+ for d in rows
+ ]
+
+
def _get_graph_store(cli_ctx: CLIContext) -> Any:
"""Return a GraphStore instance wired from the current CLIContext config."""
from .graph_store import GraphStore
cfg = cli_ctx.config.to_dict()
graph_db = dict(cfg.get("graph_db", {}))
- backend = cli_ctx.store_backend or graph_db.pop("backend", "neo4j")
+ graph_db.pop("path", None)
+ # Pop unconditionally: `store_backend or graph_db.pop(...)` short-circuits,
+ # so an override left the configured backend in the kwargs and GraphStore
+ # received it twice.
+ configured = graph_db.pop("backend", None)
+ backend = cli_ctx.store_backend or configured or _DEFAULT_GRAPH_BACKEND
+ if backend == MEMORY_GRAPH_BACKEND:
+ # Reached only if a new caller forgets to route memory through
+ # ContextGraph; GraphStore would raise "Unknown backend: memory".
+ raise click.ClickException(
+ "The 'memory' backend is served by ContextGraph, not GraphStore — "
+ "this command has not been wired for it yet. Use --store neo4j "
+ "(or falkordb/age/neptune) for a real graph database."
+ )
return GraphStore(backend=backend, **graph_db)
+def _load_policy_rules(path: str) -> Dict[str, Any]:
+ """Load a decision policy rules file as a mapping.
+
+ Distinct from ``_load_rule_definitions()``, which loads reasoning rules as a
+ list of strings. ``ContextGraph.check_decision_rules()`` takes a mapping of
+ policy constraints, so anything else is a usage error worth naming.
+ """
+ data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
+ if not isinstance(data, dict):
+ raise click.ClickException(
+ f"Policy rules file '{path}' must be a YAML mapping of rules; "
+ f"got {type(data).__name__}."
+ )
+ return data
+
+
def _load_rule_definitions(path: str) -> List[str]:
"""Load reasoning rule definitions from a YAML or plain-text rules file.
@@ -3106,7 +3370,6 @@ def decision_record(cli_ctx: CLIContext, title: str, tags: Optional[str],
return
try:
from .context.decision_methods import record_decision
- graph_store = _get_graph_store(cli_ctx)
cross_ctx: Dict[str, Any] = {"tags": tag_list}
if valid_from:
cross_ctx["valid_from"] = valid_from
@@ -3115,15 +3378,45 @@ def decision_record(cli_ctx: CLIContext, title: str, tags: Optional[str],
# Map CLI flags to API: title→scenario, rationale→reasoning,
# first tag (if any)→category, outcome and confidence use defaults.
category = tag_list[0] if tag_list else "general"
- result = record_decision(
- graph_store,
- category=category,
- scenario=title,
- reasoning=rationale or "",
- outcome="recorded",
- confidence=1.0,
- cross_system_context=cross_ctx,
- )
+ # --rationale is optional, but ContextGraph rejects empty reasoning.
+ # Normalise once so both backends store the same thing rather than
+ # one storing "" and the other refusing the command.
+ reasoning = rationale or _NO_RATIONALE
+ if _uses_memory_graph(cli_ctx):
+ with _memory_graph_lock(cli_ctx):
+ graph = _load_context_graph(cli_ctx)
+ result = graph.record_decision(
+ category=category,
+ scenario=title,
+ reasoning=reasoning,
+ outcome="recorded",
+ confidence=1.0,
+ # ContextGraph tracks node validity itself, so pass the
+ # dates as validity rather than leaving them in
+ # metadata, where they would not bound the node.
+ # They must also be REMOVED from the metadata: it is
+ # splatted into add_node() alongside these arguments,
+ # and a duplicate key raises a TypeError that
+ # record_decision logs and swallows, leaving an empty
+ # graph behind a successful exit code.
+ metadata={
+ k: v for k, v in cross_ctx.items()
+ if k not in ("valid_from", "valid_until")
+ },
+ valid_from=valid_from,
+ valid_until=valid_until,
+ )
+ _save_context_graph(cli_ctx, graph)
+ else:
+ result = record_decision(
+ _get_graph_store(cli_ctx),
+ category=category,
+ scenario=title,
+ reasoning=reasoning,
+ outcome="recorded",
+ confidence=1.0,
+ cross_system_context=cross_ctx,
+ )
except ImportError as exc:
raise click.ClickException(f"Context module not available: {exc}") from exc
if _is_json(cli_ctx, local_json):
@@ -3145,13 +3438,16 @@ def decision_list(cli_ctx: CLIContext, limit: int, fmt: str, local_json: bool) -
def _action() -> None:
try:
- from .context.decision_query import DecisionQuery
- dq = DecisionQuery(_get_graph_store(cli_ctx))
- results_raw = dq.find_by_time_range(
- __import__("datetime").datetime.min,
- __import__("datetime").datetime.now(),
- limit=limit,
- )
+ if _uses_memory_graph(cli_ctx):
+ results_raw = _memory_decision_records(cli_ctx, limit=limit)
+ else:
+ from .context.decision_query import DecisionQuery
+ dq = DecisionQuery(_get_graph_store(cli_ctx))
+ results_raw = dq.find_by_time_range(
+ __import__("datetime").datetime.min,
+ __import__("datetime").datetime.now(),
+ limit=limit,
+ )
results = [
{"id": d.decision_id, "title": d.scenario, "tags": [d.category]}
for d in (results_raw or [])
@@ -3206,11 +3502,17 @@ def decision_query(cli_ctx: CLIContext, filter_str: Optional[str],
def _action() -> None:
tag_value = _tag_filter_value(filter_str) if filter_str is not None else None
try:
- from .context.decision_query import DecisionQuery
import datetime as _dt
- dq = DecisionQuery(_get_graph_store(cli_ctx))
since_dt = _dt.datetime.fromisoformat(since) if since else _dt.datetime.min
- raw = dq.find_by_time_range(since_dt, _dt.datetime.now(), limit=500)
+ if _uses_memory_graph(cli_ctx):
+ raw = _memory_decision_records(
+ cli_ctx, limit=500,
+ since_ts=since_dt.timestamp() if since else None,
+ )
+ else:
+ from .context.decision_query import DecisionQuery
+ dq = DecisionQuery(_get_graph_store(cli_ctx))
+ raw = dq.find_by_time_range(since_dt, _dt.datetime.now(), limit=500)
results: List[Dict[str, Any]] = [
{"id": d.decision_id, "category": d.category, "scenario": d.scenario,
"outcome": d.outcome, "confidence": d.confidence}
@@ -3244,8 +3546,11 @@ def decision_trace(cli_ctx: CLIContext, decision_id: str, fmt: str, local_json:
def _action() -> None:
try:
- from .context.decision_methods import get_causal_chain
- chain_raw = get_causal_chain(_get_graph_store(cli_ctx), decision_id)
+ if _uses_memory_graph(cli_ctx):
+ chain_raw = _load_context_graph(cli_ctx).get_causal_chain(decision_id)
+ else:
+ from .context.decision_methods import get_causal_chain
+ chain_raw = get_causal_chain(_get_graph_store(cli_ctx), decision_id)
chain: Any = [
{"id": d.decision_id, "scenario": d.scenario, "outcome": d.outcome}
for d in chain_raw
@@ -3272,7 +3577,14 @@ def decision_similar(cli_ctx: CLIContext, decision_id: str, top_k: int, local_js
def _action() -> None:
try:
from .context.decision_methods import find_precedents
- raw = find_precedents(_get_graph_store(cli_ctx), decision_id, limit=top_k)
+ if _uses_memory_graph(cli_ctx):
+ raw = _load_context_graph(cli_ctx).find_precedents(
+ decision_id, limit=top_k
+ )
+ else:
+ raw = find_precedents(
+ _get_graph_store(cli_ctx), decision_id, limit=top_k
+ )
results: List[Dict[str, Any]] = [
{"id": d.decision_id, "scenario": d.scenario, "category": d.category,
"confidence": d.confidence}
@@ -3299,7 +3611,14 @@ def decision_impact(cli_ctx: CLIContext, decision_id: str, local_json: bool) ->
def _action() -> None:
try:
from .context.decision_methods import analyze_decision_impact
- result = analyze_decision_impact(_get_graph_store(cli_ctx), decision_id)
+ if _uses_memory_graph(cli_ctx):
+ result = _load_context_graph(cli_ctx).analyze_decision_impact(
+ decision_id
+ )
+ else:
+ result = analyze_decision_impact(
+ _get_graph_store(cli_ctx), decision_id
+ )
except ImportError as exc:
raise click.ClickException(f"Context module not available: {exc}") from exc
if _is_json(cli_ctx, local_json):
@@ -3323,13 +3642,29 @@ def decision_check(cli_ctx: CLIContext, decision_id: str, rules: Optional[str],
def _action() -> None:
try:
- from .context.decision_methods import check_decision_compliance
- # The API expects a policy_id string; derive it from the rules file stem
- # if provided, otherwise use the decision ID itself as the policy key.
- policy_id = Path(rules).stem if rules else decision_id
- result = check_decision_compliance(
- _get_graph_store(cli_ctx), decision_id, policy_id
- )
+ if _uses_memory_graph(cli_ctx):
+ graph = _load_context_graph(cli_ctx)
+ decision = next(
+ (d for d in _memory_decisions(cli_ctx) if d["id"] == decision_id),
+ None,
+ )
+ if decision is None:
+ raise click.ClickException(
+ f"No decision {decision_id!r} in "
+ f"{_memory_graph_path(cli_ctx)}. Run 'semantica decision "
+ f"list' to see what is recorded."
+ )
+ result = graph.check_decision_rules(
+ decision, rules=_load_policy_rules(rules) if rules else None
+ )
+ else:
+ from .context.decision_methods import check_decision_compliance
+ # The API expects a policy_id string; derive it from the rules file
+ # stem if provided, otherwise use the decision ID as the policy key.
+ policy_id = Path(rules).stem if rules else decision_id
+ result = check_decision_compliance(
+ _get_graph_store(cli_ctx), decision_id, policy_id
+ )
except ImportError as exc:
raise click.ClickException(f"Context module not available: {exc}") from exc
if _is_json(cli_ctx, local_json):
@@ -4199,17 +4534,28 @@ def export(
if fmt in MULTI_FILE_FORMATS and (compress or not output):
raise _multi_file_destination_error(fmt, compress)
- graph_db = dict(cli_ctx.config.to_dict().get("graph_db", {}))
- backend = cli_ctx.store_backend or graph_db.pop("backend", None)
- previous_graph_config = graph_store_config.get_all()
- graph_store_config.update(graph_db)
- if backend:
- graph_store_config.set("default_backend", backend)
- try:
- entities = get_nodes(limit=sys.maxsize)
- relationships = get_relationships(limit=sys.maxsize)
- finally:
- graph_store_config.update(previous_graph_config)
+ if _uses_memory_graph(cli_ctx):
+ # ContextGraph.to_kg_dict() already returns entities and
+ # relationships in the shape assembled below.
+ kg = _load_context_graph(cli_ctx).to_kg_dict()
+ entities = kg.get("entities", [])
+ relationships = kg.get("relationships", [])
+ else:
+ graph_db = dict(cli_ctx.config.to_dict().get("graph_db", {}))
+ graph_db.pop("path", None)
+ # Pop before choosing, or an override leaves the configured
+ # backend in the mapping pushed into graph_store_config.
+ configured = graph_db.pop("backend", None)
+ backend = cli_ctx.store_backend or configured
+ previous_graph_config = graph_store_config.get_all()
+ graph_store_config.update(graph_db)
+ if backend:
+ graph_store_config.set("default_backend", backend)
+ try:
+ entities = get_nodes(limit=sys.maxsize)
+ relationships = get_relationships(limit=sys.maxsize)
+ finally:
+ graph_store_config.update(previous_graph_config)
knowledge_graph = {
"entities": entities,
diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py
index f1791516..9fe59216 100644
--- a/tests/test_cli_commands.py
+++ b/tests/test_cli_commands.py
@@ -15,6 +15,7 @@ Strategy:
import json
import os
+import time
import re
import stat
import types
@@ -1763,7 +1764,9 @@ class TestDecision:
"semantica.context.decision_query", fake_decision_query)
monkeypatch.setitem(__import__("sys").modules,
"semantica.graph_store", fake_graph_store)
- result = runner.invoke(cli_module.main, ["decision", "list", "--format", "json"])
+ result = runner.invoke(
+ cli_module.main, ["decision", "list", "--format", "json"]
+ )
_ok(result)
# (filter, matching category, decoy category the mangled filter also hits)
@@ -1796,9 +1799,13 @@ class TestDecision:
monkeypatch.setitem(__import__("sys").modules, "semantica.graph_store",
_fake_module(GraphStore=MagicMock(return_value=MagicMock())))
+ # --store neo4j: these mock DecisionQuery/GraphStore, so they must name
+ # the database path explicitly rather than inherit the default backend,
+ # which is memory and would read an empty ContextGraph.
result = runner.invoke(
cli_module.main,
- ["decision", "query", "--filter", f"tag:{tag}", "--format", "json"],
+ ["--store", "neo4j", "decision", "query", "--filter", f"tag:{tag}",
+ "--format", "json"],
)
_ok(result)
ids = [d["id"] for d in json.loads(result.output)]
@@ -1854,6 +1861,359 @@ class TestDecision:
assert result.exit_code != 0
+class TestMemoryGraphBackend:
+ """The `memory` backend routes through ContextGraph instead of GraphStore.
+
+ GraphStore has no `memory` backend, so before #1481 every one of these
+ commands died with `ValidationError: Unknown backend: memory` — which is
+ what `semantica init` writes by default.
+ """
+
+ @pytest.fixture
+ def memory_cfg(self, tmp_path):
+ cfg = tmp_path / "cfg.yaml"
+ cfg.write_text(
+ "graph_db:\n"
+ " backend: memory\n"
+ f" path: {tmp_path / 'graph.json'}\n"
+ )
+ return str(cfg)
+
+ def _record(self, runner, memory_cfg, title, tags, rationale=None):
+ args = ["--config", memory_cfg, "decision", "record", "--title", title,
+ "--tags", tags]
+ if rationale:
+ args += ["--rationale", rationale]
+ result = runner.invoke(cli_module.main, args)
+ _ok(result)
+ return result
+
+ def test_record_then_list_persists_across_invocations(self, runner, memory_cfg):
+ """A CLI is one process per command, so the graph must be written back."""
+ self._record(runner, memory_cfg, "Adopt Postgres", "database", "cheaper")
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", memory_cfg, "decision", "list", "--format", "json"],
+ )
+ _ok(result)
+ rows = json.loads(result.output)
+ assert [r["title"] for r in rows] == ["Adopt Postgres"]
+ assert rows[0]["tags"] == ["database"]
+
+ def test_record_without_rationale_succeeds(self, runner, memory_cfg):
+ """--rationale is optional; ContextGraph rejects empty reasoning."""
+ self._record(runner, memory_cfg, "Use OAuth", "auth")
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", memory_cfg, "decision", "list", "--format", "json"],
+ )
+ _ok(result)
+ assert [r["title"] for r in json.loads(result.output)] == ["Use OAuth"]
+
+ def test_query_filters_by_tag(self, runner, memory_cfg):
+ self._record(runner, memory_cfg, "Adopt Postgres", "database", "cheaper")
+ self._record(runner, memory_cfg, "Use OAuth", "auth", "standard")
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", memory_cfg, "decision", "query", "--filter", "tag:database",
+ "--format", "json"],
+ )
+ _ok(result)
+ rows = json.loads(result.output)
+ assert [r["scenario"] for r in rows] == ["Adopt Postgres"]
+
+ def test_export_reads_the_context_graph(self, runner, memory_cfg):
+ self._record(runner, memory_cfg, "Adopt Postgres", "database", "cheaper")
+ result = runner.invoke(
+ cli_module.main, ["--config", memory_cfg, "export", "--format", "json"]
+ )
+ _ok(result)
+ payload = json.loads(result.output)
+ titles = [e.get("text") or e.get("name") for e in payload["entities"]]
+ assert "Adopt Postgres" in titles
+
+ def test_list_is_empty_before_anything_is_recorded(self, runner, memory_cfg):
+ """A missing graph file is an empty graph, not an error."""
+ result = runner.invoke(
+ cli_module.main,
+ ["--config", memory_cfg, "decision", "list", "--format", "json"],
+ )
+ _ok(result)
+ assert json.loads(result.output) == []
+
+ def test_check_names_the_decision_when_absent(self, runner, memory_cfg):
+ result = runner.invoke(
+ cli_module.main, ["--config", memory_cfg, "decision", "check", "nope"]
+ )
+ assert result.exit_code != 0
+ assert "nope" in result.output
+ assert "Traceback" not in result.output
+
+ def test_doctor_reports_memory_without_probing_a_server(self, runner, memory_cfg):
+ result = runner.invoke(cli_module.main, ["--config", memory_cfg, "doctor"])
+ graph_rows = [
+ line for line in result.output.splitlines() if "Graph store" in line
+ ]
+ assert graph_rows, result.output
+ assert "memory" in graph_rows[0]
+ assert "Neo4j" not in graph_rows[0]
+
+ def _ctx(self, memory_cfg, store_backend=None):
+ cfg = cli_module._build_runtime_config(memory_cfg, None)
+ return cli_module.CLIContext(
+ config_path=memory_cfg, config=cfg, log_level="INFO",
+ store_backend=store_backend,
+ )
+
+ def test_resolve_backend_reads_the_config(self, memory_cfg):
+ ctx = self._ctx(memory_cfg)
+ assert cli_module._resolve_graph_backend(ctx) == "memory"
+ assert cli_module._uses_memory_graph(ctx) is True
+
+ def test_resolve_backend_prefers_the_store_flag(self, memory_cfg):
+ """--store must win over the config file, as it does for every command."""
+ ctx = self._ctx(memory_cfg, store_backend="neo4j")
+ assert cli_module._resolve_graph_backend(ctx) == "neo4j"
+ assert cli_module._uses_memory_graph(ctx) is False
+
+ def test_graph_path_is_configurable(self, memory_cfg, tmp_path):
+ ctx = self._ctx(memory_cfg)
+ assert cli_module._memory_graph_path(ctx) == tmp_path / "graph.json"
+
+ def test_validity_flags_reach_the_graph_not_just_metadata(
+ self, runner, memory_cfg, tmp_path
+ ):
+ """ContextGraph tracks node validity itself (Qodo #2 on PR #1765).
+
+ Passing --valid-from/--valid-until only inside metadata left the
+ decision active outside its window.
+ """
+ result = runner.invoke(cli_module.main, [
+ "--config", memory_cfg, "decision", "record", "--title", "Trial run",
+ "--tags", "pilot", "--rationale", "time-boxed",
+ "--valid-from", "2026-01-01T00:00:00",
+ "--valid-until", "2026-02-01T00:00:00",
+ ])
+ _ok(result)
+ saved = json.loads((tmp_path / "graph.json").read_text())
+ blob = json.dumps(saved)
+ assert "2026-01-01" in blob and "2026-02-01" in blob
+
+ def test_check_sees_the_stored_reasoning_and_decision_maker(
+ self, runner, memory_cfg
+ ):
+ """check_decision_rules indexes decision["reasoning"] (Qodo #4).
+
+ The display mapping used by list/query omits it, so policy checks were
+ evaluating a decision that looked emptier than what was stored.
+ """
+ self._record(runner, memory_cfg, "Adopt Postgres", "database",
+ "cheaper to operate")
+ ctx = self._ctx(memory_cfg)
+ stored = cli_module._memory_decisions(ctx)
+ assert stored, "nothing recorded"
+ assert stored[0]["reasoning"] == "cheaper to operate"
+ assert "decision_maker" in stored[0]
+
+ def test_concurrent_records_do_not_lose_each_other(self, memory_cfg, tmp_path):
+ """Two processes recording at once must not drop a decision (Qodo #1).
+
+ record is a load-modify-save of the whole graph, so without a lock the
+ later save replaces the earlier decision, silently.
+ """
+ import subprocess
+ import sys as _sys
+
+ procs = [
+ subprocess.Popen(
+ [_sys.executable, "-m", "semantica.cli", "--config", memory_cfg,
+ "decision", "record", "--title", f"Decision {i}",
+ "--tags", f"tag{i}", "--rationale", "concurrent"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ for i in range(4)
+ ]
+ assert all(p.wait(timeout=120) == 0 for p in procs)
+
+ ctx = self._ctx(memory_cfg)
+ titles = {d["scenario"] for d in cli_module._memory_decisions(ctx)}
+ assert titles == {f"Decision {i}" for i in range(4)}, titles
+
+ def test_an_old_lock_held_by_a_live_writer_is_not_stolen(self, memory_cfg):
+ """Age must never grant entry while the holder is alive.
+
+ An mtime-based "reclaim a lock older than N" rule lets a second writer
+ into the critical section whenever the first is merely slow or
+ suspended. The second saves, the first then saves its older snapshot,
+ and the second decision disappears with no error anywhere.
+ """
+ import subprocess
+ import sys as _sys
+
+ ctx = self._ctx(memory_cfg)
+ lock = cli_module._memory_graph_path(ctx).with_suffix(".lock")
+
+ with cli_module._memory_graph_lock(ctx):
+ graph = cli_module._load_context_graph(ctx)
+ graph.record_decision(category="a", scenario="A", reasoning="r",
+ outcome="recorded", confidence=1.0)
+ # Make the lock look ancient while this writer still holds it.
+ lock.touch()
+ old = time.time() - 86_400
+ os.utime(lock, (old, old))
+
+ other = subprocess.run(
+ [_sys.executable, "-m", "semantica.cli", "--config", memory_cfg,
+ "decision", "record", "--title", "B", "--tags", "b",
+ "--rationale", "r"],
+ capture_output=True, text=True, timeout=120,
+ )
+ # B must be kept out, not allowed in to have its write erased.
+ assert other.returncode != 0, other.stdout + other.stderr
+ assert cli_module._memory_decisions(ctx) == [] or all(
+ d["scenario"] != "B" for d in cli_module._memory_decisions(ctx)
+ )
+ cli_module._save_context_graph(ctx, graph)
+
+ assert [d["scenario"] for d in cli_module._memory_decisions(ctx)] == ["A"]
+
+ def test_lock_is_released_when_the_holder_exits(self, memory_cfg):
+ """The OS drops an advisory lock on process death, so no timeout guess."""
+ ctx = self._ctx(memory_cfg)
+ with cli_module._memory_graph_lock(ctx):
+ pass
+ with cli_module._memory_graph_lock(ctx): # immediately re-acquirable
+ pass
+
+ def test_init_then_plain_commands_need_no_config_flag(
+ self, runner, monkeypatch, tmp_path
+ ):
+ """The workflow #1481 is actually about: init, then plain commands.
+
+ `semantica init` writes ~/.semantica/config.yaml, but nothing read it,
+ so accepting its `memory` default still left every command on the
+ built-in fallback. Supplying --config in tests hid this entirely.
+ """
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(cli_module.Path, "home", staticmethod(lambda: home))
+
+ init = runner.invoke(cli_module.main, ["init"], input="memory\nfaiss\nnone\n")
+ _ok(init)
+ assert "backend: memory" in (home / ".semantica" / "config.yaml").read_text()
+
+ # No --config from here on.
+ rec = runner.invoke(cli_module.main, [
+ "decision", "record", "--title", "First", "--tags", "pilot",
+ "--rationale", "trying it out",
+ ])
+ _ok(rec)
+ listed = runner.invoke(
+ cli_module.main, ["decision", "list", "--format", "json"]
+ )
+ _ok(listed)
+ assert [d["title"] for d in json.loads(listed.output)] == ["First"]
+
+ exported = runner.invoke(cli_module.main, ["export", "--format", "json"])
+ _ok(exported)
+ assert "First" in exported.output
+
+ def test_default_backend_is_memory_with_no_config_at_all(
+ self, runner, monkeypatch, tmp_path
+ ):
+ """A user who never ran init gets a working local graph, not a Neo4j error."""
+ home = tmp_path / "empty-home"
+ home.mkdir()
+ monkeypatch.setattr(cli_module.Path, "home", staticmethod(lambda: home))
+ result = runner.invoke(
+ cli_module.main, ["decision", "list", "--format", "json"]
+ )
+ _ok(result)
+ assert json.loads(result.output) == []
+
+ def test_explicit_config_still_wins_over_the_default_file(
+ self, runner, monkeypatch, tmp_path
+ ):
+ home = tmp_path / "home2"
+ (home / ".semantica").mkdir(parents=True)
+ (home / ".semantica" / "config.yaml").write_text(
+ "graph_db:\n backend: memory\n"
+ )
+ monkeypatch.setattr(cli_module.Path, "home", staticmethod(lambda: home))
+ explicit = tmp_path / "explicit.yaml"
+ explicit.write_text("graph_db:\n backend: falkordb\n")
+ ctx_cfg = cli_module._build_runtime_config(str(explicit), None)
+ ctx = cli_module.CLIContext(
+ config_path=str(explicit), config=ctx_cfg, log_level="INFO"
+ )
+ assert cli_module._resolve_graph_backend(ctx) == "falkordb"
+
+ @staticmethod
+ def _init_home(monkeypatch, tmp_path, name):
+ """A HOME whose ~/.semantica/config.yaml selects the memory backend."""
+ home = tmp_path / name
+ (home / ".semantica").mkdir(parents=True)
+ (home / ".semantica" / "config.yaml").write_text(
+ "graph_db:\n backend: memory\nvector_store:\n backend: faiss\n"
+ )
+ monkeypatch.setattr(cli_module.Path, "home", staticmethod(lambda: home))
+ return home
+
+ def test_store_override_constructs_the_real_backend(self, monkeypatch, tmp_path):
+ """--store must reach GraphStore, not die assembling its arguments.
+
+ `store_backend or graph_db.pop("backend", ...)` short-circuits, so an
+ override left the configured backend in the kwargs and GraphStore got
+ `backend` twice. Auto-loading ~/.semantica/config.yaml made plain
+ `init` + `--store` hit it, so this asserts on construction rather than
+ on _resolve_graph_backend().
+ """
+ self._init_home(monkeypatch, tmp_path, "home-override")
+ seen = {}
+
+ class FakeGraphStore:
+ def __init__(self, backend=None, **kwargs):
+ seen["backend"] = backend
+ seen["kwargs"] = kwargs
+
+ monkeypatch.setitem(
+ __import__("sys").modules, "semantica.graph_store",
+ _fake_module(GraphStore=FakeGraphStore),
+ )
+ cfg = cli_module._build_runtime_config(None, None)
+ ctx = cli_module.CLIContext(
+ config_path=None, config=cfg, log_level="INFO", store_backend="neo4j",
+ )
+ store = cli_module._get_graph_store(ctx)
+ assert isinstance(store, FakeGraphStore)
+ assert seen["backend"] == "neo4j"
+ assert "backend" not in seen["kwargs"], seen["kwargs"]
+
+ @pytest.mark.parametrize("args", [
+ ["decision", "list", "--format", "json"],
+ ["export", "--format", "json"],
+ ])
+ def test_store_override_after_init_does_not_fail_on_arguments(
+ self, runner, monkeypatch, tmp_path, args
+ ):
+ """init then `--store neo4j <cmd>` must not raise a TypeError."""
+ self._init_home(monkeypatch, tmp_path, f"home-{args[0]}")
+ result = runner.invoke(cli_module.main, ["--store", "neo4j"] + args)
+ # Rich wraps the error inside a box, so collapse whitespace before
+ # matching: the literal phrase is split across lines in result.output.
+ flat = " ".join(result.output.split())
+ assert "multiple values for keyword argument" not in flat, flat[:300]
+ assert "TypeError" not in flat, flat[:300]
+ assert "Traceback" not in result.output
+
+ def test_get_graph_store_refuses_memory_with_a_clear_message(self, memory_cfg):
+ """Safety net: a future caller that forgets to route memory gets told."""
+ import click as _click
+ with pytest.raises(_click.ClickException) as exc:
+ cli_module._get_graph_store(self._ctx(memory_cfg))
+ assert "ContextGraph" in str(exc.value)
+
+
# ─── temporal ─────────────────────────────────────────────────────────────────
@@ -2177,7 +2537,10 @@ class TestExport:
_patch_graph_store(monkeypatch, [STORE_RELATIONSHIP])
output_path = tmp_path / "export.json"
- result = runner.invoke(cli_module.main, ["export", "--format", "json", "--output", str(output_path)])
+ result = runner.invoke(cli_module.main, [
+ "--store", "neo4j", "export", "--format", "json",
+ "--output", str(output_path),
+ ])
_ok(result)
exported = output_path.read_text(encoding="utf-8")
assert "Alice" in exported
@@ -2193,7 +2556,9 @@ class TestExport:
(_ for _ in ()).throw(ImportError(n))
if "semantica.export" in n else original_import(n, *a, **k)
)):
- result = runner.invoke(cli_module.main, ["export", "--format", "json"])
+ result = runner.invoke(
+ cli_module.main, ["--store", "neo4j", "export", "--format", "json"]
+ )
assert result.exit_code != 0
assert "Traceback" not in result.output
@@ -2214,7 +2579,8 @@ class TestExportMultiFileFormats:
target = tmp_path / f"graph{ext}"
result = runner.invoke(
- cli_module.main, ["export", "--format", fmt, "--output", str(target)]
+ cli_module.main,
+ ["--store", "neo4j", "export", "--format", fmt, "--output", str(target)]
)
_ok(result)
@@ -2251,7 +2617,8 @@ class TestExportMultiFileFormats:
target = tmp_path / "graph.arrow"
result = runner.invoke(
- cli_module.main, ["export", "--format", "arrow", "--output", str(target)]
+ cli_module.main,
+ ["--store", "neo4j", "export", "--format", "arrow", "--output", str(target)]
)
_ok(result)
@@ -2266,7 +2633,8 @@ class TestExportMultiFileFormats:
target = tmp_path / f"graph{ext}"
result = runner.invoke(
- cli_module.main, ["export", "--format", fmt, "--output", str(target)]
+ cli_module.main,
+ ["--store", "neo4j", "export", "--format", fmt, "--output", str(target)]
)
_ok(result)