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): address review findings from PR #576
KaifAhmad18feb8c00c614
diff --git a/semantica/cli.py b/semantica/cli.pyindex 176622ba..0d001b81 100644--- a/semantica/cli.py+++ b/semantica/cli.py@@ -38,6 +38,20 @@ class CLIContext:framework: Optional["Semantica"] = None+def _require_ctx(cli_ctx: Optional[CLIContext]) -> CLIContext:+ """Guard against uninitialized CLI context.++ Under normal Click operation (standalone_mode=True) ctx.obj is always set+ before a subcommand runs. This guard protects embedded/library usage where+ standalone_mode=False might leave ctx.obj as None.+ """+ if cli_ctx is None:+ raise click.ClickException(+ "CLI context is uninitialized — this is a bug, please report it."+ )+ return cli_ctx++def _run_with_error_handling(action: Callable[[], None]) -> None:"""Run a CLI action with consistent user-facing error formatting."""try:@@ -46,7 +60,7 @@ def _run_with_error_handling(action: Callable[[], None]) -> None:raiseexcept SemanticaError as exc:raise click.ClickException(str(exc)) from exc- except Exception as exc: # pragma: no cover - fallback guard+ except Exception as exc:raise click.ClickException(f"Unexpected error: {exc}") from exc@@ -120,7 +134,21 @@ def _get_framework(cli_ctx: CLIContext) -> "Semantica":def _run_build(cli_ctx: CLIContext, sources: Sequence[str]) -> None:- """Thin wrapper around existing build orchestration flow."""+ """Thin wrapper around existing build orchestration flow.++ build_knowledge_base is expected to return a dict of the form::++ {+ "statistics": {+ "sources_processed": <int>,+ ...+ },+ ...+ }++ Both the top-level dict and the "statistics" key are optional; the+ function degrades gracefully when either is absent or None.+ """if not sources:raise click.UsageError("At least one source is required. Use --source/-s one or more times."@@ -148,14 +176,25 @@ def _run_build_command(source: Sequence[str],command_config_path: Optional[str],) -> None:- """Execute build command path with optional command-level config override."""+ """Execute build command path with optional command-level config override.++ When a per-command config file is supplied, the logging configuration from+ that file is re-applied (setup_logging clears existing handlers before+ adding new ones, so there is no handler accumulation risk).+ """if command_config_path:+ cmd_config = _build_runtime_config(+ command_config_path, cli_ctx.log_level_override+ )+ # Re-apply logging so the command-level logging section takes effect.+ setup_logging(config=cmd_config.get("logging", {}))command_ctx = CLIContext(config_path=command_config_path,- config=_build_runtime_config(- command_config_path, cli_ctx.log_level_override- ),+ config=cmd_config,log_level=cli_ctx.log_level,+ # Preserve the global --log-level override so nested config+ # lookups further down the call chain respect it.+ log_level_override=cli_ctx.log_level_override,)_run_build(command_ctx, source)else:@@ -217,10 +256,17 @@ def pipeline(ctx: click.Context) -> None:click.echo(ctx.get_help())[email protected](invoke_without_command=True)[email protected](name="services", invoke_without_command=True)@click.pass_context-def serve(ctx: click.Context) -> None:- """Service command group (foundation placeholder)."""+def services(ctx: click.Context) -> None:+ """Service management commands (server, explorer, mcp — foundation placeholder).++ Subcommands will follow the spec layout::++ semantica services server start|stop|status+ semantica services explorer start|stop|status+ semantica services mcp start|stop|status+ """if ctx.invoked_subcommand is None:click.echo(ctx.get_help())@@ -237,6 +283,7 @@ def config_group(ctx: click.Context) -> None:@click.pass_objdef info(cli_ctx: CLIContext):"""Display information about Semantica."""+ cli_ctx = _require_ctx(cli_ctx)def _action() -> None:console.print(f"[bold blue]Semantica Framework[/bold blue] v{__version__}")@@ -278,6 +325,7 @@ def kg_build(command_config_path: Optional[str],):"""Build a knowledge base from sources."""+ cli_ctx = _require_ctx(cli_ctx)def _action() -> None:_run_build_command(cli_ctx, source, command_config_path)@@ -302,6 +350,7 @@ def build_alias(command_config_path: Optional[str],):"""Backward-compatible alias for 'kg build'."""+ cli_ctx = _require_ctx(cli_ctx)def _action() -> None:_run_build_command(cli_ctx, source, command_config_path)diff --git a/tests/test_cli_foundation.py b/tests/test_cli_foundation.pyindex e3bd69cb..e22992cb 100644--- a/tests/test_cli_foundation.py+++ b/tests/test_cli_foundation.py@@ -1,11 +1,16 @@+import clickimport pytest-from click.testing import CliRunner+from click.testing import CliRunner, Resultimport semantica.cli as cli_module@pytest.fixture-def runner():+def runner() -> CliRunner:+ # Click's CliRunner captures all output in result.output by default; error+ # messages from ClickException / UsageError are included. If the project+ # ever moves to a Click version that separates stderr (mix_stderr=False),+ # update assertions that check error text to use result.stderr instead.return CliRunner()@@ -14,6 +19,11 @@ def disable_cli_logging(monkeypatch):monkeypatch.setattr(cli_module, "setup_logging", lambda *args, **kwargs: None)+# ---------------------------------------------------------------------------+# Help surfaces+# ---------------------------------------------------------------------------++def test_root_help_shows_expected_groups(runner):result = runner.invoke(cli_module.main, ["--help"])@@ -24,7 +34,7 @@ def test_root_help_shows_expected_groups(runner):)assert "kg" in result.outputassert "pipeline" in result.output- assert "serve" in result.output+ assert "services" in result.outputdef test_kg_group_help_shows_build_command(runner):@@ -45,6 +55,90 @@ def test_kg_build_help_shows_source_and_config_flags(runner):assert "-c" in result.output+# ---------------------------------------------------------------------------+# info command+# ---------------------------------------------------------------------------+++def test_info_command_shows_framework_components(runner):+ result = runner.invoke(cli_module.main, ["info"])++ assert result.exit_code == 0+ assert "Semantica Framework" in result.output+ assert "Core Orchestrator" in result.output+ assert "CLI Log Level" in result.output+++def test_info_command_shows_config_path_when_supplied(runner):+ # click.Path(resolve_path=True) turns cfg.yml into an absolute path, and+ # Rich's table may truncate long paths with '…'. Assert the row is present+ # and the "(none)" placeholder has been replaced by some path value.+ with runner.isolated_filesystem():+ with open("cfg.yml", "w", encoding="utf-8") as handle:+ handle.write("logging:\n level: INFO\n")++ result: Result = runner.invoke(+ cli_module.main, ["--config", "cfg.yml", "info"]+ )++ assert result.exit_code == 0+ assert "CLI Config File" in result.output+ assert "(none)" not in result.output+++# ---------------------------------------------------------------------------+# Global --log-level override+# ---------------------------------------------------------------------------+++def test_log_level_global_override_stores_in_context(runner, monkeypatch):+ """--log-level at the root level propagates into CLIContext."""+ captured = {}++ def fake_run_build(cli_ctx, sources):+ captured["log_level_override"] = cli_ctx.log_level_override+ captured["log_level"] = cli_ctx.log_level++ monkeypatch.setattr(cli_module, "_run_build", fake_run_build)++ result = runner.invoke(+ cli_module.main,+ ["--log-level", "DEBUG", "kg", "build", "-s", "src.txt"],+ )++ assert result.exit_code == 0+ assert captured["log_level_override"] == "DEBUG"+++# ---------------------------------------------------------------------------+# Command-level config+# ---------------------------------------------------------------------------+++def test_command_config_preserves_global_log_level_override(+ runner: CliRunner, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Global --log-level is forwarded into command_ctx.log_level_override."""+ captured: dict[str, object] = {}++ def fake_run_build(cli_ctx: cli_module.CLIContext, _: object) -> None:+ captured["log_level_override"] = cli_ctx.log_level_override++ monkeypatch.setattr(cli_module, "_run_build", fake_run_build)++ with runner.isolated_filesystem():+ with open("cfg.yml", "w", encoding="utf-8") as handle:+ handle.write("logging:\n level: INFO\n")++ result = runner.invoke(+ cli_module.main,+ ["--log-level", "DEBUG", "kg", "build", "-s", "src.txt", "-c", "cfg.yml"],+ )++ assert result.exit_code == 0+ assert captured["log_level_override"] == "DEBUG"++def test_command_config_keeps_own_logging_without_global_override(runner, monkeypatch):captured = {}@@ -68,6 +162,11 @@ def test_command_config_keeps_own_logging_without_global_override(runner, monkeyassert captured["logging_level"] == "DEBUG"+# ---------------------------------------------------------------------------+# Legacy / new command parity+# ---------------------------------------------------------------------------++@pytest.mark.parametrize("argv",[@@ -119,6 +218,72 @@ def test_build_config_short_and_long_flags_are_compatible(runner, monkeypatch, aassert captured["config_path"] is not None+# ---------------------------------------------------------------------------+# build_knowledge_base result handling+# ---------------------------------------------------------------------------+++class _MockFramework:+ """Lightweight stand-in for Semantica used to test _run_build result paths."""++ def __init__(self, return_value):+ self._return_value = return_value++ def build_knowledge_base(self, sources):+ return self._return_value+++def test_build_result_with_stats_shows_source_count(runner, monkeypatch):+ """When build returns statistics.sources_processed, that count appears in output."""+ monkeypatch.setattr(+ cli_module,+ "_get_framework",+ lambda _: _MockFramework({"statistics": {"sources_processed": 3}}),+ )++ result = runner.invoke(+ cli_module.main,+ ["kg", "build", "-s", "a.txt", "-s", "b.txt", "-s", "c.txt"],+ )++ assert result.exit_code == 0+ assert "3 source(s)" in result.output+++def test_build_result_without_stats_shows_generic_success(runner, monkeypatch):+ """When build result has no statistics key, generic success message is shown."""+ monkeypatch.setattr(+ cli_module,+ "_get_framework",+ lambda _: _MockFramework({}),+ )++ result = runner.invoke(cli_module.main, ["kg", "build", "-s", "src.txt"])++ assert result.exit_code == 0+ assert "Knowledge base build completed" in result.output+ assert "source(s)" not in result.output+++def test_build_result_none_shows_generic_success(runner, monkeypatch):+ """When build_knowledge_base returns None, generic success message is shown."""+ monkeypatch.setattr(+ cli_module,+ "_get_framework",+ lambda _: _MockFramework(None),+ )++ result = runner.invoke(cli_module.main, ["kg", "build", "-s", "src.txt"])++ assert result.exit_code == 0+ assert "Knowledge base build completed" in result.output+++# ---------------------------------------------------------------------------+# Error handling+# ---------------------------------------------------------------------------++@pytest.mark.parametrize("argv",[@@ -220,6 +385,24 @@ def test_command_config_parse_errors_are_clean_and_click_safe(assert "Traceback" not in result.output+def test_runtime_errors_are_click_safe_without_traceback(runner, monkeypatch):+ def boom(_cli_ctx, _sources):+ raise RuntimeError("boom")++ monkeypatch.setattr(cli_module, "_run_build", boom)++ result = runner.invoke(cli_module.main, ["kg", "build", "-s", "README.md"])++ assert result.exit_code != 0+ assert "Unexpected error: boom" in result.output+ assert "Traceback" not in result.output+++# ---------------------------------------------------------------------------+# Lazy initialization+# ---------------------------------------------------------------------------++@pytest.mark.parametrize("argv",[@@ -240,14 +423,24 @@ def test_help_calls_do_not_initialize_framework(runner, monkeypatch, argv):assert result.exit_code == 0-def test_runtime_errors_are_click_safe_without_traceback(runner, monkeypatch):- def boom(_cli_ctx, _sources):- raise RuntimeError("boom")+# ---------------------------------------------------------------------------+# _require_ctx guard+# ---------------------------------------------------------------------------- monkeypatch.setattr(cli_module, "_run_build", boom)- result = runner.invoke(cli_module.main, ["kg", "build", "-s", "README.md"])+def test_require_ctx_raises_click_exception_on_none():+ """_require_ctx converts None ctx into a clean ClickException."""+ with pytest.raises(+ click.ClickException,+ match="CLI context is uninitialized",+ ):+ cli_module._require_ctx(None)- assert result.exit_code != 0- assert "Unexpected error: boom" in result.output- assert "Traceback" not in result.output++def test_require_ctx_returns_ctx_unchanged():+ """_require_ctx is a pass-through when ctx is valid."""+ from semantica.core.config_manager import Config, ConfigManager++ cfg = ConfigManager().load_from_dict({}, validate=False)+ ctx = cli_module.CLIContext(config_path=None, config=cfg, log_level="INFO")+ assert cli_module._require_ctx(ctx) is ctx