Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

cli: add foundation wiring and kg build with legacy build parity

Sameer6305bc9db1ff8935
diff --git a/semantica/cli.py b/semantica/cli.py
index c5c6de9f..c1a23748 100644
--- a/semantica/cli.py
+++ b/semantica/cli.py
@@ -5,51 +5,240 @@ This module provides the command-line interface for the Semantica framework,
enabling users to interact with the framework via terminal commands.
"""
+from dataclasses import dataclass
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING, Callable, Optional, Sequence
+
+import yaml
+
import click
from rich.console import Console
from rich.table import Table
from . import __version__
-from .core.orchestrator import Semantica
+from .core.config_manager import Config, ConfigManager
+from .utils.exceptions import SemanticaError
from .utils.logging import setup_logging
+if TYPE_CHECKING:
+ from .core.orchestrator import Semantica
+
console = Console()
+
+@dataclass
+class CLIContext:
+ """Shared runtime context for all CLI commands."""
+
+ config_path: Optional[str]
+ config: Config
+ log_level: str
+ framework: Optional["Semantica"] = None
+
+
+def _run_with_error_handling(action: Callable[[], None]) -> None:
+ """Run a CLI action with consistent user-facing error formatting."""
+ try:
+ action()
+ except click.ClickException:
+ raise
+ except SemanticaError as exc:
+ raise click.ClickException(str(exc)) from exc
+ except Exception as exc: # pragma: no cover - fallback guard
+ raise click.ClickException(f"Unexpected error: {exc}") from exc
+
+
+def _build_runtime_config(config_path: Optional[str], log_level: Optional[str]) -> Config:
+ """Resolve CLI config from file plus global flag overrides."""
+ config_manager = ConfigManager()
+
+ if config_path:
+ file_path = Path(config_path)
+ suffix = file_path.suffix.lower()
+ if suffix in (".yaml", ".yml"):
+ with file_path.open("r", encoding="utf-8") as handle:
+ config_data = yaml.safe_load(handle) or {}
+ elif suffix == ".json":
+ with file_path.open("r", encoding="utf-8") as handle:
+ config_data = json.load(handle)
+ else:
+ raise click.ClickException(
+ "Unsupported configuration file format: "
+ f"{suffix}. Supported formats: .yaml, .yml, .json"
+ )
+ else:
+ config_data = {}
+
+ if log_level:
+ config_data.setdefault("logging", {})["level"] = log_level.upper()
+
+ # Keep validation disabled at CLI bootstrap to avoid blocking unrelated commands.
+ return config_manager.load_from_dict(config_data, validate=False)
+
+
+def _get_framework(cli_ctx: CLIContext) -> "Semantica":
+ """Lazily initialize framework only when a command needs it."""
+ if cli_ctx.framework is None:
+ from .core.orchestrator import Semantica
+
+ cli_ctx.framework = Semantica(config=cli_ctx.config.to_dict())
+ return cli_ctx.framework
+
+
+def _run_build(cli_ctx: CLIContext, sources: Sequence[str]) -> None:
+ """Thin wrapper around existing build orchestration flow."""
+ if not sources:
+ raise click.UsageError(
+ "At least one source is required. Use --source/-s one or more times."
+ )
+
+ framework = _get_framework(cli_ctx)
+ console.print(f"Initializing Semantica with {len(sources)} sources...")
+ result = framework.build_knowledge_base(sources=list(sources))
+
+ stats = result.get("statistics", {}) if isinstance(result, dict) else {}
+ processed = stats.get("sources_processed")
+ if processed is not None:
+ console.print(
+ f"[bold green]Success:[/bold green] Knowledge base build completed for {processed} source(s)."
+ )
+ else:
+ console.print("[bold green]Success:[/bold green] Knowledge base build completed.")
+
+
+def _run_build_command(
+ cli_ctx: CLIContext,
+ source: Sequence[str],
+ command_config_path: Optional[str],
+) -> None:
+ """Execute build command path with optional command-level config override."""
+ if command_config_path:
+ command_ctx = CLIContext(
+ config_path=command_config_path,
+ config=_build_runtime_config(command_config_path, cli_ctx.log_level),
+ log_level=cli_ctx.log_level,
+ )
+ _run_build(command_ctx, source)
+ else:
+ _run_build(cli_ctx, source)
+
+
[email protected](context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option(version=__version__)
-def main():
+ "--config",
+ "config_path",
+ type=click.Path(exists=True, dir_okay=False, resolve_path=True, path_type=str),
+ default=None,
+ help="Path to YAML/JSON config file.",
+)
+ "--log-level",
+ type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], case_sensitive=False),
+ default=None,
+ help="Override logging level for this CLI invocation.",
+)
+def main(ctx: click.Context, config_path: Optional[str], log_level: Optional[str]):
"""Semantica - Semantic Layer & Knowledge Engineering Framework"""
- setup_logging()
+ try:
+ config = _build_runtime_config(config_path=config_path, log_level=log_level)
+ setup_logging(config=config.get("logging", {}))
+ ctx.obj = CLIContext(
+ config_path=config_path,
+ config=config,
+ log_level=config.get("logging.level", "INFO"),
+ )
+ except click.ClickException:
+ raise
+ except SemanticaError as exc:
+ raise click.ClickException(str(exc)) from exc
+ except Exception as exc:
+ raise click.ClickException(f"Failed to initialize CLI: {exc}") from exc
+
+
[email protected](invoke_without_command=True)
+def kg(ctx: click.Context) -> None:
+ """Knowledge graph and semantic build commands."""
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
+
[email protected](invoke_without_command=True)
+def pipeline(ctx: click.Context) -> None:
+ """Pipeline command group (foundation placeholder)."""
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
+
[email protected](invoke_without_command=True)
+def serve(ctx: click.Context) -> None:
+ """Service command group (foundation placeholder)."""
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
+
[email protected](name="config", invoke_without_command=True)
+def config_group(ctx: click.Context) -> None:
+ """Configuration command group."""
+ if ctx.invoked_subcommand is None:
+ click.echo(ctx.get_help())
+
@main.command()
-def info():
+def info(cli_ctx: CLIContext):
"""Display information about Semantica."""
- console.print(f"[bold blue]Semantica Framework[/bold blue] v{__version__}")
- console.print("A comprehensive Python framework for transforming unstructured data into semantic layers.")
-
- table = Table(title="Framework Components")
- table.add_column("Component", style="cyan")
- table.add_column("Status", style="green")
-
- table.add_row("Core Orchestrator", "Active")
- table.add_row("Knowledge Graph Engine", "Active")
- table.add_row("Pipeline Execution", "Active")
- table.add_row("Vector Store Integration", "Active")
-
- console.print(table)
+ def _action() -> None:
+ console.print(f"[bold blue]Semantica Framework[/bold blue] v{__version__}")
+ console.print(
+ "A comprehensive Python framework for transforming unstructured data into semantic layers."
+ )
+ table = Table(title="Framework Components")
+ table.add_column("Component", style="cyan")
+ table.add_column("Status", style="green")
+
+ table.add_row("Core Orchestrator", "Active")
+ table.add_row("Knowledge Graph Engine", "Active")
+ table.add_row("Pipeline Execution", "Active")
+ table.add_row("Vector Store Integration", "Active")
+ table.add_row("CLI Config File", cli_ctx.config_path or "(none)")
+ table.add_row("CLI Log Level", cli_ctx.log_level)
+
+ console.print(table)
+
+ _run_with_error_handling(_action)
+
+
@click.option("--source", "-s", multiple=True, help="Data sources to process.")
[email protected]("--config", "-c", help="Path to configuration file.")
-def build(source, config):
[email protected]("-c", "--config", "command_config_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True, path_type=str), default=None, help="Path to YAML/JSON config file.")
+def kg_build(cli_ctx: CLIContext, source: Sequence[str], command_config_path: Optional[str]):
"""Build a knowledge base from sources."""
- console.print(f"Initializing Semantica with {len(source)} sources...")
- try:
- framework = Semantica(config=config)
- # framework.build_knowledge_base(sources=list(source))
- console.print("[bold green]Success:[/bold green] Knowledge base construction initiated.")
- except Exception as e:
- console.print(f"[bold red]Error:[/bold red] {str(e)}")
+ def _action() -> None:
+ _run_build_command(cli_ctx, source, command_config_path)
+
+ _run_with_error_handling(_action)
+
+
[email protected]("build", hidden=True)
[email protected]("--source", "-s", multiple=True, help="Data sources to process.")
[email protected]("-c", "--config", "command_config_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True, path_type=str), default=None, help="Path to YAML/JSON config file.")
+def build_alias(cli_ctx: CLIContext, source: Sequence[str], command_config_path: Optional[str]):
+ """Backward-compatible alias for 'kg build'."""
+ def _action() -> None:
+ _run_build_command(cli_ctx, source, command_config_path)
+
+ _run_with_error_handling(_action)
+
if __name__ == "__main__":
main()
diff --git a/tests/test_cli_foundation.py b/tests/test_cli_foundation.py
new file mode 100644
index 00000000..181d9dbc
--- /dev/null
+++ b/tests/test_cli_foundation.py
@@ -0,0 +1,163 @@
+import pytest
+from click.testing import CliRunner
+
+import semantica.cli as cli_module
+
+
+def runner():
+ return CliRunner()
+
+
+def test_root_help_shows_expected_groups(runner):
+ result = runner.invoke(cli_module.main, ["--help"])
+
+ assert result.exit_code == 0
+ assert "Semantica - Semantic Layer & Knowledge Engineering Framework" in result.output
+ assert "kg" in result.output
+ assert "pipeline" in result.output
+ assert "serve" in result.output
+
+
+def test_kg_group_help_shows_build_command(runner):
+ result = runner.invoke(cli_module.main, ["kg", "--help"])
+
+ assert result.exit_code == 0
+ assert "Knowledge graph and semantic build commands." in result.output
+ assert "build" in result.output
+
+
+def test_kg_build_help_shows_source_and_config_flags(runner):
+ result = runner.invoke(cli_module.main, ["kg", "build", "--help"])
+
+ assert result.exit_code == 0
+ assert "--source" in result.output
+ assert "-s" in result.output
+ assert "--config" in result.output
+ assert "-c" in result.output
+
+
+ "argv",
+ [
+ ["kg", "build", "-s", "README.md"],
+ ["build", "-s", "README.md"],
+ ],
+)
+def test_build_paths_invoke_shared_wrapper(runner, monkeypatch, argv):
+ captured = {}
+
+ def fake_run_build(cli_ctx, sources):
+ captured["config_path"] = cli_ctx.config_path
+ captured["sources"] = list(sources)
+
+ monkeypatch.setattr(cli_module, "_run_build", fake_run_build)
+
+ result = runner.invoke(cli_module.main, argv)
+
+ assert result.exit_code == 0
+ assert captured["sources"] == ["README.md"]
+
+
+ "argv",
+ [
+ ["kg", "build", "-s", "README.md", "-c", "cfg.yml"],
+ ["kg", "build", "-s", "README.md", "--config", "cfg.yml"],
+ ["build", "-s", "README.md", "-c", "cfg.yml"],
+ ["build", "-s", "README.md", "--config", "cfg.yml"],
+ ],
+)
+def test_build_config_short_and_long_flags_are_compatible(runner, monkeypatch, argv):
+ captured = {}
+
+ def fake_run_build(cli_ctx, sources):
+ captured["config_path"] = cli_ctx.config_path
+ captured["sources"] = list(sources)
+
+ 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, argv)
+
+ assert result.exit_code == 0
+ assert captured["sources"] == ["README.md"]
+ assert captured["config_path"] is not None
+
+
+ "argv",
+ [
+ ["kg", "build"],
+ ["build"],
+ ],
+)
+def test_missing_input_errors_are_clean_and_click_safe(runner, argv):
+ result = runner.invoke(cli_module.main, argv)
+
+ assert result.exit_code != 0
+ assert "At least one source is required" in result.output
+ assert "Traceback" not in result.output
+
+
+def test_invalid_root_config_error_is_clean_and_click_safe(runner):
+ with runner.isolated_filesystem():
+ with open("bad.md", "w", encoding="utf-8") as handle:
+ handle.write("not-a-config")
+
+ result = runner.invoke(cli_module.main, ["--config", "bad.md", "info"])
+
+ assert result.exit_code != 0
+ assert "Unsupported configuration file format" in result.output
+ assert "Traceback" not in result.output
+
+
+def test_invalid_command_config_error_is_clean_and_click_safe(runner):
+ with runner.isolated_filesystem():
+ with open("bad.md", "w", encoding="utf-8") as handle:
+ handle.write("not-a-config")
+
+ result = runner.invoke(
+ cli_module.main,
+ ["kg", "build", "-s", "README.md", "-c", "bad.md"],
+ )
+
+ assert result.exit_code != 0
+ assert "Unsupported configuration file format" in result.output
+ assert "Traceback" not in result.output
+
+
+ "argv",
+ [
+ ["--help"],
+ ["kg", "--help"],
+ ["kg", "build", "--help"],
+ ["build", "--help"],
+ ],
+)
+def test_help_calls_do_not_initialize_framework(runner, monkeypatch, argv):
+ def fail_get_framework(_):
+ raise AssertionError("framework initialization must not happen on help")
+
+ monkeypatch.setattr(cli_module, "_get_framework", fail_get_framework)
+
+ result = runner.invoke(cli_module.main, 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")
+
+ 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