File size: 31,658 Bytes
e965652 1bbe168 e965652 21ff762 e965652 21ff762 e965652 21ff762 e965652 21ff762 e965652 21ff762 e965652 424e16a 21ff762 e965652 21ff762 e965652 21ff762 e965652 d5d5035 e965652 21ff762 1bbe168 21ff762 e965652 21ff762 f2361ba 21ff762 f2361ba 21ff762 f2361ba 21ff762 d5d5035 21ff762 | 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 | """Tests for ctx-harness-install."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import harness_install
import pytest
def _write_harness_page(
wiki: Path,
slug: str = "text-to-cad",
**frontmatter: Any,
) -> Path:
data: dict[str, Any] = {
"title": "Text to CAD",
"type": "harness",
"status": "cataloged",
"repo_url": "https://github.com/earthtojake/text-to-cad",
"tags": ["cad", "3d"],
"runtimes": ["python", "node"],
"setup_commands": ["python -m pip install -e ."],
"verify_commands": ["python -m pytest"],
}
data.update(frontmatter)
page = wiki / "entities" / "harnesses" / f"{slug}.md"
page.parent.mkdir(parents=True, exist_ok=True)
lines = ["---"]
for key, value in data.items():
if isinstance(value, list):
lines.append(f"{key}:")
lines.extend(f" - {item}" for item in value)
else:
lines.append(f"{key}: {value}")
lines.extend(["---", "", "# Harness"])
page.write_text("\n".join(lines) + "\n", encoding="utf-8")
return page
@dataclass
class _FakeRun:
returncode: int = 0
stdout: str = "ok"
stderr: str = ""
def test_dry_run_prints_plan_without_writing(tmp_path: Path, capsys: Any) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
dry_run=True,
)
assert result.status == "dry-run"
assert not (tmp_path / "installs").exists()
assert "Text to CAD" in capsys.readouterr().out
def test_relative_custom_target_resolves_under_installs_root(tmp_path: Path) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
target=Path("custom"),
dry_run=True,
)
assert result.status == "dry-run"
assert result.target == (tmp_path / "installs" / "custom").resolve()
def test_install_copies_local_source_and_writes_manifest(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("harness", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
allow_local_sources=True,
)
assert result.status == "installed"
assert (tmp_path / "installs" / "text-to-cad" / "README.md").exists()
manifest = json.loads(
(tmp_path / "manifests" / "text-to-cad.json").read_text(encoding="utf-8")
)
assert manifest["slug"] == "text-to-cad"
assert manifest["status"] == "installed"
assert {Path(path).as_posix() for path in manifest["attach_files"]} == {
".ctx/attach/README.md",
".ctx/attach/ctx-run.txt",
".ctx/attach/mcp.json",
".ctx/attach/python.py",
}
assert manifest["setup_commands_run"] == []
assert manifest["verify_commands_run"] == []
attach_dir = tmp_path / "installs" / "text-to-cad" / ".ctx" / "attach"
assert json.loads((attach_dir / "mcp.json").read_text(encoding="utf-8")) == {
"mcpServers": {"ctx-wiki": {"command": "ctx-mcp-server", "args": []}}
}
assert "recommend_bundle" in (attach_dir / "python.py").read_text(encoding="utf-8")
assert "ctx run --model" in (attach_dir / "ctx-run.txt").read_text(encoding="utf-8")
def test_write_manifest_uses_atomic_json_writer(
tmp_path: Path,
monkeypatch: Any,
) -> None:
calls: list[tuple[Path, dict[str, Any], int | None]] = []
def fake_atomic_write_json(
path: Path,
obj: Any,
indent: int | None = 2,
) -> None:
assert isinstance(obj, dict)
calls.append((path, obj, indent))
path.write_text(json.dumps(obj, indent=indent) + "\n", encoding="utf-8")
monkeypatch.setattr(
harness_install,
"atomic_write_json",
fake_atomic_write_json,
raising=False,
)
record = harness_install.HarnessRecord(
slug="text-to-cad",
path=tmp_path / "page.md",
title="Text to CAD",
repo_url="https://github.com/earthtojake/text-to-cad",
docs_url=None,
tags=("cad",),
runtimes=("python",),
model_providers=("openai",),
capabilities=("Generate CAD",),
attach_modes=("mcp", "python-library", "ctx-run"),
setup_commands=(),
verify_commands=(),
)
path = harness_install._write_manifest(
record=record,
target=tmp_path / "installs" / "text-to-cad",
manifest_dir=tmp_path / "manifests",
setup_runs=[],
verify_runs=[],
attach_files=[],
)
assert path == tmp_path / "manifests" / "text-to-cad.json"
assert calls == [(path, json.loads(path.read_text(encoding="utf-8")), 2)]
def test_install_respects_catalog_attach_modes(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source), attach_modes=["mcp"])
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
allow_local_sources=True,
)
assert result.status == "installed"
attach_dir = tmp_path / "installs" / "text-to-cad" / ".ctx" / "attach"
assert (attach_dir / "README.md").exists()
assert (attach_dir / "mcp.json").exists()
assert not (attach_dir / "python.py").exists()
assert not (attach_dir / "ctx-run.txt").exists()
def test_dry_run_does_not_write_attach_files(tmp_path: Path) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
dry_run=True,
)
assert result.status == "dry-run"
assert not (tmp_path / "installs" / "text-to-cad" / ".ctx").exists()
def test_install_accepts_file_uri_local_source_with_opt_in(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("harness", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=source.as_uri())
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
allow_local_sources=True,
)
assert result.status == "installed"
assert (tmp_path / "installs" / "text-to-cad" / "README.md").exists()
def test_install_refuses_local_source_without_explicit_opt_in(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
)
assert result.status == "install-failed"
assert "--allow-local-source" in result.message
assert not (tmp_path / "installs" / "text-to-cad").exists()
def test_remote_install_requires_pinned_commit_by_default(tmp_path: Path) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
)
assert result.status == "install-failed"
assert "not pinned to a commit" in result.message
assert not (tmp_path / "installs" / "text-to-cad").exists()
def test_remote_install_fetches_pinned_commit_and_records_manifest(
tmp_path: Path,
monkeypatch: Any,
) -> None:
commit = "a" * 40
wiki = tmp_path / "wiki"
_write_harness_page(wiki, commit_sha=commit)
git_calls: list[list[str]] = []
def fake_run_git(args: list[str], *, timeout: int = 300) -> _FakeRun:
git_calls.append(args)
if args[:2] == ["clone", "--no-checkout"]:
target = Path(args[-1])
target.mkdir(parents=True)
(target / "README.md").write_text("remote harness", encoding="utf-8")
if "rev-parse" in args:
return _FakeRun(stdout=f"{commit}\n")
return _FakeRun()
monkeypatch.setattr(harness_install, "_run_git", fake_run_git)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
)
assert result.status == "installed"
assert git_calls[0][:2] == ["clone", "--no-checkout"]
assert any(
call[0] == "-C"
and call[2:6] == ["fetch", "--depth", "1", "origin"]
and call[-1] == commit
for call in git_calls
)
assert any(
call[0] == "-C" and call[2:] == ["checkout", "--detach", "FETCH_HEAD"]
for call in git_calls
)
assert any(
call[0] == "-C" and call[2:] == ["rev-parse", "HEAD"]
for call in git_calls
)
manifest = json.loads(
(tmp_path / "manifests" / "text-to-cad.json").read_text(encoding="utf-8")
)
assert manifest["repo_ref"] == commit
assert manifest["resolved_commit"] == commit
def test_install_failure_after_target_replace_rolls_back_new_target(
tmp_path: Path,
monkeypatch: Any,
) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("harness", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
def fail_attach(*_args: Any, **_kwargs: Any) -> list[Path]:
raise OSError("attach write failed")
monkeypatch.setattr(harness_install, "_write_attach_files", fail_attach)
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
allow_local_sources=True,
)
assert result.status == "install-failed"
assert "attach write failed" in result.message
assert not (tmp_path / "installs" / "text-to-cad").exists()
assert not (tmp_path / "manifests" / "text-to-cad.json").exists()
def test_install_refuses_symlink_inside_local_source(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
outside = tmp_path / "outside.txt"
outside.write_text("secret", encoding="utf-8")
try:
(source / "leak.txt").symlink_to(outside)
except OSError as exc:
pytest.skip(f"symlinks unavailable in this environment: {exc}")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
allow_local_sources=True,
)
assert result.status == "install-failed"
assert "symlink inside harness source" in result.message
def test_setup_and_verify_commands_require_explicit_flags(
tmp_path: Path,
monkeypatch: Any,
) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
calls: list[list[str]] = []
def fake_run(cmd: list[str], **_kwargs: Any) -> _FakeRun:
calls.append(cmd)
return _FakeRun()
monkeypatch.setattr(harness_install.subprocess, "run", fake_run)
harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs-a",
manifest_dir=tmp_path / "manifests-a",
allow_local_sources=True,
)
assert calls == []
harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs-b",
manifest_dir=tmp_path / "manifests-b",
approve_commands=True,
run_verify=True,
allow_local_sources=True,
)
assert Path(calls[0][0]).name.lower().startswith("python")
assert calls[0][1:] == ["-m", "pip", "install", "-e", "."]
assert Path(calls[1][0]).name.lower().startswith("python")
assert calls[1][1:] == ["-m", "pytest"]
def test_target_must_stay_inside_installs_root(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
target=tmp_path / "outside",
)
assert result.status == "invalid-target"
assert not (tmp_path / "outside").exists()
def test_target_cannot_be_installs_root(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
installs_root = tmp_path / "installs"
result = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=tmp_path / "manifests",
target=installs_root,
allow_local_sources=True,
)
assert result.status == "invalid-target"
assert not installs_root.exists()
def test_repo_url_identifier_resolves_matching_page(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url="https://github.com/earthtojake/text-to-cad")
record = harness_install.resolve_harness(
"https://github.com/earthtojake/text-to-cad",
wiki_path=wiki,
)
assert record.slug == "text-to-cad"
def test_missing_harness_fails_clearly(tmp_path: Path) -> None:
result = harness_install.install_harness(
"missing",
wiki_path=tmp_path / "wiki",
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
)
assert result.status == "not-found"
assert "missing" in result.message
def test_uninstall_removes_target_and_manifest(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
assert install.manifest_path is not None
result = harness_install.uninstall_harness(
"text-to-cad",
manifest_dir=manifest_dir,
)
assert result.status == "uninstalled"
assert not install.target.exists()
assert not install.manifest_path.exists()
def test_uninstall_marks_manifest_uninstalling_before_deleting_files(
tmp_path: Path,
monkeypatch: Any,
) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
assert install.manifest_path is not None
original_unlink = Path.unlink
def fail_manifest_unlink(path: Path, *args: Any, **kwargs: Any) -> None:
if path == install.manifest_path:
raise OSError("crash after deleting files")
return original_unlink(path, *args, **kwargs)
monkeypatch.setattr(Path, "unlink", fail_manifest_unlink)
result = harness_install.uninstall_harness(
"text-to-cad",
manifest_dir=manifest_dir,
)
assert result.status == "uninstall-failed"
assert not install.target.exists()
manifest = json.loads(install.manifest_path.read_text(encoding="utf-8"))
assert manifest["status"] == "uninstalling"
def test_uninstall_keep_files_only_removes_manifest(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
assert install.manifest_path is not None
result = harness_install.uninstall_harness(
"text-to-cad",
manifest_dir=manifest_dir,
keep_files=True,
)
assert result.status == "uninstalled"
assert install.target.exists()
assert not install.manifest_path.exists()
def test_uninstall_refuses_manifest_target_at_installs_root(tmp_path: Path) -> None:
manifest_dir = tmp_path / "manifests"
manifest_dir.mkdir()
installs_root = tmp_path / "installs"
installs_root.mkdir()
sibling = installs_root / "other"
sibling.mkdir()
(manifest_dir / "text-to-cad.json").write_text(
json.dumps({"slug": "text-to-cad", "target": str(installs_root)}),
encoding="utf-8",
)
result = harness_install.uninstall_harness(
"text-to-cad",
manifest_dir=manifest_dir,
installs_root=installs_root,
)
assert result.status == "invalid-target"
assert installs_root.exists()
assert sibling.exists()
def test_update_replaces_installed_target_from_catalog_source(tmp_path: Path) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
installs_root = tmp_path / "installs"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
(source / "README.md").write_text("v2", encoding="utf-8")
result = harness_install.update_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert result.status == "updated"
assert (install.target / "README.md").read_text(encoding="utf-8") == "v2"
def test_update_failure_preserves_existing_target_and_manifest(
tmp_path: Path,
monkeypatch: Any,
) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
installs_root = tmp_path / "installs"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
assert install.manifest_path is not None
before_manifest = install.manifest_path.read_text(encoding="utf-8")
(source / "README.md").write_text("v2", encoding="utf-8")
def fake_run(cmd: list[str], **_kwargs: Any) -> _FakeRun:
return _FakeRun(returncode=1, stderr="setup failed")
monkeypatch.setattr(harness_install.subprocess, "run", fake_run)
result = harness_install.update_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
approve_commands=True,
allow_local_sources=True,
)
assert result.status == "install-failed"
assert (install.target / "README.md").read_text(encoding="utf-8") == "v1"
assert install.manifest_path.read_text(encoding="utf-8") == before_manifest
def test_update_manifest_failure_rolls_back_replaced_target(
tmp_path: Path,
monkeypatch: Any,
) -> None:
source = tmp_path / "source"
source.mkdir()
(source / "README.md").write_text("v1", encoding="utf-8")
wiki = tmp_path / "wiki"
_write_harness_page(wiki, repo_url=str(source))
manifest_dir = tmp_path / "manifests"
installs_root = tmp_path / "installs"
install = harness_install.install_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert install.target is not None
assert install.manifest_path is not None
before_manifest = install.manifest_path.read_text(encoding="utf-8")
(source / "README.md").write_text("v2", encoding="utf-8")
def fail_manifest(**_kwargs: Any) -> Path:
raise OSError("manifest write failed")
monkeypatch.setattr(harness_install, "_write_manifest", fail_manifest)
result = harness_install.update_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
allow_local_sources=True,
)
assert result.status == "install-failed"
assert "manifest write failed" in result.message
assert (install.target / "README.md").read_text(encoding="utf-8") == "v1"
assert install.manifest_path.read_text(encoding="utf-8") == before_manifest
assert not list(installs_root.glob(".text-to-cad.backup-*"))
def test_update_requires_existing_manifest(tmp_path: Path) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
result = harness_install.update_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=tmp_path / "installs",
manifest_dir=tmp_path / "manifests",
)
assert result.status == "not-installed"
def test_update_dry_run_validates_manifest_target(tmp_path: Path) -> None:
wiki = tmp_path / "wiki"
_write_harness_page(wiki)
manifest_dir = tmp_path / "manifests"
manifest_dir.mkdir()
installs_root = tmp_path / "installs"
installs_root.mkdir()
(manifest_dir / "text-to-cad.json").write_text(
json.dumps({"slug": "text-to-cad", "target": str(installs_root)}),
encoding="utf-8",
)
result = harness_install.update_harness(
"text-to-cad",
wiki_path=wiki,
installs_root=installs_root,
manifest_dir=manifest_dir,
dry_run=True,
)
assert result.status == "invalid-target"
def test_cataloged_commands_use_sanitized_env_and_redact_output(
tmp_path: Path,
monkeypatch: Any,
) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "sk-secret-value")
captured_env: dict[str, str] = {}
def fake_run(cmd: list[str], **kwargs: Any) -> _FakeRun:
captured_env.update(kwargs["env"])
return _FakeRun(stdout="token sk-secret-value")
monkeypatch.setattr(harness_install.subprocess, "run", fake_run)
run = harness_install._run_command("python --version", cwd=tmp_path)
assert "OPENAI_API_KEY" not in captured_env
assert run["stdout"] == f"token {harness_install._REDACTION}"
def test_run_command_resolves_bare_executable(
tmp_path: Path,
monkeypatch: Any,
) -> None:
resolved = str(tmp_path / "npx.cmd")
captured_cmd: list[str] = []
def fake_which(command: str, *, path: str | None = None) -> str | None:
return resolved if command == "npx" else None
def fake_run(cmd: list[str], **_kwargs: Any) -> _FakeRun:
captured_cmd.extend(cmd)
return _FakeRun(stdout="9.0.0")
monkeypatch.setattr(harness_install.shutil, "which", fake_which)
monkeypatch.setattr(harness_install.subprocess, "run", fake_run)
run = harness_install._run_command("npx --version", cwd=tmp_path)
assert run["returncode"] == 0
assert captured_cmd[0] == resolved
def test_split_command_preserves_windows_backslashes() -> None:
parts = harness_install._split_command(
r'python "C:\Users\me\script.py"',
windows=True,
)
assert parts == ["python", r"C:\Users\me\script.py"]
def test_failed_run_message_includes_redacted_output() -> None:
message = harness_install._failed_run_message(
"setup",
"npm install",
{"stderr": "token leaked", "stdout": ""},
)
assert message == "setup command failed: npm install: token leaked"
def test_recommend_mode_prints_install_handoff(
monkeypatch: Any,
capsys: Any,
) -> None:
calls: list[dict[str, object]] = []
def fake_recommend(**kwargs: Any) -> list[dict[str, object]]:
calls.append(kwargs)
return [{
"name": "text-to-cad",
"normalized_score": 0.91,
"reason": "cad tag match",
}]
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", fake_recommend)
rc = harness_install.main([
"--recommend",
"--goal",
"generate CAD from text",
"--model-provider",
"openai",
"--model",
"openai/gpt-5.5",
])
assert rc == 0
assert calls[0]["model_provider"] == "openai"
assert calls[0]["model"] == "openai/gpt-5.5"
output = capsys.readouterr().out
assert "Recommended harnesses" in output
assert "ctx-harness-install text-to-cad --dry-run" in output
def test_recommend_mode_passes_structured_harness_requirements(
monkeypatch: Any,
) -> None:
calls: list[dict[str, object]] = []
def fake_recommend(**kwargs: Any) -> list[dict[str, object]]:
calls.append(kwargs)
return []
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", fake_recommend)
rc = harness_install.main([
"--recommend",
"--goal",
"build a code agent",
"--model",
"openai/gpt-5.5",
"--harness-runtime",
"windows python",
"--harness-autonomy",
"supervised",
"--harness-tools",
"filesystem shell browser",
"--harness-verify",
"pytest ruff",
"--harness-privacy",
"private repo no secrets",
"--harness-attach-mode",
"mcp",
])
assert rc == 0
assert calls[0]["harness_requirements"] == {
"runtime": "windows python",
"autonomy": "supervised",
"tools": "filesystem shell browser",
"verification": "pytest ruff",
"privacy": "private repo no secrets",
"attach_mode": "mcp",
}
def test_recommend_cli_query_includes_structured_harness_requirements(
monkeypatch: Any,
) -> None:
import ctx_init
calls: list[dict[str, object]] = []
def fake_recommend(
goal: str,
top_k: int = 5,
model_provider: str | None = None,
model: str | None = None,
) -> list[dict[str, object]]:
calls.append({
"goal": goal,
"top_k": top_k,
"model_provider": model_provider,
"model": model,
})
return []
monkeypatch.setattr(ctx_init, "recommend_harnesses", fake_recommend)
harness_install.recommend_harnesses_for_cli(
goal="build a code agent",
model_provider="openai",
model="openai/gpt-5.5",
top_k=5,
harness_requirements={
"runtime": "windows python",
"tools": "filesystem shell browser",
"verification": "pytest ruff",
"privacy": "private repo no secrets",
"attach_mode": "mcp",
},
)
query = str(calls[0]["goal"])
assert "windows python" in query
assert "filesystem shell browser" in query
assert "pytest ruff" in query
assert "private repo no secrets" in query
assert "mcp" in query
def test_recommend_no_fit_prints_custom_harness_plan(
monkeypatch: Any,
capsys: Any,
) -> None:
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", lambda **_: [])
rc = harness_install.main([
"--recommend",
"--goal",
"build a private CAD workflow with a local model",
"--model-provider",
"ollama",
"--model",
"ollama/llama3.1",
"--harness-runtime",
"linux server",
"--harness-tools",
"filesystem shell",
"--harness-verify",
"pytest",
"--harness-privacy",
"offline source code",
"--plan-on-no-fit",
])
assert rc == 0
output = capsys.readouterr().out
assert "No harness recommendations matched." in output
assert "# Custom Harness PRD" in output
assert "ctx-mcp-server" in output
assert "ctx.recommend_bundle" in output
assert "Windows, macOS, and Linux" in output
assert "Runtime / OS: linux server" in output
assert "Allowed tools/access: filesystem shell" in output
assert "Verification: pytest" in output
assert "Privacy/network: offline source code" in output
def test_recommend_no_fit_writes_custom_harness_plan(
tmp_path: Path,
monkeypatch: Any,
capsys: Any,
) -> None:
monkeypatch.setattr(harness_install, "recommend_harnesses_for_cli", lambda **_: [])
target = tmp_path / "custom-harness.md"
rc = harness_install.main([
"--recommend",
"--goal",
"repair a legacy Python service",
"--model",
"openrouter/openai/gpt-5.5",
"--plan-on-no-fit",
"--plan-output",
str(target),
])
assert rc == 0
assert f"Custom harness plan: {target}" in capsys.readouterr().out
text = target.read_text(encoding="utf-8")
assert "repair a legacy Python service" in text
assert "Model provider: openrouter" in text
assert "openrouter/openai/gpt-5.5" in text
assert "Build the harness described above" in text
|