File size: 38,351 Bytes
3fbbaab 9135e0b 3fbbaab 21ff762 3fbbaab 9135e0b 3fbbaab 0bcc198 3fbbaab 0bcc198 3fbbaab 0bcc198 3fbbaab 21ff762 3fbbaab 1bbe168 9135e0b 1bbe168 3fbbaab 21ff762 3fbbaab 21ff762 b9238de 21ff762 3fbbaab 21ff762 b9238de 21ff762 b9238de 21ff762 424e16a 21ff762 b9238de 3fbbaab b9238de 3fbbaab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 | """
test_harness_ctx_core.py -- CtxCoreToolbox integration with the harness.
Covers:
* Tool-definition shapes the model will see.
* Dispatcher routing + ctx__ namespace guard.
* Each dispatcher's happy path + error paths against a synthetic
wiki + graph built on tmp_path (no reliance on the real wiki).
* Query tokenisation + stopword removal.
* Integer argument clamping.
* make_tool_executor composition (ctx-owned vs fallback).
"""
from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Any
import networkx as nx
import pytest
from ctx.adapters.generic.ctx_core_tools import (
CtxCoreToolbox,
_clamp_int,
_excerpt,
_file_signature,
_query_to_tags,
make_tool_executor,
)
from ctx.adapters.generic.providers import ToolCall, ToolDefinition
# ── Helpers: build a synthetic wiki + graph for the toolbox ────────────────
def _build_synthetic_graph(tmp_path: Path) -> Path:
"""Write a minimal but valid graph.json under graphify-out/."""
G = nx.Graph()
G.graph["external_catalog_nodes"] = {"skills.sh": 1}
G.graph["source_catalog_nodes"] = {"skills.sh": 1}
G.add_node("skill:python-patterns", label="python-patterns", type="skill",
tags=["python", "patterns"])
G.add_node("skill:fastapi-pro", label="fastapi-pro", type="skill",
tags=["python", "api", "web"])
G.add_node("skill:django-pro", label="django-pro", type="skill",
tags=["python", "web"])
G.add_node("agent:code-reviewer", label="code-reviewer", type="agent",
tags=["python", "review"])
G.add_node("mcp-server:filesystem", label="filesystem", type="mcp-server",
tags=["filesystem", "io"])
G.add_edge("skill:python-patterns", "skill:fastapi-pro",
weight=0.8, shared_tags=["python"])
G.add_edge("skill:python-patterns", "agent:code-reviewer",
weight=0.6, shared_tags=["python"])
G.add_edge("skill:fastapi-pro", "skill:django-pro",
weight=0.4, shared_tags=["python", "web"])
out_dir = tmp_path / "graphify-out"
out_dir.mkdir(parents=True, exist_ok=True)
path = out_dir / "graph.json"
data = nx.node_link_data(G, edges="edges")
path.write_text(json.dumps(data), encoding="utf-8")
return path
def _build_synthetic_wiki(tmp_path: Path) -> Path:
"""Create a tiny wiki with a few entity pages + converted stubs."""
wiki = tmp_path / "wiki"
skills = wiki / "entities" / "skills"
agents = wiki / "entities" / "agents"
mcps = wiki / "entities" / "mcp-servers" / "f"
skills.mkdir(parents=True)
agents.mkdir(parents=True)
mcps.mkdir(parents=True)
(skills / "python-patterns.md").write_text(
"---\n"
"name: python-patterns\n"
"title: Python Patterns\n"
"tags: [python, patterns]\n"
"status: cataloged\n"
"---\n"
"# Python Patterns\n\n"
"Idiomatic Python patterns and best practices.\n",
encoding="utf-8",
)
(skills / "fastapi-pro.md").write_text(
"---\n"
"name: fastapi-pro\n"
"title: FastAPI Pro\n"
"tags: [python, api, web]\n"
"status: cataloged\n"
"---\n"
"# FastAPI Pro\n\n"
"Advanced FastAPI patterns for production.\n",
encoding="utf-8",
)
(agents / "code-reviewer.md").write_text(
"---\n"
"name: code-reviewer\n"
"title: Code Reviewer\n"
"type: agent\n"
"tags: [review, quality]\n"
"status: cataloged\n"
"---\n"
"# Code Reviewer\n\n"
"Reviews code for defects and quality risks.\n",
encoding="utf-8",
)
(mcps / "filesystem.md").write_text(
"---\n"
"name: filesystem\n"
"title: Filesystem MCP\n"
"type: mcp-server\n"
"tags: [filesystem, io]\n"
"status: cataloged\n"
"---\n"
"# Filesystem MCP\n\n"
"Filesystem tools for local files.\n",
encoding="utf-8",
)
# Also a converted stub so wiki_query sees has_transformed=True.
converted = wiki / "converted" / "python-patterns"
converted.mkdir(parents=True)
(converted / "SKILL.md").write_text("# body", encoding="utf-8")
return wiki
@pytest.fixture()
def toolbox(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> CtxCoreToolbox:
"""Toolbox pointed at a synthetic wiki + graph."""
import ctx_config
monkeypatch.setattr(
ctx_config.cfg,
"graph_semantic_cache_dir",
tmp_path / "semantic-cache",
)
graph_path = _build_synthetic_graph(tmp_path)
wiki_dir = _build_synthetic_wiki(tmp_path)
return CtxCoreToolbox(
wiki_dir=wiki_dir,
graph_path=graph_path,
lifecycle_dir=tmp_path / "runtime",
)
def test_graph_cache_reloads_when_graph_json_changes(tmp_path: Path) -> None:
graph_path = tmp_path / "graph.json"
def write_graph(target: str) -> None:
graph = nx.Graph()
graph.add_node("skill:seed", label="seed", type="skill", tags=[])
graph.add_node(f"skill:{target}", label=target, type="skill", tags=[])
graph.add_edge("skill:seed", f"skill:{target}", weight=1.0)
graph_path.write_text(
json.dumps(nx.node_link_data(graph, edges="edges")),
encoding="utf-8",
)
write_graph("old-target")
toolbox = CtxCoreToolbox(wiki_dir=tmp_path / "wiki", graph_path=graph_path)
first = json.loads(toolbox.dispatch(ToolCall(
id="c1",
name="ctx__graph_query",
arguments={"seeds": ["seed"], "max_hops": 1},
)))
write_graph("new-target")
second = json.loads(toolbox.dispatch(ToolCall(
id="c2",
name="ctx__graph_query",
arguments={"seeds": ["seed"], "max_hops": 1},
)))
assert first["results"][0]["name"] == "old-target"
assert second["results"][0]["name"] == "new-target"
def test_graph_file_signature_detects_same_size_rewrite(
tmp_path: Path,
) -> None:
graph_path = tmp_path / "graph.json"
fixed_time_ns = 1_700_000_000_000_000_000
graph_path.write_text('{"target":"old-target"}', encoding="utf-8")
os.utime(graph_path, ns=(fixed_time_ns, fixed_time_ns))
first = _file_signature(graph_path)
graph_path.write_text('{"target":"new-target"}', encoding="utf-8")
os.utime(graph_path, ns=(fixed_time_ns, fixed_time_ns))
second = _file_signature(graph_path)
assert graph_path.stat().st_size == len('{"target":"new-target"}')
assert first is not None
assert second is not None
assert first[:2] == second[:2]
assert first != second
def test_wiki_page_cache_reloads_when_entity_page_changes(tmp_path: Path) -> None:
wiki = _build_synthetic_wiki(tmp_path)
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
first = json.loads(toolbox.dispatch(ToolCall(
id="c1",
name="ctx__wiki_search",
arguments={"query": "newunique"},
)))
(wiki / "entities" / "skills" / "new-skill.md").write_text(
"---\nname: new-skill\ntags: [newunique]\n---\n# New Skill\n",
encoding="utf-8",
)
second = json.loads(toolbox.dispatch(ToolCall(
id="c2",
name="ctx__wiki_search",
arguments={"query": "newunique"},
)))
assert first["results"] == []
assert second["results"][0]["slug"] == "new-skill"
def test_semantic_miss_cache_clears_when_embedding_artifacts_change(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import ctx_config
from ctx.core.resolve import recommendations as rec
wiki = tmp_path / "wiki"
cache_dir = wiki / ".embedding-cache" / "graph"
cache_dir.mkdir(parents=True)
monkeypatch.setattr(ctx_config.cfg, "graph_semantic_cache_dir", cache_dir)
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
graph = nx.Graph()
toolbox._refresh_semantic_cache_signature()
rec._semantic_cache[graph] = None
(cache_dir / "topk-state.json").write_text("{}", encoding="utf-8")
toolbox._refresh_semantic_cache_signature()
assert len(rec._semantic_cache) == 0
# ── Tool definitions ────────────────────────────────────────────────────
class TestToolDefinitions:
def test_ctx_tools_exposed(self, toolbox: CtxCoreToolbox) -> None:
defs = toolbox.tool_definitions()
names = [d.name for d in defs]
assert set(names) == {
"ctx__recommend_bundle",
"ctx__graph_query",
"ctx__wiki_search",
"ctx__wiki_get",
"ctx__observe_dev_event",
"ctx__load_entity",
"ctx__mark_entity_used",
"ctx__record_validation",
"ctx__record_escalation",
"ctx__unload_entity",
"ctx__session_end",
"ctx__session_state",
}
def test_all_are_tool_definitions(self, toolbox: CtxCoreToolbox) -> None:
for td in toolbox.tool_definitions():
assert isinstance(td, ToolDefinition)
assert td.description # non-empty
assert td.parameters["type"] == "object"
assert "properties" in td.parameters
def test_recommend_requires_query(self, toolbox: CtxCoreToolbox) -> None:
td = next(
d for d in toolbox.tool_definitions()
if d.name == "ctx__recommend_bundle"
)
assert td.parameters["required"] == ["query"]
def test_graph_query_requires_seeds(self, toolbox: CtxCoreToolbox) -> None:
td = next(
d for d in toolbox.tool_definitions()
if d.name == "ctx__graph_query"
)
assert td.parameters["required"] == ["seeds"]
# ── Namespace + dispatch ───────────────────────────────────────────────────
class TestDispatchRouting:
def test_owns(self, toolbox: CtxCoreToolbox) -> None:
assert toolbox.owns("ctx__recommend_bundle")
assert toolbox.owns("ctx__anything")
assert not toolbox.owns("fs__read_file")
assert not toolbox.owns("no_separator")
def test_dispatch_rejects_non_ctx_call(self, toolbox: CtxCoreToolbox) -> None:
with pytest.raises(ValueError, match="non-ctx call"):
toolbox.dispatch(ToolCall(id="c1", name="fs__read", arguments={}))
def test_dispatch_unknown_tool(self, toolbox: CtxCoreToolbox) -> None:
with pytest.raises(ValueError, match="unknown ctx-core tool"):
toolbox.dispatch(ToolCall(id="c1", name="ctx__bogus", arguments={}))
class TestRuntimeLifecycle:
def test_lifecycle_tools_append_events(
self,
toolbox: CtxCoreToolbox,
tmp_path: Path,
) -> None:
calls: list[tuple[str, dict[str, Any]]] = [
("ctx__observe_dev_event", {
"session_id": "s-1",
"event_type": "task",
"payload": {"goal": "ship api"},
}),
("ctx__load_entity", {
"session_id": "s-1",
"entity_type": "skill",
"slug": "fastapi-pro",
}),
("ctx__mark_entity_used", {
"session_id": "s-1",
"entity_type": "skill",
"slug": "fastapi-pro",
"evidence": "used in implementation",
}),
("ctx__record_validation", {
"session_id": "s-1",
"check_name": "pytest",
"status": "passed",
"command": "python -m pytest",
"summary": "all tests passed",
}),
("ctx__record_escalation", {
"session_id": "s-1",
"trigger": "destructive-action",
"reason": "delete requires user approval",
"severity": "blocking",
}),
("ctx__unload_entity", {
"session_id": "s-1",
"entity_type": "skill",
"slug": "fastapi-pro",
"reason": "not needed",
}),
("ctx__session_end", {"session_id": "s-1", "status": "complete"}),
]
for name, arguments in calls:
result = json.loads(
toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
)
assert result["ok"] is True
events = [
json.loads(line)
for line in (tmp_path / "runtime" / "events.jsonl").read_text(
encoding="utf-8"
).splitlines()
]
assert [event["action"] for event in events] == [
"dev_event",
"load_requested",
"used",
"validation",
"escalation",
"unload_requested",
"session_end",
]
def test_bound_session_id_is_hidden_and_enforced(self, tmp_path: Path) -> None:
toolbox = CtxCoreToolbox(
lifecycle_dir=tmp_path / "runtime",
bound_session_id="host-session",
)
lifecycle_defs = [
definition
for definition in toolbox.tool_definitions()
if definition.name.startswith("ctx__")
and definition.name.rsplit("__", 1)[-1]
in {
"observe_dev_event",
"load_entity",
"mark_entity_used",
"record_validation",
"record_escalation",
"unload_entity",
"session_end",
"session_state",
}
]
assert lifecycle_defs
for definition in lifecycle_defs:
assert "session_id" not in definition.parameters["properties"]
assert "session_id" not in definition.parameters.get("required", [])
loaded = json.loads(toolbox.dispatch(ToolCall(
id="c1",
name="ctx__load_entity",
arguments={"entity_type": "skill", "slug": "fastapi-pro"},
)))
assert loaded["ok"] is True
state = json.loads(toolbox.dispatch(ToolCall(
id="c2",
name="ctx__session_state",
arguments={},
)))
assert state["ok"] is True
assert state["session_id"] == "host-session"
mismatch = json.loads(toolbox.dispatch(ToolCall(
id="c3",
name="ctx__session_state",
arguments={"session_id": "attacker-session"},
)))
assert mismatch == {
"ok": False,
"error": "session_id is host-bound and cannot be overridden",
}
def test_lifecycle_validation_errors_are_structured(
self,
toolbox: CtxCoreToolbox,
) -> None:
result = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__load_entity",
arguments={
"session_id": "s-1",
"entity_type": "bogus",
"slug": "fastapi-pro",
},
))
)
assert result["ok"] is False
assert "entity_type" in result["error"]
def test_session_state_surfaces_unused_loads_as_unload_candidates(
self,
toolbox: CtxCoreToolbox,
) -> None:
for name, arguments in [
("ctx__load_entity", {
"session_id": "s-2",
"entity_type": "skill",
"slug": "fastapi-pro",
}),
("ctx__load_entity", {
"session_id": "s-2",
"entity_type": "agent",
"slug": "code-reviewer",
}),
("ctx__mark_entity_used", {
"session_id": "s-2",
"entity_type": "agent",
"slug": "code-reviewer",
"evidence": "reviewed diff",
}),
]:
toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
result = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__session_state",
arguments={"session_id": "s-2"},
))
)
assert result["ok"] is True
assert [entry["slug"] for entry in result["used"]] == ["code-reviewer"]
assert [entry["slug"] for entry in result["unload_candidates"]] == [
"fastapi-pro",
]
# -- runtime validation ledger ----------------------------------------------
class TestRuntimeValidationLedger:
def test_session_state_surfaces_validation_and_escalation_ledger(
self,
toolbox: CtxCoreToolbox,
) -> None:
for name, arguments in [
("ctx__record_validation", {
"session_id": "s-ledger",
"check_name": "mypy",
"status": "failed",
"command": "python -m mypy src",
"summary": "type gate failed",
"payload": {"errors": 3},
}),
("ctx__record_escalation", {
"session_id": "s-ledger",
"trigger": "validation-failed",
"reason": "mypy failed after retry",
"severity": "blocking",
"payload": {"check_name": "mypy"},
}),
]:
result = json.loads(
toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
)
assert result["ok"] is True
state = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__session_state",
arguments={"session_id": "s-ledger"},
))
)
assert state["validations"] == [{
"check_name": "mypy",
"status": "failed",
"command": "python -m mypy src",
"summary": "type gate failed",
"entity_type": None,
"slug": None,
"payload": {"errors": 3},
}]
assert state["escalations"] == [{
"trigger": "validation-failed",
"reason": "mypy failed after retry",
"severity": "blocking",
"status": "open",
"entity_type": None,
"slug": None,
"payload": {"check_name": "mypy"},
}]
assert state["latest_validation_status"] == "failed"
assert state["open_escalations"] == state["escalations"]
def test_invalid_validation_status_is_structured(
self,
toolbox: CtxCoreToolbox,
) -> None:
result = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__record_validation",
arguments={
"session_id": "s-ledger",
"check_name": "pytest",
"status": "maybe",
},
))
)
assert result["ok"] is False
assert "status" in result["error"]
# -- recommend_bundle --------------------------------------------------------
def test_session_state_suppresses_current_dev_window_unloads(
toolbox: CtxCoreToolbox,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from ctx.adapters.generic import runtime_lifecycle
timestamps = iter([100.0, 101.0, 102.0, 103.0, 104.0, 105.0])
monkeypatch.setattr(runtime_lifecycle.time, "time", lambda: next(timestamps))
for name, arguments in [
("ctx__observe_dev_event", {
"session_id": "s-window",
"event_type": "task",
}),
("ctx__load_entity", {
"session_id": "s-window",
"entity_type": "skill",
"slug": "fastapi-pro",
}),
]:
toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
current_window = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__session_state",
arguments={"session_id": "s-window"},
))
)
assert current_window["unload_candidates"] == []
for name, arguments in [
("ctx__session_end", {"session_id": "s-window"}),
("ctx__observe_dev_event", {
"session_id": "s-window",
"event_type": "resume",
}),
]:
toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
next_window = json.loads(
toolbox.dispatch(ToolCall(
id="c1",
name="ctx__session_state",
arguments={"session_id": "s-window"},
))
)
assert [entry["slug"] for entry in next_window["unload_candidates"]] == [
"fastapi-pro",
]
class TestRecommendBundle:
def test_happy_path_ranks_by_tag_overlap(
self, toolbox: CtxCoreToolbox
) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__recommend_bundle",
arguments={"query": "python web api", "top_k": 5},
)
)
)
assert "error" not in result
assert result["query"] == "python web api"
assert "tags" in result
# python + web + api should score fastapi-pro highly (3 tags match).
names = [r["name"] for r in result["results"]]
assert "fastapi-pro" in names
def test_companion_harnesses_are_separate_from_dev_results(
self,
toolbox: CtxCoreToolbox,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import ctx_init
calls: list[dict[str, Any]] = []
def fake_recommend_harnesses(
goal: str,
*,
top_k: int = 5,
model_provider: str | None = None,
model: str | None = None,
) -> list[dict[str, Any]]:
calls.append({
"goal": goal,
"top_k": top_k,
"model_provider": model_provider,
"model": model,
})
return [{
"name": "langgraph",
"fit_score": 0.92,
"normalized_score": 0.88,
"matching_tags": ["agents"],
"provider_match": "openai",
"detail_url": "https://example.test/langgraph",
"install_command": "ctx-harness-install langgraph",
}]
monkeypatch.setattr(ctx_init, "recommend_harnesses", fake_recommend_harnesses)
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__recommend_bundle",
arguments={
"query": "python agent workflow",
"top_k": 5,
"model_provider": "openai",
"model": "openai/gpt-5.5",
},
)
)
)
assert calls == [{
"goal": "python agent workflow",
"top_k": 5,
"model_provider": "openai",
"model": "openai/gpt-5.5",
}]
assert all(row["type"] != "harness" for row in result["results"])
assert result["companion_harnesses"] == [{
"name": "langgraph",
"type": "harness",
"fit_score": 0.92,
"normalized_score": 0.88,
"matching_tags": ["agents"],
"provider_match": "openai",
"detail_url": "https://example.test/langgraph",
"install_command": "ctx-harness-install langgraph",
}]
def test_companion_harnesses_can_be_empty(
self,
toolbox: CtxCoreToolbox,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import ctx_init
monkeypatch.setattr(ctx_init, "recommend_harnesses", lambda *a, **kw: [])
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__recommend_bundle",
arguments={
"query": "python web api",
"model_provider": "ollama",
},
)
)
)
assert result["companion_harnesses"] == []
def test_empty_query(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1", name="ctx__recommend_bundle",
arguments={"query": ""},
)
)
)
assert "error" in result
def test_pure_stopwords_query(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__recommend_bundle",
arguments={"query": "the a an and"},
)
)
)
assert "error" in result
def test_top_k_clamped(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__recommend_bundle",
arguments={"query": "python", "top_k": 999},
)
)
)
# top_k clamped to <= 50, and our graph has only 5 entities.
assert len(result["results"]) <= 50
def test_missing_graph_returns_empty(self, tmp_path: Path) -> None:
toolbox = CtxCoreToolbox(
graph_path=tmp_path / "does-not-exist.json",
wiki_dir=tmp_path / "wiki",
)
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__recommend_bundle",
arguments={"query": "python"})
)
)
assert "error" in result
assert result["results"] == []
# ── graph_query ────────────────────────────────────────────────────────────
class TestGraphQuery:
def test_happy_path(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__graph_query",
arguments={"seeds": ["python-patterns"], "top_n": 5},
)
)
)
assert "error" not in result
assert result["seeds"] == ["python-patterns"]
names = [r["name"] for r in result["results"]]
# Direct neighbours: fastapi-pro + code-reviewer.
assert "fastapi-pro" in names or "code-reviewer" in names
def test_missing_seeds(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__graph_query",
arguments={"seeds": []})
)
)
assert "error" in result
def test_seeds_not_list(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__graph_query",
arguments={"seeds": "python-patterns"})
)
)
assert "error" in result
def test_max_hops_clamped(self, toolbox: CtxCoreToolbox) -> None:
# max_hops clamps to 1..4; 100 gets capped.
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__graph_query",
arguments={
"seeds": ["python-patterns"],
"max_hops": 100,
"top_n": 5,
},
)
)
)
assert "error" not in result
# ── wiki_search ────────────────────────────────────────────────────────────
class TestWikiSearch:
def test_happy_path(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1", name="ctx__wiki_search",
arguments={"query": "FastAPI patterns"},
)
)
)
assert "error" not in result
slugs = [r["slug"] for r in result["results"]]
# Either of our two pages could match — just confirm we got hits.
assert len(slugs) >= 1
def test_empty_query(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__wiki_search",
arguments={"query": ""})
)
)
assert "error" in result
def test_result_shape(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1", name="ctx__wiki_search",
arguments={"query": "python"},
)
)
)
if result["results"]:
row = result["results"][0]
assert {
"slug", "title", "entity_type", "wikilink",
"excerpt", "tags", "status", "score",
} <= set(row)
def test_search_includes_agents_and_mcps(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1", name="ctx__wiki_search",
arguments={"query": "filesystem review", "top_n": 10},
)
)
)
by_slug = {row["slug"]: row for row in result["results"]}
assert by_slug["code-reviewer"]["entity_type"] == "agent"
assert by_slug["code-reviewer"]["wikilink"] == "[[entities/agents/code-reviewer]]"
assert by_slug["filesystem"]["entity_type"] == "mcp-server"
assert by_slug["filesystem"]["wikilink"] == "[[entities/mcp-servers/f/filesystem]]"
# ── wiki_get ───────────────────────────────────────────────────────────────
class TestWikiGet:
def test_happy_path(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__wiki_get",
arguments={"slug": "python-patterns"})
)
)
assert "error" not in result
assert result["slug"] == "python-patterns"
assert "frontmatter" in result
assert "body" in result
assert "Python Patterns" in result["body"]
def test_missing_slug(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__wiki_get", arguments={})
)
)
assert "error" in result
def test_invalid_slug_rejected(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1", name="ctx__wiki_get",
arguments={"slug": "../../etc/passwd"},
)
)
)
assert "error" in result
assert "invalid" in result["error"].lower()
def test_nonexistent_slug(self, toolbox: CtxCoreToolbox) -> None:
result = json.loads(
toolbox.dispatch(
ToolCall(id="c1", name="ctx__wiki_get",
arguments={"slug": "does-not-exist"})
)
)
assert "error" in result
assert "looked_in" in result
def test_entity_type_disambiguates_duplicate_slugs(self, tmp_path: Path) -> None:
wiki = _build_synthetic_wiki(tmp_path)
(wiki / "entities" / "skills" / "filesystem.md").write_text(
"---\n"
"name: filesystem\n"
"title: Filesystem Skill\n"
"type: skill\n"
"tags: [skill]\n"
"status: cataloged\n"
"---\n"
"# Filesystem Skill\n\n"
"This is the skill page, not the MCP page.\n",
encoding="utf-8",
)
toolbox = CtxCoreToolbox(wiki_dir=wiki, graph_path=tmp_path / "missing.json")
result = json.loads(
toolbox.dispatch(
ToolCall(
id="c1",
name="ctx__wiki_get",
arguments={"slug": "filesystem", "entity_type": "mcp-server"},
)
)
)
assert "error" not in result
assert result["entity_type"] == "mcp-server"
assert result["wikilink"] == "[[entities/mcp-servers/f/filesystem]]"
assert "Filesystem MCP" in result["body"]
# ── _query_to_tags ────────────────────────────────────────────────────────
class TestQueryToTags:
def test_basic_tokenisation(self) -> None:
assert _query_to_tags("python web api") == ["python", "web", "api"]
def test_stopwords_removed(self) -> None:
out = _query_to_tags("how do I use the python api")
assert "python" in out
assert "the" not in out
assert "how" not in out
# Too short tokens also dropped: 'do', 'i'.
assert "do" not in out
def test_dedup_preserves_order(self) -> None:
out = _query_to_tags("python python web api python")
assert out == ["python", "web", "api"]
def test_hyphens_and_underscores_preserved(self) -> None:
out = _query_to_tags("react-native state-management my_lib")
assert "react-native" in out
assert "state-management" in out
assert "my_lib" in out
def test_case_normalised(self) -> None:
assert _query_to_tags("PYTHON Web") == ["python", "web"]
# ── _clamp_int ────────────────────────────────────────────────────────────
class TestClampInt:
def test_default(self) -> None:
assert _clamp_int(None, default=5, lo=1, hi=50) == 5
def test_in_range(self) -> None:
assert _clamp_int(10, default=5, lo=1, hi=50) == 10
def test_below_lo(self) -> None:
assert _clamp_int(0, default=5, lo=1, hi=50) == 1
def test_above_hi(self) -> None:
assert _clamp_int(1000, default=5, lo=1, hi=50) == 50
def test_invalid_string(self) -> None:
assert _clamp_int("nope", default=5, lo=1, hi=50) == 5
def test_string_number(self) -> None:
assert _clamp_int("7", default=5, lo=1, hi=50) == 7
# ── _excerpt ──────────────────────────────────────────────────────────────
class TestExcerpt:
def test_empty_body(self) -> None:
assert _excerpt("", 50) == ""
def test_skips_heading(self) -> None:
body = "# Heading\n\nActual body text here.\n"
assert _excerpt(body, 50) == "Actual body text here."
def test_trims_to_length(self) -> None:
body = "a" * 200
out = _excerpt(body, 50)
assert len(out) <= 50
assert out.endswith("…")
# ── make_tool_executor composition ────────────────────────────────────────
class TestMakeToolExecutor:
def test_ctx_call_routed_to_toolbox(self, toolbox: CtxCoreToolbox) -> None:
def fallback(_call):
raise AssertionError("fallback should not fire for ctx__ calls")
exe = make_tool_executor(toolbox, fallback=fallback)
out = exe(
ToolCall(
id="c1", name="ctx__recommend_bundle",
arguments={"query": "python", "top_k": 3},
)
)
data = json.loads(out)
assert "results" in data
def test_non_ctx_call_delegates_to_fallback(
self, toolbox: CtxCoreToolbox
) -> None:
calls = []
def fallback(call):
calls.append(call)
return f"fallback-handled:{call.name}"
exe = make_tool_executor(toolbox, fallback=fallback)
out = exe(ToolCall(id="c1", name="fs__read_file", arguments={}))
assert out == "fallback-handled:fs__read_file"
assert calls and calls[0].name == "fs__read_file"
def test_no_fallback_raises_on_non_ctx(
self, toolbox: CtxCoreToolbox
) -> None:
exe = make_tool_executor(toolbox, fallback=None)
with pytest.raises(ValueError, match="no executor"):
exe(ToolCall(id="c1", name="anything__else", arguments={}))
|