Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.
fix: normalize search hits and share KA GraphML/CSV export adapters
Cursor Agent3d1ea7ccccb9
diff --git a/hyperextract/cli/cli.py b/hyperextract/cli/cli.pyindex 4f6d33d..b31b13e 100644--- a/hyperextract/cli/cli.py+++ b/hyperextract/cli/cli.py@@ -572,24 +572,21 @@ def _load_graph_ka_for_export(ka_path: str):console.print(f"[red]Error loading Knowledge Abstract:[/red] {e}")raise typer.Exit(1)- if not hasattr(ka, "export_obsidian"):- console.print(- "[red]Error:[/red] GraphML/CSV export is only supported for graph-type "- "Knowledge Abstracts (graph, hypergraph, temporal/spatial graphs)."- )+ from hyperextract.utils.exporters.ka import (+ GRAPH_TYPE_ERROR,+ GraphTypeError,+ require_graph_ka,+ )++ try:+ require_graph_ka(ka)+ except GraphTypeError:+ console.print(f"[red]Error:[/red] {GRAPH_TYPE_ERROR}")raise typer.Exit(1)return ka, path, template-def _is_hypergraph_ka(ka) -> bool:- """True for AutoHypergraph; temporal/spatial graphs are pairwise."""- if type(ka).__name__ == "AutoHypergraph":- return True- meta = getattr(ka, "metadata", None)- return isinstance(meta, dict) and meta.get("type") == "hypergraph"--@export_app.command(name="graphml")def export_graphml_cmd(ka_path: str = typer.Argument(..., help="Knowledge Abstract directory"),@@ -600,7 +597,8 @@ def export_graphml_cmd(Binary edges are written as `<edge source target>`. Edges with threeor more endpoints are written as GraphML 1.0 `<hyperedge>` elements."""- from hyperextract.utils.exporters import GraphMLHypergraphError, export_to_graphml+ from hyperextract.utils.exporters import GraphMLHypergraphError+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_graphmllogger.info("command=export-graphml ka_path=%s output=%s", ka_path, output)@@ -614,14 +612,10 @@ def export_graphml_cmd(with console.status("[bold blue]Exporting to GraphML..."):try:- export_to_graphml(- ka.nodes,- ka.edges,- node_id_extractor=ka.node_key_extractor,- incident_nodes_extractor=ka.nodes_in_edge_extractor,- file_path=output_path,- edge_id_extractor=getattr(ka, "edge_key_extractor", None),- )+ export_ka_graphml(ka, output_path)+ except GraphTypeError as e:+ console.print(f"[red]Error:[/red] {e}")+ raise typer.Exit(1)except GraphMLHypergraphError as e:console.print(f"[red]Error:[/red] {e}")raise typer.Exit(1)@@ -644,7 +638,11 @@ def export_csv_cmd(),):"""Export a Knowledge Abstract to node and edge CSV tables."""- from hyperextract.utils.exporters import export_to_csv+ from hyperextract.utils.exporters.ka import (+ GraphTypeError,+ export_ka_csv,+ is_hypergraph_ka,+ )logger.info("command=export-csv ka_path=%s output=%s", ka_path, output)@@ -660,7 +658,7 @@ def export_csv_cmd(raise typer.Exit(1)ka, _path, template = _load_graph_ka_for_export(ka_path)- hypergraph = _is_hypergraph_ka(ka)+ hypergraph = is_hypergraph_ka(ka)console.print(f"[blue]Knowledge Abstract:[/blue] {ka_path}")console.print(f"[blue]Template:[/blue] {template}")@@ -669,16 +667,10 @@ def export_csv_cmd(with console.status("[bold blue]Exporting to CSV..."):try:- export_to_csv(- ka.nodes,- ka.edges,- node_id_extractor=ka.node_key_extractor,- incident_nodes_extractor=ka.nodes_in_edge_extractor,- folder_path=output_path,- edge_id_extractor=getattr(ka, "edge_key_extractor", None),- hypergraph=hypergraph,- overwrite=force,- )+ export_ka_csv(ka, output_path, overwrite=force)+ except GraphTypeError as e:+ console.print(f"[red]Error:[/red] {e}")+ raise typer.Exit(1)except FileExistsError:console.print("[red]Error:[/red] Output directory already exists and is not empty. "@@ -816,6 +808,59 @@ def info()+def _print_jsonish(payload) -> None:+ import json++ if isinstance(payload, (dict, list)):+ console.print_json(json.dumps(payload, indent=2, ensure_ascii=False))+ else:+ console.print(str(payload))+ console.print()+++def _print_search_section(title: str, items) -> None:+ console.print(f"[bold cyan]{title}[/bold cyan]")+ if not items:+ console.print("[dim](none)[/dim]")+ console.print()+ return+ if isinstance(items, dict):+ _print_jsonish(items)+ return+ for item in items:+ _print_jsonish(item)+++def _print_search_hits(hits) -> None:+ """Print `he search` hits from :class:`SearchHits`."""+ if hits.count == 0:+ console.print("[yellow]No results found.[/yellow]")+ return++ console.print(f"[bold green]Found {hits.count} result(s):[/bold green]")+ console.print()++ if hits.kind == "mapping":+ preferred = [key for key in ("themes", "entities") if key in hits.payload]+ other = [key for key in hits.payload if key not in preferred]+ for key in preferred + other:+ title = key[:1].upper() + key[1:] if key else key+ _print_search_section(title, hits.payload[key])+ return++ if hits.kind == "graph":+ _print_search_section("Nodes", hits.payload.get("nodes") or [])+ _print_search_section("Edges", hits.payload.get("edges") or [])+ community = hits.payload.get("community_context")+ if isinstance(community, dict) and community:+ _print_search_section("Community", community)+ return++ for i, result in enumerate(hits.payload.get("results") or [], 1):+ console.print(f"[bold cyan]Result {i}:[/bold cyan]")+ _print_jsonish(result)++@app.command(name="search")def search(ka_path: str = typer.Argument(..., help="Knowledge Abstract directory"),@@ -829,8 +874,9 @@ def search(),):"""Semantic search in Knowledge Abstract."""+ from hyperextract.utils.search_results import coerce_search_results+logger.info("command=search ka_path=%s query=%s top_k=%d", ka_path, query, top_k)- import jsonvalidate_config()@@ -876,32 +922,15 @@ def search()raise typer.Exit(1)results = ka.search(query, top_k=top_k, **scope_kwargs)- logger.info("stage=search_complete results=%d", len(results))+ hits = coerce_search_results(results)+ logger.info("stage=search_complete results=%d", hits.count)except Exception as e:console.print(f"[red]Error:[/red] {e}")raise typer.Exit(1)console.print()- if not results:- console.print("[yellow]No results found.[/yellow]")- else:- console.print(f"[bold green]Found {len(results)} result(s):[/bold green]")- console.print()-- for i, result in enumerate(results, 1):- console.print(f"[bold cyan]Result {i}:[/bold cyan]")- if hasattr(result, "model_dump"):- console.print_json(- json.dumps(result.model_dump(), indent=2, ensure_ascii=False)- )- elif hasattr(result, "dict"):- console.print_json(- json.dumps(result.dict(), indent=2, ensure_ascii=False)- )- else:- console.print(str(result))- console.print()+ _print_search_hits(hits)console.print("[dim]Continue:[/dim]")console.print(diff --git a/hyperextract/mcp_server.py b/hyperextract/mcp_server.pyindex 3b4a1c1..313b43c 100644--- a/hyperextract/mcp_server.py+++ b/hyperextract/mcp_server.py@@ -152,24 +152,24 @@ def search(ka_path: str, query: str, top_k: int = 5) -> str:query: Natural-language search query.top_k: Maximum number of results (for graphs: nodes and edges each).- Returns matching nodes/edges as JSON. The KA must have an index- (build it with `he build-index`).+ Returns JSON shaped by the AutoType search return via SearchHits:++ - 2-tuple → ``{"nodes": [...], "edges": [...]}``+ - 3-tuple → same plus ``community_context`` (``null`` is written)+ - dict → passed through (values recursively dumped)+ - list → ``{"results": [...]}``++ The KA must have an index (build it with `he build-index`)."""+ from hyperextract.utils.search_results import coerce_search_results+ka = _load_ka(ka_path)try:results = ka.search(query, top_k=top_k)except ValueError as e:return f"Cannot search: {e}. Build the index first with `he build-index {ka_path}`."- if isinstance(results, tuple):- nodes, edges = results- return _dump(- {- "nodes": [_model_to_dict(n) for n in nodes],- "edges": [_model_to_dict(e) for e in edges],- }- )- return _dump({"results": [_model_to_dict(r) for r in results]})+ return _dump(coerce_search_results(results).payload)def ask(ka_path: str, question: str, top_k: int = 5) -> str:@@ -221,23 +221,6 @@ def export_obsidian(return f"Exported {count} notes to {vault}"-def _is_hypergraph_ka(ka) -> bool:- """True for AutoHypergraph; temporal/spatial graphs are pairwise."""- if type(ka).__name__ == "AutoHypergraph":- return True- meta = getattr(ka, "metadata", None)- return isinstance(meta, dict) and meta.get("type") == "hypergraph"---def _require_graph_ka(ka) -> str | None:- if hasattr(ka, "export_obsidian"):- return None- return (- "GraphML/CSV export is only supported for graph-type knowledge abstracts "- "(graph, hypergraph, temporal/spatial graphs)."- )--def export_graphml(ka_path: str, output: str) -> str:"""Export a knowledge abstract to GraphML.@@ -245,24 +228,17 @@ def export_graphml(ka_path: str, output: str) -> str:ka_path: Path to the knowledge abstract directory.output: Destination ``.graphml`` file.- Uses the same ``export_to_graphml`` implementation as ``he export graphml``.+ Uses the same ``export_ka_graphml`` adapter as ``he export graphml``.Does not create, mutate, or delete the KA."""- from hyperextract.utils.exporters import GraphMLHypergraphError, export_to_graphml+ from hyperextract.utils.exporters import GraphMLHypergraphError+ from hyperextract.utils.exporters.ka import GraphTypeError, export_ka_graphmlka = _load_ka(ka_path)- err = _require_graph_ka(ka)- if err:- return errtry:- dest = export_to_graphml(- ka.nodes,- ka.edges,- node_id_extractor=ka.node_key_extractor,- incident_nodes_extractor=ka.nodes_in_edge_extractor,- file_path=output,- edge_id_extractor=getattr(ka, "edge_key_extractor", None),- )+ dest = export_ka_graphml(ka, output)+ except GraphTypeError as e:+ return str(e)except GraphMLHypergraphError as e:return str(e)return f"Wrote GraphML to {dest}"@@ -276,39 +252,27 @@ def export_csv(ka_path: str, output: str, overwrite: bool = False) -> str:output: Destination directory.overwrite: Allow writing into an existing, non-empty directory.- Uses the same ``export_to_csv`` implementation as ``he export csv``.+ Uses the same ``export_ka_csv`` adapter as ``he export csv``.Does not create, mutate, or delete the KA."""- from hyperextract.utils.exporters import export_to_csv+ from hyperextract.utils.exporters.ka import (+ GraphTypeError,+ export_ka_csv,+ is_hypergraph_ka,+ )ka = _load_ka(ka_path)- err = _require_graph_ka(ka)- if err:- return err- hypergraph = _is_hypergraph_ka(ka)+ hypergraph = is_hypergraph_ka(ka)try:- dest = export_to_csv(- ka.nodes,- ka.edges,- node_id_extractor=ka.node_key_extractor,- incident_nodes_extractor=ka.nodes_in_edge_extractor,- folder_path=output,- edge_id_extractor=getattr(ka, "edge_key_extractor", None),- hypergraph=hypergraph,- overwrite=overwrite,- )+ dest = export_ka_csv(ka, output, overwrite=overwrite)+ except GraphTypeError as e:+ return str(e)except FileExistsError as e:return f"{e} Pass overwrite=true to write into it."written = "nodes.csv + hyperedges.csv" if hypergraph else "nodes.csv + edges.csv"return f"Wrote {written} to {dest}"-def _model_to_dict(item: Any) -> Any:- if hasattr(item, "model_dump"):- return item.model_dump()- return item--# ---------------------------------------------------------------------------# Server wiring# ---------------------------------------------------------------------------diff --git a/hyperextract/utils/exporters/common.py b/hyperextract/utils/exporters/common.pyindex 91081c1..051d343 100644--- a/hyperextract/utils/exporters/common.py+++ b/hyperextract/utils/exporters/common.py@@ -6,6 +6,7 @@ import AutoType classes."""from collections.abc import Callable, Sequence+from pathlib import Pathfrom typing import Anyfrom pydantic import BaseModel@@ -119,3 +120,40 @@ def incident_ids(if isinstance(raw, (list, tuple, set)):return [str(item) for item in raw if item is not None]return [str(raw)]+++def default_edge_id(+ edge: Any, index: int, extractor: Callable[[Any], str] | None+) -> str:+ """Return an edge id from ``extractor``, falling back to ``e{index}``."""+ if extractor is None:+ return f"e{index}"+ try:+ value = extractor(edge)+ except Exception as exc:+ logger.debug("export: edge_id_extractor raised %s", exc)+ return f"e{index}"+ if value in (None, ""):+ return f"e{index}"+ return str(value)+++def resolve_export_file(path: str | Path, *, overwrite: bool = False) -> Path:+ """Resolve a file-export destination, optionally refusing overwrite.++ GraphML CLI does not pass ``overwrite`` yet (#123 owns ``--force``).+ JSON-LD / Cypher can reuse this helper after those PRs land.+ """+ dest = Path(path)+ if dest.exists() and dest.is_dir():+ raise IsADirectoryError(+ f"Destination '{dest}' is a directory; pass a file path."+ )+ existing_nonempty = dest.exists() and dest.is_file() and dest.stat().st_size > 0+ if existing_nonempty and not overwrite:+ raise FileExistsError(+ f"Destination '{dest}' already exists. "+ "Pass overwrite=True to overwrite it."+ )+ dest.parent.mkdir(parents=True, exist_ok=True)+ return destdiff --git a/hyperextract/utils/exporters/csv_export.py b/hyperextract/utils/exporters/csv_export.pyindex 25aa448..d725634 100644--- a/hyperextract/utils/exporters/csv_export.py+++ b/hyperextract/utils/exporters/csv_export.py@@ -30,6 +30,7 @@ from hyperextract.utils.logging import get_loggerfrom .common import (HYPEREDGE_MEMBER_SEP,+ default_edge_id,incident_ids,resolve_nodes,scalar_fields,@@ -187,7 +188,7 @@ def _hyperedge_rows(if not known:skipped += 1continue- edge_id = _edge_id(edge, index, edge_id_extractor)+ edge_id = default_edge_id(edge, index, edge_id_extractor)# Sorted for stable output; binary CSV must not sort endpoints.members_cell = HYPEREDGE_MEMBER_SEP.join(sorted(known))row: dict[str, Any] = {"id": edge_id, "members": members_cell}@@ -203,19 +204,6 @@ def _hyperedge_rows(return rows, skipped-def _edge_id(edge: Any, index: int, extractor: Callable[[Any], str] | None) -> str:- if extractor is None:- return f"e{index}"- try:- value = extractor(edge)- except Exception as exc:- logger.debug("export.csv: edge_id_extractor raised %s", exc)- return f"e{index}"- if value in (None, ""):- return f"e{index}"- return str(value)--def _write_csv(path: Path, primary: Sequence[str], rows: list[dict[str, Any]]) -> None:fieldnames = _fieldnames(primary, rows)with path.open("w", encoding="utf-8", newline="") as handle:diff --git a/hyperextract/utils/exporters/graphml.py b/hyperextract/utils/exporters/graphml.pyindex 776cc1f..630660b 100644--- a/hyperextract/utils/exporters/graphml.py+++ b/hyperextract/utils/exporters/graphml.py@@ -18,6 +18,7 @@ from pydantic import BaseModelfrom hyperextract.utils.logging import get_loggerfrom .common import (+ default_edge_id,graphml_attr_type,graphml_attr_value,incident_ids,@@ -112,7 +113,7 @@ def export_to_graphml(target,)continue- edge_id = _edge_id(edge, index, edge_id_extractor)+ edge_id = default_edge_id(edge, index, edge_id_extractor)fields = scalar_fields(edge)for name, value in fields.items():edge_keys[name] = merge_graphml_type(@@ -129,7 +130,7 @@ def export_to_graphml(missing,)continue- edge_id = _edge_id(edge, index, edge_id_extractor)+ edge_id = default_edge_id(edge, index, edge_id_extractor)fields = scalar_fields(edge)for name, value in fields.items():hyperedge_keys[name] = merge_graphml_type(@@ -159,19 +160,6 @@ def export_to_graphml(return dest-def _edge_id(edge: Any, index: int, extractor: Callable[[Any], str] | None) -> str:- if extractor is None:- return f"e{index}"- try:- value = extractor(edge)- except Exception as exc:- logger.debug("export.graphml: edge_id_extractor raised %s", exc)- return f"e{index}"- if value in (None, ""):- return f"e{index}"- return str(value)--def _key_id(prefix: str, name: str) -> str:safe = "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in name)if not safe or safe[0].isdigit():diff --git a/hyperextract/utils/exporters/ka.py b/hyperextract/utils/exporters/ka.pynew file mode 100644index 0000000..86268cc--- /dev/null+++ b/hyperextract/utils/exporters/ka.py@@ -0,0 +1,65 @@+"""KA-level adapters for GraphML and CSV export.++CLI ``he export graphml/csv`` and MCP ``export_graphml`` / ``export_csv``+call these functions so extractor wiring and the graph-type check live in+one place. Encoders stay pure functions over node/edge models.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from .csv_export import export_to_csv+from .graphml import export_to_graphml++GRAPH_TYPE_ERROR = (+ "GraphML/CSV export is only supported for graph-type knowledge abstracts "+ "(graph, hypergraph, temporal/spatial graphs)."+)+++class GraphTypeError(ValueError):+ """Raised when a non-graph KA is passed to a graph exporter."""+++def is_hypergraph_ka(ka: Any) -> bool:+ """True for AutoHypergraph; temporal/spatial graphs are pairwise."""+ if type(ka).__name__ == "AutoHypergraph":+ return True+ meta = getattr(ka, "metadata", None)+ return isinstance(meta, dict) and meta.get("type") == "hypergraph"+++def require_graph_ka(ka: Any) -> None:+ if hasattr(ka, "export_obsidian"):+ return+ raise GraphTypeError(GRAPH_TYPE_ERROR)+++def export_ka_graphml(ka: Any, dest: str | Path) -> Path:+ """Export a loaded graph-family KA to GraphML."""+ require_graph_ka(ka)+ return export_to_graphml(+ ka.nodes,+ ka.edges,+ node_id_extractor=ka.node_key_extractor,+ incident_nodes_extractor=ka.nodes_in_edge_extractor,+ file_path=dest,+ edge_id_extractor=getattr(ka, "edge_key_extractor", None),+ )+++def export_ka_csv(ka: Any, dest: str | Path, *, overwrite: bool = False) -> Path:+ """Export a loaded graph-family KA to CSV tables."""+ require_graph_ka(ka)+ return export_to_csv(+ ka.nodes,+ ka.edges,+ node_id_extractor=ka.node_key_extractor,+ incident_nodes_extractor=ka.nodes_in_edge_extractor,+ folder_path=dest,+ edge_id_extractor=getattr(ka, "edge_key_extractor", None),+ hypergraph=is_hypergraph_ka(ka),+ overwrite=overwrite,+ )diff --git a/hyperextract/utils/search_results.py b/hyperextract/utils/search_results.pynew file mode 100644index 0000000..fe5d85e--- /dev/null+++ b/hyperextract/utils/search_results.py@@ -0,0 +1,78 @@+"""Normalize AutoType.search returns for CLI and MCP display.++``AutoType.search`` keeps its native shapes (list, ``(nodes, edges)``,+``(nodes, edges, community_context)``, or a mapping). Presentation layers+must not iterate a graph tuple as two opaque results.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Literal++SearchKind = Literal["list", "graph", "mapping"]+++def dump_search_value(item: Any) -> Any:+ """Recursively coerce Pydantic models (and nested containers) to dicts."""+ if hasattr(item, "model_dump"):+ return item.model_dump()+ if hasattr(item, "dict") and callable(item.dict) and not isinstance(item, dict):+ return item.dict()+ if isinstance(item, list):+ return [dump_search_value(child) for child in item]+ if isinstance(item, tuple):+ return [dump_search_value(child) for child in item]+ if isinstance(item, dict):+ return {key: dump_search_value(value) for key, value in item.items()}+ return item+++@dataclass(frozen=True)+class SearchHits:+ """Display-ready search hits.++ ``kind``:+ * ``list`` — payload ``{"results": [...]}``+ * ``graph`` — payload ``{"nodes", "edges"}`` plus optional+ ``community_context`` (may be ``None``)+ * ``mapping`` — dumped mapping (e.g. cog_rag ``themes`` / ``entities``)+ """++ kind: SearchKind+ payload: dict[str, Any]++ @property+ def count(self) -> int:+ """Hit count: nodes+edges for graphs, not ``len(tuple)``."""+ if self.kind == "list":+ results = self.payload.get("results") or []+ return len(results) if isinstance(results, list) else 1+ if self.kind == "graph":+ nodes = self.payload.get("nodes") or []+ edges = self.payload.get("edges") or []+ return len(nodes) + len(edges)+ total = 0+ for value in self.payload.values():+ total += len(value) if isinstance(value, list) else 1+ return total+++def coerce_search_results(results: Any) -> SearchHits:+ """Wrap an AutoType search return into :class:`SearchHits`."""+ if results is None:+ return SearchHits(kind="list", payload={"results": []})+ if isinstance(results, dict):+ return SearchHits(kind="mapping", payload=dump_search_value(results))+ if isinstance(results, tuple):+ nodes = dump_search_value(results[0] if len(results) >= 1 else [])+ edges = dump_search_value(results[1] if len(results) >= 2 else [])+ payload: dict[str, Any] = {"nodes": nodes, "edges": edges}+ if len(results) >= 3:+ payload["community_context"] = dump_search_value(results[2])+ return SearchHits(kind="graph", payload=payload)+ if isinstance(results, list):+ return SearchHits(+ kind="list", payload={"results": dump_search_value(results)}+ )+ return SearchHits(kind="list", payload={"results": [dump_search_value(results)]})diff --git a/tests/cli/test_search.py b/tests/cli/test_search.pynew file mode 100644index 0000000..13e21d9--- /dev/null+++ b/tests/cli/test_search.py@@ -0,0 +1,128 @@+"""CLI rendering of `he search` across AutoType return shapes."""++import json+from pathlib import Path+from unittest.mock import MagicMock, patch++from pydantic import BaseModel+from typer.testing import CliRunner++from hyperextract.cli.cli import app++runner = CliRunner()+++class _Node(BaseModel):+ name: str+++class _Edge(BaseModel):+ source: str+ target: str+++class _Theme(BaseModel):+ title: str+++def _ka_dir(tmp_path: Path) -> Path:+ ka = tmp_path / "ka"+ ka.mkdir()+ (ka / "data.json").write_text("{}", encoding="utf-8")+ (ka / "metadata.json").write_text(+ json.dumps({"template": "general/graph", "lang": "en"}),+ encoding="utf-8",+ )+ index = ka / "index"+ index.mkdir()+ (index / "dummy").write_text("x", encoding="utf-8")+ return ka+++def _invoke_search(tmp_path, search_return):+ ka_dir = _ka_dir(tmp_path)+ fake = MagicMock()+ fake.search.return_value = search_return+ fake.load = MagicMock()+ with (+ patch("hyperextract.cli.cli.validate_config"),+ patch("hyperextract.cli.cli.Template.create", return_value=fake),+ ):+ return runner.invoke(app, ["search", str(ka_dir), "query"])+++def test_search_pair_tuple_prints_nodes_and_edges(tmp_path):+ nodes = [_Node(name="Alice")]+ edges = [_Edge(source="Alice", target="Bob")]+ result = _invoke_search(tmp_path, (nodes, edges))++ assert result.exit_code == 0, result.output+ assert "Nodes" in result.output+ assert "Edges" in result.output+ assert "Alice" in result.output+ assert "Result 1:" not in result.output+ assert "Found 2 result(s)" in result.output+++def test_search_empty_pair_tuple_prints_no_results(tmp_path):+ result = _invoke_search(tmp_path, ([], []))++ assert result.exit_code == 0, result.output+ assert "No results found." in result.output+ assert "Result 1:" not in result.output+ assert "Nodes" not in result.output+++def test_search_triple_prints_community_when_present(tmp_path):+ nodes = [_Node(name="Alice")]+ edges = [_Edge(source="Alice", target="Bob")]+ community = {"summary": "a cluster"}+ result = _invoke_search(tmp_path, (nodes, edges, community))++ assert result.exit_code == 0, result.output+ assert "Nodes" in result.output+ assert "Edges" in result.output+ assert "Community" in result.output+ assert "a cluster" in result.output+ assert "Result 1:" not in result.output+++def test_search_triple_omits_none_community(tmp_path):+ nodes = [_Node(name="Alice")]+ edges = []+ result = _invoke_search(tmp_path, (nodes, edges, None))++ assert result.exit_code == 0, result.output+ assert "Nodes" in result.output+ assert "Community" not in result.output+++def test_search_list_keeps_numbered_results(tmp_path):+ result = _invoke_search(tmp_path, [_Node(name="Alice"), _Node(name="Bob")])++ assert result.exit_code == 0, result.output+ assert "Found 2 result(s)" in result.output+ assert "Result 1:" in result.output+ assert "Result 2:" in result.output+ assert "Alice" in result.output+++def test_search_dict_sections_themes_and_entities(tmp_path):+ payload = {+ "themes": [_Theme(title="power")],+ "entities": [_Node(name="Tesla")],+ }+ result = _invoke_search(tmp_path, payload)++ assert result.exit_code == 0, result.output+ assert "themes" in result.output.lower() or "Themes" in result.output+ assert "entities" in result.output.lower() or "Entities" in result.output+ assert "Tesla" in result.output+ assert "Result 1:" not in result.output+++def test_search_empty_list_prints_no_results(tmp_path):+ result = _invoke_search(tmp_path, [])++ assert result.exit_code == 0, result.output+ assert "No results found." in result.outputdiff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.pyindex ef4c689..2d0ea23 100644--- a/tests/test_mcp_server.py+++ b/tests/test_mcp_server.py@@ -95,6 +95,61 @@ def test_search_returns_nodes_and_edges(monkeypatch):assert isinstance(out["nodes"], list)+def test_search_graph_rag_triple_includes_community_context(monkeypatch):+ class _TripleKA:+ def search(self, query, top_k=5):+ return (+ [Entity(name="Alice")],+ [Relation(source="Alice", target="Bob", relation_type="knows")],+ {"summary": "cluster"},+ )++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _TripleKA())+ out = json.loads(mcp_server.search("x", "query"))+ assert "nodes" in out and "edges" in out+ assert out["community_context"] == {"summary": "cluster"}+ assert out["nodes"][0]["name"] == "Alice"+++def test_search_graph_rag_triple_writes_null_community(monkeypatch):+ class _TripleKA:+ def search(self, query, top_k=5):+ return ([], [], None)++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _TripleKA())+ out = json.loads(mcp_server.search("x", "query"))+ assert out["nodes"] == []+ assert out["edges"] == []+ assert out["community_context"] is None+++def test_search_list_wraps_results(monkeypatch):+ class _ListKA:+ def search(self, query, top_k=5):+ return [Entity(name="Alice"), Entity(name="Bob")]++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())+ out = json.loads(mcp_server.search("x", "query"))+ assert "results" in out+ assert [item["name"] for item in out["results"]] == ["Alice", "Bob"]+++def test_search_dict_recursively_dumps_models(monkeypatch):+ class _DictKA:+ def search(self, query, top_k=5):+ return {+ "themes": [Entity(name="power")],+ "entities": [Entity(name="Tesla")],+ "nested": {"inner": [Entity(name="nested")]},+ }++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _DictKA())+ out = json.loads(mcp_server.search("x", "query"))+ assert out["themes"][0]["name"] == "power"+ assert out["entities"][0]["name"] == "Tesla"+ assert out["nested"]["inner"][0]["name"] == "nested"++def test_search_without_index_is_handled(monkeypatch):g = AutoGraph(node_schema=Entity,@@ -166,6 +221,29 @@ def test_export_csv(monkeypatch, tmp_path):assert "nodes.csv + edges.csv" in out+def test_export_graphml_rejects_non_graph(monkeypatch, tmp_path):+ class _ListKA:+ pass++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())+ out = mcp_server.export_graphml("x", str(tmp_path / "out.graphml"))+ assert out == (+ "GraphML/CSV export is only supported for graph-type knowledge abstracts "+ "(graph, hypergraph, temporal/spatial graphs)."+ )+++def test_export_csv_rejects_non_graph_with_same_message(monkeypatch, tmp_path):+ class _ListKA:+ pass++ monkeypatch.setattr(mcp_server, "_load_ka", lambda p: _ListKA())+ graphml = mcp_server.export_graphml("x", str(tmp_path / "out.graphml"))+ csv_out = mcp_server.export_csv("x", str(tmp_path / "csv"))+ assert graphml == csv_out+ assert "graph-type knowledge abstracts" in graphml++# ---------------------------------------------------------------------------# FastMCP wiring (needs the optional `mcp` package)# ---------------------------------------------------------------------------diff --git a/tests/utils/test_exporters.py b/tests/utils/test_exporters.pyindex 4e54e67..86e8c99 100644--- a/tests/utils/test_exporters.py+++ b/tests/utils/test_exporters.py@@ -20,6 +20,13 @@ from hyperextract.utils.exporters import (export_to_csv,export_to_graphml,)+from hyperextract.utils.exporters.common import default_edge_id, resolve_export_file+from hyperextract.utils.exporters.ka import (+ GRAPH_TYPE_ERROR,+ GraphTypeError,+ export_ka_csv,+ export_ka_graphml,+)from hyperextract.utils.exporters.graphml import GRAPHML_NSrunner = CliRunner()@@ -346,6 +353,47 @@ def _ka_dir(tmp_path):return ka+class TestCommonHelpers:+ def test_default_edge_id_falls_back(self):+ def _boom(_edge):+ raise ValueError("no id")++ assert default_edge_id(object(), 3, None) == "e3"+ assert default_edge_id(object(), 1, lambda e: None) == "e1"+ assert default_edge_id(object(), 1, lambda e: "") == "e1"+ assert default_edge_id(object(), 1, _boom) == "e1"+ assert default_edge_id(object(), 1, lambda e: "rel") == "rel"++ def test_resolve_export_file_refuses_nonempty_without_overwrite(self, tmp_path):+ dest = tmp_path / "out.graphml"+ dest.write_text("KEEP", encoding="utf-8")+ with pytest.raises(FileExistsError):+ resolve_export_file(dest, overwrite=False)+ assert dest.read_text(encoding="utf-8") == "KEEP"+ resolved = resolve_export_file(dest, overwrite=True)+ assert resolved == dest++ def test_export_ka_graphml_and_csv_match_encoders(self, tmp_path):+ fake = FakeGraphKA(+ [Entity(name="A"), Entity(name="B")],+ [Relation(source="B", target="A", relation_type="leads_to")],+ )+ path = export_ka_graphml(fake, tmp_path / "g.graphml")+ _root, graph, ns = _parse_graphml(path)+ assert _edge_endpoints(graph, ns) == [("B", "A")]+ folder = export_ka_csv(fake, tmp_path / "csv")+ with (folder / "edges.csv").open(encoding="utf-8", newline="") as handle:+ rows = list(csv.DictReader(handle))+ assert rows[0]["source"] == "B"++ def test_export_ka_rejects_non_graph(self, tmp_path):+ with pytest.raises(GraphTypeError, match="graph-type"):+ export_ka_graphml(FakeListKA(), tmp_path / "g.graphml")+ with pytest.raises(GraphTypeError) as exc:+ export_ka_csv(FakeListKA(), tmp_path / "csv")+ assert str(exc.value) == GRAPH_TYPE_ERROR++class TestCLIExport:def test_graphml_writes_directed_edge(self, tmp_path):ka_dir = _ka_dir(tmp_path)diff --git a/tests/utils/test_search_results.py b/tests/utils/test_search_results.pynew file mode 100644index 0000000..b0764e1--- /dev/null+++ b/tests/utils/test_search_results.py@@ -0,0 +1,76 @@+"""Unit tests for SearchHits / coerce_search_results."""++from pydantic import BaseModel++from hyperextract.utils.search_results import SearchHits, coerce_search_results+++class _Node(BaseModel):+ name: str+++class _Edge(BaseModel):+ source: str+ target: str+++class _Theme(BaseModel):+ title: str+++def test_list_wraps_results_and_counts_items():+ hits = coerce_search_results([_Node(name="Alice"), _Node(name="Bob")])+ assert hits.kind == "list"+ assert hits.count == 2+ assert hits.payload == {+ "results": [{"name": "Alice"}, {"name": "Bob"}],+ }+++def test_pair_tuple_count_is_nodes_plus_edges_not_arity():+ hits = coerce_search_results(+ ([_Node(name="Alice")], [_Edge(source="Alice", target="Bob")])+ )+ assert hits.kind == "graph"+ assert hits.count == 2+ assert hits.payload["nodes"] == [{"name": "Alice"}]+ assert hits.payload["edges"] == [{"source": "Alice", "target": "Bob"}]+ assert "community_context" not in hits.payload+++def test_empty_pair_tuple_has_zero_count():+ hits = coerce_search_results(([], []))+ assert isinstance(hits, SearchHits)+ assert hits.kind == "graph"+ assert hits.count == 0+ assert hits.payload == {"nodes": [], "edges": []}+++def test_triple_includes_null_community_context():+ hits = coerce_search_results(([], [], None))+ assert hits.kind == "graph"+ assert hits.count == 0+ assert hits.payload["community_context"] is None+++def test_triple_dumps_community_dict():+ hits = coerce_search_results(+ ([_Node(name="Alice")], [], {"summary": "cluster"})+ )+ assert hits.count == 1+ assert hits.payload["community_context"] == {"summary": "cluster"}+++def test_mapping_recursively_dumps_models():+ hits = coerce_search_results(+ {+ "themes": [_Theme(title="power")],+ "entities": [_Node(name="Tesla")],+ "nested": {"inner": [_Node(name="nested")]},+ }+ )+ assert hits.kind == "mapping"+ assert hits.count == 3+ assert hits.payload["themes"] == [{"title": "power"}]+ assert hits.payload["entities"] == [{"name": "Tesla"}]+ assert hits.payload["nested"] == {"inner": [{"name": "nested"}]}